sqlite3.c 6.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.9.1. 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. /*
  43. ** Include the header file used to customize the compiler options for MSVC.
  44. ** This should be done first so that it can successfully prevent spurious
  45. ** compiler warnings due to subsequent content in this file and other files
  46. ** that are included by this file.
  47. */
  48. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  49. /************** Begin file msvc.h ********************************************/
  50. /*
  51. ** 2015 January 12
  52. **
  53. ** The author disclaims copyright to this source code. In place of
  54. ** a legal notice, here is a blessing:
  55. **
  56. ** May you do good and not evil.
  57. ** May you find forgiveness for yourself and forgive others.
  58. ** May you share freely, never taking more than you give.
  59. **
  60. ******************************************************************************
  61. **
  62. ** This file contains code that is specific to MSVC.
  63. */
  64. #ifndef _MSVC_H_
  65. #define _MSVC_H_
  66. #if defined(_MSC_VER)
  67. #pragma warning(disable : 4054)
  68. #pragma warning(disable : 4055)
  69. #pragma warning(disable : 4100)
  70. #pragma warning(disable : 4127)
  71. #pragma warning(disable : 4130)
  72. #pragma warning(disable : 4152)
  73. #pragma warning(disable : 4189)
  74. #pragma warning(disable : 4206)
  75. #pragma warning(disable : 4210)
  76. #pragma warning(disable : 4232)
  77. #pragma warning(disable : 4244)
  78. #pragma warning(disable : 4305)
  79. #pragma warning(disable : 4306)
  80. #pragma warning(disable : 4702)
  81. #pragma warning(disable : 4706)
  82. #endif /* defined(_MSC_VER) */
  83. #endif /* _MSVC_H_ */
  84. /************** End of msvc.h ************************************************/
  85. /************** Continuing where we left off in sqliteInt.h ******************/
  86. /*
  87. ** Special setup for VxWorks
  88. */
  89. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  90. /************** Begin file vxworks.h *****************************************/
  91. /*
  92. ** 2015-03-02
  93. **
  94. ** The author disclaims copyright to this source code. In place of
  95. ** a legal notice, here is a blessing:
  96. **
  97. ** May you do good and not evil.
  98. ** May you find forgiveness for yourself and forgive others.
  99. ** May you share freely, never taking more than you give.
  100. **
  101. ******************************************************************************
  102. **
  103. ** This file contains code that is specific to Wind River's VxWorks
  104. */
  105. #if defined(__RTP__) || defined(_WRS_KERNEL)
  106. /* This is VxWorks. Set up things specially for that OS
  107. */
  108. #include <vxWorks.h>
  109. #include <pthread.h> /* amalgamator: dontcache */
  110. #define OS_VXWORKS 1
  111. #define SQLITE_OS_OTHER 0
  112. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  113. #define SQLITE_OMIT_LOAD_EXTENSION 1
  114. #define SQLITE_ENABLE_LOCKING_STYLE 0
  115. #define HAVE_UTIME 1
  116. #else
  117. /* This is not VxWorks. */
  118. #define OS_VXWORKS 0
  119. #endif /* defined(_WRS_KERNEL) */
  120. /************** End of vxworks.h *********************************************/
  121. /************** Continuing where we left off in sqliteInt.h ******************/
  122. /*
  123. ** These #defines should enable >2GB file support on POSIX if the
  124. ** underlying operating system supports it. If the OS lacks
  125. ** large file support, or if the OS is windows, these should be no-ops.
  126. **
  127. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  128. ** system #includes. Hence, this block of code must be the very first
  129. ** code in all source files.
  130. **
  131. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  132. ** on the compiler command line. This is necessary if you are compiling
  133. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  134. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  135. ** without this option, LFS is enable. But LFS does not exist in the kernel
  136. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  137. ** portability you should omit LFS.
  138. **
  139. ** The previous paragraph was written in 2005. (This paragraph is written
  140. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  141. ** you should probably leave LFS enabled. But some embedded platforms might
  142. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  143. **
  144. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  145. */
  146. #ifndef SQLITE_DISABLE_LFS
  147. # define _LARGE_FILE 1
  148. # ifndef _FILE_OFFSET_BITS
  149. # define _FILE_OFFSET_BITS 64
  150. # endif
  151. # define _LARGEFILE_SOURCE 1
  152. #endif
  153. /* What version of GCC is being used. 0 means GCC is not being used */
  154. #ifdef __GNUC__
  155. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  156. #else
  157. # define GCC_VERSION 0
  158. #endif
  159. /* Needed for various definitions... */
  160. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  161. # define _GNU_SOURCE
  162. #endif
  163. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  164. # define _BSD_SOURCE
  165. #endif
  166. /*
  167. ** For MinGW, check to see if we can include the header file containing its
  168. ** version information, among other things. Normally, this internal MinGW
  169. ** header file would [only] be included automatically by other MinGW header
  170. ** files; however, the contained version information is now required by this
  171. ** header file to work around binary compatibility issues (see below) and
  172. ** this is the only known way to reliably obtain it. This entire #if block
  173. ** would be completely unnecessary if there was any other way of detecting
  174. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  175. ** some MinGW-specific macros). When compiling for MinGW, either the
  176. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  177. ** defined; otherwise, detection of conditions specific to MinGW will be
  178. ** disabled.
  179. */
  180. #if defined(_HAVE_MINGW_H)
  181. # include "mingw.h"
  182. #elif defined(_HAVE__MINGW_H)
  183. # include "_mingw.h"
  184. #endif
  185. /*
  186. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  187. ** define is required to maintain binary compatibility with the MSVC runtime
  188. ** library in use (e.g. for Windows XP).
  189. */
  190. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  191. defined(_WIN32) && !defined(_WIN64) && \
  192. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  193. defined(__MSVCRT__)
  194. # define _USE_32BIT_TIME_T
  195. #endif
  196. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  197. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  198. ** MinGW.
  199. */
  200. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  201. /************** Begin file sqlite3.h *****************************************/
  202. /*
  203. ** 2001 September 15
  204. **
  205. ** The author disclaims copyright to this source code. In place of
  206. ** a legal notice, here is a blessing:
  207. **
  208. ** May you do good and not evil.
  209. ** May you find forgiveness for yourself and forgive others.
  210. ** May you share freely, never taking more than you give.
  211. **
  212. *************************************************************************
  213. ** This header file defines the interface that the SQLite library
  214. ** presents to client programs. If a C-function, structure, datatype,
  215. ** or constant definition does not appear in this file, then it is
  216. ** not a published API of SQLite, is subject to change without
  217. ** notice, and should not be referenced by programs that use SQLite.
  218. **
  219. ** Some of the definitions that are in this file are marked as
  220. ** "experimental". Experimental interfaces are normally new
  221. ** features recently added to SQLite. We do not anticipate changes
  222. ** to experimental interfaces but reserve the right to make minor changes
  223. ** if experience from use "in the wild" suggest such changes are prudent.
  224. **
  225. ** The official C-language API documentation for SQLite is derived
  226. ** from comments in this file. This file is the authoritative source
  227. ** on how SQLite interfaces are supposed to operate.
  228. **
  229. ** The name of this file under configuration management is "sqlite.h.in".
  230. ** The makefile makes some minor changes to this file (such as inserting
  231. ** the version number) and changes its name to "sqlite3.h" as
  232. ** part of the build process.
  233. */
  234. #ifndef _SQLITE3_H_
  235. #define _SQLITE3_H_
  236. #include <stdarg.h> /* Needed for the definition of va_list */
  237. /*
  238. ** Make sure we can call this stuff from C++.
  239. */
  240. #if 0
  241. extern "C" {
  242. #endif
  243. /*
  244. ** Provide the ability to override linkage features of the interface.
  245. */
  246. #ifndef SQLITE_EXTERN
  247. # define SQLITE_EXTERN extern
  248. #endif
  249. #ifndef SQLITE_API
  250. # define SQLITE_API
  251. #endif
  252. #ifndef SQLITE_CDECL
  253. # define SQLITE_CDECL
  254. #endif
  255. #ifndef SQLITE_STDCALL
  256. # define SQLITE_STDCALL
  257. #endif
  258. /*
  259. ** These no-op macros are used in front of interfaces to mark those
  260. ** interfaces as either deprecated or experimental. New applications
  261. ** should not use deprecated interfaces - they are supported for backwards
  262. ** compatibility only. Application writers should be aware that
  263. ** experimental interfaces are subject to change in point releases.
  264. **
  265. ** These macros used to resolve to various kinds of compiler magic that
  266. ** would generate warning messages when they were used. But that
  267. ** compiler magic ended up generating such a flurry of bug reports
  268. ** that we have taken it all out and gone back to using simple
  269. ** noop macros.
  270. */
  271. #define SQLITE_DEPRECATED
  272. #define SQLITE_EXPERIMENTAL
  273. /*
  274. ** Ensure these symbols were not defined by some previous header file.
  275. */
  276. #ifdef SQLITE_VERSION
  277. # undef SQLITE_VERSION
  278. #endif
  279. #ifdef SQLITE_VERSION_NUMBER
  280. # undef SQLITE_VERSION_NUMBER
  281. #endif
  282. /*
  283. ** CAPI3REF: Compile-Time Library Version Numbers
  284. **
  285. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  286. ** evaluates to a string literal that is the SQLite version in the
  287. ** format "X.Y.Z" where X is the major version number (always 3 for
  288. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  289. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  290. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  291. ** numbers used in [SQLITE_VERSION].)^
  292. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  293. ** be larger than the release from which it is derived. Either Y will
  294. ** be held constant and Z will be incremented or else Y will be incremented
  295. ** and Z will be reset to zero.
  296. **
  297. ** Since version 3.6.18, SQLite source code has been stored in the
  298. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  299. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  300. ** a string which identifies a particular check-in of SQLite
  301. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  302. ** string contains the date and time of the check-in (UTC) and an SHA1
  303. ** hash of the entire source tree.
  304. **
  305. ** See also: [sqlite3_libversion()],
  306. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  307. ** [sqlite_version()] and [sqlite_source_id()].
  308. */
  309. #define SQLITE_VERSION "3.9.1"
  310. #define SQLITE_VERSION_NUMBER 3009001
  311. #define SQLITE_SOURCE_ID "2015-10-16 17:31:12 767c1727fec4ce11b83f25b3f1bfcfe68a2c8b02"
  312. /*
  313. ** CAPI3REF: Run-Time Library Version Numbers
  314. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  315. **
  316. ** These interfaces provide the same information as the [SQLITE_VERSION],
  317. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  318. ** but are associated with the library instead of the header file. ^(Cautious
  319. ** programmers might include assert() statements in their application to
  320. ** verify that values returned by these interfaces match the macros in
  321. ** the header, and thus ensure that the application is
  322. ** compiled with matching library and header files.
  323. **
  324. ** <blockquote><pre>
  325. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  326. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  327. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  328. ** </pre></blockquote>)^
  329. **
  330. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  331. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  332. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  333. ** function is provided for use in DLLs since DLL users usually do not have
  334. ** direct access to string constants within the DLL. ^The
  335. ** sqlite3_libversion_number() function returns an integer equal to
  336. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  337. ** a pointer to a string constant whose value is the same as the
  338. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  339. **
  340. ** See also: [sqlite_version()] and [sqlite_source_id()].
  341. */
  342. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  343. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
  344. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
  345. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
  346. /*
  347. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  348. **
  349. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  350. ** indicating whether the specified option was defined at
  351. ** compile time. ^The SQLITE_ prefix may be omitted from the
  352. ** option name passed to sqlite3_compileoption_used().
  353. **
  354. ** ^The sqlite3_compileoption_get() function allows iterating
  355. ** over the list of options that were defined at compile time by
  356. ** returning the N-th compile time option string. ^If N is out of range,
  357. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  358. ** prefix is omitted from any strings returned by
  359. ** sqlite3_compileoption_get().
  360. **
  361. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  362. ** and sqlite3_compileoption_get() may be omitted by specifying the
  363. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  364. **
  365. ** See also: SQL functions [sqlite_compileoption_used()] and
  366. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  367. */
  368. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  369. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
  370. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
  371. #endif
  372. /*
  373. ** CAPI3REF: Test To See If The Library Is Threadsafe
  374. **
  375. ** ^The sqlite3_threadsafe() function returns zero if and only if
  376. ** SQLite was compiled with mutexing code omitted due to the
  377. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  378. **
  379. ** SQLite can be compiled with or without mutexes. When
  380. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  381. ** are enabled and SQLite is threadsafe. When the
  382. ** [SQLITE_THREADSAFE] macro is 0,
  383. ** the mutexes are omitted. Without the mutexes, it is not safe
  384. ** to use SQLite concurrently from more than one thread.
  385. **
  386. ** Enabling mutexes incurs a measurable performance penalty.
  387. ** So if speed is of utmost importance, it makes sense to disable
  388. ** the mutexes. But for maximum safety, mutexes should be enabled.
  389. ** ^The default behavior is for mutexes to be enabled.
  390. **
  391. ** This interface can be used by an application to make sure that the
  392. ** version of SQLite that it is linking against was compiled with
  393. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  394. **
  395. ** This interface only reports on the compile-time mutex setting
  396. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  397. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  398. ** can be fully or partially disabled using a call to [sqlite3_config()]
  399. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  400. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  401. ** sqlite3_threadsafe() function shows only the compile-time setting of
  402. ** thread safety, not any run-time changes to that setting made by
  403. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  404. ** is unchanged by calls to sqlite3_config().)^
  405. **
  406. ** See the [threading mode] documentation for additional information.
  407. */
  408. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
  409. /*
  410. ** CAPI3REF: Database Connection Handle
  411. ** KEYWORDS: {database connection} {database connections}
  412. **
  413. ** Each open SQLite database is represented by a pointer to an instance of
  414. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  415. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  416. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  417. ** and [sqlite3_close_v2()] are its destructors. There are many other
  418. ** interfaces (such as
  419. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  420. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  421. ** sqlite3 object.
  422. */
  423. typedef struct sqlite3 sqlite3;
  424. /*
  425. ** CAPI3REF: 64-Bit Integer Types
  426. ** KEYWORDS: sqlite_int64 sqlite_uint64
  427. **
  428. ** Because there is no cross-platform way to specify 64-bit integer types
  429. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  430. **
  431. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  432. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  433. ** compatibility only.
  434. **
  435. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  436. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  437. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  438. ** between 0 and +18446744073709551615 inclusive.
  439. */
  440. #ifdef SQLITE_INT64_TYPE
  441. typedef SQLITE_INT64_TYPE sqlite_int64;
  442. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  443. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  444. typedef __int64 sqlite_int64;
  445. typedef unsigned __int64 sqlite_uint64;
  446. #else
  447. typedef long long int sqlite_int64;
  448. typedef unsigned long long int sqlite_uint64;
  449. #endif
  450. typedef sqlite_int64 sqlite3_int64;
  451. typedef sqlite_uint64 sqlite3_uint64;
  452. /*
  453. ** If compiling for a processor that lacks floating point support,
  454. ** substitute integer for floating-point.
  455. */
  456. #ifdef SQLITE_OMIT_FLOATING_POINT
  457. # define double sqlite3_int64
  458. #endif
  459. /*
  460. ** CAPI3REF: Closing A Database Connection
  461. ** DESTRUCTOR: sqlite3
  462. **
  463. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  464. ** for the [sqlite3] object.
  465. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  466. ** the [sqlite3] object is successfully destroyed and all associated
  467. ** resources are deallocated.
  468. **
  469. ** ^If the database connection is associated with unfinalized prepared
  470. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  471. ** will leave the database connection open and return [SQLITE_BUSY].
  472. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  473. ** and/or unfinished sqlite3_backups, then the database connection becomes
  474. ** an unusable "zombie" which will automatically be deallocated when the
  475. ** last prepared statement is finalized or the last sqlite3_backup is
  476. ** finished. The sqlite3_close_v2() interface is intended for use with
  477. ** host languages that are garbage collected, and where the order in which
  478. ** destructors are called is arbitrary.
  479. **
  480. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  481. ** [sqlite3_blob_close | close] all [BLOB handles], and
  482. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  483. ** with the [sqlite3] object prior to attempting to close the object. ^If
  484. ** sqlite3_close_v2() is called on a [database connection] that still has
  485. ** outstanding [prepared statements], [BLOB handles], and/or
  486. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  487. ** of resources is deferred until all [prepared statements], [BLOB handles],
  488. ** and [sqlite3_backup] objects are also destroyed.
  489. **
  490. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  491. ** the transaction is automatically rolled back.
  492. **
  493. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  494. ** must be either a NULL
  495. ** pointer or an [sqlite3] object pointer obtained
  496. ** from [sqlite3_open()], [sqlite3_open16()], or
  497. ** [sqlite3_open_v2()], and not previously closed.
  498. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  499. ** argument is a harmless no-op.
  500. */
  501. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
  502. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
  503. /*
  504. ** The type for a callback function.
  505. ** This is legacy and deprecated. It is included for historical
  506. ** compatibility and is not documented.
  507. */
  508. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  509. /*
  510. ** CAPI3REF: One-Step Query Execution Interface
  511. ** METHOD: sqlite3
  512. **
  513. ** The sqlite3_exec() interface is a convenience wrapper around
  514. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  515. ** that allows an application to run multiple statements of SQL
  516. ** without having to use a lot of C code.
  517. **
  518. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  519. ** semicolon-separate SQL statements passed into its 2nd argument,
  520. ** in the context of the [database connection] passed in as its 1st
  521. ** argument. ^If the callback function of the 3rd argument to
  522. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  523. ** coming out of the evaluated SQL statements. ^The 4th argument to
  524. ** sqlite3_exec() is relayed through to the 1st argument of each
  525. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  526. ** is NULL, then no callback is ever invoked and result rows are
  527. ** ignored.
  528. **
  529. ** ^If an error occurs while evaluating the SQL statements passed into
  530. ** sqlite3_exec(), then execution of the current statement stops and
  531. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  532. ** is not NULL then any error message is written into memory obtained
  533. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  534. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  535. ** on error message strings returned through the 5th parameter of
  536. ** of sqlite3_exec() after the error message string is no longer needed.
  537. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  538. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  539. ** NULL before returning.
  540. **
  541. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  542. ** routine returns SQLITE_ABORT without invoking the callback again and
  543. ** without running any subsequent SQL statements.
  544. **
  545. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  546. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  547. ** callback is an array of pointers to strings obtained as if from
  548. ** [sqlite3_column_text()], one for each column. ^If an element of a
  549. ** result row is NULL then the corresponding string pointer for the
  550. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  551. ** sqlite3_exec() callback is an array of pointers to strings where each
  552. ** entry represents the name of corresponding result column as obtained
  553. ** from [sqlite3_column_name()].
  554. **
  555. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  556. ** to an empty string, or a pointer that contains only whitespace and/or
  557. ** SQL comments, then no SQL statements are evaluated and the database
  558. ** is not changed.
  559. **
  560. ** Restrictions:
  561. **
  562. ** <ul>
  563. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  564. ** is a valid and open [database connection].
  565. ** <li> The application must not close the [database connection] specified by
  566. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  567. ** <li> The application must not modify the SQL statement text passed into
  568. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  569. ** </ul>
  570. */
  571. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  572. sqlite3*, /* An open database */
  573. const char *sql, /* SQL to be evaluated */
  574. int (*callback)(void*,int,char**,char**), /* Callback function */
  575. void *, /* 1st argument to callback */
  576. char **errmsg /* Error msg written here */
  577. );
  578. /*
  579. ** CAPI3REF: Result Codes
  580. ** KEYWORDS: {result code definitions}
  581. **
  582. ** Many SQLite functions return an integer result code from the set shown
  583. ** here in order to indicate success or failure.
  584. **
  585. ** New error codes may be added in future versions of SQLite.
  586. **
  587. ** See also: [extended result code definitions]
  588. */
  589. #define SQLITE_OK 0 /* Successful result */
  590. /* beginning-of-error-codes */
  591. #define SQLITE_ERROR 1 /* SQL error or missing database */
  592. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  593. #define SQLITE_PERM 3 /* Access permission denied */
  594. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  595. #define SQLITE_BUSY 5 /* The database file is locked */
  596. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  597. #define SQLITE_NOMEM 7 /* A malloc() failed */
  598. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  599. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  600. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  601. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  602. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  603. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  604. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  605. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  606. #define SQLITE_EMPTY 16 /* Database is empty */
  607. #define SQLITE_SCHEMA 17 /* The database schema changed */
  608. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  609. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  610. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  611. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  612. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  613. #define SQLITE_AUTH 23 /* Authorization denied */
  614. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  615. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  616. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  617. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  618. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  619. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  620. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  621. /* end-of-error-codes */
  622. /*
  623. ** CAPI3REF: Extended Result Codes
  624. ** KEYWORDS: {extended result code definitions}
  625. **
  626. ** In its default configuration, SQLite API routines return one of 30 integer
  627. ** [result codes]. However, experience has shown that many of
  628. ** these result codes are too coarse-grained. They do not provide as
  629. ** much information about problems as programmers might like. In an effort to
  630. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  631. ** support for additional result codes that provide more detailed information
  632. ** about errors. These [extended result codes] are enabled or disabled
  633. ** on a per database connection basis using the
  634. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  635. ** the most recent error can be obtained using
  636. ** [sqlite3_extended_errcode()].
  637. */
  638. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  639. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  640. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  641. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  642. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  643. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  644. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  645. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  646. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  647. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  648. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  649. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  650. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  651. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  652. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  653. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  654. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  655. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  656. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  657. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  658. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  659. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  660. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  661. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  662. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  663. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  664. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  665. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  666. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  667. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  668. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  669. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  670. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  671. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  672. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  673. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  674. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  675. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  676. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  677. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  678. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  679. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  680. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  681. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  682. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  683. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  684. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  685. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  686. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  687. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  688. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  689. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  690. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  691. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  692. /*
  693. ** CAPI3REF: Flags For File Open Operations
  694. **
  695. ** These bit values are intended for use in the
  696. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  697. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  698. */
  699. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  700. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  701. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  702. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  703. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  704. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  705. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  706. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  707. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  708. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  709. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  710. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  711. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  712. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  713. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  714. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  715. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  716. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  717. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  718. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  719. /* Reserved: 0x00F00000 */
  720. /*
  721. ** CAPI3REF: Device Characteristics
  722. **
  723. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  724. ** object returns an integer which is a vector of these
  725. ** bit values expressing I/O characteristics of the mass storage
  726. ** device that holds the file that the [sqlite3_io_methods]
  727. ** refers to.
  728. **
  729. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  730. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  731. ** mean that writes of blocks that are nnn bytes in size and
  732. ** are aligned to an address which is an integer multiple of
  733. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  734. ** that when data is appended to a file, the data is appended
  735. ** first then the size of the file is extended, never the other
  736. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  737. ** information is written to disk in the same order as calls
  738. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  739. ** after reboot following a crash or power loss, the only bytes in a
  740. ** file that were written at the application level might have changed
  741. ** and that adjacent bytes, even bytes within the same sector are
  742. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  743. ** flag indicate that a file cannot be deleted when open. The
  744. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  745. ** read-only media and cannot be changed even by processes with
  746. ** elevated privileges.
  747. */
  748. #define SQLITE_IOCAP_ATOMIC 0x00000001
  749. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  750. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  751. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  752. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  753. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  754. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  755. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  756. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  757. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  758. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  759. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  760. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  761. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  762. /*
  763. ** CAPI3REF: File Locking Levels
  764. **
  765. ** SQLite uses one of these integer values as the second
  766. ** argument to calls it makes to the xLock() and xUnlock() methods
  767. ** of an [sqlite3_io_methods] object.
  768. */
  769. #define SQLITE_LOCK_NONE 0
  770. #define SQLITE_LOCK_SHARED 1
  771. #define SQLITE_LOCK_RESERVED 2
  772. #define SQLITE_LOCK_PENDING 3
  773. #define SQLITE_LOCK_EXCLUSIVE 4
  774. /*
  775. ** CAPI3REF: Synchronization Type Flags
  776. **
  777. ** When SQLite invokes the xSync() method of an
  778. ** [sqlite3_io_methods] object it uses a combination of
  779. ** these integer values as the second argument.
  780. **
  781. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  782. ** sync operation only needs to flush data to mass storage. Inode
  783. ** information need not be flushed. If the lower four bits of the flag
  784. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  785. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  786. ** to use Mac OS X style fullsync instead of fsync().
  787. **
  788. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  789. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  790. ** settings. The [synchronous pragma] determines when calls to the
  791. ** xSync VFS method occur and applies uniformly across all platforms.
  792. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  793. ** energetic or rigorous or forceful the sync operations are and
  794. ** only make a difference on Mac OSX for the default SQLite code.
  795. ** (Third-party VFS implementations might also make the distinction
  796. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  797. ** operating systems natively supported by SQLite, only Mac OSX
  798. ** cares about the difference.)
  799. */
  800. #define SQLITE_SYNC_NORMAL 0x00002
  801. #define SQLITE_SYNC_FULL 0x00003
  802. #define SQLITE_SYNC_DATAONLY 0x00010
  803. /*
  804. ** CAPI3REF: OS Interface Open File Handle
  805. **
  806. ** An [sqlite3_file] object represents an open file in the
  807. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  808. ** implementations will
  809. ** want to subclass this object by appending additional fields
  810. ** for their own use. The pMethods entry is a pointer to an
  811. ** [sqlite3_io_methods] object that defines methods for performing
  812. ** I/O operations on the open file.
  813. */
  814. typedef struct sqlite3_file sqlite3_file;
  815. struct sqlite3_file {
  816. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  817. };
  818. /*
  819. ** CAPI3REF: OS Interface File Virtual Methods Object
  820. **
  821. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  822. ** [sqlite3_file] object (or, more commonly, a subclass of the
  823. ** [sqlite3_file] object) with a pointer to an instance of this object.
  824. ** This object defines the methods used to perform various operations
  825. ** against the open file represented by the [sqlite3_file] object.
  826. **
  827. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  828. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  829. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  830. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  831. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  832. ** to NULL.
  833. **
  834. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  835. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  836. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  837. ** flag may be ORed in to indicate that only the data of the file
  838. ** and not its inode needs to be synced.
  839. **
  840. ** The integer values to xLock() and xUnlock() are one of
  841. ** <ul>
  842. ** <li> [SQLITE_LOCK_NONE],
  843. ** <li> [SQLITE_LOCK_SHARED],
  844. ** <li> [SQLITE_LOCK_RESERVED],
  845. ** <li> [SQLITE_LOCK_PENDING], or
  846. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  847. ** </ul>
  848. ** xLock() increases the lock. xUnlock() decreases the lock.
  849. ** The xCheckReservedLock() method checks whether any database connection,
  850. ** either in this process or in some other process, is holding a RESERVED,
  851. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  852. ** if such a lock exists and false otherwise.
  853. **
  854. ** The xFileControl() method is a generic interface that allows custom
  855. ** VFS implementations to directly control an open file using the
  856. ** [sqlite3_file_control()] interface. The second "op" argument is an
  857. ** integer opcode. The third argument is a generic pointer intended to
  858. ** point to a structure that may contain arguments or space in which to
  859. ** write return values. Potential uses for xFileControl() might be
  860. ** functions to enable blocking locks with timeouts, to change the
  861. ** locking strategy (for example to use dot-file locks), to inquire
  862. ** about the status of a lock, or to break stale locks. The SQLite
  863. ** core reserves all opcodes less than 100 for its own use.
  864. ** A [file control opcodes | list of opcodes] less than 100 is available.
  865. ** Applications that define a custom xFileControl method should use opcodes
  866. ** greater than 100 to avoid conflicts. VFS implementations should
  867. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  868. ** recognize.
  869. **
  870. ** The xSectorSize() method returns the sector size of the
  871. ** device that underlies the file. The sector size is the
  872. ** minimum write that can be performed without disturbing
  873. ** other bytes in the file. The xDeviceCharacteristics()
  874. ** method returns a bit vector describing behaviors of the
  875. ** underlying device:
  876. **
  877. ** <ul>
  878. ** <li> [SQLITE_IOCAP_ATOMIC]
  879. ** <li> [SQLITE_IOCAP_ATOMIC512]
  880. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  881. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  882. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  883. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  884. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  885. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  886. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  887. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  888. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  889. ** </ul>
  890. **
  891. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  892. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  893. ** mean that writes of blocks that are nnn bytes in size and
  894. ** are aligned to an address which is an integer multiple of
  895. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  896. ** that when data is appended to a file, the data is appended
  897. ** first then the size of the file is extended, never the other
  898. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  899. ** information is written to disk in the same order as calls
  900. ** to xWrite().
  901. **
  902. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  903. ** in the unread portions of the buffer with zeros. A VFS that
  904. ** fails to zero-fill short reads might seem to work. However,
  905. ** failure to zero-fill short reads will eventually lead to
  906. ** database corruption.
  907. */
  908. typedef struct sqlite3_io_methods sqlite3_io_methods;
  909. struct sqlite3_io_methods {
  910. int iVersion;
  911. int (*xClose)(sqlite3_file*);
  912. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  913. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  914. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  915. int (*xSync)(sqlite3_file*, int flags);
  916. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  917. int (*xLock)(sqlite3_file*, int);
  918. int (*xUnlock)(sqlite3_file*, int);
  919. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  920. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  921. int (*xSectorSize)(sqlite3_file*);
  922. int (*xDeviceCharacteristics)(sqlite3_file*);
  923. /* Methods above are valid for version 1 */
  924. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  925. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  926. void (*xShmBarrier)(sqlite3_file*);
  927. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  928. /* Methods above are valid for version 2 */
  929. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  930. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  931. /* Methods above are valid for version 3 */
  932. /* Additional methods may be added in future releases */
  933. };
  934. /*
  935. ** CAPI3REF: Standard File Control Opcodes
  936. ** KEYWORDS: {file control opcodes} {file control opcode}
  937. **
  938. ** These integer constants are opcodes for the xFileControl method
  939. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  940. ** interface.
  941. **
  942. ** <ul>
  943. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  944. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  945. ** opcode causes the xFileControl method to write the current state of
  946. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  947. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  948. ** into an integer that the pArg argument points to. This capability
  949. ** is used during testing and is only available when the SQLITE_TEST
  950. ** compile-time option is used.
  951. **
  952. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  953. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  954. ** layer a hint of how large the database file will grow to be during the
  955. ** current transaction. This hint is not guaranteed to be accurate but it
  956. ** is often close. The underlying VFS might choose to preallocate database
  957. ** file space based on this hint in order to help writes to the database
  958. ** file run faster.
  959. **
  960. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  961. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  962. ** extends and truncates the database file in chunks of a size specified
  963. ** by the user. The fourth argument to [sqlite3_file_control()] should
  964. ** point to an integer (type int) containing the new chunk-size to use
  965. ** for the nominated database. Allocating database file space in large
  966. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  967. ** improve performance on some systems.
  968. **
  969. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  970. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  971. ** to the [sqlite3_file] object associated with a particular database
  972. ** connection. See the [sqlite3_file_control()] documentation for
  973. ** additional information.
  974. **
  975. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  976. ** No longer in use.
  977. **
  978. ** <li>[[SQLITE_FCNTL_SYNC]]
  979. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  980. ** sent to the VFS immediately before the xSync method is invoked on a
  981. ** database file descriptor. Or, if the xSync method is not invoked
  982. ** because the user has configured SQLite with
  983. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  984. ** of the xSync method. In most cases, the pointer argument passed with
  985. ** this file-control is NULL. However, if the database file is being synced
  986. ** as part of a multi-database commit, the argument points to a nul-terminated
  987. ** string containing the transactions master-journal file name. VFSes that
  988. ** do not need this signal should silently ignore this opcode. Applications
  989. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  990. ** disrupt the operation of the specialized VFSes that do require it.
  991. **
  992. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  993. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  994. ** and sent to the VFS after a transaction has been committed immediately
  995. ** but before the database is unlocked. VFSes that do not need this signal
  996. ** should silently ignore this opcode. Applications should not call
  997. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  998. ** operation of the specialized VFSes that do require it.
  999. **
  1000. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1001. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1002. ** retry counts and intervals for certain disk I/O operations for the
  1003. ** windows [VFS] in order to provide robustness in the presence of
  1004. ** anti-virus programs. By default, the windows VFS will retry file read,
  1005. ** file write, and file delete operations up to 10 times, with a delay
  1006. ** of 25 milliseconds before the first retry and with the delay increasing
  1007. ** by an additional 25 milliseconds with each subsequent retry. This
  1008. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1009. ** to be adjusted. The values are changed for all database connections
  1010. ** within the same process. The argument is a pointer to an array of two
  1011. ** integers where the first integer i the new retry count and the second
  1012. ** integer is the delay. If either integer is negative, then the setting
  1013. ** is not changed but instead the prior value of that setting is written
  1014. ** into the array entry, allowing the current retry settings to be
  1015. ** interrogated. The zDbName parameter is ignored.
  1016. **
  1017. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1018. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1019. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1020. ** write ahead log and shared memory files used for transaction control
  1021. ** are automatically deleted when the latest connection to the database
  1022. ** closes. Setting persistent WAL mode causes those files to persist after
  1023. ** close. Persisting the files is useful when other processes that do not
  1024. ** have write permission on the directory containing the database file want
  1025. ** to read the database file, as the WAL and shared memory files must exist
  1026. ** in order for the database to be readable. The fourth parameter to
  1027. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1028. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1029. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1030. ** WAL persistence setting.
  1031. **
  1032. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1033. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1034. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1035. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1036. ** xDeviceCharacteristics methods. The fourth parameter to
  1037. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1038. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1039. ** mode. If the integer is -1, then it is overwritten with the current
  1040. ** zero-damage mode setting.
  1041. **
  1042. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1043. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1044. ** a write transaction to indicate that, unless it is rolled back for some
  1045. ** reason, the entire database file will be overwritten by the current
  1046. ** transaction. This is used by VACUUM operations.
  1047. **
  1048. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1049. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1050. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1051. ** final bottom-level VFS are written into memory obtained from
  1052. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1053. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1054. ** The caller is responsible for freeing the memory when done. As with
  1055. ** all file-control actions, there is no guarantee that this will actually
  1056. ** do anything. Callers should initialize the char* variable to a NULL
  1057. ** pointer in case this file-control is not implemented. This file-control
  1058. ** is intended for diagnostic use only.
  1059. **
  1060. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1061. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1062. ** file control is sent to the open [sqlite3_file] object corresponding
  1063. ** to the database file to which the pragma statement refers. ^The argument
  1064. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1065. ** pointers to strings (char**) in which the second element of the array
  1066. ** is the name of the pragma and the third element is the argument to the
  1067. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1068. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1069. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1070. ** or the equivalent and that string will become the result of the pragma or
  1071. ** the error message if the pragma fails. ^If the
  1072. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1073. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1074. ** file control returns [SQLITE_OK], then the parser assumes that the
  1075. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1076. ** prepared statement if result string is NULL, or that returns a copy
  1077. ** of the result string if the string is non-NULL.
  1078. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1079. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1080. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1081. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1082. ** file control occurs at the beginning of pragma statement analysis and so
  1083. ** it is able to override built-in [PRAGMA] statements.
  1084. **
  1085. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1086. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1087. ** file-control may be invoked by SQLite on the database file handle
  1088. ** shortly after it is opened in order to provide a custom VFS with access
  1089. ** to the connections busy-handler callback. The argument is of type (void **)
  1090. ** - an array of two (void *) values. The first (void *) actually points
  1091. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1092. ** busy-handler, this function should be invoked with the second (void *) in
  1093. ** the array as the only argument. If it returns non-zero, then the operation
  1094. ** should be retried. If it returns zero, the custom VFS should abandon the
  1095. ** current operation.
  1096. **
  1097. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1098. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1099. ** to have SQLite generate a
  1100. ** temporary filename using the same algorithm that is followed to generate
  1101. ** temporary filenames for TEMP tables and other internal uses. The
  1102. ** argument should be a char** which will be filled with the filename
  1103. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1104. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1105. **
  1106. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1107. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1108. ** maximum number of bytes that will be used for memory-mapped I/O.
  1109. ** The argument is a pointer to a value of type sqlite3_int64 that
  1110. ** is an advisory maximum number of bytes in the file to memory map. The
  1111. ** pointer is overwritten with the old value. The limit is not changed if
  1112. ** the value originally pointed to is negative, and so the current limit
  1113. ** can be queried by passing in a pointer to a negative number. This
  1114. ** file-control is used internally to implement [PRAGMA mmap_size].
  1115. **
  1116. ** <li>[[SQLITE_FCNTL_TRACE]]
  1117. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1118. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1119. ** This file control is used by some VFS activity tracing [shims].
  1120. ** The argument is a zero-terminated string. Higher layers in the
  1121. ** SQLite stack may generate instances of this file control if
  1122. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1123. **
  1124. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1125. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1126. ** pointer to an integer and it writes a boolean into that integer depending
  1127. ** on whether or not the file has been renamed, moved, or deleted since it
  1128. ** was first opened.
  1129. **
  1130. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1131. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1132. ** opcode causes the xFileControl method to swap the file handle with the one
  1133. ** pointed to by the pArg argument. This capability is used during testing
  1134. ** and only needs to be supported when SQLITE_TEST is defined.
  1135. **
  1136. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1137. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1138. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1139. ** available. The WAL subsystem issues this signal during rare
  1140. ** circumstances in order to fix a problem with priority inversion.
  1141. ** Applications should <em>not</em> use this file-control.
  1142. **
  1143. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1144. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1145. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1146. **
  1147. ** <li>[[SQLITE_FCNTL_RBU]]
  1148. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1149. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1150. ** this opcode.
  1151. ** </ul>
  1152. */
  1153. #define SQLITE_FCNTL_LOCKSTATE 1
  1154. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1155. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1156. #define SQLITE_FCNTL_LAST_ERRNO 4
  1157. #define SQLITE_FCNTL_SIZE_HINT 5
  1158. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1159. #define SQLITE_FCNTL_FILE_POINTER 7
  1160. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1161. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1162. #define SQLITE_FCNTL_PERSIST_WAL 10
  1163. #define SQLITE_FCNTL_OVERWRITE 11
  1164. #define SQLITE_FCNTL_VFSNAME 12
  1165. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1166. #define SQLITE_FCNTL_PRAGMA 14
  1167. #define SQLITE_FCNTL_BUSYHANDLER 15
  1168. #define SQLITE_FCNTL_TEMPFILENAME 16
  1169. #define SQLITE_FCNTL_MMAP_SIZE 18
  1170. #define SQLITE_FCNTL_TRACE 19
  1171. #define SQLITE_FCNTL_HAS_MOVED 20
  1172. #define SQLITE_FCNTL_SYNC 21
  1173. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1174. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1175. #define SQLITE_FCNTL_WAL_BLOCK 24
  1176. #define SQLITE_FCNTL_ZIPVFS 25
  1177. #define SQLITE_FCNTL_RBU 26
  1178. /* deprecated names */
  1179. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1180. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1181. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1182. /*
  1183. ** CAPI3REF: Mutex Handle
  1184. **
  1185. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1186. ** abstract type for a mutex object. The SQLite core never looks
  1187. ** at the internal representation of an [sqlite3_mutex]. It only
  1188. ** deals with pointers to the [sqlite3_mutex] object.
  1189. **
  1190. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1191. */
  1192. typedef struct sqlite3_mutex sqlite3_mutex;
  1193. /*
  1194. ** CAPI3REF: OS Interface Object
  1195. **
  1196. ** An instance of the sqlite3_vfs object defines the interface between
  1197. ** the SQLite core and the underlying operating system. The "vfs"
  1198. ** in the name of the object stands for "virtual file system". See
  1199. ** the [VFS | VFS documentation] for further information.
  1200. **
  1201. ** The value of the iVersion field is initially 1 but may be larger in
  1202. ** future versions of SQLite. Additional fields may be appended to this
  1203. ** object when the iVersion value is increased. Note that the structure
  1204. ** of the sqlite3_vfs object changes in the transaction between
  1205. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1206. ** modified.
  1207. **
  1208. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1209. ** structure used by this VFS. mxPathname is the maximum length of
  1210. ** a pathname in this VFS.
  1211. **
  1212. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1213. ** the pNext pointer. The [sqlite3_vfs_register()]
  1214. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1215. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1216. ** searches the list. Neither the application code nor the VFS
  1217. ** implementation should use the pNext pointer.
  1218. **
  1219. ** The pNext field is the only field in the sqlite3_vfs
  1220. ** structure that SQLite will ever modify. SQLite will only access
  1221. ** or modify this field while holding a particular static mutex.
  1222. ** The application should never modify anything within the sqlite3_vfs
  1223. ** object once the object has been registered.
  1224. **
  1225. ** The zName field holds the name of the VFS module. The name must
  1226. ** be unique across all VFS modules.
  1227. **
  1228. ** [[sqlite3_vfs.xOpen]]
  1229. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1230. ** is either a NULL pointer or string obtained
  1231. ** from xFullPathname() with an optional suffix added.
  1232. ** ^If a suffix is added to the zFilename parameter, it will
  1233. ** consist of a single "-" character followed by no more than
  1234. ** 11 alphanumeric and/or "-" characters.
  1235. ** ^SQLite further guarantees that
  1236. ** the string will be valid and unchanged until xClose() is
  1237. ** called. Because of the previous sentence,
  1238. ** the [sqlite3_file] can safely store a pointer to the
  1239. ** filename if it needs to remember the filename for some reason.
  1240. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1241. ** must invent its own temporary name for the file. ^Whenever the
  1242. ** xFilename parameter is NULL it will also be the case that the
  1243. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1244. **
  1245. ** The flags argument to xOpen() includes all bits set in
  1246. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1247. ** or [sqlite3_open16()] is used, then flags includes at least
  1248. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1249. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1250. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1251. **
  1252. ** ^(SQLite will also add one of the following flags to the xOpen()
  1253. ** call, depending on the object being opened:
  1254. **
  1255. ** <ul>
  1256. ** <li> [SQLITE_OPEN_MAIN_DB]
  1257. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1258. ** <li> [SQLITE_OPEN_TEMP_DB]
  1259. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1260. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1261. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1262. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1263. ** <li> [SQLITE_OPEN_WAL]
  1264. ** </ul>)^
  1265. **
  1266. ** The file I/O implementation can use the object type flags to
  1267. ** change the way it deals with files. For example, an application
  1268. ** that does not care about crash recovery or rollback might make
  1269. ** the open of a journal file a no-op. Writes to this journal would
  1270. ** also be no-ops, and any attempt to read the journal would return
  1271. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1272. ** file will be doing page-aligned sector reads and writes in a random
  1273. ** order and set up its I/O subsystem accordingly.
  1274. **
  1275. ** SQLite might also add one of the following flags to the xOpen method:
  1276. **
  1277. ** <ul>
  1278. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1279. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1280. ** </ul>
  1281. **
  1282. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1283. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1284. ** will be set for TEMP databases and their journals, transient
  1285. ** databases, and subjournals.
  1286. **
  1287. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1288. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1289. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1290. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1291. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1292. ** be created, and that it is an error if it already exists.
  1293. ** It is <i>not</i> used to indicate the file should be opened
  1294. ** for exclusive access.
  1295. **
  1296. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1297. ** to hold the [sqlite3_file] structure passed as the third
  1298. ** argument to xOpen. The xOpen method does not have to
  1299. ** allocate the structure; it should just fill it in. Note that
  1300. ** the xOpen method must set the sqlite3_file.pMethods to either
  1301. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1302. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1303. ** element will be valid after xOpen returns regardless of the success
  1304. ** or failure of the xOpen call.
  1305. **
  1306. ** [[sqlite3_vfs.xAccess]]
  1307. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1308. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1309. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1310. ** to test whether a file is at least readable. The file can be a
  1311. ** directory.
  1312. **
  1313. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1314. ** output buffer xFullPathname. The exact size of the output buffer
  1315. ** is also passed as a parameter to both methods. If the output buffer
  1316. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1317. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1318. ** to prevent this by setting mxPathname to a sufficiently large value.
  1319. **
  1320. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1321. ** interfaces are not strictly a part of the filesystem, but they are
  1322. ** included in the VFS structure for completeness.
  1323. ** The xRandomness() function attempts to return nBytes bytes
  1324. ** of good-quality randomness into zOut. The return value is
  1325. ** the actual number of bytes of randomness obtained.
  1326. ** The xSleep() method causes the calling thread to sleep for at
  1327. ** least the number of microseconds given. ^The xCurrentTime()
  1328. ** method returns a Julian Day Number for the current date and time as
  1329. ** a floating point value.
  1330. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1331. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1332. ** a 24-hour day).
  1333. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1334. ** date and time if that method is available (if iVersion is 2 or
  1335. ** greater and the function pointer is not NULL) and will fall back
  1336. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1337. **
  1338. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1339. ** are not used by the SQLite core. These optional interfaces are provided
  1340. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1341. ** system calls with functions under its control, a test program can
  1342. ** simulate faults and error conditions that would otherwise be difficult
  1343. ** or impossible to induce. The set of system calls that can be overridden
  1344. ** varies from one VFS to another, and from one version of the same VFS to the
  1345. ** next. Applications that use these interfaces must be prepared for any
  1346. ** or all of these interfaces to be NULL or for their behavior to change
  1347. ** from one release to the next. Applications must not attempt to access
  1348. ** any of these methods if the iVersion of the VFS is less than 3.
  1349. */
  1350. typedef struct sqlite3_vfs sqlite3_vfs;
  1351. typedef void (*sqlite3_syscall_ptr)(void);
  1352. struct sqlite3_vfs {
  1353. int iVersion; /* Structure version number (currently 3) */
  1354. int szOsFile; /* Size of subclassed sqlite3_file */
  1355. int mxPathname; /* Maximum file pathname length */
  1356. sqlite3_vfs *pNext; /* Next registered VFS */
  1357. const char *zName; /* Name of this virtual file system */
  1358. void *pAppData; /* Pointer to application-specific data */
  1359. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1360. int flags, int *pOutFlags);
  1361. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1362. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1363. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1364. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1365. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1366. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1367. void (*xDlClose)(sqlite3_vfs*, void*);
  1368. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1369. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1370. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1371. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1372. /*
  1373. ** The methods above are in version 1 of the sqlite_vfs object
  1374. ** definition. Those that follow are added in version 2 or later
  1375. */
  1376. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1377. /*
  1378. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1379. ** Those below are for version 3 and greater.
  1380. */
  1381. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1382. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1383. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1384. /*
  1385. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1386. ** New fields may be appended in figure versions. The iVersion
  1387. ** value will increment whenever this happens.
  1388. */
  1389. };
  1390. /*
  1391. ** CAPI3REF: Flags for the xAccess VFS method
  1392. **
  1393. ** These integer constants can be used as the third parameter to
  1394. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1395. ** what kind of permissions the xAccess method is looking for.
  1396. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1397. ** simply checks whether the file exists.
  1398. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1399. ** checks whether the named directory is both readable and writable
  1400. ** (in other words, if files can be added, removed, and renamed within
  1401. ** the directory).
  1402. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1403. ** [temp_store_directory pragma], though this could change in a future
  1404. ** release of SQLite.
  1405. ** With SQLITE_ACCESS_READ, the xAccess method
  1406. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1407. ** currently unused, though it might be used in a future release of
  1408. ** SQLite.
  1409. */
  1410. #define SQLITE_ACCESS_EXISTS 0
  1411. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1412. #define SQLITE_ACCESS_READ 2 /* Unused */
  1413. /*
  1414. ** CAPI3REF: Flags for the xShmLock VFS method
  1415. **
  1416. ** These integer constants define the various locking operations
  1417. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1418. ** following are the only legal combinations of flags to the
  1419. ** xShmLock method:
  1420. **
  1421. ** <ul>
  1422. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1423. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1424. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1425. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1426. ** </ul>
  1427. **
  1428. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1429. ** was given on the corresponding lock.
  1430. **
  1431. ** The xShmLock method can transition between unlocked and SHARED or
  1432. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1433. ** and EXCLUSIVE.
  1434. */
  1435. #define SQLITE_SHM_UNLOCK 1
  1436. #define SQLITE_SHM_LOCK 2
  1437. #define SQLITE_SHM_SHARED 4
  1438. #define SQLITE_SHM_EXCLUSIVE 8
  1439. /*
  1440. ** CAPI3REF: Maximum xShmLock index
  1441. **
  1442. ** The xShmLock method on [sqlite3_io_methods] may use values
  1443. ** between 0 and this upper bound as its "offset" argument.
  1444. ** The SQLite core will never attempt to acquire or release a
  1445. ** lock outside of this range
  1446. */
  1447. #define SQLITE_SHM_NLOCK 8
  1448. /*
  1449. ** CAPI3REF: Initialize The SQLite Library
  1450. **
  1451. ** ^The sqlite3_initialize() routine initializes the
  1452. ** SQLite library. ^The sqlite3_shutdown() routine
  1453. ** deallocates any resources that were allocated by sqlite3_initialize().
  1454. ** These routines are designed to aid in process initialization and
  1455. ** shutdown on embedded systems. Workstation applications using
  1456. ** SQLite normally do not need to invoke either of these routines.
  1457. **
  1458. ** A call to sqlite3_initialize() is an "effective" call if it is
  1459. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1460. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1461. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1462. ** of sqlite3_initialize() does any initialization. All other calls
  1463. ** are harmless no-ops.)^
  1464. **
  1465. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1466. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1467. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1468. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1469. **
  1470. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1471. ** is not. The sqlite3_shutdown() interface must only be called from a
  1472. ** single thread. All open [database connections] must be closed and all
  1473. ** other SQLite resources must be deallocated prior to invoking
  1474. ** sqlite3_shutdown().
  1475. **
  1476. ** Among other things, ^sqlite3_initialize() will invoke
  1477. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1478. ** will invoke sqlite3_os_end().
  1479. **
  1480. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1481. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1482. ** the library (perhaps it is unable to allocate a needed resource such
  1483. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1484. **
  1485. ** ^The sqlite3_initialize() routine is called internally by many other
  1486. ** SQLite interfaces so that an application usually does not need to
  1487. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1488. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1489. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1490. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1491. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1492. ** are omitted and the application must call sqlite3_initialize() directly
  1493. ** prior to using any other SQLite interface. For maximum portability,
  1494. ** it is recommended that applications always invoke sqlite3_initialize()
  1495. ** directly prior to using any other SQLite interface. Future releases
  1496. ** of SQLite may require this. In other words, the behavior exhibited
  1497. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1498. ** default behavior in some future release of SQLite.
  1499. **
  1500. ** The sqlite3_os_init() routine does operating-system specific
  1501. ** initialization of the SQLite library. The sqlite3_os_end()
  1502. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1503. ** performed by these routines include allocation or deallocation
  1504. ** of static resources, initialization of global variables,
  1505. ** setting up a default [sqlite3_vfs] module, or setting up
  1506. ** a default configuration using [sqlite3_config()].
  1507. **
  1508. ** The application should never invoke either sqlite3_os_init()
  1509. ** or sqlite3_os_end() directly. The application should only invoke
  1510. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1511. ** interface is called automatically by sqlite3_initialize() and
  1512. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1513. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1514. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1515. ** When [custom builds | built for other platforms]
  1516. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1517. ** option) the application must supply a suitable implementation for
  1518. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1519. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1520. ** must return [SQLITE_OK] on success and some other [error code] upon
  1521. ** failure.
  1522. */
  1523. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
  1524. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
  1525. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
  1526. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
  1527. /*
  1528. ** CAPI3REF: Configuring The SQLite Library
  1529. **
  1530. ** The sqlite3_config() interface is used to make global configuration
  1531. ** changes to SQLite in order to tune SQLite to the specific needs of
  1532. ** the application. The default configuration is recommended for most
  1533. ** applications and so this routine is usually not necessary. It is
  1534. ** provided to support rare applications with unusual needs.
  1535. **
  1536. ** <b>The sqlite3_config() interface is not threadsafe. The application
  1537. ** must ensure that no other SQLite interfaces are invoked by other
  1538. ** threads while sqlite3_config() is running.</b>
  1539. **
  1540. ** The sqlite3_config() interface
  1541. ** may only be invoked prior to library initialization using
  1542. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1543. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1544. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1545. ** Note, however, that ^sqlite3_config() can be called as part of the
  1546. ** implementation of an application-defined [sqlite3_os_init()].
  1547. **
  1548. ** The first argument to sqlite3_config() is an integer
  1549. ** [configuration option] that determines
  1550. ** what property of SQLite is to be configured. Subsequent arguments
  1551. ** vary depending on the [configuration option]
  1552. ** in the first argument.
  1553. **
  1554. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1555. ** ^If the option is unknown or SQLite is unable to set the option
  1556. ** then this routine returns a non-zero [error code].
  1557. */
  1558. SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
  1559. /*
  1560. ** CAPI3REF: Configure database connections
  1561. ** METHOD: sqlite3
  1562. **
  1563. ** The sqlite3_db_config() interface is used to make configuration
  1564. ** changes to a [database connection]. The interface is similar to
  1565. ** [sqlite3_config()] except that the changes apply to a single
  1566. ** [database connection] (specified in the first argument).
  1567. **
  1568. ** The second argument to sqlite3_db_config(D,V,...) is the
  1569. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1570. ** that indicates what aspect of the [database connection] is being configured.
  1571. ** Subsequent arguments vary depending on the configuration verb.
  1572. **
  1573. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1574. ** the call is considered successful.
  1575. */
  1576. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
  1577. /*
  1578. ** CAPI3REF: Memory Allocation Routines
  1579. **
  1580. ** An instance of this object defines the interface between SQLite
  1581. ** and low-level memory allocation routines.
  1582. **
  1583. ** This object is used in only one place in the SQLite interface.
  1584. ** A pointer to an instance of this object is the argument to
  1585. ** [sqlite3_config()] when the configuration option is
  1586. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1587. ** By creating an instance of this object
  1588. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1589. ** during configuration, an application can specify an alternative
  1590. ** memory allocation subsystem for SQLite to use for all of its
  1591. ** dynamic memory needs.
  1592. **
  1593. ** Note that SQLite comes with several [built-in memory allocators]
  1594. ** that are perfectly adequate for the overwhelming majority of applications
  1595. ** and that this object is only useful to a tiny minority of applications
  1596. ** with specialized memory allocation requirements. This object is
  1597. ** also used during testing of SQLite in order to specify an alternative
  1598. ** memory allocator that simulates memory out-of-memory conditions in
  1599. ** order to verify that SQLite recovers gracefully from such
  1600. ** conditions.
  1601. **
  1602. ** The xMalloc, xRealloc, and xFree methods must work like the
  1603. ** malloc(), realloc() and free() functions from the standard C library.
  1604. ** ^SQLite guarantees that the second argument to
  1605. ** xRealloc is always a value returned by a prior call to xRoundup.
  1606. **
  1607. ** xSize should return the allocated size of a memory allocation
  1608. ** previously obtained from xMalloc or xRealloc. The allocated size
  1609. ** is always at least as big as the requested size but may be larger.
  1610. **
  1611. ** The xRoundup method returns what would be the allocated size of
  1612. ** a memory allocation given a particular requested size. Most memory
  1613. ** allocators round up memory allocations at least to the next multiple
  1614. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1615. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1616. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1617. ** that causes the corresponding memory allocation to fail.
  1618. **
  1619. ** The xInit method initializes the memory allocator. For example,
  1620. ** it might allocate any require mutexes or initialize internal data
  1621. ** structures. The xShutdown method is invoked (indirectly) by
  1622. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1623. ** by xInit. The pAppData pointer is used as the only parameter to
  1624. ** xInit and xShutdown.
  1625. **
  1626. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1627. ** the xInit method, so the xInit method need not be threadsafe. The
  1628. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1629. ** not need to be threadsafe either. For all other methods, SQLite
  1630. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1631. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1632. ** it is by default) and so the methods are automatically serialized.
  1633. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1634. ** methods must be threadsafe or else make their own arrangements for
  1635. ** serialization.
  1636. **
  1637. ** SQLite will never invoke xInit() more than once without an intervening
  1638. ** call to xShutdown().
  1639. */
  1640. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1641. struct sqlite3_mem_methods {
  1642. void *(*xMalloc)(int); /* Memory allocation function */
  1643. void (*xFree)(void*); /* Free a prior allocation */
  1644. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1645. int (*xSize)(void*); /* Return the size of an allocation */
  1646. int (*xRoundup)(int); /* Round up request size to allocation size */
  1647. int (*xInit)(void*); /* Initialize the memory allocator */
  1648. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1649. void *pAppData; /* Argument to xInit() and xShutdown() */
  1650. };
  1651. /*
  1652. ** CAPI3REF: Configuration Options
  1653. ** KEYWORDS: {configuration option}
  1654. **
  1655. ** These constants are the available integer configuration options that
  1656. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1657. **
  1658. ** New configuration options may be added in future releases of SQLite.
  1659. ** Existing configuration options might be discontinued. Applications
  1660. ** should check the return code from [sqlite3_config()] to make sure that
  1661. ** the call worked. The [sqlite3_config()] interface will return a
  1662. ** non-zero [error code] if a discontinued or unsupported configuration option
  1663. ** is invoked.
  1664. **
  1665. ** <dl>
  1666. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1667. ** <dd>There are no arguments to this option. ^This option sets the
  1668. ** [threading mode] to Single-thread. In other words, it disables
  1669. ** all mutexing and puts SQLite into a mode where it can only be used
  1670. ** by a single thread. ^If SQLite is compiled with
  1671. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1672. ** it is not possible to change the [threading mode] from its default
  1673. ** value of Single-thread and so [sqlite3_config()] will return
  1674. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1675. ** configuration option.</dd>
  1676. **
  1677. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1678. ** <dd>There are no arguments to this option. ^This option sets the
  1679. ** [threading mode] to Multi-thread. In other words, it disables
  1680. ** mutexing on [database connection] and [prepared statement] objects.
  1681. ** The application is responsible for serializing access to
  1682. ** [database connections] and [prepared statements]. But other mutexes
  1683. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1684. ** environment as long as no two threads attempt to use the same
  1685. ** [database connection] at the same time. ^If SQLite is compiled with
  1686. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1687. ** it is not possible to set the Multi-thread [threading mode] and
  1688. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1689. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1690. **
  1691. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1692. ** <dd>There are no arguments to this option. ^This option sets the
  1693. ** [threading mode] to Serialized. In other words, this option enables
  1694. ** all mutexes including the recursive
  1695. ** mutexes on [database connection] and [prepared statement] objects.
  1696. ** In this mode (which is the default when SQLite is compiled with
  1697. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1698. ** to [database connections] and [prepared statements] so that the
  1699. ** application is free to use the same [database connection] or the
  1700. ** same [prepared statement] in different threads at the same time.
  1701. ** ^If SQLite is compiled with
  1702. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1703. ** it is not possible to set the Serialized [threading mode] and
  1704. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1705. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1706. **
  1707. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1708. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1709. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1710. ** The argument specifies
  1711. ** alternative low-level memory allocation routines to be used in place of
  1712. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1713. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1714. ** before the [sqlite3_config()] call returns.</dd>
  1715. **
  1716. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1717. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1718. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1719. ** The [sqlite3_mem_methods]
  1720. ** structure is filled with the currently defined memory allocation routines.)^
  1721. ** This option can be used to overload the default memory allocation
  1722. ** routines with a wrapper that simulations memory allocation failure or
  1723. ** tracks memory usage, for example. </dd>
  1724. **
  1725. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1726. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1727. ** interpreted as a boolean, which enables or disables the collection of
  1728. ** memory allocation statistics. ^(When memory allocation statistics are
  1729. ** disabled, the following SQLite interfaces become non-operational:
  1730. ** <ul>
  1731. ** <li> [sqlite3_memory_used()]
  1732. ** <li> [sqlite3_memory_highwater()]
  1733. ** <li> [sqlite3_soft_heap_limit64()]
  1734. ** <li> [sqlite3_status64()]
  1735. ** </ul>)^
  1736. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1737. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1738. ** allocation statistics are disabled by default.
  1739. ** </dd>
  1740. **
  1741. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1742. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1743. ** that SQLite can use for scratch memory. ^(There are three arguments
  1744. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1745. ** aligned memory buffer from which the scratch allocations will be
  1746. ** drawn, the size of each scratch allocation (sz),
  1747. ** and the maximum number of scratch allocations (N).)^
  1748. ** The first argument must be a pointer to an 8-byte aligned buffer
  1749. ** of at least sz*N bytes of memory.
  1750. ** ^SQLite will not use more than one scratch buffers per thread.
  1751. ** ^SQLite will never request a scratch buffer that is more than 6
  1752. ** times the database page size.
  1753. ** ^If SQLite needs needs additional
  1754. ** scratch memory beyond what is provided by this configuration option, then
  1755. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1756. ** ^When the application provides any amount of scratch memory using
  1757. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1758. ** [sqlite3_malloc|heap allocations].
  1759. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1760. ** fragmentation in low-memory embedded systems.
  1761. ** </dd>
  1762. **
  1763. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1764. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
  1765. ** that SQLite can use for the database page cache with the default page
  1766. ** cache implementation.
  1767. ** This configuration should not be used if an application-define page
  1768. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
  1769. ** configuration option.
  1770. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1771. ** 8-byte aligned
  1772. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1773. ** The sz argument should be the size of the largest database page
  1774. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1775. ** page header. ^The number of extra bytes needed by the page header
  1776. ** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option
  1777. ** to [sqlite3_config()].
  1778. ** ^It is harmless, apart from the wasted memory,
  1779. ** for the sz parameter to be larger than necessary. The first
  1780. ** argument should pointer to an 8-byte aligned block of memory that
  1781. ** is at least sz*N bytes of memory, otherwise subsequent behavior is
  1782. ** undefined.
  1783. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1784. ** memory needs for the first N pages that it adds to cache. ^If additional
  1785. ** page cache memory is needed beyond what is provided by this option, then
  1786. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
  1787. **
  1788. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1789. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1790. ** that SQLite will use for all of its dynamic memory allocation needs
  1791. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1792. ** [SQLITE_CONFIG_PAGECACHE].
  1793. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1794. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1795. ** [SQLITE_ERROR] if invoked otherwise.
  1796. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1797. ** An 8-byte aligned pointer to the memory,
  1798. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1799. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1800. ** to using its default memory allocator (the system malloc() implementation),
  1801. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1802. ** memory pointer is not NULL then the alternative memory
  1803. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1804. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1805. ** boundary or subsequent behavior of SQLite will be undefined.
  1806. ** The minimum allocation size is capped at 2**12. Reasonable values
  1807. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1808. **
  1809. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1810. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1811. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1812. ** The argument specifies alternative low-level mutex routines to be used
  1813. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1814. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1815. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1816. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1817. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1818. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1819. ** return [SQLITE_ERROR].</dd>
  1820. **
  1821. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1822. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1823. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1824. ** [sqlite3_mutex_methods]
  1825. ** structure is filled with the currently defined mutex routines.)^
  1826. ** This option can be used to overload the default mutex allocation
  1827. ** routines with a wrapper used to track mutex usage for performance
  1828. ** profiling or testing, for example. ^If SQLite is compiled with
  1829. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1830. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1831. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1832. ** return [SQLITE_ERROR].</dd>
  1833. **
  1834. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1835. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1836. ** the default size of lookaside memory on each [database connection].
  1837. ** The first argument is the
  1838. ** size of each lookaside buffer slot and the second is the number of
  1839. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1840. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1841. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1842. ** configuration on individual connections.)^ </dd>
  1843. **
  1844. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1845. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1846. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1847. ** the interface to a custom page cache implementation.)^
  1848. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1849. **
  1850. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1851. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1852. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1853. ** the current page cache implementation into that object.)^ </dd>
  1854. **
  1855. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1856. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1857. ** global [error log].
  1858. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1859. ** function with a call signature of void(*)(void*,int,const char*),
  1860. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1861. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1862. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1863. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1864. ** passed through as the first parameter to the application-defined logger
  1865. ** function whenever that function is invoked. ^The second parameter to
  1866. ** the logger function is a copy of the first parameter to the corresponding
  1867. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1868. ** [extended result code]. ^The third parameter passed to the logger is
  1869. ** log message after formatting via [sqlite3_snprintf()].
  1870. ** The SQLite logging interface is not reentrant; the logger function
  1871. ** supplied by the application must not invoke any SQLite interface.
  1872. ** In a multi-threaded application, the application-defined logger
  1873. ** function must be threadsafe. </dd>
  1874. **
  1875. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1876. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1877. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1878. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1879. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1880. ** [sqlite3_open16()] or
  1881. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1882. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1883. ** connection is opened. ^If it is globally disabled, filenames are
  1884. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1885. ** database connection is opened. ^(By default, URI handling is globally
  1886. ** disabled. The default value may be changed by compiling with the
  1887. ** [SQLITE_USE_URI] symbol defined.)^
  1888. **
  1889. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1890. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  1891. ** argument which is interpreted as a boolean in order to enable or disable
  1892. ** the use of covering indices for full table scans in the query optimizer.
  1893. ** ^The default setting is determined
  1894. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1895. ** if that compile-time option is omitted.
  1896. ** The ability to disable the use of covering indices for full table scans
  1897. ** is because some incorrectly coded legacy applications might malfunction
  1898. ** when the optimization is enabled. Providing the ability to
  1899. ** disable the optimization allows the older, buggy application code to work
  1900. ** without change even with newer versions of SQLite.
  1901. **
  1902. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1903. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1904. ** <dd> These options are obsolete and should not be used by new code.
  1905. ** They are retained for backwards compatibility but are now no-ops.
  1906. ** </dd>
  1907. **
  1908. ** [[SQLITE_CONFIG_SQLLOG]]
  1909. ** <dt>SQLITE_CONFIG_SQLLOG
  1910. ** <dd>This option is only available if sqlite is compiled with the
  1911. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1912. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1913. ** The second should be of type (void*). The callback is invoked by the library
  1914. ** in three separate circumstances, identified by the value passed as the
  1915. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1916. ** passed as the second argument has just been opened. The third argument
  1917. ** points to a buffer containing the name of the main database file. If the
  1918. ** fourth parameter is 1, then the SQL statement that the third parameter
  1919. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1920. ** the connection being passed as the second parameter is being closed. The
  1921. ** third parameter is passed NULL In this case. An example of using this
  1922. ** configuration option can be seen in the "test_sqllog.c" source file in
  1923. ** the canonical SQLite source tree.</dd>
  1924. **
  1925. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1926. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1927. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1928. ** that are the default mmap size limit (the default setting for
  1929. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1930. ** ^The default setting can be overridden by each database connection using
  1931. ** either the [PRAGMA mmap_size] command, or by using the
  1932. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1933. ** will be silently truncated if necessary so that it does not exceed the
  1934. ** compile-time maximum mmap size set by the
  1935. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1936. ** ^If either argument to this option is negative, then that argument is
  1937. ** changed to its compile-time default.
  1938. **
  1939. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1940. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1941. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  1942. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  1943. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1944. ** that specifies the maximum size of the created heap.
  1945. **
  1946. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  1947. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  1948. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  1949. ** is a pointer to an integer and writes into that integer the number of extra
  1950. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  1951. ** The amount of extra space required can change depending on the compiler,
  1952. ** target platform, and SQLite version.
  1953. **
  1954. ** [[SQLITE_CONFIG_PMASZ]]
  1955. ** <dt>SQLITE_CONFIG_PMASZ
  1956. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  1957. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  1958. ** sorter to that integer. The default minimum PMA Size is set by the
  1959. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  1960. ** to help with sort operations when multithreaded sorting
  1961. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  1962. ** to be sorted exceeds the page size times the minimum of the
  1963. ** [PRAGMA cache_size] setting and this value.
  1964. ** </dl>
  1965. */
  1966. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1967. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1968. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1969. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1970. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1971. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1972. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1973. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1974. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1975. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1976. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1977. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1978. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1979. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1980. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1981. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1982. #define SQLITE_CONFIG_URI 17 /* int */
  1983. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1984. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1985. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1986. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1987. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1988. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  1989. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  1990. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  1991. /*
  1992. ** CAPI3REF: Database Connection Configuration Options
  1993. **
  1994. ** These constants are the available integer configuration options that
  1995. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1996. **
  1997. ** New configuration options may be added in future releases of SQLite.
  1998. ** Existing configuration options might be discontinued. Applications
  1999. ** should check the return code from [sqlite3_db_config()] to make sure that
  2000. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2001. ** non-zero [error code] if a discontinued or unsupported configuration option
  2002. ** is invoked.
  2003. **
  2004. ** <dl>
  2005. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2006. ** <dd> ^This option takes three additional arguments that determine the
  2007. ** [lookaside memory allocator] configuration for the [database connection].
  2008. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2009. ** pointer to a memory buffer to use for lookaside memory.
  2010. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2011. ** may be NULL in which case SQLite will allocate the
  2012. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2013. ** size of each lookaside buffer slot. ^The third argument is the number of
  2014. ** slots. The size of the buffer in the first argument must be greater than
  2015. ** or equal to the product of the second and third arguments. The buffer
  2016. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2017. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2018. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2019. ** configuration for a database connection can only be changed when that
  2020. ** connection is not currently using lookaside memory, or in other words
  2021. ** when the "current value" returned by
  2022. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2023. ** Any attempt to change the lookaside memory configuration when lookaside
  2024. ** memory is in use leaves the configuration unchanged and returns
  2025. ** [SQLITE_BUSY].)^</dd>
  2026. **
  2027. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2028. ** <dd> ^This option is used to enable or disable the enforcement of
  2029. ** [foreign key constraints]. There should be two additional arguments.
  2030. ** The first argument is an integer which is 0 to disable FK enforcement,
  2031. ** positive to enable FK enforcement or negative to leave FK enforcement
  2032. ** unchanged. The second parameter is a pointer to an integer into which
  2033. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2034. ** following this call. The second parameter may be a NULL pointer, in
  2035. ** which case the FK enforcement setting is not reported back. </dd>
  2036. **
  2037. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2038. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2039. ** There should be two additional arguments.
  2040. ** The first argument is an integer which is 0 to disable triggers,
  2041. ** positive to enable triggers or negative to leave the setting unchanged.
  2042. ** The second parameter is a pointer to an integer into which
  2043. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2044. ** following this call. The second parameter may be a NULL pointer, in
  2045. ** which case the trigger setting is not reported back. </dd>
  2046. **
  2047. ** </dl>
  2048. */
  2049. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2050. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2051. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2052. /*
  2053. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2054. ** METHOD: sqlite3
  2055. **
  2056. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2057. ** [extended result codes] feature of SQLite. ^The extended result
  2058. ** codes are disabled by default for historical compatibility.
  2059. */
  2060. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
  2061. /*
  2062. ** CAPI3REF: Last Insert Rowid
  2063. ** METHOD: sqlite3
  2064. **
  2065. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2066. ** has a unique 64-bit signed
  2067. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2068. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2069. ** names are not also used by explicitly declared columns. ^If
  2070. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2071. ** is another alias for the rowid.
  2072. **
  2073. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  2074. ** most recent successful [INSERT] into a rowid table or [virtual table]
  2075. ** on database connection D.
  2076. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  2077. ** ^If no successful [INSERT]s into rowid tables
  2078. ** have ever occurred on the database connection D,
  2079. ** then sqlite3_last_insert_rowid(D) returns zero.
  2080. **
  2081. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2082. ** method, then this routine will return the [rowid] of the inserted
  2083. ** row as long as the trigger or virtual table method is running.
  2084. ** But once the trigger or virtual table method ends, the value returned
  2085. ** by this routine reverts to what it was before the trigger or virtual
  2086. ** table method began.)^
  2087. **
  2088. ** ^An [INSERT] that fails due to a constraint violation is not a
  2089. ** successful [INSERT] and does not change the value returned by this
  2090. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2091. ** and INSERT OR ABORT make no changes to the return value of this
  2092. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2093. ** encounters a constraint violation, it does not fail. The
  2094. ** INSERT continues to completion after deleting rows that caused
  2095. ** the constraint problem so INSERT OR REPLACE will always change
  2096. ** the return value of this interface.)^
  2097. **
  2098. ** ^For the purposes of this routine, an [INSERT] is considered to
  2099. ** be successful even if it is subsequently rolled back.
  2100. **
  2101. ** This function is accessible to SQL statements via the
  2102. ** [last_insert_rowid() SQL function].
  2103. **
  2104. ** If a separate thread performs a new [INSERT] on the same
  2105. ** database connection while the [sqlite3_last_insert_rowid()]
  2106. ** function is running and thus changes the last insert [rowid],
  2107. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2108. ** unpredictable and might not equal either the old or the new
  2109. ** last insert [rowid].
  2110. */
  2111. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
  2112. /*
  2113. ** CAPI3REF: Count The Number Of Rows Modified
  2114. ** METHOD: sqlite3
  2115. **
  2116. ** ^This function returns the number of rows modified, inserted or
  2117. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2118. ** statement on the database connection specified by the only parameter.
  2119. ** ^Executing any other type of SQL statement does not modify the value
  2120. ** returned by this function.
  2121. **
  2122. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2123. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2124. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2125. **
  2126. ** Changes to a view that are intercepted by
  2127. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2128. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2129. ** DELETE statement run on a view is always zero. Only changes made to real
  2130. ** tables are counted.
  2131. **
  2132. ** Things are more complicated if the sqlite3_changes() function is
  2133. ** executed while a trigger program is running. This may happen if the
  2134. ** program uses the [changes() SQL function], or if some other callback
  2135. ** function invokes sqlite3_changes() directly. Essentially:
  2136. **
  2137. ** <ul>
  2138. ** <li> ^(Before entering a trigger program the value returned by
  2139. ** sqlite3_changes() function is saved. After the trigger program
  2140. ** has finished, the original value is restored.)^
  2141. **
  2142. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2143. ** statement sets the value returned by sqlite3_changes()
  2144. ** upon completion as normal. Of course, this value will not include
  2145. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2146. ** value will be saved and restored after each sub-trigger has run.)^
  2147. ** </ul>
  2148. **
  2149. ** ^This means that if the changes() SQL function (or similar) is used
  2150. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2151. ** returns the value as set when the calling statement began executing.
  2152. ** ^If it is used by the second or subsequent such statement within a trigger
  2153. ** program, the value returned reflects the number of rows modified by the
  2154. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2155. **
  2156. ** See also the [sqlite3_total_changes()] interface, the
  2157. ** [count_changes pragma], and the [changes() SQL function].
  2158. **
  2159. ** If a separate thread makes changes on the same database connection
  2160. ** while [sqlite3_changes()] is running then the value returned
  2161. ** is unpredictable and not meaningful.
  2162. */
  2163. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
  2164. /*
  2165. ** CAPI3REF: Total Number Of Rows Modified
  2166. ** METHOD: sqlite3
  2167. **
  2168. ** ^This function returns the total number of rows inserted, modified or
  2169. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2170. ** since the database connection was opened, including those executed as
  2171. ** part of trigger programs. ^Executing any other type of SQL statement
  2172. ** does not affect the value returned by sqlite3_total_changes().
  2173. **
  2174. ** ^Changes made as part of [foreign key actions] are included in the
  2175. ** count, but those made as part of REPLACE constraint resolution are
  2176. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2177. ** are not counted.
  2178. **
  2179. ** See also the [sqlite3_changes()] interface, the
  2180. ** [count_changes pragma], and the [total_changes() SQL function].
  2181. **
  2182. ** If a separate thread makes changes on the same database connection
  2183. ** while [sqlite3_total_changes()] is running then the value
  2184. ** returned is unpredictable and not meaningful.
  2185. */
  2186. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
  2187. /*
  2188. ** CAPI3REF: Interrupt A Long-Running Query
  2189. ** METHOD: sqlite3
  2190. **
  2191. ** ^This function causes any pending database operation to abort and
  2192. ** return at its earliest opportunity. This routine is typically
  2193. ** called in response to a user action such as pressing "Cancel"
  2194. ** or Ctrl-C where the user wants a long query operation to halt
  2195. ** immediately.
  2196. **
  2197. ** ^It is safe to call this routine from a thread different from the
  2198. ** thread that is currently running the database operation. But it
  2199. ** is not safe to call this routine with a [database connection] that
  2200. ** is closed or might close before sqlite3_interrupt() returns.
  2201. **
  2202. ** ^If an SQL operation is very nearly finished at the time when
  2203. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2204. ** to be interrupted and might continue to completion.
  2205. **
  2206. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2207. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2208. ** that is inside an explicit transaction, then the entire transaction
  2209. ** will be rolled back automatically.
  2210. **
  2211. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2212. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2213. ** that are started after the sqlite3_interrupt() call and before the
  2214. ** running statements reaches zero are interrupted as if they had been
  2215. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2216. ** that are started after the running statement count reaches zero are
  2217. ** not effected by the sqlite3_interrupt().
  2218. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2219. ** SQL statements is a no-op and has no effect on SQL statements
  2220. ** that are started after the sqlite3_interrupt() call returns.
  2221. **
  2222. ** If the database connection closes while [sqlite3_interrupt()]
  2223. ** is running then bad things will likely happen.
  2224. */
  2225. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
  2226. /*
  2227. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2228. **
  2229. ** These routines are useful during command-line input to determine if the
  2230. ** currently entered text seems to form a complete SQL statement or
  2231. ** if additional input is needed before sending the text into
  2232. ** SQLite for parsing. ^These routines return 1 if the input string
  2233. ** appears to be a complete SQL statement. ^A statement is judged to be
  2234. ** complete if it ends with a semicolon token and is not a prefix of a
  2235. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2236. ** string literals or quoted identifier names or comments are not
  2237. ** independent tokens (they are part of the token in which they are
  2238. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2239. ** and comments that follow the final semicolon are ignored.
  2240. **
  2241. ** ^These routines return 0 if the statement is incomplete. ^If a
  2242. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2243. **
  2244. ** ^These routines do not parse the SQL statements thus
  2245. ** will not detect syntactically incorrect SQL.
  2246. **
  2247. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2248. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2249. ** automatically by sqlite3_complete16(). If that initialization fails,
  2250. ** then the return value from sqlite3_complete16() will be non-zero
  2251. ** regardless of whether or not the input SQL is complete.)^
  2252. **
  2253. ** The input to [sqlite3_complete()] must be a zero-terminated
  2254. ** UTF-8 string.
  2255. **
  2256. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2257. ** UTF-16 string in native byte order.
  2258. */
  2259. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
  2260. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
  2261. /*
  2262. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2263. ** KEYWORDS: {busy-handler callback} {busy handler}
  2264. ** METHOD: sqlite3
  2265. **
  2266. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2267. ** that might be invoked with argument P whenever
  2268. ** an attempt is made to access a database table associated with
  2269. ** [database connection] D when another thread
  2270. ** or process has the table locked.
  2271. ** The sqlite3_busy_handler() interface is used to implement
  2272. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2273. **
  2274. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2275. ** is returned immediately upon encountering the lock. ^If the busy callback
  2276. ** is not NULL, then the callback might be invoked with two arguments.
  2277. **
  2278. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2279. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2280. ** the busy handler callback is the number of times that the busy handler has
  2281. ** been invoked previously for the same locking event. ^If the
  2282. ** busy callback returns 0, then no additional attempts are made to
  2283. ** access the database and [SQLITE_BUSY] is returned
  2284. ** to the application.
  2285. ** ^If the callback returns non-zero, then another attempt
  2286. ** is made to access the database and the cycle repeats.
  2287. **
  2288. ** The presence of a busy handler does not guarantee that it will be invoked
  2289. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2290. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2291. ** to the application instead of invoking the
  2292. ** busy handler.
  2293. ** Consider a scenario where one process is holding a read lock that
  2294. ** it is trying to promote to a reserved lock and
  2295. ** a second process is holding a reserved lock that it is trying
  2296. ** to promote to an exclusive lock. The first process cannot proceed
  2297. ** because it is blocked by the second and the second process cannot
  2298. ** proceed because it is blocked by the first. If both processes
  2299. ** invoke the busy handlers, neither will make any progress. Therefore,
  2300. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2301. ** will induce the first process to release its read lock and allow
  2302. ** the second process to proceed.
  2303. **
  2304. ** ^The default busy callback is NULL.
  2305. **
  2306. ** ^(There can only be a single busy handler defined for each
  2307. ** [database connection]. Setting a new busy handler clears any
  2308. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2309. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2310. ** busy handler and thus clear any previously set busy handler.
  2311. **
  2312. ** The busy callback should not take any actions which modify the
  2313. ** database connection that invoked the busy handler. In other words,
  2314. ** the busy handler is not reentrant. Any such actions
  2315. ** result in undefined behavior.
  2316. **
  2317. ** A busy handler must not close the database connection
  2318. ** or [prepared statement] that invoked the busy handler.
  2319. */
  2320. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2321. /*
  2322. ** CAPI3REF: Set A Busy Timeout
  2323. ** METHOD: sqlite3
  2324. **
  2325. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2326. ** for a specified amount of time when a table is locked. ^The handler
  2327. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2328. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2329. ** the handler returns 0 which causes [sqlite3_step()] to return
  2330. ** [SQLITE_BUSY].
  2331. **
  2332. ** ^Calling this routine with an argument less than or equal to zero
  2333. ** turns off all busy handlers.
  2334. **
  2335. ** ^(There can only be a single busy handler for a particular
  2336. ** [database connection] at any given moment. If another busy handler
  2337. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2338. ** this routine, that other busy handler is cleared.)^
  2339. **
  2340. ** See also: [PRAGMA busy_timeout]
  2341. */
  2342. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
  2343. /*
  2344. ** CAPI3REF: Convenience Routines For Running Queries
  2345. ** METHOD: sqlite3
  2346. **
  2347. ** This is a legacy interface that is preserved for backwards compatibility.
  2348. ** Use of this interface is not recommended.
  2349. **
  2350. ** Definition: A <b>result table</b> is memory data structure created by the
  2351. ** [sqlite3_get_table()] interface. A result table records the
  2352. ** complete query results from one or more queries.
  2353. **
  2354. ** The table conceptually has a number of rows and columns. But
  2355. ** these numbers are not part of the result table itself. These
  2356. ** numbers are obtained separately. Let N be the number of rows
  2357. ** and M be the number of columns.
  2358. **
  2359. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2360. ** There are (N+1)*M elements in the array. The first M pointers point
  2361. ** to zero-terminated strings that contain the names of the columns.
  2362. ** The remaining entries all point to query results. NULL values result
  2363. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2364. ** string representation as returned by [sqlite3_column_text()].
  2365. **
  2366. ** A result table might consist of one or more memory allocations.
  2367. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2368. ** A result table should be deallocated using [sqlite3_free_table()].
  2369. **
  2370. ** ^(As an example of the result table format, suppose a query result
  2371. ** is as follows:
  2372. **
  2373. ** <blockquote><pre>
  2374. ** Name | Age
  2375. ** -----------------------
  2376. ** Alice | 43
  2377. ** Bob | 28
  2378. ** Cindy | 21
  2379. ** </pre></blockquote>
  2380. **
  2381. ** There are two column (M==2) and three rows (N==3). Thus the
  2382. ** result table has 8 entries. Suppose the result table is stored
  2383. ** in an array names azResult. Then azResult holds this content:
  2384. **
  2385. ** <blockquote><pre>
  2386. ** azResult&#91;0] = "Name";
  2387. ** azResult&#91;1] = "Age";
  2388. ** azResult&#91;2] = "Alice";
  2389. ** azResult&#91;3] = "43";
  2390. ** azResult&#91;4] = "Bob";
  2391. ** azResult&#91;5] = "28";
  2392. ** azResult&#91;6] = "Cindy";
  2393. ** azResult&#91;7] = "21";
  2394. ** </pre></blockquote>)^
  2395. **
  2396. ** ^The sqlite3_get_table() function evaluates one or more
  2397. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2398. ** string of its 2nd parameter and returns a result table to the
  2399. ** pointer given in its 3rd parameter.
  2400. **
  2401. ** After the application has finished with the result from sqlite3_get_table(),
  2402. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2403. ** release the memory that was malloced. Because of the way the
  2404. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2405. ** function must not try to call [sqlite3_free()] directly. Only
  2406. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2407. **
  2408. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2409. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2410. ** to any internal data structures of SQLite. It uses only the public
  2411. ** interface defined here. As a consequence, errors that occur in the
  2412. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2413. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2414. ** [sqlite3_errmsg()].
  2415. */
  2416. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  2417. sqlite3 *db, /* An open database */
  2418. const char *zSql, /* SQL to be evaluated */
  2419. char ***pazResult, /* Results of the query */
  2420. int *pnRow, /* Number of result rows written here */
  2421. int *pnColumn, /* Number of result columns written here */
  2422. char **pzErrmsg /* Error msg written here */
  2423. );
  2424. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
  2425. /*
  2426. ** CAPI3REF: Formatted String Printing Functions
  2427. **
  2428. ** These routines are work-alikes of the "printf()" family of functions
  2429. ** from the standard C library.
  2430. ** These routines understand most of the common K&R formatting options,
  2431. ** plus some additional non-standard formats, detailed below.
  2432. ** Note that some of the more obscure formatting options from recent
  2433. ** C-library standards are omitted from this implementation.
  2434. **
  2435. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2436. ** results into memory obtained from [sqlite3_malloc()].
  2437. ** The strings returned by these two routines should be
  2438. ** released by [sqlite3_free()]. ^Both routines return a
  2439. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2440. ** memory to hold the resulting string.
  2441. **
  2442. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2443. ** the standard C library. The result is written into the
  2444. ** buffer supplied as the second parameter whose size is given by
  2445. ** the first parameter. Note that the order of the
  2446. ** first two parameters is reversed from snprintf().)^ This is an
  2447. ** historical accident that cannot be fixed without breaking
  2448. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2449. ** returns a pointer to its buffer instead of the number of
  2450. ** characters actually written into the buffer.)^ We admit that
  2451. ** the number of characters written would be a more useful return
  2452. ** value but we cannot change the implementation of sqlite3_snprintf()
  2453. ** now without breaking compatibility.
  2454. **
  2455. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2456. ** guarantees that the buffer is always zero-terminated. ^The first
  2457. ** parameter "n" is the total size of the buffer, including space for
  2458. ** the zero terminator. So the longest string that can be completely
  2459. ** written will be n-1 characters.
  2460. **
  2461. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2462. **
  2463. ** These routines all implement some additional formatting
  2464. ** options that are useful for constructing SQL statements.
  2465. ** All of the usual printf() formatting options apply. In addition, there
  2466. ** is are "%q", "%Q", "%w" and "%z" options.
  2467. **
  2468. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2469. ** string from the argument list. But %q also doubles every '\'' character.
  2470. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2471. ** character it escapes that character and allows it to be inserted into
  2472. ** the string.
  2473. **
  2474. ** For example, assume the string variable zText contains text as follows:
  2475. **
  2476. ** <blockquote><pre>
  2477. ** char *zText = "It's a happy day!";
  2478. ** </pre></blockquote>
  2479. **
  2480. ** One can use this text in an SQL statement as follows:
  2481. **
  2482. ** <blockquote><pre>
  2483. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2484. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2485. ** sqlite3_free(zSQL);
  2486. ** </pre></blockquote>
  2487. **
  2488. ** Because the %q format string is used, the '\'' character in zText
  2489. ** is escaped and the SQL generated is as follows:
  2490. **
  2491. ** <blockquote><pre>
  2492. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2493. ** </pre></blockquote>
  2494. **
  2495. ** This is correct. Had we used %s instead of %q, the generated SQL
  2496. ** would have looked like this:
  2497. **
  2498. ** <blockquote><pre>
  2499. ** INSERT INTO table1 VALUES('It's a happy day!');
  2500. ** </pre></blockquote>
  2501. **
  2502. ** This second example is an SQL syntax error. As a general rule you should
  2503. ** always use %q instead of %s when inserting text into a string literal.
  2504. **
  2505. ** ^(The %Q option works like %q except it also adds single quotes around
  2506. ** the outside of the total string. Additionally, if the parameter in the
  2507. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2508. ** single quotes).)^ So, for example, one could say:
  2509. **
  2510. ** <blockquote><pre>
  2511. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2512. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2513. ** sqlite3_free(zSQL);
  2514. ** </pre></blockquote>
  2515. **
  2516. ** The code above will render a correct SQL statement in the zSQL
  2517. ** variable even if the zText variable is a NULL pointer.
  2518. **
  2519. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2520. ** be contained within double-quotes instead of single quotes, and it
  2521. ** escapes the double-quote character instead of the single-quote
  2522. ** character.)^ The "%w" formatting option is intended for safely inserting
  2523. ** table and column names into a constructed SQL statement.
  2524. **
  2525. ** ^(The "%z" formatting option works like "%s" but with the
  2526. ** addition that after the string has been read and copied into
  2527. ** the result, [sqlite3_free()] is called on the input string.)^
  2528. */
  2529. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
  2530. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
  2531. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
  2532. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
  2533. /*
  2534. ** CAPI3REF: Memory Allocation Subsystem
  2535. **
  2536. ** The SQLite core uses these three routines for all of its own
  2537. ** internal memory allocation needs. "Core" in the previous sentence
  2538. ** does not include operating-system specific VFS implementation. The
  2539. ** Windows VFS uses native malloc() and free() for some operations.
  2540. **
  2541. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2542. ** of memory at least N bytes in length, where N is the parameter.
  2543. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2544. ** memory, it returns a NULL pointer. ^If the parameter N to
  2545. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2546. ** a NULL pointer.
  2547. **
  2548. ** ^The sqlite3_malloc64(N) routine works just like
  2549. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2550. ** of a signed 32-bit integer.
  2551. **
  2552. ** ^Calling sqlite3_free() with a pointer previously returned
  2553. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2554. ** that it might be reused. ^The sqlite3_free() routine is
  2555. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2556. ** to sqlite3_free() is harmless. After being freed, memory
  2557. ** should neither be read nor written. Even reading previously freed
  2558. ** memory might result in a segmentation fault or other severe error.
  2559. ** Memory corruption, a segmentation fault, or other severe error
  2560. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2561. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2562. **
  2563. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2564. ** prior memory allocation X to be at least N bytes.
  2565. ** ^If the X parameter to sqlite3_realloc(X,N)
  2566. ** is a NULL pointer then its behavior is identical to calling
  2567. ** sqlite3_malloc(N).
  2568. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2569. ** negative then the behavior is exactly the same as calling
  2570. ** sqlite3_free(X).
  2571. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2572. ** of at least N bytes in size or NULL if insufficient memory is available.
  2573. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2574. ** of the prior allocation are copied into the beginning of buffer returned
  2575. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2576. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2577. ** prior allocation is not freed.
  2578. **
  2579. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2580. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2581. ** of a 32-bit signed integer.
  2582. **
  2583. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2584. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2585. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2586. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2587. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2588. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2589. ** the beginning of memory allocation, or if it points to a formerly
  2590. ** valid memory allocation that has now been freed, then the behavior
  2591. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2592. **
  2593. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2594. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2595. ** is always aligned to at least an 8 byte boundary, or to a
  2596. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2597. ** option is used.
  2598. **
  2599. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2600. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2601. ** implementation of these routines to be omitted. That capability
  2602. ** is no longer provided. Only built-in memory allocators can be used.
  2603. **
  2604. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2605. ** the system malloc() and free() directly when converting
  2606. ** filenames between the UTF-8 encoding used by SQLite
  2607. ** and whatever filename encoding is used by the particular Windows
  2608. ** installation. Memory allocation errors were detected, but
  2609. ** they were reported back as [SQLITE_CANTOPEN] or
  2610. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2611. **
  2612. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2613. ** must be either NULL or else pointers obtained from a prior
  2614. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2615. ** not yet been released.
  2616. **
  2617. ** The application must not read or write any part of
  2618. ** a block of memory after it has been released using
  2619. ** [sqlite3_free()] or [sqlite3_realloc()].
  2620. */
  2621. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
  2622. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
  2623. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
  2624. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
  2625. SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
  2626. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
  2627. /*
  2628. ** CAPI3REF: Memory Allocator Statistics
  2629. **
  2630. ** SQLite provides these two interfaces for reporting on the status
  2631. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2632. ** routines, which form the built-in memory allocation subsystem.
  2633. **
  2634. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2635. ** of memory currently outstanding (malloced but not freed).
  2636. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2637. ** value of [sqlite3_memory_used()] since the high-water mark
  2638. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2639. ** [sqlite3_memory_highwater()] include any overhead
  2640. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2641. ** but not overhead added by the any underlying system library
  2642. ** routines that [sqlite3_malloc()] may call.
  2643. **
  2644. ** ^The memory high-water mark is reset to the current value of
  2645. ** [sqlite3_memory_used()] if and only if the parameter to
  2646. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2647. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2648. ** prior to the reset.
  2649. */
  2650. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
  2651. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
  2652. /*
  2653. ** CAPI3REF: Pseudo-Random Number Generator
  2654. **
  2655. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2656. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2657. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2658. ** the build-in random() and randomblob() SQL functions. This interface allows
  2659. ** applications to access the same PRNG for other purposes.
  2660. **
  2661. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2662. ** ^The P parameter can be a NULL pointer.
  2663. **
  2664. ** ^If this routine has not been previously called or if the previous
  2665. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2666. ** seeded using randomness obtained from the xRandomness method of
  2667. ** the default [sqlite3_vfs] object.
  2668. ** ^If the previous call to this routine had an N of 1 or more and a
  2669. ** non-NULL P then the pseudo-randomness is generated
  2670. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2671. ** method.
  2672. */
  2673. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
  2674. /*
  2675. ** CAPI3REF: Compile-Time Authorization Callbacks
  2676. ** METHOD: sqlite3
  2677. **
  2678. ** ^This routine registers an authorizer callback with a particular
  2679. ** [database connection], supplied in the first argument.
  2680. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2681. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2682. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2683. ** points during the compilation process, as logic is being created
  2684. ** to perform various actions, the authorizer callback is invoked to
  2685. ** see if those actions are allowed. ^The authorizer callback should
  2686. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2687. ** specific action but allow the SQL statement to continue to be
  2688. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2689. ** rejected with an error. ^If the authorizer callback returns
  2690. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2691. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2692. ** the authorizer will fail with an error message.
  2693. **
  2694. ** When the callback returns [SQLITE_OK], that means the operation
  2695. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2696. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2697. ** authorizer will fail with an error message explaining that
  2698. ** access is denied.
  2699. **
  2700. ** ^The first parameter to the authorizer callback is a copy of the third
  2701. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2702. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2703. ** the particular action to be authorized. ^The third through sixth parameters
  2704. ** to the callback are zero-terminated strings that contain additional
  2705. ** details about the action to be authorized.
  2706. **
  2707. ** ^If the action code is [SQLITE_READ]
  2708. ** and the callback returns [SQLITE_IGNORE] then the
  2709. ** [prepared statement] statement is constructed to substitute
  2710. ** a NULL value in place of the table column that would have
  2711. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2712. ** return can be used to deny an untrusted user access to individual
  2713. ** columns of a table.
  2714. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2715. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2716. ** [truncate optimization] is disabled and all rows are deleted individually.
  2717. **
  2718. ** An authorizer is used when [sqlite3_prepare | preparing]
  2719. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2720. ** do not try to access data they are not allowed to see, or that they do not
  2721. ** try to execute malicious statements that damage the database. For
  2722. ** example, an application may allow a user to enter arbitrary
  2723. ** SQL queries for evaluation by a database. But the application does
  2724. ** not want the user to be able to make arbitrary changes to the
  2725. ** database. An authorizer could then be put in place while the
  2726. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2727. ** disallows everything except [SELECT] statements.
  2728. **
  2729. ** Applications that need to process SQL from untrusted sources
  2730. ** might also consider lowering resource limits using [sqlite3_limit()]
  2731. ** and limiting database size using the [max_page_count] [PRAGMA]
  2732. ** in addition to using an authorizer.
  2733. **
  2734. ** ^(Only a single authorizer can be in place on a database connection
  2735. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2736. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2737. ** The authorizer is disabled by default.
  2738. **
  2739. ** The authorizer callback must not do anything that will modify
  2740. ** the database connection that invoked the authorizer callback.
  2741. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2742. ** database connections for the meaning of "modify" in this paragraph.
  2743. **
  2744. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2745. ** statement might be re-prepared during [sqlite3_step()] due to a
  2746. ** schema change. Hence, the application should ensure that the
  2747. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2748. **
  2749. ** ^Note that the authorizer callback is invoked only during
  2750. ** [sqlite3_prepare()] or its variants. Authorization is not
  2751. ** performed during statement evaluation in [sqlite3_step()], unless
  2752. ** as stated in the previous paragraph, sqlite3_step() invokes
  2753. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2754. */
  2755. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  2756. sqlite3*,
  2757. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2758. void *pUserData
  2759. );
  2760. /*
  2761. ** CAPI3REF: Authorizer Return Codes
  2762. **
  2763. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2764. ** return either [SQLITE_OK] or one of these two constants in order
  2765. ** to signal SQLite whether or not the action is permitted. See the
  2766. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2767. ** information.
  2768. **
  2769. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2770. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2771. */
  2772. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2773. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2774. /*
  2775. ** CAPI3REF: Authorizer Action Codes
  2776. **
  2777. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2778. ** that is invoked to authorize certain SQL statement actions. The
  2779. ** second parameter to the callback is an integer code that specifies
  2780. ** what action is being authorized. These are the integer action codes that
  2781. ** the authorizer callback may be passed.
  2782. **
  2783. ** These action code values signify what kind of operation is to be
  2784. ** authorized. The 3rd and 4th parameters to the authorization
  2785. ** callback function will be parameters or NULL depending on which of these
  2786. ** codes is used as the second parameter. ^(The 5th parameter to the
  2787. ** authorizer callback is the name of the database ("main", "temp",
  2788. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2789. ** is the name of the inner-most trigger or view that is responsible for
  2790. ** the access attempt or NULL if this access attempt is directly from
  2791. ** top-level SQL code.
  2792. */
  2793. /******************************************* 3rd ************ 4th ***********/
  2794. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2795. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2796. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2797. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2798. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2799. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2800. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2801. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2802. #define SQLITE_DELETE 9 /* Table Name NULL */
  2803. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2804. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2805. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2806. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2807. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2808. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2809. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2810. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2811. #define SQLITE_INSERT 18 /* Table Name NULL */
  2812. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2813. #define SQLITE_READ 20 /* Table Name Column Name */
  2814. #define SQLITE_SELECT 21 /* NULL NULL */
  2815. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2816. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2817. #define SQLITE_ATTACH 24 /* Filename NULL */
  2818. #define SQLITE_DETACH 25 /* Database Name NULL */
  2819. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2820. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2821. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2822. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2823. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2824. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2825. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2826. #define SQLITE_COPY 0 /* No longer used */
  2827. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2828. /*
  2829. ** CAPI3REF: Tracing And Profiling Functions
  2830. ** METHOD: sqlite3
  2831. **
  2832. ** These routines register callback functions that can be used for
  2833. ** tracing and profiling the execution of SQL statements.
  2834. **
  2835. ** ^The callback function registered by sqlite3_trace() is invoked at
  2836. ** various times when an SQL statement is being run by [sqlite3_step()].
  2837. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2838. ** SQL statement text as the statement first begins executing.
  2839. ** ^(Additional sqlite3_trace() callbacks might occur
  2840. ** as each triggered subprogram is entered. The callbacks for triggers
  2841. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2842. **
  2843. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2844. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2845. **
  2846. ** ^The callback function registered by sqlite3_profile() is invoked
  2847. ** as each SQL statement finishes. ^The profile callback contains
  2848. ** the original statement text and an estimate of wall-clock time
  2849. ** of how long that statement took to run. ^The profile callback
  2850. ** time is in units of nanoseconds, however the current implementation
  2851. ** is only capable of millisecond resolution so the six least significant
  2852. ** digits in the time are meaningless. Future versions of SQLite
  2853. ** might provide greater resolution on the profiler callback. The
  2854. ** sqlite3_profile() function is considered experimental and is
  2855. ** subject to change in future versions of SQLite.
  2856. */
  2857. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2858. SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
  2859. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2860. /*
  2861. ** CAPI3REF: Query Progress Callbacks
  2862. ** METHOD: sqlite3
  2863. **
  2864. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2865. ** function X to be invoked periodically during long running calls to
  2866. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2867. ** database connection D. An example use for this
  2868. ** interface is to keep a GUI updated during a large query.
  2869. **
  2870. ** ^The parameter P is passed through as the only parameter to the
  2871. ** callback function X. ^The parameter N is the approximate number of
  2872. ** [virtual machine instructions] that are evaluated between successive
  2873. ** invocations of the callback X. ^If N is less than one then the progress
  2874. ** handler is disabled.
  2875. **
  2876. ** ^Only a single progress handler may be defined at one time per
  2877. ** [database connection]; setting a new progress handler cancels the
  2878. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2879. ** ^The progress handler is also disabled by setting N to a value less
  2880. ** than 1.
  2881. **
  2882. ** ^If the progress callback returns non-zero, the operation is
  2883. ** interrupted. This feature can be used to implement a
  2884. ** "Cancel" button on a GUI progress dialog box.
  2885. **
  2886. ** The progress handler callback must not do anything that will modify
  2887. ** the database connection that invoked the progress handler.
  2888. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2889. ** database connections for the meaning of "modify" in this paragraph.
  2890. **
  2891. */
  2892. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2893. /*
  2894. ** CAPI3REF: Opening A New Database Connection
  2895. ** CONSTRUCTOR: sqlite3
  2896. **
  2897. ** ^These routines open an SQLite database file as specified by the
  2898. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2899. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2900. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2901. ** returned in *ppDb, even if an error occurs. The only exception is that
  2902. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2903. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2904. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2905. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2906. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2907. ** an English language description of the error following a failure of any
  2908. ** of the sqlite3_open() routines.
  2909. **
  2910. ** ^The default encoding will be UTF-8 for databases created using
  2911. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2912. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2913. **
  2914. ** Whether or not an error occurs when it is opened, resources
  2915. ** associated with the [database connection] handle should be released by
  2916. ** passing it to [sqlite3_close()] when it is no longer required.
  2917. **
  2918. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2919. ** except that it accepts two additional parameters for additional control
  2920. ** over the new database connection. ^(The flags parameter to
  2921. ** sqlite3_open_v2() can take one of
  2922. ** the following three values, optionally combined with the
  2923. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2924. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2925. **
  2926. ** <dl>
  2927. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2928. ** <dd>The database is opened in read-only mode. If the database does not
  2929. ** already exist, an error is returned.</dd>)^
  2930. **
  2931. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2932. ** <dd>The database is opened for reading and writing if possible, or reading
  2933. ** only if the file is write protected by the operating system. In either
  2934. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2935. **
  2936. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2937. ** <dd>The database is opened for reading and writing, and is created if
  2938. ** it does not already exist. This is the behavior that is always used for
  2939. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2940. ** </dl>
  2941. **
  2942. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2943. ** combinations shown above optionally combined with other
  2944. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2945. ** then the behavior is undefined.
  2946. **
  2947. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2948. ** opens in the multi-thread [threading mode] as long as the single-thread
  2949. ** mode has not been set at compile-time or start-time. ^If the
  2950. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2951. ** in the serialized [threading mode] unless single-thread was
  2952. ** previously selected at compile-time or start-time.
  2953. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2954. ** eligible to use [shared cache mode], regardless of whether or not shared
  2955. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2956. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2957. ** participate in [shared cache mode] even if it is enabled.
  2958. **
  2959. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2960. ** [sqlite3_vfs] object that defines the operating system interface that
  2961. ** the new database connection should use. ^If the fourth parameter is
  2962. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2963. **
  2964. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2965. ** is created for the connection. ^This in-memory database will vanish when
  2966. ** the database connection is closed. Future versions of SQLite might
  2967. ** make use of additional special filenames that begin with the ":" character.
  2968. ** It is recommended that when a database filename actually does begin with
  2969. ** a ":" character you should prefix the filename with a pathname such as
  2970. ** "./" to avoid ambiguity.
  2971. **
  2972. ** ^If the filename is an empty string, then a private, temporary
  2973. ** on-disk database will be created. ^This private database will be
  2974. ** automatically deleted as soon as the database connection is closed.
  2975. **
  2976. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2977. **
  2978. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2979. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2980. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2981. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2982. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2983. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2984. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2985. ** by default, but future releases of SQLite might enable URI filename
  2986. ** interpretation by default. See "[URI filenames]" for additional
  2987. ** information.
  2988. **
  2989. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2990. ** authority, then it must be either an empty string or the string
  2991. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2992. ** error is returned to the caller. ^The fragment component of a URI, if
  2993. ** present, is ignored.
  2994. **
  2995. ** ^SQLite uses the path component of the URI as the name of the disk file
  2996. ** which contains the database. ^If the path begins with a '/' character,
  2997. ** then it is interpreted as an absolute path. ^If the path does not begin
  2998. ** with a '/' (meaning that the authority section is omitted from the URI)
  2999. ** then the path is interpreted as a relative path.
  3000. ** ^(On windows, the first component of an absolute path
  3001. ** is a drive specification (e.g. "C:").)^
  3002. **
  3003. ** [[core URI query parameters]]
  3004. ** The query component of a URI may contain parameters that are interpreted
  3005. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3006. ** SQLite and its built-in [VFSes] interpret the
  3007. ** following query parameters:
  3008. **
  3009. ** <ul>
  3010. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3011. ** a VFS object that provides the operating system interface that should
  3012. ** be used to access the database file on disk. ^If this option is set to
  3013. ** an empty string the default VFS object is used. ^Specifying an unknown
  3014. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3015. ** present, then the VFS specified by the option takes precedence over
  3016. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3017. **
  3018. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3019. ** "rwc", or "memory". Attempting to set it to any other value is
  3020. ** an error)^.
  3021. ** ^If "ro" is specified, then the database is opened for read-only
  3022. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3023. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3024. ** "rw", then the database is opened for read-write (but not create)
  3025. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3026. ** been set. ^Value "rwc" is equivalent to setting both
  3027. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3028. ** set to "memory" then a pure [in-memory database] that never reads
  3029. ** or writes from disk is used. ^It is an error to specify a value for
  3030. ** the mode parameter that is less restrictive than that specified by
  3031. ** the flags passed in the third parameter to sqlite3_open_v2().
  3032. **
  3033. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3034. ** "private". ^Setting it to "shared" is equivalent to setting the
  3035. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3036. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3037. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3038. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3039. ** a URI filename, its value overrides any behavior requested by setting
  3040. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3041. **
  3042. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3043. ** [powersafe overwrite] property does or does not apply to the
  3044. ** storage media on which the database file resides.
  3045. **
  3046. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3047. ** which if set disables file locking in rollback journal modes. This
  3048. ** is useful for accessing a database on a filesystem that does not
  3049. ** support locking. Caution: Database corruption might result if two
  3050. ** or more processes write to the same database and any one of those
  3051. ** processes uses nolock=1.
  3052. **
  3053. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3054. ** parameter that indicates that the database file is stored on
  3055. ** read-only media. ^When immutable is set, SQLite assumes that the
  3056. ** database file cannot be changed, even by a process with higher
  3057. ** privilege, and so the database is opened read-only and all locking
  3058. ** and change detection is disabled. Caution: Setting the immutable
  3059. ** property on a database file that does in fact change can result
  3060. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3061. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3062. **
  3063. ** </ul>
  3064. **
  3065. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3066. ** error. Future versions of SQLite might understand additional query
  3067. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3068. ** additional information.
  3069. **
  3070. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3071. **
  3072. ** <table border="1" align=center cellpadding=5>
  3073. ** <tr><th> URI filenames <th> Results
  3074. ** <tr><td> file:data.db <td>
  3075. ** Open the file "data.db" in the current directory.
  3076. ** <tr><td> file:/home/fred/data.db<br>
  3077. ** file:///home/fred/data.db <br>
  3078. ** file://localhost/home/fred/data.db <br> <td>
  3079. ** Open the database file "/home/fred/data.db".
  3080. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3081. ** An error. "darkstar" is not a recognized authority.
  3082. ** <tr><td style="white-space:nowrap">
  3083. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3084. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3085. ** C:. Note that the %20 escaping in this example is not strictly
  3086. ** necessary - space characters can be used literally
  3087. ** in URI filenames.
  3088. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3089. ** Open file "data.db" in the current directory for read-only access.
  3090. ** Regardless of whether or not shared-cache mode is enabled by
  3091. ** default, use a private cache.
  3092. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3093. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3094. ** that uses dot-files in place of posix advisory locking.
  3095. ** <tr><td> file:data.db?mode=readonly <td>
  3096. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3097. ** </table>
  3098. **
  3099. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3100. ** query components of a URI. A hexadecimal escape sequence consists of a
  3101. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3102. ** specifying an octet value. ^Before the path or query components of a
  3103. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3104. ** hexadecimal escape sequences replaced by a single byte containing the
  3105. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3106. ** the results are undefined.
  3107. **
  3108. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3109. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3110. ** codepage is currently defined. Filenames containing international
  3111. ** characters must be converted to UTF-8 prior to passing them into
  3112. ** sqlite3_open() or sqlite3_open_v2().
  3113. **
  3114. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3115. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3116. ** features that require the use of temporary files may fail.
  3117. **
  3118. ** See also: [sqlite3_temp_directory]
  3119. */
  3120. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  3121. const char *filename, /* Database filename (UTF-8) */
  3122. sqlite3 **ppDb /* OUT: SQLite db handle */
  3123. );
  3124. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  3125. const void *filename, /* Database filename (UTF-16) */
  3126. sqlite3 **ppDb /* OUT: SQLite db handle */
  3127. );
  3128. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  3129. const char *filename, /* Database filename (UTF-8) */
  3130. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3131. int flags, /* Flags */
  3132. const char *zVfs /* Name of VFS module to use */
  3133. );
  3134. /*
  3135. ** CAPI3REF: Obtain Values For URI Parameters
  3136. **
  3137. ** These are utility routines, useful to VFS implementations, that check
  3138. ** to see if a database file was a URI that contained a specific query
  3139. ** parameter, and if so obtains the value of that query parameter.
  3140. **
  3141. ** If F is the database filename pointer passed into the xOpen() method of
  3142. ** a VFS implementation when the flags parameter to xOpen() has one or
  3143. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3144. ** P is the name of the query parameter, then
  3145. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3146. ** parameter if it exists or a NULL pointer if P does not appear as a
  3147. ** query parameter on F. If P is a query parameter of F
  3148. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3149. ** a pointer to an empty string.
  3150. **
  3151. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3152. ** parameter and returns true (1) or false (0) according to the value
  3153. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3154. ** value of query parameter P is one of "yes", "true", or "on" in any
  3155. ** case or if the value begins with a non-zero number. The
  3156. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3157. ** query parameter P is one of "no", "false", or "off" in any case or
  3158. ** if the value begins with a numeric zero. If P is not a query
  3159. ** parameter on F or if the value of P is does not match any of the
  3160. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3161. **
  3162. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3163. ** 64-bit signed integer and returns that integer, or D if P does not
  3164. ** exist. If the value of P is something other than an integer, then
  3165. ** zero is returned.
  3166. **
  3167. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3168. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3169. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3170. ** VFS method, then the behavior of this routine is undefined and probably
  3171. ** undesirable.
  3172. */
  3173. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3174. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3175. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3176. /*
  3177. ** CAPI3REF: Error Codes And Messages
  3178. ** METHOD: sqlite3
  3179. **
  3180. ** ^If the most recent sqlite3_* API call associated with
  3181. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3182. ** returns the numeric [result code] or [extended result code] for that
  3183. ** API call.
  3184. ** If the most recent API call was successful,
  3185. ** then the return value from sqlite3_errcode() is undefined.
  3186. ** ^The sqlite3_extended_errcode()
  3187. ** interface is the same except that it always returns the
  3188. ** [extended result code] even when extended result codes are
  3189. ** disabled.
  3190. **
  3191. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3192. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3193. ** ^(Memory to hold the error message string is managed internally.
  3194. ** The application does not need to worry about freeing the result.
  3195. ** However, the error string might be overwritten or deallocated by
  3196. ** subsequent calls to other SQLite interface functions.)^
  3197. **
  3198. ** ^The sqlite3_errstr() interface returns the English-language text
  3199. ** that describes the [result code], as UTF-8.
  3200. ** ^(Memory to hold the error message string is managed internally
  3201. ** and must not be freed by the application)^.
  3202. **
  3203. ** When the serialized [threading mode] is in use, it might be the
  3204. ** case that a second error occurs on a separate thread in between
  3205. ** the time of the first error and the call to these interfaces.
  3206. ** When that happens, the second error will be reported since these
  3207. ** interfaces always report the most recent result. To avoid
  3208. ** this, each thread can obtain exclusive use of the [database connection] D
  3209. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3210. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3211. ** all calls to the interfaces listed here are completed.
  3212. **
  3213. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3214. ** was invoked incorrectly by the application. In that case, the
  3215. ** error code and message may or may not be set.
  3216. */
  3217. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
  3218. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
  3219. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
  3220. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
  3221. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
  3222. /*
  3223. ** CAPI3REF: Prepared Statement Object
  3224. ** KEYWORDS: {prepared statement} {prepared statements}
  3225. **
  3226. ** An instance of this object represents a single SQL statement that
  3227. ** has been compiled into binary form and is ready to be evaluated.
  3228. **
  3229. ** Think of each SQL statement as a separate computer program. The
  3230. ** original SQL text is source code. A prepared statement object
  3231. ** is the compiled object code. All SQL must be converted into a
  3232. ** prepared statement before it can be run.
  3233. **
  3234. ** The life-cycle of a prepared statement object usually goes like this:
  3235. **
  3236. ** <ol>
  3237. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3238. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3239. ** interfaces.
  3240. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3241. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3242. ** to step 2. Do this zero or more times.
  3243. ** <li> Destroy the object using [sqlite3_finalize()].
  3244. ** </ol>
  3245. */
  3246. typedef struct sqlite3_stmt sqlite3_stmt;
  3247. /*
  3248. ** CAPI3REF: Run-time Limits
  3249. ** METHOD: sqlite3
  3250. **
  3251. ** ^(This interface allows the size of various constructs to be limited
  3252. ** on a connection by connection basis. The first parameter is the
  3253. ** [database connection] whose limit is to be set or queried. The
  3254. ** second parameter is one of the [limit categories] that define a
  3255. ** class of constructs to be size limited. The third parameter is the
  3256. ** new limit for that construct.)^
  3257. **
  3258. ** ^If the new limit is a negative number, the limit is unchanged.
  3259. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3260. ** [limits | hard upper bound]
  3261. ** set at compile-time by a C preprocessor macro called
  3262. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3263. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3264. ** ^Attempts to increase a limit above its hard upper bound are
  3265. ** silently truncated to the hard upper bound.
  3266. **
  3267. ** ^Regardless of whether or not the limit was changed, the
  3268. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3269. ** ^Hence, to find the current value of a limit without changing it,
  3270. ** simply invoke this interface with the third parameter set to -1.
  3271. **
  3272. ** Run-time limits are intended for use in applications that manage
  3273. ** both their own internal database and also databases that are controlled
  3274. ** by untrusted external sources. An example application might be a
  3275. ** web browser that has its own databases for storing history and
  3276. ** separate databases controlled by JavaScript applications downloaded
  3277. ** off the Internet. The internal databases can be given the
  3278. ** large, default limits. Databases managed by external sources can
  3279. ** be given much smaller limits designed to prevent a denial of service
  3280. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3281. ** interface to further control untrusted SQL. The size of the database
  3282. ** created by an untrusted script can be contained using the
  3283. ** [max_page_count] [PRAGMA].
  3284. **
  3285. ** New run-time limit categories may be added in future releases.
  3286. */
  3287. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
  3288. /*
  3289. ** CAPI3REF: Run-Time Limit Categories
  3290. ** KEYWORDS: {limit category} {*limit categories}
  3291. **
  3292. ** These constants define various performance limits
  3293. ** that can be lowered at run-time using [sqlite3_limit()].
  3294. ** The synopsis of the meanings of the various limits is shown below.
  3295. ** Additional information is available at [limits | Limits in SQLite].
  3296. **
  3297. ** <dl>
  3298. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3299. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3300. **
  3301. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3302. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3303. **
  3304. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3305. ** <dd>The maximum number of columns in a table definition or in the
  3306. ** result set of a [SELECT] or the maximum number of columns in an index
  3307. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3308. **
  3309. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3310. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3311. **
  3312. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3313. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3314. **
  3315. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3316. ** <dd>The maximum number of instructions in a virtual machine program
  3317. ** used to implement an SQL statement. This limit is not currently
  3318. ** enforced, though that might be added in some future release of
  3319. ** SQLite.</dd>)^
  3320. **
  3321. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3322. ** <dd>The maximum number of arguments on a function.</dd>)^
  3323. **
  3324. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3325. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3326. **
  3327. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3328. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3329. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3330. ** [GLOB] operators.</dd>)^
  3331. **
  3332. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3333. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3334. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3335. **
  3336. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3337. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3338. **
  3339. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3340. ** <dd>The maximum number of auxiliary worker threads that a single
  3341. ** [prepared statement] may start.</dd>)^
  3342. ** </dl>
  3343. */
  3344. #define SQLITE_LIMIT_LENGTH 0
  3345. #define SQLITE_LIMIT_SQL_LENGTH 1
  3346. #define SQLITE_LIMIT_COLUMN 2
  3347. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3348. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3349. #define SQLITE_LIMIT_VDBE_OP 5
  3350. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3351. #define SQLITE_LIMIT_ATTACHED 7
  3352. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3353. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3354. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3355. #define SQLITE_LIMIT_WORKER_THREADS 11
  3356. /*
  3357. ** CAPI3REF: Compiling An SQL Statement
  3358. ** KEYWORDS: {SQL statement compiler}
  3359. ** METHOD: sqlite3
  3360. ** CONSTRUCTOR: sqlite3_stmt
  3361. **
  3362. ** To execute an SQL query, it must first be compiled into a byte-code
  3363. ** program using one of these routines.
  3364. **
  3365. ** The first argument, "db", is a [database connection] obtained from a
  3366. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3367. ** [sqlite3_open16()]. The database connection must not have been closed.
  3368. **
  3369. ** The second argument, "zSql", is the statement to be compiled, encoded
  3370. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3371. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3372. ** use UTF-16.
  3373. **
  3374. ** ^If the nByte argument is negative, then zSql is read up to the
  3375. ** first zero terminator. ^If nByte is positive, then it is the
  3376. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3377. ** statement is generated.
  3378. ** If the caller knows that the supplied string is nul-terminated, then
  3379. ** there is a small performance advantage to passing an nByte parameter that
  3380. ** is the number of bytes in the input string <i>including</i>
  3381. ** the nul-terminator.
  3382. **
  3383. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3384. ** past the end of the first SQL statement in zSql. These routines only
  3385. ** compile the first statement in zSql, so *pzTail is left pointing to
  3386. ** what remains uncompiled.
  3387. **
  3388. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3389. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3390. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3391. ** string or a comment) then *ppStmt is set to NULL.
  3392. ** The calling procedure is responsible for deleting the compiled
  3393. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3394. ** ppStmt may not be NULL.
  3395. **
  3396. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3397. ** otherwise an [error code] is returned.
  3398. **
  3399. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3400. ** recommended for all new programs. The two older interfaces are retained
  3401. ** for backwards compatibility, but their use is discouraged.
  3402. ** ^In the "v2" interfaces, the prepared statement
  3403. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3404. ** original SQL text. This causes the [sqlite3_step()] interface to
  3405. ** behave differently in three ways:
  3406. **
  3407. ** <ol>
  3408. ** <li>
  3409. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3410. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3411. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3412. ** retries will occur before sqlite3_step() gives up and returns an error.
  3413. ** </li>
  3414. **
  3415. ** <li>
  3416. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3417. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3418. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3419. ** and the application would have to make a second call to [sqlite3_reset()]
  3420. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3421. ** interfaces, the underlying reason for the error is returned immediately.
  3422. ** </li>
  3423. **
  3424. ** <li>
  3425. ** ^If the specific value bound to [parameter | host parameter] in the
  3426. ** WHERE clause might influence the choice of query plan for a statement,
  3427. ** then the statement will be automatically recompiled, as if there had been
  3428. ** a schema change, on the first [sqlite3_step()] call following any change
  3429. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3430. ** ^The specific value of WHERE-clause [parameter] might influence the
  3431. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3432. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3433. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3434. ** </li>
  3435. ** </ol>
  3436. */
  3437. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  3438. sqlite3 *db, /* Database handle */
  3439. const char *zSql, /* SQL statement, UTF-8 encoded */
  3440. int nByte, /* Maximum length of zSql in bytes. */
  3441. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3442. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3443. );
  3444. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  3445. sqlite3 *db, /* Database handle */
  3446. const char *zSql, /* SQL statement, UTF-8 encoded */
  3447. int nByte, /* Maximum length of zSql in bytes. */
  3448. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3449. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3450. );
  3451. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  3452. sqlite3 *db, /* Database handle */
  3453. const void *zSql, /* SQL statement, UTF-16 encoded */
  3454. int nByte, /* Maximum length of zSql in bytes. */
  3455. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3456. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3457. );
  3458. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  3459. sqlite3 *db, /* Database handle */
  3460. const void *zSql, /* SQL statement, UTF-16 encoded */
  3461. int nByte, /* Maximum length of zSql in bytes. */
  3462. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3463. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3464. );
  3465. /*
  3466. ** CAPI3REF: Retrieving Statement SQL
  3467. ** METHOD: sqlite3_stmt
  3468. **
  3469. ** ^This interface can be used to retrieve a saved copy of the original
  3470. ** SQL text used to create a [prepared statement] if that statement was
  3471. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3472. */
  3473. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
  3474. /*
  3475. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3476. ** METHOD: sqlite3_stmt
  3477. **
  3478. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3479. ** and only if the [prepared statement] X makes no direct changes to
  3480. ** the content of the database file.
  3481. **
  3482. ** Note that [application-defined SQL functions] or
  3483. ** [virtual tables] might change the database indirectly as a side effect.
  3484. ** ^(For example, if an application defines a function "eval()" that
  3485. ** calls [sqlite3_exec()], then the following SQL statement would
  3486. ** change the database file through side-effects:
  3487. **
  3488. ** <blockquote><pre>
  3489. ** SELECT eval('DELETE FROM t1') FROM t2;
  3490. ** </pre></blockquote>
  3491. **
  3492. ** But because the [SELECT] statement does not change the database file
  3493. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3494. **
  3495. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3496. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3497. ** since the statements themselves do not actually modify the database but
  3498. ** rather they control the timing of when other statements modify the
  3499. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3500. ** sqlite3_stmt_readonly() to return true since, while those statements
  3501. ** change the configuration of a database connection, they do not make
  3502. ** changes to the content of the database files on disk.
  3503. */
  3504. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3505. /*
  3506. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3507. ** METHOD: sqlite3_stmt
  3508. **
  3509. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3510. ** [prepared statement] S has been stepped at least once using
  3511. ** [sqlite3_step(S)] but has neither run to completion (returned
  3512. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  3513. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3514. ** interface returns false if S is a NULL pointer. If S is not a
  3515. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3516. ** object, then the behavior is undefined and probably undesirable.
  3517. **
  3518. ** This interface can be used in combination [sqlite3_next_stmt()]
  3519. ** to locate all prepared statements associated with a database
  3520. ** connection that are in need of being reset. This can be used,
  3521. ** for example, in diagnostic routines to search for prepared
  3522. ** statements that are holding a transaction open.
  3523. */
  3524. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
  3525. /*
  3526. ** CAPI3REF: Dynamically Typed Value Object
  3527. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3528. **
  3529. ** SQLite uses the sqlite3_value object to represent all values
  3530. ** that can be stored in a database table. SQLite uses dynamic typing
  3531. ** for the values it stores. ^Values stored in sqlite3_value objects
  3532. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3533. **
  3534. ** An sqlite3_value object may be either "protected" or "unprotected".
  3535. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3536. ** will accept either a protected or an unprotected sqlite3_value.
  3537. ** Every interface that accepts sqlite3_value arguments specifies
  3538. ** whether or not it requires a protected sqlite3_value. The
  3539. ** [sqlite3_value_dup()] interface can be used to construct a new
  3540. ** protected sqlite3_value from an unprotected sqlite3_value.
  3541. **
  3542. ** The terms "protected" and "unprotected" refer to whether or not
  3543. ** a mutex is held. An internal mutex is held for a protected
  3544. ** sqlite3_value object but no mutex is held for an unprotected
  3545. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3546. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3547. ** or if SQLite is run in one of reduced mutex modes
  3548. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3549. ** then there is no distinction between protected and unprotected
  3550. ** sqlite3_value objects and they can be used interchangeably. However,
  3551. ** for maximum code portability it is recommended that applications
  3552. ** still make the distinction between protected and unprotected
  3553. ** sqlite3_value objects even when not strictly required.
  3554. **
  3555. ** ^The sqlite3_value objects that are passed as parameters into the
  3556. ** implementation of [application-defined SQL functions] are protected.
  3557. ** ^The sqlite3_value object returned by
  3558. ** [sqlite3_column_value()] is unprotected.
  3559. ** Unprotected sqlite3_value objects may only be used with
  3560. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3561. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3562. ** interfaces require protected sqlite3_value objects.
  3563. */
  3564. typedef struct Mem sqlite3_value;
  3565. /*
  3566. ** CAPI3REF: SQL Function Context Object
  3567. **
  3568. ** The context in which an SQL function executes is stored in an
  3569. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3570. ** is always first parameter to [application-defined SQL functions].
  3571. ** The application-defined SQL function implementation will pass this
  3572. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3573. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3574. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3575. ** and/or [sqlite3_set_auxdata()].
  3576. */
  3577. typedef struct sqlite3_context sqlite3_context;
  3578. /*
  3579. ** CAPI3REF: Binding Values To Prepared Statements
  3580. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3581. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3582. ** METHOD: sqlite3_stmt
  3583. **
  3584. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3585. ** literals may be replaced by a [parameter] that matches one of following
  3586. ** templates:
  3587. **
  3588. ** <ul>
  3589. ** <li> ?
  3590. ** <li> ?NNN
  3591. ** <li> :VVV
  3592. ** <li> @VVV
  3593. ** <li> $VVV
  3594. ** </ul>
  3595. **
  3596. ** In the templates above, NNN represents an integer literal,
  3597. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3598. ** parameters (also called "host parameter names" or "SQL parameters")
  3599. ** can be set using the sqlite3_bind_*() routines defined here.
  3600. **
  3601. ** ^The first argument to the sqlite3_bind_*() routines is always
  3602. ** a pointer to the [sqlite3_stmt] object returned from
  3603. ** [sqlite3_prepare_v2()] or its variants.
  3604. **
  3605. ** ^The second argument is the index of the SQL parameter to be set.
  3606. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3607. ** SQL parameter is used more than once, second and subsequent
  3608. ** occurrences have the same index as the first occurrence.
  3609. ** ^The index for named parameters can be looked up using the
  3610. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3611. ** for "?NNN" parameters is the value of NNN.
  3612. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3613. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3614. **
  3615. ** ^The third argument is the value to bind to the parameter.
  3616. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3617. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3618. ** is ignored and the end result is the same as sqlite3_bind_null().
  3619. **
  3620. ** ^(In those routines that have a fourth argument, its value is the
  3621. ** number of bytes in the parameter. To be clear: the value is the
  3622. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3623. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3624. ** is negative, then the length of the string is
  3625. ** the number of bytes up to the first zero terminator.
  3626. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3627. ** the behavior is undefined.
  3628. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3629. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3630. ** that parameter must be the byte offset
  3631. ** where the NUL terminator would occur assuming the string were NUL
  3632. ** terminated. If any NUL characters occur at byte offsets less than
  3633. ** the value of the fourth parameter then the resulting string value will
  3634. ** contain embedded NULs. The result of expressions involving strings
  3635. ** with embedded NULs is undefined.
  3636. **
  3637. ** ^The fifth argument to the BLOB and string binding interfaces
  3638. ** is a destructor used to dispose of the BLOB or
  3639. ** string after SQLite has finished with it. ^The destructor is called
  3640. ** to dispose of the BLOB or string even if the call to bind API fails.
  3641. ** ^If the fifth argument is
  3642. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3643. ** information is in static, unmanaged space and does not need to be freed.
  3644. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3645. ** SQLite makes its own private copy of the data immediately, before
  3646. ** the sqlite3_bind_*() routine returns.
  3647. **
  3648. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3649. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3650. ** to specify the encoding of the text in the third parameter. If
  3651. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3652. ** allowed values shown above, or if the text encoding is different
  3653. ** from the encoding specified by the sixth parameter, then the behavior
  3654. ** is undefined.
  3655. **
  3656. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3657. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3658. ** (just an integer to hold its size) while it is being processed.
  3659. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3660. ** content is later written using
  3661. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3662. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3663. **
  3664. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3665. ** for the [prepared statement] or with a prepared statement for which
  3666. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3667. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3668. ** routine is passed a [prepared statement] that has been finalized, the
  3669. ** result is undefined and probably harmful.
  3670. **
  3671. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3672. ** ^Unbound parameters are interpreted as NULL.
  3673. **
  3674. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3675. ** [error code] if anything goes wrong.
  3676. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3677. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3678. ** [SQLITE_MAX_LENGTH].
  3679. ** ^[SQLITE_RANGE] is returned if the parameter
  3680. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3681. **
  3682. ** See also: [sqlite3_bind_parameter_count()],
  3683. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3684. */
  3685. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3686. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3687. void(*)(void*));
  3688. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
  3689. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
  3690. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3691. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
  3692. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3693. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3694. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3695. void(*)(void*), unsigned char encoding);
  3696. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3697. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3698. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  3699. /*
  3700. ** CAPI3REF: Number Of SQL Parameters
  3701. ** METHOD: sqlite3_stmt
  3702. **
  3703. ** ^This routine can be used to find the number of [SQL parameters]
  3704. ** in a [prepared statement]. SQL parameters are tokens of the
  3705. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3706. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3707. ** to the parameters at a later time.
  3708. **
  3709. ** ^(This routine actually returns the index of the largest (rightmost)
  3710. ** parameter. For all forms except ?NNN, this will correspond to the
  3711. ** number of unique parameters. If parameters of the ?NNN form are used,
  3712. ** there may be gaps in the list.)^
  3713. **
  3714. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3715. ** [sqlite3_bind_parameter_name()], and
  3716. ** [sqlite3_bind_parameter_index()].
  3717. */
  3718. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
  3719. /*
  3720. ** CAPI3REF: Name Of A Host Parameter
  3721. ** METHOD: sqlite3_stmt
  3722. **
  3723. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3724. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3725. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3726. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3727. ** respectively.
  3728. ** In other words, the initial ":" or "$" or "@" or "?"
  3729. ** is included as part of the name.)^
  3730. ** ^Parameters of the form "?" without a following integer have no name
  3731. ** and are referred to as "nameless" or "anonymous parameters".
  3732. **
  3733. ** ^The first host parameter has an index of 1, not 0.
  3734. **
  3735. ** ^If the value N is out of range or if the N-th parameter is
  3736. ** nameless, then NULL is returned. ^The returned string is
  3737. ** always in UTF-8 encoding even if the named parameter was
  3738. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3739. ** [sqlite3_prepare16_v2()].
  3740. **
  3741. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3742. ** [sqlite3_bind_parameter_count()], and
  3743. ** [sqlite3_bind_parameter_index()].
  3744. */
  3745. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3746. /*
  3747. ** CAPI3REF: Index Of A Parameter With A Given Name
  3748. ** METHOD: sqlite3_stmt
  3749. **
  3750. ** ^Return the index of an SQL parameter given its name. ^The
  3751. ** index value returned is suitable for use as the second
  3752. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3753. ** is returned if no matching parameter is found. ^The parameter
  3754. ** name must be given in UTF-8 even if the original statement
  3755. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3756. **
  3757. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3758. ** [sqlite3_bind_parameter_count()], and
  3759. ** [sqlite3_bind_parameter_name()].
  3760. */
  3761. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3762. /*
  3763. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3764. ** METHOD: sqlite3_stmt
  3765. **
  3766. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3767. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3768. ** ^Use this routine to reset all host parameters to NULL.
  3769. */
  3770. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
  3771. /*
  3772. ** CAPI3REF: Number Of Columns In A Result Set
  3773. ** METHOD: sqlite3_stmt
  3774. **
  3775. ** ^Return the number of columns in the result set returned by the
  3776. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3777. ** statement that does not return data (for example an [UPDATE]).
  3778. **
  3779. ** See also: [sqlite3_data_count()]
  3780. */
  3781. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
  3782. /*
  3783. ** CAPI3REF: Column Names In A Result Set
  3784. ** METHOD: sqlite3_stmt
  3785. **
  3786. ** ^These routines return the name assigned to a particular column
  3787. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3788. ** interface returns a pointer to a zero-terminated UTF-8 string
  3789. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3790. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3791. ** that implements the [SELECT] statement. ^The second parameter is the
  3792. ** column number. ^The leftmost column is number 0.
  3793. **
  3794. ** ^The returned string pointer is valid until either the [prepared statement]
  3795. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3796. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3797. ** or until the next call to
  3798. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3799. **
  3800. ** ^If sqlite3_malloc() fails during the processing of either routine
  3801. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3802. ** NULL pointer is returned.
  3803. **
  3804. ** ^The name of a result column is the value of the "AS" clause for
  3805. ** that column, if there is an AS clause. If there is no AS clause
  3806. ** then the name of the column is unspecified and may change from
  3807. ** one release of SQLite to the next.
  3808. */
  3809. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
  3810. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
  3811. /*
  3812. ** CAPI3REF: Source Of Data In A Query Result
  3813. ** METHOD: sqlite3_stmt
  3814. **
  3815. ** ^These routines provide a means to determine the database, table, and
  3816. ** table column that is the origin of a particular result column in
  3817. ** [SELECT] statement.
  3818. ** ^The name of the database or table or column can be returned as
  3819. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3820. ** the database name, the _table_ routines return the table name, and
  3821. ** the origin_ routines return the column name.
  3822. ** ^The returned string is valid until the [prepared statement] is destroyed
  3823. ** using [sqlite3_finalize()] or until the statement is automatically
  3824. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3825. ** or until the same information is requested
  3826. ** again in a different encoding.
  3827. **
  3828. ** ^The names returned are the original un-aliased names of the
  3829. ** database, table, and column.
  3830. **
  3831. ** ^The first argument to these interfaces is a [prepared statement].
  3832. ** ^These functions return information about the Nth result column returned by
  3833. ** the statement, where N is the second function argument.
  3834. ** ^The left-most column is column 0 for these routines.
  3835. **
  3836. ** ^If the Nth column returned by the statement is an expression or
  3837. ** subquery and is not a column value, then all of these functions return
  3838. ** NULL. ^These routine might also return NULL if a memory allocation error
  3839. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3840. ** or column that query result column was extracted from.
  3841. **
  3842. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3843. ** UTF-16 encoded strings and the other functions return UTF-8.
  3844. **
  3845. ** ^These APIs are only available if the library was compiled with the
  3846. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3847. **
  3848. ** If two or more threads call one or more of these routines against the same
  3849. ** prepared statement and column at the same time then the results are
  3850. ** undefined.
  3851. **
  3852. ** If two or more threads call one or more
  3853. ** [sqlite3_column_database_name | column metadata interfaces]
  3854. ** for the same [prepared statement] and result column
  3855. ** at the same time then the results are undefined.
  3856. */
  3857. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
  3858. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
  3859. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
  3860. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
  3861. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
  3862. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3863. /*
  3864. ** CAPI3REF: Declared Datatype Of A Query Result
  3865. ** METHOD: sqlite3_stmt
  3866. **
  3867. ** ^(The first parameter is a [prepared statement].
  3868. ** If this statement is a [SELECT] statement and the Nth column of the
  3869. ** returned result set of that [SELECT] is a table column (not an
  3870. ** expression or subquery) then the declared type of the table
  3871. ** column is returned.)^ ^If the Nth column of the result set is an
  3872. ** expression or subquery, then a NULL pointer is returned.
  3873. ** ^The returned string is always UTF-8 encoded.
  3874. **
  3875. ** ^(For example, given the database schema:
  3876. **
  3877. ** CREATE TABLE t1(c1 VARIANT);
  3878. **
  3879. ** and the following statement to be compiled:
  3880. **
  3881. ** SELECT c1 + 1, c1 FROM t1;
  3882. **
  3883. ** this routine would return the string "VARIANT" for the second result
  3884. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3885. **
  3886. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3887. ** is declared to contain a particular type does not mean that the
  3888. ** data stored in that column is of the declared type. SQLite is
  3889. ** strongly typed, but the typing is dynamic not static. ^Type
  3890. ** is associated with individual values, not with the containers
  3891. ** used to hold those values.
  3892. */
  3893. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
  3894. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
  3895. /*
  3896. ** CAPI3REF: Evaluate An SQL Statement
  3897. ** METHOD: sqlite3_stmt
  3898. **
  3899. ** After a [prepared statement] has been prepared using either
  3900. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3901. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3902. ** must be called one or more times to evaluate the statement.
  3903. **
  3904. ** The details of the behavior of the sqlite3_step() interface depend
  3905. ** on whether the statement was prepared using the newer "v2" interface
  3906. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3907. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3908. ** new "v2" interface is recommended for new applications but the legacy
  3909. ** interface will continue to be supported.
  3910. **
  3911. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3912. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3913. ** ^With the "v2" interface, any of the other [result codes] or
  3914. ** [extended result codes] might be returned as well.
  3915. **
  3916. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3917. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3918. ** or occurs outside of an explicit transaction, then you can retry the
  3919. ** statement. If the statement is not a [COMMIT] and occurs within an
  3920. ** explicit transaction then you should rollback the transaction before
  3921. ** continuing.
  3922. **
  3923. ** ^[SQLITE_DONE] means that the statement has finished executing
  3924. ** successfully. sqlite3_step() should not be called again on this virtual
  3925. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3926. ** machine back to its initial state.
  3927. **
  3928. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3929. ** is returned each time a new row of data is ready for processing by the
  3930. ** caller. The values may be accessed using the [column access functions].
  3931. ** sqlite3_step() is called again to retrieve the next row of data.
  3932. **
  3933. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3934. ** violation) has occurred. sqlite3_step() should not be called again on
  3935. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3936. ** ^With the legacy interface, a more specific error code (for example,
  3937. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3938. ** can be obtained by calling [sqlite3_reset()] on the
  3939. ** [prepared statement]. ^In the "v2" interface,
  3940. ** the more specific error code is returned directly by sqlite3_step().
  3941. **
  3942. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3943. ** Perhaps it was called on a [prepared statement] that has
  3944. ** already been [sqlite3_finalize | finalized] or on one that had
  3945. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3946. ** be the case that the same database connection is being used by two or
  3947. ** more threads at the same moment in time.
  3948. **
  3949. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3950. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3951. ** other than [SQLITE_ROW] before any subsequent invocation of
  3952. ** sqlite3_step(). Failure to reset the prepared statement using
  3953. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3954. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3955. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3956. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3957. ** break because any application that ever receives an SQLITE_MISUSE error
  3958. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3959. ** can be used to restore the legacy behavior.
  3960. **
  3961. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3962. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3963. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3964. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3965. ** specific [error codes] that better describes the error.
  3966. ** We admit that this is a goofy design. The problem has been fixed
  3967. ** with the "v2" interface. If you prepare all of your SQL statements
  3968. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3969. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3970. ** then the more specific [error codes] are returned directly
  3971. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3972. */
  3973. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
  3974. /*
  3975. ** CAPI3REF: Number of columns in a result set
  3976. ** METHOD: sqlite3_stmt
  3977. **
  3978. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3979. ** current row of the result set of [prepared statement] P.
  3980. ** ^If prepared statement P does not have results ready to return
  3981. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3982. ** interfaces) then sqlite3_data_count(P) returns 0.
  3983. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3984. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3985. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3986. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3987. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3988. ** where it always returns zero since each step of that multi-step
  3989. ** pragma returns 0 columns of data.
  3990. **
  3991. ** See also: [sqlite3_column_count()]
  3992. */
  3993. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
  3994. /*
  3995. ** CAPI3REF: Fundamental Datatypes
  3996. ** KEYWORDS: SQLITE_TEXT
  3997. **
  3998. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3999. **
  4000. ** <ul>
  4001. ** <li> 64-bit signed integer
  4002. ** <li> 64-bit IEEE floating point number
  4003. ** <li> string
  4004. ** <li> BLOB
  4005. ** <li> NULL
  4006. ** </ul>)^
  4007. **
  4008. ** These constants are codes for each of those types.
  4009. **
  4010. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4011. ** for a completely different meaning. Software that links against both
  4012. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4013. ** SQLITE_TEXT.
  4014. */
  4015. #define SQLITE_INTEGER 1
  4016. #define SQLITE_FLOAT 2
  4017. #define SQLITE_BLOB 4
  4018. #define SQLITE_NULL 5
  4019. #ifdef SQLITE_TEXT
  4020. # undef SQLITE_TEXT
  4021. #else
  4022. # define SQLITE_TEXT 3
  4023. #endif
  4024. #define SQLITE3_TEXT 3
  4025. /*
  4026. ** CAPI3REF: Result Values From A Query
  4027. ** KEYWORDS: {column access functions}
  4028. ** METHOD: sqlite3_stmt
  4029. **
  4030. ** ^These routines return information about a single column of the current
  4031. ** result row of a query. ^In every case the first argument is a pointer
  4032. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4033. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4034. ** and the second argument is the index of the column for which information
  4035. ** should be returned. ^The leftmost column of the result set has the index 0.
  4036. ** ^The number of columns in the result can be determined using
  4037. ** [sqlite3_column_count()].
  4038. **
  4039. ** If the SQL statement does not currently point to a valid row, or if the
  4040. ** column index is out of range, the result is undefined.
  4041. ** These routines may only be called when the most recent call to
  4042. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4043. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4044. ** If any of these routines are called after [sqlite3_reset()] or
  4045. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4046. ** something other than [SQLITE_ROW], the results are undefined.
  4047. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4048. ** are called from a different thread while any of these routines
  4049. ** are pending, then the results are undefined.
  4050. **
  4051. ** ^The sqlite3_column_type() routine returns the
  4052. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4053. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4054. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4055. ** returned by sqlite3_column_type() is only meaningful if no type
  4056. ** conversions have occurred as described below. After a type conversion,
  4057. ** the value returned by sqlite3_column_type() is undefined. Future
  4058. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4059. ** following a type conversion.
  4060. **
  4061. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4062. ** routine returns the number of bytes in that BLOB or string.
  4063. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4064. ** the string to UTF-8 and then returns the number of bytes.
  4065. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4066. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4067. ** the number of bytes in that string.
  4068. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4069. **
  4070. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4071. ** routine returns the number of bytes in that BLOB or string.
  4072. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4073. ** the string to UTF-16 and then returns the number of bytes.
  4074. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4075. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4076. ** the number of bytes in that string.
  4077. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4078. **
  4079. ** ^The values returned by [sqlite3_column_bytes()] and
  4080. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4081. ** of the string. ^For clarity: the values returned by
  4082. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4083. ** bytes in the string, not the number of characters.
  4084. **
  4085. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4086. ** even empty strings, are always zero-terminated. ^The return
  4087. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4088. **
  4089. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4090. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4091. ** an unprotected sqlite3_value object may only be used safely with
  4092. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4093. ** If the [unprotected sqlite3_value] object returned by
  4094. ** [sqlite3_column_value()] is used in any other way, including calls
  4095. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4096. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4097. **
  4098. ** These routines attempt to convert the value where appropriate. ^For
  4099. ** example, if the internal representation is FLOAT and a text result
  4100. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4101. ** conversion automatically. ^(The following table details the conversions
  4102. ** that are applied:
  4103. **
  4104. ** <blockquote>
  4105. ** <table border="1">
  4106. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4107. **
  4108. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4109. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4110. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4111. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4112. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4113. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4114. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4115. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4116. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4117. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4118. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4119. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4120. ** <tr><td> TEXT <td> BLOB <td> No change
  4121. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4122. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4123. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4124. ** </table>
  4125. ** </blockquote>)^
  4126. **
  4127. ** Note that when type conversions occur, pointers returned by prior
  4128. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4129. ** sqlite3_column_text16() may be invalidated.
  4130. ** Type conversions and pointer invalidations might occur
  4131. ** in the following cases:
  4132. **
  4133. ** <ul>
  4134. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4135. ** sqlite3_column_text16() is called. A zero-terminator might
  4136. ** need to be added to the string.</li>
  4137. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4138. ** sqlite3_column_text16() is called. The content must be converted
  4139. ** to UTF-16.</li>
  4140. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4141. ** sqlite3_column_text() is called. The content must be converted
  4142. ** to UTF-8.</li>
  4143. ** </ul>
  4144. **
  4145. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4146. ** not invalidate a prior pointer, though of course the content of the buffer
  4147. ** that the prior pointer references will have been modified. Other kinds
  4148. ** of conversion are done in place when it is possible, but sometimes they
  4149. ** are not possible and in those cases prior pointers are invalidated.
  4150. **
  4151. ** The safest policy is to invoke these routines
  4152. ** in one of the following ways:
  4153. **
  4154. ** <ul>
  4155. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4156. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4157. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4158. ** </ul>
  4159. **
  4160. ** In other words, you should call sqlite3_column_text(),
  4161. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4162. ** into the desired format, then invoke sqlite3_column_bytes() or
  4163. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4164. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4165. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4166. ** with calls to sqlite3_column_bytes().
  4167. **
  4168. ** ^The pointers returned are valid until a type conversion occurs as
  4169. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4170. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4171. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4172. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4173. ** [sqlite3_free()].
  4174. **
  4175. ** ^(If a memory allocation error occurs during the evaluation of any
  4176. ** of these routines, a default value is returned. The default value
  4177. ** is either the integer 0, the floating point number 0.0, or a NULL
  4178. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4179. ** [SQLITE_NOMEM].)^
  4180. */
  4181. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4182. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4183. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4184. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
  4185. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
  4186. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4187. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
  4188. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4189. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
  4190. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
  4191. /*
  4192. ** CAPI3REF: Destroy A Prepared Statement Object
  4193. ** DESTRUCTOR: sqlite3_stmt
  4194. **
  4195. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4196. ** ^If the most recent evaluation of the statement encountered no errors
  4197. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4198. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4199. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4200. ** [extended error code].
  4201. **
  4202. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4203. ** the life cycle of [prepared statement] S:
  4204. ** before statement S is ever evaluated, after
  4205. ** one or more calls to [sqlite3_reset()], or after any call
  4206. ** to [sqlite3_step()] regardless of whether or not the statement has
  4207. ** completed execution.
  4208. **
  4209. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4210. **
  4211. ** The application must finalize every [prepared statement] in order to avoid
  4212. ** resource leaks. It is a grievous error for the application to try to use
  4213. ** a prepared statement after it has been finalized. Any use of a prepared
  4214. ** statement after it has been finalized can result in undefined and
  4215. ** undesirable behavior such as segfaults and heap corruption.
  4216. */
  4217. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
  4218. /*
  4219. ** CAPI3REF: Reset A Prepared Statement Object
  4220. ** METHOD: sqlite3_stmt
  4221. **
  4222. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4223. ** object back to its initial state, ready to be re-executed.
  4224. ** ^Any SQL statement variables that had values bound to them using
  4225. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4226. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4227. **
  4228. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4229. ** back to the beginning of its program.
  4230. **
  4231. ** ^If the most recent call to [sqlite3_step(S)] for the
  4232. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4233. ** or if [sqlite3_step(S)] has never before been called on S,
  4234. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4235. **
  4236. ** ^If the most recent call to [sqlite3_step(S)] for the
  4237. ** [prepared statement] S indicated an error, then
  4238. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4239. **
  4240. ** ^The [sqlite3_reset(S)] interface does not change the values
  4241. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4242. */
  4243. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
  4244. /*
  4245. ** CAPI3REF: Create Or Redefine SQL Functions
  4246. ** KEYWORDS: {function creation routines}
  4247. ** KEYWORDS: {application-defined SQL function}
  4248. ** KEYWORDS: {application-defined SQL functions}
  4249. ** METHOD: sqlite3
  4250. **
  4251. ** ^These functions (collectively known as "function creation routines")
  4252. ** are used to add SQL functions or aggregates or to redefine the behavior
  4253. ** of existing SQL functions or aggregates. The only differences between
  4254. ** these routines are the text encoding expected for
  4255. ** the second parameter (the name of the function being created)
  4256. ** and the presence or absence of a destructor callback for
  4257. ** the application data pointer.
  4258. **
  4259. ** ^The first parameter is the [database connection] to which the SQL
  4260. ** function is to be added. ^If an application uses more than one database
  4261. ** connection then application-defined SQL functions must be added
  4262. ** to each database connection separately.
  4263. **
  4264. ** ^The second parameter is the name of the SQL function to be created or
  4265. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4266. ** representation, exclusive of the zero-terminator. ^Note that the name
  4267. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4268. ** ^Any attempt to create a function with a longer name
  4269. ** will result in [SQLITE_MISUSE] being returned.
  4270. **
  4271. ** ^The third parameter (nArg)
  4272. ** is the number of arguments that the SQL function or
  4273. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4274. ** aggregate may take any number of arguments between 0 and the limit
  4275. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4276. ** parameter is less than -1 or greater than 127 then the behavior is
  4277. ** undefined.
  4278. **
  4279. ** ^The fourth parameter, eTextRep, specifies what
  4280. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4281. ** its parameters. The application should set this parameter to
  4282. ** [SQLITE_UTF16LE] if the function implementation invokes
  4283. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4284. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4285. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4286. ** otherwise. ^The same SQL function may be registered multiple times using
  4287. ** different preferred text encodings, with different implementations for
  4288. ** each encoding.
  4289. ** ^When multiple implementations of the same function are available, SQLite
  4290. ** will pick the one that involves the least amount of data conversion.
  4291. **
  4292. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4293. ** to signal that the function will always return the same result given
  4294. ** the same inputs within a single SQL statement. Most SQL functions are
  4295. ** deterministic. The built-in [random()] SQL function is an example of a
  4296. ** function that is not deterministic. The SQLite query planner is able to
  4297. ** perform additional optimizations on deterministic functions, so use
  4298. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4299. **
  4300. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4301. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4302. **
  4303. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4304. ** pointers to C-language functions that implement the SQL function or
  4305. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4306. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4307. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4308. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4309. ** SQL function or aggregate, pass NULL pointers for all three function
  4310. ** callbacks.
  4311. **
  4312. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4313. ** then it is destructor for the application data pointer.
  4314. ** The destructor is invoked when the function is deleted, either by being
  4315. ** overloaded or when the database connection closes.)^
  4316. ** ^The destructor is also invoked if the call to
  4317. ** sqlite3_create_function_v2() fails.
  4318. ** ^When the destructor callback of the tenth parameter is invoked, it
  4319. ** is passed a single argument which is a copy of the application data
  4320. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4321. **
  4322. ** ^It is permitted to register multiple implementations of the same
  4323. ** functions with the same name but with either differing numbers of
  4324. ** arguments or differing preferred text encodings. ^SQLite will use
  4325. ** the implementation that most closely matches the way in which the
  4326. ** SQL function is used. ^A function implementation with a non-negative
  4327. ** nArg parameter is a better match than a function implementation with
  4328. ** a negative nArg. ^A function where the preferred text encoding
  4329. ** matches the database encoding is a better
  4330. ** match than a function where the encoding is different.
  4331. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4332. ** is a closer match than a function where the encoding difference is
  4333. ** between UTF8 and UTF16.
  4334. **
  4335. ** ^Built-in functions may be overloaded by new application-defined functions.
  4336. **
  4337. ** ^An application-defined function is permitted to call other
  4338. ** SQLite interfaces. However, such calls must not
  4339. ** close the database connection nor finalize or reset the prepared
  4340. ** statement in which the function is running.
  4341. */
  4342. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  4343. sqlite3 *db,
  4344. const char *zFunctionName,
  4345. int nArg,
  4346. int eTextRep,
  4347. void *pApp,
  4348. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4349. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4350. void (*xFinal)(sqlite3_context*)
  4351. );
  4352. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  4353. sqlite3 *db,
  4354. const void *zFunctionName,
  4355. int nArg,
  4356. int eTextRep,
  4357. void *pApp,
  4358. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4359. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4360. void (*xFinal)(sqlite3_context*)
  4361. );
  4362. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  4363. sqlite3 *db,
  4364. const char *zFunctionName,
  4365. int nArg,
  4366. int eTextRep,
  4367. void *pApp,
  4368. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4369. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4370. void (*xFinal)(sqlite3_context*),
  4371. void(*xDestroy)(void*)
  4372. );
  4373. /*
  4374. ** CAPI3REF: Text Encodings
  4375. **
  4376. ** These constant define integer codes that represent the various
  4377. ** text encodings supported by SQLite.
  4378. */
  4379. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4380. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4381. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4382. #define SQLITE_UTF16 4 /* Use native byte order */
  4383. #define SQLITE_ANY 5 /* Deprecated */
  4384. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4385. /*
  4386. ** CAPI3REF: Function Flags
  4387. **
  4388. ** These constants may be ORed together with the
  4389. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4390. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4391. ** [sqlite3_create_function_v2()].
  4392. */
  4393. #define SQLITE_DETERMINISTIC 0x800
  4394. /*
  4395. ** CAPI3REF: Deprecated Functions
  4396. ** DEPRECATED
  4397. **
  4398. ** These functions are [deprecated]. In order to maintain
  4399. ** backwards compatibility with older code, these functions continue
  4400. ** to be supported. However, new applications should avoid
  4401. ** the use of these functions. To encourage programmers to avoid
  4402. ** these functions, we will not explain what they do.
  4403. */
  4404. #ifndef SQLITE_OMIT_DEPRECATED
  4405. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
  4406. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
  4407. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4408. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
  4409. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
  4410. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4411. void*,sqlite3_int64);
  4412. #endif
  4413. /*
  4414. ** CAPI3REF: Obtaining SQL Values
  4415. ** METHOD: sqlite3_value
  4416. **
  4417. ** The C-language implementation of SQL functions and aggregates uses
  4418. ** this set of interface routines to access the parameter values on
  4419. ** the function or aggregate.
  4420. **
  4421. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4422. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4423. ** define callbacks that implement the SQL functions and aggregates.
  4424. ** The 3rd parameter to these callbacks is an array of pointers to
  4425. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4426. ** each parameter to the SQL function. These routines are used to
  4427. ** extract values from the [sqlite3_value] objects.
  4428. **
  4429. ** These routines work only with [protected sqlite3_value] objects.
  4430. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4431. ** object results in undefined behavior.
  4432. **
  4433. ** ^These routines work just like the corresponding [column access functions]
  4434. ** except that these routines take a single [protected sqlite3_value] object
  4435. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4436. **
  4437. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4438. ** in the native byte-order of the host machine. ^The
  4439. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4440. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4441. **
  4442. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4443. ** numeric affinity to the value. This means that an attempt is
  4444. ** made to convert the value to an integer or floating point. If
  4445. ** such a conversion is possible without loss of information (in other
  4446. ** words, if the value is a string that looks like a number)
  4447. ** then the conversion is performed. Otherwise no conversion occurs.
  4448. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4449. **
  4450. ** Please pay particular attention to the fact that the pointer returned
  4451. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4452. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4453. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4454. ** or [sqlite3_value_text16()].
  4455. **
  4456. ** These routines must be called from the same thread as
  4457. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4458. */
  4459. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
  4460. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
  4461. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
  4462. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
  4463. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
  4464. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
  4465. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
  4466. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
  4467. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
  4468. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
  4469. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
  4470. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
  4471. /*
  4472. ** CAPI3REF: Finding The Subtype Of SQL Values
  4473. ** METHOD: sqlite3_value
  4474. **
  4475. ** The sqlite3_value_subtype(V) function returns the subtype for
  4476. ** an [application-defined SQL function] argument V. The subtype
  4477. ** information can be used to pass a limited amount of context from
  4478. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  4479. ** routine to set the subtype for the return value of an SQL function.
  4480. **
  4481. ** SQLite makes no use of subtype itself. It merely passes the subtype
  4482. ** from the result of one [application-defined SQL function] into the
  4483. ** input of another.
  4484. */
  4485. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
  4486. /*
  4487. ** CAPI3REF: Copy And Free SQL Values
  4488. ** METHOD: sqlite3_value
  4489. **
  4490. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4491. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4492. ** is a [protected sqlite3_value] object even if the input is not.
  4493. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4494. ** memory allocation fails.
  4495. **
  4496. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4497. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4498. ** then sqlite3_value_free(V) is a harmless no-op.
  4499. */
  4500. SQLITE_API SQLITE_EXPERIMENTAL sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
  4501. SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
  4502. /*
  4503. ** CAPI3REF: Obtain Aggregate Function Context
  4504. ** METHOD: sqlite3_context
  4505. **
  4506. ** Implementations of aggregate SQL functions use this
  4507. ** routine to allocate memory for storing their state.
  4508. **
  4509. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4510. ** for a particular aggregate function, SQLite
  4511. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4512. ** to the new memory. ^On second and subsequent calls to
  4513. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4514. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4515. ** called once for each invocation of the xStep callback and then one
  4516. ** last time when the xFinal callback is invoked. ^(When no rows match
  4517. ** an aggregate query, the xStep() callback of the aggregate function
  4518. ** implementation is never called and xFinal() is called exactly once.
  4519. ** In those cases, sqlite3_aggregate_context() might be called for the
  4520. ** first time from within xFinal().)^
  4521. **
  4522. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4523. ** when first called if N is less than or equal to zero or if a memory
  4524. ** allocate error occurs.
  4525. **
  4526. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4527. ** determined by the N parameter on first successful call. Changing the
  4528. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4529. ** the same aggregate function instance will not resize the memory
  4530. ** allocation.)^ Within the xFinal callback, it is customary to set
  4531. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4532. ** pointless memory allocations occur.
  4533. **
  4534. ** ^SQLite automatically frees the memory allocated by
  4535. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4536. **
  4537. ** The first parameter must be a copy of the
  4538. ** [sqlite3_context | SQL function context] that is the first parameter
  4539. ** to the xStep or xFinal callback routine that implements the aggregate
  4540. ** function.
  4541. **
  4542. ** This routine must be called from the same thread in which
  4543. ** the aggregate SQL function is running.
  4544. */
  4545. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4546. /*
  4547. ** CAPI3REF: User Data For Functions
  4548. ** METHOD: sqlite3_context
  4549. **
  4550. ** ^The sqlite3_user_data() interface returns a copy of
  4551. ** the pointer that was the pUserData parameter (the 5th parameter)
  4552. ** of the [sqlite3_create_function()]
  4553. ** and [sqlite3_create_function16()] routines that originally
  4554. ** registered the application defined function.
  4555. **
  4556. ** This routine must be called from the same thread in which
  4557. ** the application-defined function is running.
  4558. */
  4559. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
  4560. /*
  4561. ** CAPI3REF: Database Connection For Functions
  4562. ** METHOD: sqlite3_context
  4563. **
  4564. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4565. ** the pointer to the [database connection] (the 1st parameter)
  4566. ** of the [sqlite3_create_function()]
  4567. ** and [sqlite3_create_function16()] routines that originally
  4568. ** registered the application defined function.
  4569. */
  4570. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
  4571. /*
  4572. ** CAPI3REF: Function Auxiliary Data
  4573. ** METHOD: sqlite3_context
  4574. **
  4575. ** These functions may be used by (non-aggregate) SQL functions to
  4576. ** associate metadata with argument values. If the same value is passed to
  4577. ** multiple invocations of the same SQL function during query execution, under
  4578. ** some circumstances the associated metadata may be preserved. An example
  4579. ** of where this might be useful is in a regular-expression matching
  4580. ** function. The compiled version of the regular expression can be stored as
  4581. ** metadata associated with the pattern string.
  4582. ** Then as long as the pattern string remains the same,
  4583. ** the compiled regular expression can be reused on multiple
  4584. ** invocations of the same function.
  4585. **
  4586. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4587. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4588. ** value to the application-defined function. ^If there is no metadata
  4589. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4590. ** returns a NULL pointer.
  4591. **
  4592. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4593. ** argument of the application-defined function. ^Subsequent
  4594. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4595. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4596. ** NULL if the metadata has been discarded.
  4597. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4598. ** SQLite will invoke the destructor function X with parameter P exactly
  4599. ** once, when the metadata is discarded.
  4600. ** SQLite is free to discard the metadata at any time, including: <ul>
  4601. ** <li> when the corresponding function parameter changes, or
  4602. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4603. ** SQL statement, or
  4604. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4605. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4606. ** allocation error occurs. </ul>)^
  4607. **
  4608. ** Note the last bullet in particular. The destructor X in
  4609. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4610. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4611. ** should be called near the end of the function implementation and the
  4612. ** function implementation should not make any use of P after
  4613. ** sqlite3_set_auxdata() has been called.
  4614. **
  4615. ** ^(In practice, metadata is preserved between function calls for
  4616. ** function parameters that are compile-time constants, including literal
  4617. ** values and [parameters] and expressions composed from the same.)^
  4618. **
  4619. ** These routines must be called from the same thread in which
  4620. ** the SQL function is running.
  4621. */
  4622. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
  4623. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4624. /*
  4625. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4626. **
  4627. ** These are special values for the destructor that is passed in as the
  4628. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4629. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4630. ** and will never change. It does not need to be destroyed. ^The
  4631. ** SQLITE_TRANSIENT value means that the content will likely change in
  4632. ** the near future and that SQLite should make its own private copy of
  4633. ** the content before returning.
  4634. **
  4635. ** The typedef is necessary to work around problems in certain
  4636. ** C++ compilers.
  4637. */
  4638. typedef void (*sqlite3_destructor_type)(void*);
  4639. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4640. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4641. /*
  4642. ** CAPI3REF: Setting The Result Of An SQL Function
  4643. ** METHOD: sqlite3_context
  4644. **
  4645. ** These routines are used by the xFunc or xFinal callbacks that
  4646. ** implement SQL functions and aggregates. See
  4647. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4648. ** for additional information.
  4649. **
  4650. ** These functions work very much like the [parameter binding] family of
  4651. ** functions used to bind values to host parameters in prepared statements.
  4652. ** Refer to the [SQL parameter] documentation for additional information.
  4653. **
  4654. ** ^The sqlite3_result_blob() interface sets the result from
  4655. ** an application-defined function to be the BLOB whose content is pointed
  4656. ** to by the second parameter and which is N bytes long where N is the
  4657. ** third parameter.
  4658. **
  4659. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  4660. ** interfaces set the result of the application-defined function to be
  4661. ** a BLOB containing all zero bytes and N bytes in size.
  4662. **
  4663. ** ^The sqlite3_result_double() interface sets the result from
  4664. ** an application-defined function to be a floating point value specified
  4665. ** by its 2nd argument.
  4666. **
  4667. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4668. ** cause the implemented SQL function to throw an exception.
  4669. ** ^SQLite uses the string pointed to by the
  4670. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4671. ** as the text of an error message. ^SQLite interprets the error
  4672. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4673. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4674. ** byte order. ^If the third parameter to sqlite3_result_error()
  4675. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4676. ** message all text up through the first zero character.
  4677. ** ^If the third parameter to sqlite3_result_error() or
  4678. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4679. ** bytes (not characters) from the 2nd parameter as the error message.
  4680. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4681. ** routines make a private copy of the error message text before
  4682. ** they return. Hence, the calling function can deallocate or
  4683. ** modify the text after they return without harm.
  4684. ** ^The sqlite3_result_error_code() function changes the error code
  4685. ** returned by SQLite as a result of an error in a function. ^By default,
  4686. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4687. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4688. **
  4689. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4690. ** error indicating that a string or BLOB is too long to represent.
  4691. **
  4692. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4693. ** error indicating that a memory allocation failed.
  4694. **
  4695. ** ^The sqlite3_result_int() interface sets the return value
  4696. ** of the application-defined function to be the 32-bit signed integer
  4697. ** value given in the 2nd argument.
  4698. ** ^The sqlite3_result_int64() interface sets the return value
  4699. ** of the application-defined function to be the 64-bit signed integer
  4700. ** value given in the 2nd argument.
  4701. **
  4702. ** ^The sqlite3_result_null() interface sets the return value
  4703. ** of the application-defined function to be NULL.
  4704. **
  4705. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4706. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4707. ** set the return value of the application-defined function to be
  4708. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4709. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4710. ** ^The sqlite3_result_text64() interface sets the return value of an
  4711. ** application-defined function to be a text string in an encoding
  4712. ** specified by the fifth (and last) parameter, which must be one
  4713. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4714. ** ^SQLite takes the text result from the application from
  4715. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4716. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4717. ** is negative, then SQLite takes result text from the 2nd parameter
  4718. ** through the first zero character.
  4719. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4720. ** is non-negative, then as many bytes (not characters) of the text
  4721. ** pointed to by the 2nd parameter are taken as the application-defined
  4722. ** function result. If the 3rd parameter is non-negative, then it
  4723. ** must be the byte offset into the string where the NUL terminator would
  4724. ** appear if the string where NUL terminated. If any NUL characters occur
  4725. ** in the string at a byte offset that is less than the value of the 3rd
  4726. ** parameter, then the resulting string will contain embedded NULs and the
  4727. ** result of expressions operating on strings with embedded NULs is undefined.
  4728. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4729. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4730. ** function as the destructor on the text or BLOB result when it has
  4731. ** finished using that result.
  4732. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4733. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4734. ** assumes that the text or BLOB result is in constant space and does not
  4735. ** copy the content of the parameter nor call a destructor on the content
  4736. ** when it has finished using that result.
  4737. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4738. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4739. ** then SQLite makes a copy of the result into space obtained from
  4740. ** from [sqlite3_malloc()] before it returns.
  4741. **
  4742. ** ^The sqlite3_result_value() interface sets the result of
  4743. ** the application-defined function to be a copy of the
  4744. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4745. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4746. ** so that the [sqlite3_value] specified in the parameter may change or
  4747. ** be deallocated after sqlite3_result_value() returns without harm.
  4748. ** ^A [protected sqlite3_value] object may always be used where an
  4749. ** [unprotected sqlite3_value] object is required, so either
  4750. ** kind of [sqlite3_value] object can be used with this interface.
  4751. **
  4752. ** If these routines are called from within the different thread
  4753. ** than the one containing the application-defined function that received
  4754. ** the [sqlite3_context] pointer, the results are undefined.
  4755. */
  4756. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4757. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
  4758. sqlite3_uint64,void(*)(void*));
  4759. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
  4760. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
  4761. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
  4762. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
  4763. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
  4764. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
  4765. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
  4766. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4767. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
  4768. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4769. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4770. void(*)(void*), unsigned char encoding);
  4771. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4772. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4773. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4774. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4775. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
  4776. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  4777. /*
  4778. ** CAPI3REF: Setting The Subtype Of An SQL Function
  4779. ** METHOD: sqlite3_context
  4780. **
  4781. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  4782. ** the result from the [application-defined SQL function] with
  4783. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  4784. ** of the subtype T are preserved in current versions of SQLite;
  4785. ** higher order bits are discarded.
  4786. ** The number of subtype bytes preserved by SQLite might increase
  4787. ** in future releases of SQLite.
  4788. */
  4789. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
  4790. /*
  4791. ** CAPI3REF: Define New Collating Sequences
  4792. ** METHOD: sqlite3
  4793. **
  4794. ** ^These functions add, remove, or modify a [collation] associated
  4795. ** with the [database connection] specified as the first argument.
  4796. **
  4797. ** ^The name of the collation is a UTF-8 string
  4798. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4799. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4800. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4801. ** considered to be the same name.
  4802. **
  4803. ** ^(The third argument (eTextRep) must be one of the constants:
  4804. ** <ul>
  4805. ** <li> [SQLITE_UTF8],
  4806. ** <li> [SQLITE_UTF16LE],
  4807. ** <li> [SQLITE_UTF16BE],
  4808. ** <li> [SQLITE_UTF16], or
  4809. ** <li> [SQLITE_UTF16_ALIGNED].
  4810. ** </ul>)^
  4811. ** ^The eTextRep argument determines the encoding of strings passed
  4812. ** to the collating function callback, xCallback.
  4813. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4814. ** force strings to be UTF16 with native byte order.
  4815. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4816. ** on an even byte address.
  4817. **
  4818. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4819. ** through as the first argument to the collating function callback.
  4820. **
  4821. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4822. ** ^Multiple collating functions can be registered using the same name but
  4823. ** with different eTextRep parameters and SQLite will use whichever
  4824. ** function requires the least amount of data transformation.
  4825. ** ^If the xCallback argument is NULL then the collating function is
  4826. ** deleted. ^When all collating functions having the same name are deleted,
  4827. ** that collation is no longer usable.
  4828. **
  4829. ** ^The collating function callback is invoked with a copy of the pArg
  4830. ** application data pointer and with two strings in the encoding specified
  4831. ** by the eTextRep argument. The collating function must return an
  4832. ** integer that is negative, zero, or positive
  4833. ** if the first string is less than, equal to, or greater than the second,
  4834. ** respectively. A collating function must always return the same answer
  4835. ** given the same inputs. If two or more collating functions are registered
  4836. ** to the same collation name (using different eTextRep values) then all
  4837. ** must give an equivalent answer when invoked with equivalent strings.
  4838. ** The collating function must obey the following properties for all
  4839. ** strings A, B, and C:
  4840. **
  4841. ** <ol>
  4842. ** <li> If A==B then B==A.
  4843. ** <li> If A==B and B==C then A==C.
  4844. ** <li> If A&lt;B THEN B&gt;A.
  4845. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4846. ** </ol>
  4847. **
  4848. ** If a collating function fails any of the above constraints and that
  4849. ** collating function is registered and used, then the behavior of SQLite
  4850. ** is undefined.
  4851. **
  4852. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4853. ** with the addition that the xDestroy callback is invoked on pArg when
  4854. ** the collating function is deleted.
  4855. ** ^Collating functions are deleted when they are overridden by later
  4856. ** calls to the collation creation functions or when the
  4857. ** [database connection] is closed using [sqlite3_close()].
  4858. **
  4859. ** ^The xDestroy callback is <u>not</u> called if the
  4860. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4861. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4862. ** check the return code and dispose of the application data pointer
  4863. ** themselves rather than expecting SQLite to deal with it for them.
  4864. ** This is different from every other SQLite interface. The inconsistency
  4865. ** is unfortunate but cannot be changed without breaking backwards
  4866. ** compatibility.
  4867. **
  4868. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4869. */
  4870. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  4871. sqlite3*,
  4872. const char *zName,
  4873. int eTextRep,
  4874. void *pArg,
  4875. int(*xCompare)(void*,int,const void*,int,const void*)
  4876. );
  4877. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  4878. sqlite3*,
  4879. const char *zName,
  4880. int eTextRep,
  4881. void *pArg,
  4882. int(*xCompare)(void*,int,const void*,int,const void*),
  4883. void(*xDestroy)(void*)
  4884. );
  4885. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  4886. sqlite3*,
  4887. const void *zName,
  4888. int eTextRep,
  4889. void *pArg,
  4890. int(*xCompare)(void*,int,const void*,int,const void*)
  4891. );
  4892. /*
  4893. ** CAPI3REF: Collation Needed Callbacks
  4894. ** METHOD: sqlite3
  4895. **
  4896. ** ^To avoid having to register all collation sequences before a database
  4897. ** can be used, a single callback function may be registered with the
  4898. ** [database connection] to be invoked whenever an undefined collation
  4899. ** sequence is required.
  4900. **
  4901. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4902. ** then it is passed the names of undefined collation sequences as strings
  4903. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4904. ** the names are passed as UTF-16 in machine native byte order.
  4905. ** ^A call to either function replaces the existing collation-needed callback.
  4906. **
  4907. ** ^(When the callback is invoked, the first argument passed is a copy
  4908. ** of the second argument to sqlite3_collation_needed() or
  4909. ** sqlite3_collation_needed16(). The second argument is the database
  4910. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4911. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4912. ** sequence function required. The fourth parameter is the name of the
  4913. ** required collation sequence.)^
  4914. **
  4915. ** The callback function should register the desired collation using
  4916. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4917. ** [sqlite3_create_collation_v2()].
  4918. */
  4919. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  4920. sqlite3*,
  4921. void*,
  4922. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4923. );
  4924. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  4925. sqlite3*,
  4926. void*,
  4927. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4928. );
  4929. #ifdef SQLITE_HAS_CODEC
  4930. /*
  4931. ** Specify the key for an encrypted database. This routine should be
  4932. ** called right after sqlite3_open().
  4933. **
  4934. ** The code to implement this API is not available in the public release
  4935. ** of SQLite.
  4936. */
  4937. SQLITE_API int SQLITE_STDCALL sqlite3_key(
  4938. sqlite3 *db, /* Database to be rekeyed */
  4939. const void *pKey, int nKey /* The key */
  4940. );
  4941. SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
  4942. sqlite3 *db, /* Database to be rekeyed */
  4943. const char *zDbName, /* Name of the database */
  4944. const void *pKey, int nKey /* The key */
  4945. );
  4946. /*
  4947. ** Change the key on an open database. If the current database is not
  4948. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4949. ** database is decrypted.
  4950. **
  4951. ** The code to implement this API is not available in the public release
  4952. ** of SQLite.
  4953. */
  4954. SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
  4955. sqlite3 *db, /* Database to be rekeyed */
  4956. const void *pKey, int nKey /* The new key */
  4957. );
  4958. SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
  4959. sqlite3 *db, /* Database to be rekeyed */
  4960. const char *zDbName, /* Name of the database */
  4961. const void *pKey, int nKey /* The new key */
  4962. );
  4963. /*
  4964. ** Specify the activation key for a SEE database. Unless
  4965. ** activated, none of the SEE routines will work.
  4966. */
  4967. SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
  4968. const char *zPassPhrase /* Activation phrase */
  4969. );
  4970. #endif
  4971. #ifdef SQLITE_ENABLE_CEROD
  4972. /*
  4973. ** Specify the activation key for a CEROD database. Unless
  4974. ** activated, none of the CEROD routines will work.
  4975. */
  4976. SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
  4977. const char *zPassPhrase /* Activation phrase */
  4978. );
  4979. #endif
  4980. /*
  4981. ** CAPI3REF: Suspend Execution For A Short Time
  4982. **
  4983. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4984. ** for at least a number of milliseconds specified in its parameter.
  4985. **
  4986. ** If the operating system does not support sleep requests with
  4987. ** millisecond time resolution, then the time will be rounded up to
  4988. ** the nearest second. The number of milliseconds of sleep actually
  4989. ** requested from the operating system is returned.
  4990. **
  4991. ** ^SQLite implements this interface by calling the xSleep()
  4992. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4993. ** of the default VFS is not implemented correctly, or not implemented at
  4994. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4995. ** in the previous paragraphs.
  4996. */
  4997. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
  4998. /*
  4999. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  5000. **
  5001. ** ^(If this global variable is made to point to a string which is
  5002. ** the name of a folder (a.k.a. directory), then all temporary files
  5003. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5004. ** will be placed in that directory.)^ ^If this variable
  5005. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5006. ** temporary file directory.
  5007. **
  5008. ** Applications are strongly discouraged from using this global variable.
  5009. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  5010. ** But for all other platforms, it is highly recommended that applications
  5011. ** neither read nor write this variable. This global variable is a relic
  5012. ** that exists for backwards compatibility of legacy applications and should
  5013. ** be avoided in new projects.
  5014. **
  5015. ** It is not safe to read or modify this variable in more than one
  5016. ** thread at a time. It is not safe to read or modify this variable
  5017. ** if a [database connection] is being used at the same time in a separate
  5018. ** thread.
  5019. ** It is intended that this variable be set once
  5020. ** as part of process initialization and before any SQLite interface
  5021. ** routines have been called and that this variable remain unchanged
  5022. ** thereafter.
  5023. **
  5024. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5025. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5026. ** the [temp_store_directory pragma] always assumes that any string
  5027. ** that this variable points to is held in memory obtained from
  5028. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5029. ** using [sqlite3_free].
  5030. ** Hence, if this variable is modified directly, either it should be
  5031. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5032. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5033. ** Except when requested by the [temp_store_directory pragma], SQLite
  5034. ** does not free the memory that sqlite3_temp_directory points to. If
  5035. ** the application wants that memory to be freed, it must do
  5036. ** so itself, taking care to only do so after all [database connection]
  5037. ** objects have been destroyed.
  5038. **
  5039. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5040. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5041. ** features that require the use of temporary files may fail. Here is an
  5042. ** example of how to do this using C++ with the Windows Runtime:
  5043. **
  5044. ** <blockquote><pre>
  5045. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5046. ** &nbsp; TemporaryFolder->Path->Data();
  5047. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5048. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5049. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5050. ** &nbsp; NULL, NULL);
  5051. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5052. ** </pre></blockquote>
  5053. */
  5054. SQLITE_API char *sqlite3_temp_directory;
  5055. /*
  5056. ** CAPI3REF: Name Of The Folder Holding Database Files
  5057. **
  5058. ** ^(If this global variable is made to point to a string which is
  5059. ** the name of a folder (a.k.a. directory), then all database files
  5060. ** specified with a relative pathname and created or accessed by
  5061. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5062. ** to be relative to that directory.)^ ^If this variable is a NULL
  5063. ** pointer, then SQLite assumes that all database files specified
  5064. ** with a relative pathname are relative to the current directory
  5065. ** for the process. Only the windows VFS makes use of this global
  5066. ** variable; it is ignored by the unix VFS.
  5067. **
  5068. ** Changing the value of this variable while a database connection is
  5069. ** open can result in a corrupt database.
  5070. **
  5071. ** It is not safe to read or modify this variable in more than one
  5072. ** thread at a time. It is not safe to read or modify this variable
  5073. ** if a [database connection] is being used at the same time in a separate
  5074. ** thread.
  5075. ** It is intended that this variable be set once
  5076. ** as part of process initialization and before any SQLite interface
  5077. ** routines have been called and that this variable remain unchanged
  5078. ** thereafter.
  5079. **
  5080. ** ^The [data_store_directory pragma] may modify this variable and cause
  5081. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5082. ** the [data_store_directory pragma] always assumes that any string
  5083. ** that this variable points to is held in memory obtained from
  5084. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5085. ** using [sqlite3_free].
  5086. ** Hence, if this variable is modified directly, either it should be
  5087. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5088. ** or else the use of the [data_store_directory pragma] should be avoided.
  5089. */
  5090. SQLITE_API char *sqlite3_data_directory;
  5091. /*
  5092. ** CAPI3REF: Test For Auto-Commit Mode
  5093. ** KEYWORDS: {autocommit mode}
  5094. ** METHOD: sqlite3
  5095. **
  5096. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5097. ** zero if the given database connection is or is not in autocommit mode,
  5098. ** respectively. ^Autocommit mode is on by default.
  5099. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5100. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5101. **
  5102. ** If certain kinds of errors occur on a statement within a multi-statement
  5103. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5104. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5105. ** transaction might be rolled back automatically. The only way to
  5106. ** find out whether SQLite automatically rolled back the transaction after
  5107. ** an error is to use this function.
  5108. **
  5109. ** If another thread changes the autocommit status of the database
  5110. ** connection while this routine is running, then the return value
  5111. ** is undefined.
  5112. */
  5113. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
  5114. /*
  5115. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5116. ** METHOD: sqlite3_stmt
  5117. **
  5118. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5119. ** to which a [prepared statement] belongs. ^The [database connection]
  5120. ** returned by sqlite3_db_handle is the same [database connection]
  5121. ** that was the first argument
  5122. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5123. ** create the statement in the first place.
  5124. */
  5125. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
  5126. /*
  5127. ** CAPI3REF: Return The Filename For A Database Connection
  5128. ** METHOD: sqlite3
  5129. **
  5130. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5131. ** associated with database N of connection D. ^The main database file
  5132. ** has the name "main". If there is no attached database N on the database
  5133. ** connection D, or if database N is a temporary or in-memory database, then
  5134. ** a NULL pointer is returned.
  5135. **
  5136. ** ^The filename returned by this function is the output of the
  5137. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5138. ** will be an absolute pathname, even if the filename used
  5139. ** to open the database originally was a URI or relative pathname.
  5140. */
  5141. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5142. /*
  5143. ** CAPI3REF: Determine if a database is read-only
  5144. ** METHOD: sqlite3
  5145. **
  5146. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5147. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5148. ** the name of a database on connection D.
  5149. */
  5150. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5151. /*
  5152. ** CAPI3REF: Find the next prepared statement
  5153. ** METHOD: sqlite3
  5154. **
  5155. ** ^This interface returns a pointer to the next [prepared statement] after
  5156. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5157. ** then this interface returns a pointer to the first prepared statement
  5158. ** associated with the database connection pDb. ^If no prepared statement
  5159. ** satisfies the conditions of this routine, it returns NULL.
  5160. **
  5161. ** The [database connection] pointer D in a call to
  5162. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5163. ** connection and in particular must not be a NULL pointer.
  5164. */
  5165. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5166. /*
  5167. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5168. ** METHOD: sqlite3
  5169. **
  5170. ** ^The sqlite3_commit_hook() interface registers a callback
  5171. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5172. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5173. ** for the same database connection is overridden.
  5174. ** ^The sqlite3_rollback_hook() interface registers a callback
  5175. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5176. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5177. ** for the same database connection is overridden.
  5178. ** ^The pArg argument is passed through to the callback.
  5179. ** ^If the callback on a commit hook function returns non-zero,
  5180. ** then the commit is converted into a rollback.
  5181. **
  5182. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5183. ** return the P argument from the previous call of the same function
  5184. ** on the same [database connection] D, or NULL for
  5185. ** the first call for each function on D.
  5186. **
  5187. ** The commit and rollback hook callbacks are not reentrant.
  5188. ** The callback implementation must not do anything that will modify
  5189. ** the database connection that invoked the callback. Any actions
  5190. ** to modify the database connection must be deferred until after the
  5191. ** completion of the [sqlite3_step()] call that triggered the commit
  5192. ** or rollback hook in the first place.
  5193. ** Note that running any other SQL statements, including SELECT statements,
  5194. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5195. ** the database connections for the meaning of "modify" in this paragraph.
  5196. **
  5197. ** ^Registering a NULL function disables the callback.
  5198. **
  5199. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5200. ** operation is allowed to continue normally. ^If the commit hook
  5201. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5202. ** ^The rollback hook is invoked on a rollback that results from a commit
  5203. ** hook returning non-zero, just as it would be with any other rollback.
  5204. **
  5205. ** ^For the purposes of this API, a transaction is said to have been
  5206. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5207. ** an error or constraint causes an implicit rollback to occur.
  5208. ** ^The rollback callback is not invoked if a transaction is
  5209. ** automatically rolled back because the database connection is closed.
  5210. **
  5211. ** See also the [sqlite3_update_hook()] interface.
  5212. */
  5213. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5214. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5215. /*
  5216. ** CAPI3REF: Data Change Notification Callbacks
  5217. ** METHOD: sqlite3
  5218. **
  5219. ** ^The sqlite3_update_hook() interface registers a callback function
  5220. ** with the [database connection] identified by the first argument
  5221. ** to be invoked whenever a row is updated, inserted or deleted in
  5222. ** a rowid table.
  5223. ** ^Any callback set by a previous call to this function
  5224. ** for the same database connection is overridden.
  5225. **
  5226. ** ^The second argument is a pointer to the function to invoke when a
  5227. ** row is updated, inserted or deleted in a rowid table.
  5228. ** ^The first argument to the callback is a copy of the third argument
  5229. ** to sqlite3_update_hook().
  5230. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5231. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5232. ** to be invoked.
  5233. ** ^The third and fourth arguments to the callback contain pointers to the
  5234. ** database and table name containing the affected row.
  5235. ** ^The final callback parameter is the [rowid] of the row.
  5236. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5237. **
  5238. ** ^(The update hook is not invoked when internal system tables are
  5239. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5240. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5241. **
  5242. ** ^In the current implementation, the update hook
  5243. ** is not invoked when duplication rows are deleted because of an
  5244. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5245. ** invoked when rows are deleted using the [truncate optimization].
  5246. ** The exceptions defined in this paragraph might change in a future
  5247. ** release of SQLite.
  5248. **
  5249. ** The update hook implementation must not do anything that will modify
  5250. ** the database connection that invoked the update hook. Any actions
  5251. ** to modify the database connection must be deferred until after the
  5252. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5253. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5254. ** database connections for the meaning of "modify" in this paragraph.
  5255. **
  5256. ** ^The sqlite3_update_hook(D,C,P) function
  5257. ** returns the P argument from the previous call
  5258. ** on the same [database connection] D, or NULL for
  5259. ** the first call on D.
  5260. **
  5261. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5262. ** interfaces.
  5263. */
  5264. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  5265. sqlite3*,
  5266. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5267. void*
  5268. );
  5269. /*
  5270. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5271. **
  5272. ** ^(This routine enables or disables the sharing of the database cache
  5273. ** and schema data structures between [database connection | connections]
  5274. ** to the same database. Sharing is enabled if the argument is true
  5275. ** and disabled if the argument is false.)^
  5276. **
  5277. ** ^Cache sharing is enabled and disabled for an entire process.
  5278. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5279. ** sharing was enabled or disabled for each thread separately.
  5280. **
  5281. ** ^(The cache sharing mode set by this interface effects all subsequent
  5282. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5283. ** Existing database connections continue use the sharing mode
  5284. ** that was in effect at the time they were opened.)^
  5285. **
  5286. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5287. ** successfully. An [error code] is returned otherwise.)^
  5288. **
  5289. ** ^Shared cache is disabled by default. But this might change in
  5290. ** future releases of SQLite. Applications that care about shared
  5291. ** cache setting should set it explicitly.
  5292. **
  5293. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5294. ** and will always return SQLITE_MISUSE. On those systems,
  5295. ** shared cache mode should be enabled per-database connection via
  5296. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5297. **
  5298. ** This interface is threadsafe on processors where writing a
  5299. ** 32-bit integer is atomic.
  5300. **
  5301. ** See Also: [SQLite Shared-Cache Mode]
  5302. */
  5303. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
  5304. /*
  5305. ** CAPI3REF: Attempt To Free Heap Memory
  5306. **
  5307. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5308. ** of heap memory by deallocating non-essential memory allocations
  5309. ** held by the database library. Memory used to cache database
  5310. ** pages to improve performance is an example of non-essential memory.
  5311. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5312. ** which might be more or less than the amount requested.
  5313. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5314. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5315. **
  5316. ** See also: [sqlite3_db_release_memory()]
  5317. */
  5318. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
  5319. /*
  5320. ** CAPI3REF: Free Memory Used By A Database Connection
  5321. ** METHOD: sqlite3
  5322. **
  5323. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5324. ** memory as possible from database connection D. Unlike the
  5325. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5326. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5327. ** omitted.
  5328. **
  5329. ** See also: [sqlite3_release_memory()]
  5330. */
  5331. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
  5332. /*
  5333. ** CAPI3REF: Impose A Limit On Heap Size
  5334. **
  5335. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5336. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5337. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5338. ** limit by reducing the number of pages held in the page cache
  5339. ** as heap memory usages approaches the limit.
  5340. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5341. ** below the limit, it will exceed the limit rather than generate
  5342. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5343. ** is advisory only.
  5344. **
  5345. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5346. ** the soft heap limit prior to the call, or negative in the case of an
  5347. ** error. ^If the argument N is negative
  5348. ** then no change is made to the soft heap limit. Hence, the current
  5349. ** size of the soft heap limit can be determined by invoking
  5350. ** sqlite3_soft_heap_limit64() with a negative argument.
  5351. **
  5352. ** ^If the argument N is zero then the soft heap limit is disabled.
  5353. **
  5354. ** ^(The soft heap limit is not enforced in the current implementation
  5355. ** if one or more of following conditions are true:
  5356. **
  5357. ** <ul>
  5358. ** <li> The soft heap limit is set to zero.
  5359. ** <li> Memory accounting is disabled using a combination of the
  5360. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5361. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5362. ** <li> An alternative page cache implementation is specified using
  5363. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5364. ** <li> The page cache allocates from its own memory pool supplied
  5365. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5366. ** from the heap.
  5367. ** </ul>)^
  5368. **
  5369. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5370. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5371. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5372. ** the soft heap limit is enforced on every memory allocation. Without
  5373. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5374. ** when memory is allocated by the page cache. Testing suggests that because
  5375. ** the page cache is the predominate memory user in SQLite, most
  5376. ** applications will achieve adequate soft heap limit enforcement without
  5377. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5378. **
  5379. ** The circumstances under which SQLite will enforce the soft heap limit may
  5380. ** changes in future releases of SQLite.
  5381. */
  5382. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5383. /*
  5384. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5385. ** DEPRECATED
  5386. **
  5387. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5388. ** interface. This routine is provided for historical compatibility
  5389. ** only. All new applications should use the
  5390. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5391. */
  5392. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
  5393. /*
  5394. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5395. ** METHOD: sqlite3
  5396. **
  5397. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5398. ** information about column C of table T in database D
  5399. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5400. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5401. ** the final five arguments with appropriate values if the specified
  5402. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5403. ** SQLITE_ERROR and if the specified column does not exist.
  5404. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5405. ** NULL pointer, then this routine simply checks for the existance of the
  5406. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5407. ** does not.
  5408. **
  5409. ** ^The column is identified by the second, third and fourth parameters to
  5410. ** this function. ^(The second parameter is either the name of the database
  5411. ** (i.e. "main", "temp", or an attached database) containing the specified
  5412. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5413. ** for the table using the same algorithm used by the database engine to
  5414. ** resolve unqualified table references.
  5415. **
  5416. ** ^The third and fourth parameters to this function are the table and column
  5417. ** name of the desired column, respectively.
  5418. **
  5419. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5420. ** and subsequent parameters to this function. ^Any of these arguments may be
  5421. ** NULL, in which case the corresponding element of metadata is omitted.
  5422. **
  5423. ** ^(<blockquote>
  5424. ** <table border="1">
  5425. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5426. **
  5427. ** <tr><td> 5th <td> const char* <td> Data type
  5428. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5429. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5430. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5431. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5432. ** </table>
  5433. ** </blockquote>)^
  5434. **
  5435. ** ^The memory pointed to by the character pointers returned for the
  5436. ** declaration type and collation sequence is valid until the next
  5437. ** call to any SQLite API function.
  5438. **
  5439. ** ^If the specified table is actually a view, an [error code] is returned.
  5440. **
  5441. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5442. ** is not a [WITHOUT ROWID] table and an
  5443. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5444. ** parameters are set for the explicitly declared column. ^(If there is no
  5445. ** [INTEGER PRIMARY KEY] column, then the outputs
  5446. ** for the [rowid] are set as follows:
  5447. **
  5448. ** <pre>
  5449. ** data type: "INTEGER"
  5450. ** collation sequence: "BINARY"
  5451. ** not null: 0
  5452. ** primary key: 1
  5453. ** auto increment: 0
  5454. ** </pre>)^
  5455. **
  5456. ** ^This function causes all database schemas to be read from disk and
  5457. ** parsed, if that has not already been done, and returns an error if
  5458. ** any errors are encountered while loading the schema.
  5459. */
  5460. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  5461. sqlite3 *db, /* Connection handle */
  5462. const char *zDbName, /* Database name or NULL */
  5463. const char *zTableName, /* Table name */
  5464. const char *zColumnName, /* Column name */
  5465. char const **pzDataType, /* OUTPUT: Declared data type */
  5466. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5467. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5468. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5469. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5470. );
  5471. /*
  5472. ** CAPI3REF: Load An Extension
  5473. ** METHOD: sqlite3
  5474. **
  5475. ** ^This interface loads an SQLite extension library from the named file.
  5476. **
  5477. ** ^The sqlite3_load_extension() interface attempts to load an
  5478. ** [SQLite extension] library contained in the file zFile. If
  5479. ** the file cannot be loaded directly, attempts are made to load
  5480. ** with various operating-system specific extensions added.
  5481. ** So for example, if "samplelib" cannot be loaded, then names like
  5482. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5483. ** be tried also.
  5484. **
  5485. ** ^The entry point is zProc.
  5486. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5487. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5488. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5489. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5490. ** characters in the filename from the last "/" to the first following
  5491. ** "." and omitting any initial "lib".)^
  5492. ** ^The sqlite3_load_extension() interface returns
  5493. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5494. ** ^If an error occurs and pzErrMsg is not 0, then the
  5495. ** [sqlite3_load_extension()] interface shall attempt to
  5496. ** fill *pzErrMsg with error message text stored in memory
  5497. ** obtained from [sqlite3_malloc()]. The calling function
  5498. ** should free this memory by calling [sqlite3_free()].
  5499. **
  5500. ** ^Extension loading must be enabled using
  5501. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5502. ** otherwise an error will be returned.
  5503. **
  5504. ** See also the [load_extension() SQL function].
  5505. */
  5506. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  5507. sqlite3 *db, /* Load the extension into this database connection */
  5508. const char *zFile, /* Name of the shared library containing extension */
  5509. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5510. char **pzErrMsg /* Put error message here if not 0 */
  5511. );
  5512. /*
  5513. ** CAPI3REF: Enable Or Disable Extension Loading
  5514. ** METHOD: sqlite3
  5515. **
  5516. ** ^So as not to open security holes in older applications that are
  5517. ** unprepared to deal with [extension loading], and as a means of disabling
  5518. ** [extension loading] while evaluating user-entered SQL, the following API
  5519. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5520. **
  5521. ** ^Extension loading is off by default.
  5522. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5523. ** to turn extension loading on and call it with onoff==0 to turn
  5524. ** it back off again.
  5525. */
  5526. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5527. /*
  5528. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5529. **
  5530. ** ^This interface causes the xEntryPoint() function to be invoked for
  5531. ** each new [database connection] that is created. The idea here is that
  5532. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5533. ** that is to be automatically loaded into all new database connections.
  5534. **
  5535. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5536. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5537. ** arguments and expects and integer result as if the signature of the
  5538. ** entry point where as follows:
  5539. **
  5540. ** <blockquote><pre>
  5541. ** &nbsp; int xEntryPoint(
  5542. ** &nbsp; sqlite3 *db,
  5543. ** &nbsp; const char **pzErrMsg,
  5544. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5545. ** &nbsp; );
  5546. ** </pre></blockquote>)^
  5547. **
  5548. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5549. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5550. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5551. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5552. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5553. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5554. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5555. **
  5556. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5557. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5558. ** will be called more than once for each database connection that is opened.
  5559. **
  5560. ** See also: [sqlite3_reset_auto_extension()]
  5561. ** and [sqlite3_cancel_auto_extension()]
  5562. */
  5563. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
  5564. /*
  5565. ** CAPI3REF: Cancel Automatic Extension Loading
  5566. **
  5567. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5568. ** initialization routine X that was registered using a prior call to
  5569. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5570. ** routine returns 1 if initialization routine X was successfully
  5571. ** unregistered and it returns 0 if X was not on the list of initialization
  5572. ** routines.
  5573. */
  5574. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5575. /*
  5576. ** CAPI3REF: Reset Automatic Extension Loading
  5577. **
  5578. ** ^This interface disables all automatic extensions previously
  5579. ** registered using [sqlite3_auto_extension()].
  5580. */
  5581. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
  5582. /*
  5583. ** The interface to the virtual-table mechanism is currently considered
  5584. ** to be experimental. The interface might change in incompatible ways.
  5585. ** If this is a problem for you, do not use the interface at this time.
  5586. **
  5587. ** When the virtual-table mechanism stabilizes, we will declare the
  5588. ** interface fixed, support it indefinitely, and remove this comment.
  5589. */
  5590. /*
  5591. ** Structures used by the virtual table interface
  5592. */
  5593. typedef struct sqlite3_vtab sqlite3_vtab;
  5594. typedef struct sqlite3_index_info sqlite3_index_info;
  5595. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5596. typedef struct sqlite3_module sqlite3_module;
  5597. /*
  5598. ** CAPI3REF: Virtual Table Object
  5599. ** KEYWORDS: sqlite3_module {virtual table module}
  5600. **
  5601. ** This structure, sometimes called a "virtual table module",
  5602. ** defines the implementation of a [virtual tables].
  5603. ** This structure consists mostly of methods for the module.
  5604. **
  5605. ** ^A virtual table module is created by filling in a persistent
  5606. ** instance of this structure and passing a pointer to that instance
  5607. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5608. ** ^The registration remains valid until it is replaced by a different
  5609. ** module or until the [database connection] closes. The content
  5610. ** of this structure must not change while it is registered with
  5611. ** any database connection.
  5612. */
  5613. struct sqlite3_module {
  5614. int iVersion;
  5615. int (*xCreate)(sqlite3*, void *pAux,
  5616. int argc, const char *const*argv,
  5617. sqlite3_vtab **ppVTab, char**);
  5618. int (*xConnect)(sqlite3*, void *pAux,
  5619. int argc, const char *const*argv,
  5620. sqlite3_vtab **ppVTab, char**);
  5621. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5622. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5623. int (*xDestroy)(sqlite3_vtab *pVTab);
  5624. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5625. int (*xClose)(sqlite3_vtab_cursor*);
  5626. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5627. int argc, sqlite3_value **argv);
  5628. int (*xNext)(sqlite3_vtab_cursor*);
  5629. int (*xEof)(sqlite3_vtab_cursor*);
  5630. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5631. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5632. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5633. int (*xBegin)(sqlite3_vtab *pVTab);
  5634. int (*xSync)(sqlite3_vtab *pVTab);
  5635. int (*xCommit)(sqlite3_vtab *pVTab);
  5636. int (*xRollback)(sqlite3_vtab *pVTab);
  5637. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5638. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5639. void **ppArg);
  5640. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5641. /* The methods above are in version 1 of the sqlite_module object. Those
  5642. ** below are for version 2 and greater. */
  5643. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5644. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5645. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5646. };
  5647. /*
  5648. ** CAPI3REF: Virtual Table Indexing Information
  5649. ** KEYWORDS: sqlite3_index_info
  5650. **
  5651. ** The sqlite3_index_info structure and its substructures is used as part
  5652. ** of the [virtual table] interface to
  5653. ** pass information into and receive the reply from the [xBestIndex]
  5654. ** method of a [virtual table module]. The fields under **Inputs** are the
  5655. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5656. ** results into the **Outputs** fields.
  5657. **
  5658. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5659. **
  5660. ** <blockquote>column OP expr</blockquote>
  5661. **
  5662. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5663. ** stored in aConstraint[].op using one of the
  5664. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5665. ** ^(The index of the column is stored in
  5666. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5667. ** expr on the right-hand side can be evaluated (and thus the constraint
  5668. ** is usable) and false if it cannot.)^
  5669. **
  5670. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5671. ** and makes other simplifications to the WHERE clause in an attempt to
  5672. ** get as many WHERE clause terms into the form shown above as possible.
  5673. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5674. ** relevant to the particular virtual table being queried.
  5675. **
  5676. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5677. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5678. **
  5679. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5680. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5681. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5682. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5683. ** is true, then the constraint is assumed to be fully handled by the
  5684. ** virtual table and is not checked again by SQLite.)^
  5685. **
  5686. ** ^The idxNum and idxPtr values are recorded and passed into the
  5687. ** [xFilter] method.
  5688. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5689. ** needToFreeIdxPtr is true.
  5690. **
  5691. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5692. ** the correct order to satisfy the ORDER BY clause so that no separate
  5693. ** sorting step is required.
  5694. **
  5695. ** ^The estimatedCost value is an estimate of the cost of a particular
  5696. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5697. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5698. ** indicates that the expense of the operation is similar to that of a
  5699. ** binary search on a unique indexed field of an SQLite table with N rows.
  5700. **
  5701. ** ^The estimatedRows value is an estimate of the number of rows that
  5702. ** will be returned by the strategy.
  5703. **
  5704. ** The xBestIndex method may optionally populate the idxFlags field with a
  5705. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  5706. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  5707. ** assumes that the strategy may visit at most one row.
  5708. **
  5709. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  5710. ** SQLite also assumes that if a call to the xUpdate() method is made as
  5711. ** part of the same statement to delete or update a virtual table row and the
  5712. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  5713. ** any database changes. In other words, if the xUpdate() returns
  5714. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  5715. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  5716. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  5717. ** the xUpdate method are automatically rolled back by SQLite.
  5718. **
  5719. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5720. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5721. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5722. ** to read or write the estimatedRows field are undefined (but are likely
  5723. ** to included crashing the application). The estimatedRows field should
  5724. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5725. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  5726. ** was added for version 3.9.0. It may therefore only be used if
  5727. ** sqlite3_libversion_number() returns a value greater than or equal to
  5728. ** 3009000.
  5729. */
  5730. struct sqlite3_index_info {
  5731. /* Inputs */
  5732. int nConstraint; /* Number of entries in aConstraint */
  5733. struct sqlite3_index_constraint {
  5734. int iColumn; /* Column on left-hand side of constraint */
  5735. unsigned char op; /* Constraint operator */
  5736. unsigned char usable; /* True if this constraint is usable */
  5737. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5738. } *aConstraint; /* Table of WHERE clause constraints */
  5739. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5740. struct sqlite3_index_orderby {
  5741. int iColumn; /* Column number */
  5742. unsigned char desc; /* True for DESC. False for ASC. */
  5743. } *aOrderBy; /* The ORDER BY clause */
  5744. /* Outputs */
  5745. struct sqlite3_index_constraint_usage {
  5746. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5747. unsigned char omit; /* Do not code a test for this constraint */
  5748. } *aConstraintUsage;
  5749. int idxNum; /* Number used to identify the index */
  5750. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5751. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5752. int orderByConsumed; /* True if output is already ordered */
  5753. double estimatedCost; /* Estimated cost of using this index */
  5754. /* Fields below are only available in SQLite 3.8.2 and later */
  5755. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5756. /* Fields below are only available in SQLite 3.9.0 and later */
  5757. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  5758. };
  5759. /*
  5760. ** CAPI3REF: Virtual Table Scan Flags
  5761. */
  5762. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  5763. /*
  5764. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5765. **
  5766. ** These macros defined the allowed values for the
  5767. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5768. ** an operator that is part of a constraint term in the wHERE clause of
  5769. ** a query that uses a [virtual table].
  5770. */
  5771. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5772. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5773. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5774. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5775. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5776. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5777. /*
  5778. ** CAPI3REF: Register A Virtual Table Implementation
  5779. ** METHOD: sqlite3
  5780. **
  5781. ** ^These routines are used to register a new [virtual table module] name.
  5782. ** ^Module names must be registered before
  5783. ** creating a new [virtual table] using the module and before using a
  5784. ** preexisting [virtual table] for the module.
  5785. **
  5786. ** ^The module name is registered on the [database connection] specified
  5787. ** by the first parameter. ^The name of the module is given by the
  5788. ** second parameter. ^The third parameter is a pointer to
  5789. ** the implementation of the [virtual table module]. ^The fourth
  5790. ** parameter is an arbitrary client data pointer that is passed through
  5791. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5792. ** when a new virtual table is be being created or reinitialized.
  5793. **
  5794. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5795. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5796. ** invoke the destructor function (if it is not NULL) when SQLite
  5797. ** no longer needs the pClientData pointer. ^The destructor will also
  5798. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5799. ** ^The sqlite3_create_module()
  5800. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5801. ** destructor.
  5802. */
  5803. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  5804. sqlite3 *db, /* SQLite connection to register module with */
  5805. const char *zName, /* Name of the module */
  5806. const sqlite3_module *p, /* Methods for the module */
  5807. void *pClientData /* Client data for xCreate/xConnect */
  5808. );
  5809. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  5810. sqlite3 *db, /* SQLite connection to register module with */
  5811. const char *zName, /* Name of the module */
  5812. const sqlite3_module *p, /* Methods for the module */
  5813. void *pClientData, /* Client data for xCreate/xConnect */
  5814. void(*xDestroy)(void*) /* Module destructor function */
  5815. );
  5816. /*
  5817. ** CAPI3REF: Virtual Table Instance Object
  5818. ** KEYWORDS: sqlite3_vtab
  5819. **
  5820. ** Every [virtual table module] implementation uses a subclass
  5821. ** of this object to describe a particular instance
  5822. ** of the [virtual table]. Each subclass will
  5823. ** be tailored to the specific needs of the module implementation.
  5824. ** The purpose of this superclass is to define certain fields that are
  5825. ** common to all module implementations.
  5826. **
  5827. ** ^Virtual tables methods can set an error message by assigning a
  5828. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5829. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5830. ** prior to assigning a new string to zErrMsg. ^After the error message
  5831. ** is delivered up to the client application, the string will be automatically
  5832. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5833. */
  5834. struct sqlite3_vtab {
  5835. const sqlite3_module *pModule; /* The module for this virtual table */
  5836. int nRef; /* Number of open cursors */
  5837. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5838. /* Virtual table implementations will typically add additional fields */
  5839. };
  5840. /*
  5841. ** CAPI3REF: Virtual Table Cursor Object
  5842. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5843. **
  5844. ** Every [virtual table module] implementation uses a subclass of the
  5845. ** following structure to describe cursors that point into the
  5846. ** [virtual table] and are used
  5847. ** to loop through the virtual table. Cursors are created using the
  5848. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5849. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5850. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5851. ** of the module. Each module implementation will define
  5852. ** the content of a cursor structure to suit its own needs.
  5853. **
  5854. ** This superclass exists in order to define fields of the cursor that
  5855. ** are common to all implementations.
  5856. */
  5857. struct sqlite3_vtab_cursor {
  5858. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5859. /* Virtual table implementations will typically add additional fields */
  5860. };
  5861. /*
  5862. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5863. **
  5864. ** ^The [xCreate] and [xConnect] methods of a
  5865. ** [virtual table module] call this interface
  5866. ** to declare the format (the names and datatypes of the columns) of
  5867. ** the virtual tables they implement.
  5868. */
  5869. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5870. /*
  5871. ** CAPI3REF: Overload A Function For A Virtual Table
  5872. ** METHOD: sqlite3
  5873. **
  5874. ** ^(Virtual tables can provide alternative implementations of functions
  5875. ** using the [xFindFunction] method of the [virtual table module].
  5876. ** But global versions of those functions
  5877. ** must exist in order to be overloaded.)^
  5878. **
  5879. ** ^(This API makes sure a global version of a function with a particular
  5880. ** name and number of parameters exists. If no such function exists
  5881. ** before this API is called, a new function is created.)^ ^The implementation
  5882. ** of the new function always causes an exception to be thrown. So
  5883. ** the new function is not good for anything by itself. Its only
  5884. ** purpose is to be a placeholder function that can be overloaded
  5885. ** by a [virtual table].
  5886. */
  5887. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5888. /*
  5889. ** The interface to the virtual-table mechanism defined above (back up
  5890. ** to a comment remarkably similar to this one) is currently considered
  5891. ** to be experimental. The interface might change in incompatible ways.
  5892. ** If this is a problem for you, do not use the interface at this time.
  5893. **
  5894. ** When the virtual-table mechanism stabilizes, we will declare the
  5895. ** interface fixed, support it indefinitely, and remove this comment.
  5896. */
  5897. /*
  5898. ** CAPI3REF: A Handle To An Open BLOB
  5899. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5900. **
  5901. ** An instance of this object represents an open BLOB on which
  5902. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5903. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5904. ** and destroyed by [sqlite3_blob_close()].
  5905. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5906. ** can be used to read or write small subsections of the BLOB.
  5907. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5908. */
  5909. typedef struct sqlite3_blob sqlite3_blob;
  5910. /*
  5911. ** CAPI3REF: Open A BLOB For Incremental I/O
  5912. ** METHOD: sqlite3
  5913. ** CONSTRUCTOR: sqlite3_blob
  5914. **
  5915. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5916. ** in row iRow, column zColumn, table zTable in database zDb;
  5917. ** in other words, the same BLOB that would be selected by:
  5918. **
  5919. ** <pre>
  5920. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5921. ** </pre>)^
  5922. **
  5923. ** ^(Parameter zDb is not the filename that contains the database, but
  5924. ** rather the symbolic name of the database. For attached databases, this is
  5925. ** the name that appears after the AS keyword in the [ATTACH] statement.
  5926. ** For the main database file, the database name is "main". For TEMP
  5927. ** tables, the database name is "temp".)^
  5928. **
  5929. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5930. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  5931. ** read-only access.
  5932. **
  5933. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  5934. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  5935. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  5936. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  5937. ** on *ppBlob after this function it returns.
  5938. **
  5939. ** This function fails with SQLITE_ERROR if any of the following are true:
  5940. ** <ul>
  5941. ** <li> ^(Database zDb does not exist)^,
  5942. ** <li> ^(Table zTable does not exist within database zDb)^,
  5943. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  5944. ** <li> ^(Column zColumn does not exist)^,
  5945. ** <li> ^(Row iRow is not present in the table)^,
  5946. ** <li> ^(The specified column of row iRow contains a value that is not
  5947. ** a TEXT or BLOB value)^,
  5948. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  5949. ** constraint and the blob is being opened for read/write access)^,
  5950. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  5951. ** column zColumn is part of a [child key] definition and the blob is
  5952. ** being opened for read/write access)^.
  5953. ** </ul>
  5954. **
  5955. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  5956. ** [database connection] error code and message accessible via
  5957. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  5958. **
  5959. **
  5960. ** ^(If the row that a BLOB handle points to is modified by an
  5961. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5962. ** then the BLOB handle is marked as "expired".
  5963. ** This is true if any column of the row is changed, even a column
  5964. ** other than the one the BLOB handle is open on.)^
  5965. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5966. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5967. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5968. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5969. ** commit if the transaction continues to completion.)^
  5970. **
  5971. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5972. ** the opened blob. ^The size of a blob may not be changed by this
  5973. ** interface. Use the [UPDATE] SQL command to change the size of a
  5974. ** blob.
  5975. **
  5976. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5977. ** and the built-in [zeroblob] SQL function may be used to create a
  5978. ** zero-filled blob to read or write using the incremental-blob interface.
  5979. **
  5980. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5981. ** be released by a call to [sqlite3_blob_close()].
  5982. */
  5983. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  5984. sqlite3*,
  5985. const char *zDb,
  5986. const char *zTable,
  5987. const char *zColumn,
  5988. sqlite3_int64 iRow,
  5989. int flags,
  5990. sqlite3_blob **ppBlob
  5991. );
  5992. /*
  5993. ** CAPI3REF: Move a BLOB Handle to a New Row
  5994. ** METHOD: sqlite3_blob
  5995. **
  5996. ** ^This function is used to move an existing blob handle so that it points
  5997. ** to a different row of the same database table. ^The new row is identified
  5998. ** by the rowid value passed as the second argument. Only the row can be
  5999. ** changed. ^The database, table and column on which the blob handle is open
  6000. ** remain the same. Moving an existing blob handle to a new row can be
  6001. ** faster than closing the existing handle and opening a new one.
  6002. **
  6003. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  6004. ** it must exist and there must be either a blob or text value stored in
  6005. ** the nominated column.)^ ^If the new row is not present in the table, or if
  6006. ** it does not contain a blob or text value, or if another error occurs, an
  6007. ** SQLite error code is returned and the blob handle is considered aborted.
  6008. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  6009. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  6010. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  6011. ** always returns zero.
  6012. **
  6013. ** ^This function sets the database handle error code and message.
  6014. */
  6015. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  6016. /*
  6017. ** CAPI3REF: Close A BLOB Handle
  6018. ** DESTRUCTOR: sqlite3_blob
  6019. **
  6020. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  6021. ** unconditionally. Even if this routine returns an error code, the
  6022. ** handle is still closed.)^
  6023. **
  6024. ** ^If the blob handle being closed was opened for read-write access, and if
  6025. ** the database is in auto-commit mode and there are no other open read-write
  6026. ** blob handles or active write statements, the current transaction is
  6027. ** committed. ^If an error occurs while committing the transaction, an error
  6028. ** code is returned and the transaction rolled back.
  6029. **
  6030. ** Calling this function with an argument that is not a NULL pointer or an
  6031. ** open blob handle results in undefined behaviour. ^Calling this routine
  6032. ** with a null pointer (such as would be returned by a failed call to
  6033. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  6034. ** is passed a valid open blob handle, the values returned by the
  6035. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  6036. */
  6037. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
  6038. /*
  6039. ** CAPI3REF: Return The Size Of An Open BLOB
  6040. ** METHOD: sqlite3_blob
  6041. **
  6042. ** ^Returns the size in bytes of the BLOB accessible via the
  6043. ** successfully opened [BLOB handle] in its only argument. ^The
  6044. ** incremental blob I/O routines can only read or overwriting existing
  6045. ** blob content; they cannot change the size of a blob.
  6046. **
  6047. ** This routine only works on a [BLOB handle] which has been created
  6048. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6049. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6050. ** to this routine results in undefined and probably undesirable behavior.
  6051. */
  6052. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
  6053. /*
  6054. ** CAPI3REF: Read Data From A BLOB Incrementally
  6055. ** METHOD: sqlite3_blob
  6056. **
  6057. ** ^(This function is used to read data from an open [BLOB handle] into a
  6058. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6059. ** from the open BLOB, starting at offset iOffset.)^
  6060. **
  6061. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6062. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6063. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6064. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6065. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6066. **
  6067. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6068. ** error code of [SQLITE_ABORT].
  6069. **
  6070. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6071. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6072. **
  6073. ** This routine only works on a [BLOB handle] which has been created
  6074. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6075. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6076. ** to this routine results in undefined and probably undesirable behavior.
  6077. **
  6078. ** See also: [sqlite3_blob_write()].
  6079. */
  6080. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6081. /*
  6082. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6083. ** METHOD: sqlite3_blob
  6084. **
  6085. ** ^(This function is used to write data into an open [BLOB handle] from a
  6086. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6087. ** into the open BLOB, starting at offset iOffset.)^
  6088. **
  6089. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6090. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6091. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6092. ** [database connection] error code and message accessible via
  6093. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6094. **
  6095. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6096. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6097. ** this function returns [SQLITE_READONLY].
  6098. **
  6099. ** This function may only modify the contents of the BLOB; it is
  6100. ** not possible to increase the size of a BLOB using this API.
  6101. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6102. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6103. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6104. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6105. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6106. **
  6107. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6108. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6109. ** before the [BLOB handle] expired are not rolled back by the
  6110. ** expiration of the handle, though of course those changes might
  6111. ** have been overwritten by the statement that expired the BLOB handle
  6112. ** or by other independent statements.
  6113. **
  6114. ** This routine only works on a [BLOB handle] which has been created
  6115. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6116. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6117. ** to this routine results in undefined and probably undesirable behavior.
  6118. **
  6119. ** See also: [sqlite3_blob_read()].
  6120. */
  6121. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6122. /*
  6123. ** CAPI3REF: Virtual File System Objects
  6124. **
  6125. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6126. ** that SQLite uses to interact
  6127. ** with the underlying operating system. Most SQLite builds come with a
  6128. ** single default VFS that is appropriate for the host computer.
  6129. ** New VFSes can be registered and existing VFSes can be unregistered.
  6130. ** The following interfaces are provided.
  6131. **
  6132. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6133. ** ^Names are case sensitive.
  6134. ** ^Names are zero-terminated UTF-8 strings.
  6135. ** ^If there is no match, a NULL pointer is returned.
  6136. ** ^If zVfsName is NULL then the default VFS is returned.
  6137. **
  6138. ** ^New VFSes are registered with sqlite3_vfs_register().
  6139. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6140. ** ^The same VFS can be registered multiple times without injury.
  6141. ** ^To make an existing VFS into the default VFS, register it again
  6142. ** with the makeDflt flag set. If two different VFSes with the
  6143. ** same name are registered, the behavior is undefined. If a
  6144. ** VFS is registered with a name that is NULL or an empty string,
  6145. ** then the behavior is undefined.
  6146. **
  6147. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6148. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6149. ** the default. The choice for the new VFS is arbitrary.)^
  6150. */
  6151. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
  6152. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6153. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
  6154. /*
  6155. ** CAPI3REF: Mutexes
  6156. **
  6157. ** The SQLite core uses these routines for thread
  6158. ** synchronization. Though they are intended for internal
  6159. ** use by SQLite, code that links against SQLite is
  6160. ** permitted to use any of these routines.
  6161. **
  6162. ** The SQLite source code contains multiple implementations
  6163. ** of these mutex routines. An appropriate implementation
  6164. ** is selected automatically at compile-time. The following
  6165. ** implementations are available in the SQLite core:
  6166. **
  6167. ** <ul>
  6168. ** <li> SQLITE_MUTEX_PTHREADS
  6169. ** <li> SQLITE_MUTEX_W32
  6170. ** <li> SQLITE_MUTEX_NOOP
  6171. ** </ul>
  6172. **
  6173. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6174. ** that does no real locking and is appropriate for use in
  6175. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6176. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6177. ** and Windows.
  6178. **
  6179. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6180. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6181. ** implementation is included with the library. In this case the
  6182. ** application must supply a custom mutex implementation using the
  6183. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6184. ** before calling sqlite3_initialize() or any other public sqlite3_
  6185. ** function that calls sqlite3_initialize().
  6186. **
  6187. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6188. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6189. ** routine returns NULL if it is unable to allocate the requested
  6190. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6191. ** integer constants:
  6192. **
  6193. ** <ul>
  6194. ** <li> SQLITE_MUTEX_FAST
  6195. ** <li> SQLITE_MUTEX_RECURSIVE
  6196. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6197. ** <li> SQLITE_MUTEX_STATIC_MEM
  6198. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6199. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6200. ** <li> SQLITE_MUTEX_STATIC_LRU
  6201. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6202. ** <li> SQLITE_MUTEX_STATIC_APP1
  6203. ** <li> SQLITE_MUTEX_STATIC_APP2
  6204. ** <li> SQLITE_MUTEX_STATIC_APP3
  6205. ** <li> SQLITE_MUTEX_STATIC_VFS1
  6206. ** <li> SQLITE_MUTEX_STATIC_VFS2
  6207. ** <li> SQLITE_MUTEX_STATIC_VFS3
  6208. ** </ul>
  6209. **
  6210. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6211. ** cause sqlite3_mutex_alloc() to create
  6212. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6213. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6214. ** The mutex implementation does not need to make a distinction
  6215. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6216. ** not want to. SQLite will only request a recursive mutex in
  6217. ** cases where it really needs one. If a faster non-recursive mutex
  6218. ** implementation is available on the host platform, the mutex subsystem
  6219. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6220. **
  6221. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6222. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6223. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6224. ** used by the current version of SQLite. Future versions of SQLite
  6225. ** may add additional static mutexes. Static mutexes are for internal
  6226. ** use by SQLite only. Applications that use SQLite mutexes should
  6227. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6228. ** SQLITE_MUTEX_RECURSIVE.
  6229. **
  6230. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6231. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6232. ** returns a different mutex on every call. ^For the static
  6233. ** mutex types, the same mutex is returned on every call that has
  6234. ** the same type number.
  6235. **
  6236. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6237. ** allocated dynamic mutex. Attempting to deallocate a static
  6238. ** mutex results in undefined behavior.
  6239. **
  6240. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6241. ** to enter a mutex. ^If another thread is already within the mutex,
  6242. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6243. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6244. ** upon successful entry. ^(Mutexes created using
  6245. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6246. ** In such cases, the
  6247. ** mutex must be exited an equal number of times before another thread
  6248. ** can enter.)^ If the same thread tries to enter any mutex other
  6249. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6250. **
  6251. ** ^(Some systems (for example, Windows 95) do not support the operation
  6252. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6253. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6254. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6255. ** behavior.)^
  6256. **
  6257. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6258. ** previously entered by the same thread. The behavior
  6259. ** is undefined if the mutex is not currently entered by the
  6260. ** calling thread or is not currently allocated.
  6261. **
  6262. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6263. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6264. ** behave as no-ops.
  6265. **
  6266. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6267. */
  6268. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
  6269. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
  6270. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
  6271. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
  6272. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
  6273. /*
  6274. ** CAPI3REF: Mutex Methods Object
  6275. **
  6276. ** An instance of this structure defines the low-level routines
  6277. ** used to allocate and use mutexes.
  6278. **
  6279. ** Usually, the default mutex implementations provided by SQLite are
  6280. ** sufficient, however the application has the option of substituting a custom
  6281. ** implementation for specialized deployments or systems for which SQLite
  6282. ** does not provide a suitable implementation. In this case, the application
  6283. ** creates and populates an instance of this structure to pass
  6284. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6285. ** Additionally, an instance of this structure can be used as an
  6286. ** output variable when querying the system for the current mutex
  6287. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6288. **
  6289. ** ^The xMutexInit method defined by this structure is invoked as
  6290. ** part of system initialization by the sqlite3_initialize() function.
  6291. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6292. ** effective call to [sqlite3_initialize()].
  6293. **
  6294. ** ^The xMutexEnd method defined by this structure is invoked as
  6295. ** part of system shutdown by the sqlite3_shutdown() function. The
  6296. ** implementation of this method is expected to release all outstanding
  6297. ** resources obtained by the mutex methods implementation, especially
  6298. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6299. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6300. **
  6301. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6302. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6303. ** xMutexNotheld) implement the following interfaces (respectively):
  6304. **
  6305. ** <ul>
  6306. ** <li> [sqlite3_mutex_alloc()] </li>
  6307. ** <li> [sqlite3_mutex_free()] </li>
  6308. ** <li> [sqlite3_mutex_enter()] </li>
  6309. ** <li> [sqlite3_mutex_try()] </li>
  6310. ** <li> [sqlite3_mutex_leave()] </li>
  6311. ** <li> [sqlite3_mutex_held()] </li>
  6312. ** <li> [sqlite3_mutex_notheld()] </li>
  6313. ** </ul>)^
  6314. **
  6315. ** The only difference is that the public sqlite3_XXX functions enumerated
  6316. ** above silently ignore any invocations that pass a NULL pointer instead
  6317. ** of a valid mutex handle. The implementations of the methods defined
  6318. ** by this structure are not required to handle this case, the results
  6319. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6320. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6321. ** it is passed a NULL pointer).
  6322. **
  6323. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6324. ** invoke xMutexInit() multiple times within the same process and without
  6325. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6326. ** xMutexInit() must be no-ops.
  6327. **
  6328. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6329. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6330. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6331. ** memory allocation for a fast or recursive mutex.
  6332. **
  6333. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6334. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6335. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6336. ** prior to returning.
  6337. */
  6338. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6339. struct sqlite3_mutex_methods {
  6340. int (*xMutexInit)(void);
  6341. int (*xMutexEnd)(void);
  6342. sqlite3_mutex *(*xMutexAlloc)(int);
  6343. void (*xMutexFree)(sqlite3_mutex *);
  6344. void (*xMutexEnter)(sqlite3_mutex *);
  6345. int (*xMutexTry)(sqlite3_mutex *);
  6346. void (*xMutexLeave)(sqlite3_mutex *);
  6347. int (*xMutexHeld)(sqlite3_mutex *);
  6348. int (*xMutexNotheld)(sqlite3_mutex *);
  6349. };
  6350. /*
  6351. ** CAPI3REF: Mutex Verification Routines
  6352. **
  6353. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6354. ** are intended for use inside assert() statements. The SQLite core
  6355. ** never uses these routines except inside an assert() and applications
  6356. ** are advised to follow the lead of the core. The SQLite core only
  6357. ** provides implementations for these routines when it is compiled
  6358. ** with the SQLITE_DEBUG flag. External mutex implementations
  6359. ** are only required to provide these routines if SQLITE_DEBUG is
  6360. ** defined and if NDEBUG is not defined.
  6361. **
  6362. ** These routines should return true if the mutex in their argument
  6363. ** is held or not held, respectively, by the calling thread.
  6364. **
  6365. ** The implementation is not required to provide versions of these
  6366. ** routines that actually work. If the implementation does not provide working
  6367. ** versions of these routines, it should at least provide stubs that always
  6368. ** return true so that one does not get spurious assertion failures.
  6369. **
  6370. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6371. ** the routine should return 1. This seems counter-intuitive since
  6372. ** clearly the mutex cannot be held if it does not exist. But
  6373. ** the reason the mutex does not exist is because the build is not
  6374. ** using mutexes. And we do not want the assert() containing the
  6375. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6376. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6377. ** interface should also return 1 when given a NULL pointer.
  6378. */
  6379. #ifndef NDEBUG
  6380. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
  6381. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
  6382. #endif
  6383. /*
  6384. ** CAPI3REF: Mutex Types
  6385. **
  6386. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6387. ** which is one of these integer constants.
  6388. **
  6389. ** The set of static mutexes may change from one SQLite release to the
  6390. ** next. Applications that override the built-in mutex logic must be
  6391. ** prepared to accommodate additional static mutexes.
  6392. */
  6393. #define SQLITE_MUTEX_FAST 0
  6394. #define SQLITE_MUTEX_RECURSIVE 1
  6395. #define SQLITE_MUTEX_STATIC_MASTER 2
  6396. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6397. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6398. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6399. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6400. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6401. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6402. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6403. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6404. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6405. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6406. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6407. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6408. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6409. /*
  6410. ** CAPI3REF: Retrieve the mutex for a database connection
  6411. ** METHOD: sqlite3
  6412. **
  6413. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6414. ** serializes access to the [database connection] given in the argument
  6415. ** when the [threading mode] is Serialized.
  6416. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6417. ** routine returns a NULL pointer.
  6418. */
  6419. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
  6420. /*
  6421. ** CAPI3REF: Low-Level Control Of Database Files
  6422. ** METHOD: sqlite3
  6423. **
  6424. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6425. ** xFileControl method for the [sqlite3_io_methods] object associated
  6426. ** with a particular database identified by the second argument. ^The
  6427. ** name of the database is "main" for the main database or "temp" for the
  6428. ** TEMP database, or the name that appears after the AS keyword for
  6429. ** databases that are added using the [ATTACH] SQL command.
  6430. ** ^A NULL pointer can be used in place of "main" to refer to the
  6431. ** main database file.
  6432. ** ^The third and fourth parameters to this routine
  6433. ** are passed directly through to the second and third parameters of
  6434. ** the xFileControl method. ^The return value of the xFileControl
  6435. ** method becomes the return value of this routine.
  6436. **
  6437. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6438. ** a pointer to the underlying [sqlite3_file] object to be written into
  6439. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6440. ** case is a short-circuit path which does not actually invoke the
  6441. ** underlying sqlite3_io_methods.xFileControl method.
  6442. **
  6443. ** ^If the second parameter (zDbName) does not match the name of any
  6444. ** open database file, then SQLITE_ERROR is returned. ^This error
  6445. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6446. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6447. ** also return SQLITE_ERROR. There is no way to distinguish between
  6448. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6449. ** xFileControl method.
  6450. **
  6451. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6452. */
  6453. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6454. /*
  6455. ** CAPI3REF: Testing Interface
  6456. **
  6457. ** ^The sqlite3_test_control() interface is used to read out internal
  6458. ** state of SQLite and to inject faults into SQLite for testing
  6459. ** purposes. ^The first parameter is an operation code that determines
  6460. ** the number, meaning, and operation of all subsequent parameters.
  6461. **
  6462. ** This interface is not for use by applications. It exists solely
  6463. ** for verifying the correct operation of the SQLite library. Depending
  6464. ** on how the SQLite library is compiled, this interface might not exist.
  6465. **
  6466. ** The details of the operation codes, their meanings, the parameters
  6467. ** they take, and what they do are all subject to change without notice.
  6468. ** Unlike most of the SQLite API, this function is not guaranteed to
  6469. ** operate consistently from one release to the next.
  6470. */
  6471. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
  6472. /*
  6473. ** CAPI3REF: Testing Interface Operation Codes
  6474. **
  6475. ** These constants are the valid operation code parameters used
  6476. ** as the first argument to [sqlite3_test_control()].
  6477. **
  6478. ** These parameters and their meanings are subject to change
  6479. ** without notice. These values are for testing purposes only.
  6480. ** Applications should not use any of these parameters or the
  6481. ** [sqlite3_test_control()] interface.
  6482. */
  6483. #define SQLITE_TESTCTRL_FIRST 5
  6484. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6485. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6486. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6487. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6488. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6489. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6490. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6491. #define SQLITE_TESTCTRL_ASSERT 12
  6492. #define SQLITE_TESTCTRL_ALWAYS 13
  6493. #define SQLITE_TESTCTRL_RESERVE 14
  6494. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6495. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6496. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6497. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6498. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6499. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6500. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6501. #define SQLITE_TESTCTRL_BYTEORDER 22
  6502. #define SQLITE_TESTCTRL_ISINIT 23
  6503. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6504. #define SQLITE_TESTCTRL_IMPOSTER 25
  6505. #define SQLITE_TESTCTRL_LAST 25
  6506. /*
  6507. ** CAPI3REF: SQLite Runtime Status
  6508. **
  6509. ** ^These interfaces are used to retrieve runtime status information
  6510. ** about the performance of SQLite, and optionally to reset various
  6511. ** highwater marks. ^The first argument is an integer code for
  6512. ** the specific parameter to measure. ^(Recognized integer codes
  6513. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6514. ** ^The current value of the parameter is returned into *pCurrent.
  6515. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6516. ** resetFlag is true, then the highest record value is reset after
  6517. ** *pHighwater is written. ^(Some parameters do not record the highest
  6518. ** value. For those parameters
  6519. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6520. ** ^(Other parameters record only the highwater mark and not the current
  6521. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6522. **
  6523. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6524. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6525. **
  6526. ** If either the current value or the highwater mark is too large to
  6527. ** be represented by a 32-bit integer, then the values returned by
  6528. ** sqlite3_status() are undefined.
  6529. **
  6530. ** See also: [sqlite3_db_status()]
  6531. */
  6532. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6533. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  6534. int op,
  6535. sqlite3_int64 *pCurrent,
  6536. sqlite3_int64 *pHighwater,
  6537. int resetFlag
  6538. );
  6539. /*
  6540. ** CAPI3REF: Status Parameters
  6541. ** KEYWORDS: {status parameters}
  6542. **
  6543. ** These integer constants designate various run-time status parameters
  6544. ** that can be returned by [sqlite3_status()].
  6545. **
  6546. ** <dl>
  6547. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6548. ** <dd>This parameter is the current amount of memory checked out
  6549. ** using [sqlite3_malloc()], either directly or indirectly. The
  6550. ** figure includes calls made to [sqlite3_malloc()] by the application
  6551. ** and internal memory usage by the SQLite library. Scratch memory
  6552. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6553. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6554. ** this parameter. The amount returned is the sum of the allocation
  6555. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6556. **
  6557. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6558. ** <dd>This parameter records the largest memory allocation request
  6559. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6560. ** internal equivalents). Only the value returned in the
  6561. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6562. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6563. **
  6564. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6565. ** <dd>This parameter records the number of separate memory allocations
  6566. ** currently checked out.</dd>)^
  6567. **
  6568. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6569. ** <dd>This parameter returns the number of pages used out of the
  6570. ** [pagecache memory allocator] that was configured using
  6571. ** [SQLITE_CONFIG_PAGECACHE]. The
  6572. ** value returned is in pages, not in bytes.</dd>)^
  6573. **
  6574. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6575. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6576. ** <dd>This parameter returns the number of bytes of page cache
  6577. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6578. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6579. ** returned value includes allocations that overflowed because they
  6580. ** where too large (they were larger than the "sz" parameter to
  6581. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6582. ** no space was left in the page cache.</dd>)^
  6583. **
  6584. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6585. ** <dd>This parameter records the largest memory allocation request
  6586. ** handed to [pagecache memory allocator]. Only the value returned in the
  6587. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6588. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6589. **
  6590. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6591. ** <dd>This parameter returns the number of allocations used out of the
  6592. ** [scratch memory allocator] configured using
  6593. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6594. ** in bytes. Since a single thread may only have one scratch allocation
  6595. ** outstanding at time, this parameter also reports the number of threads
  6596. ** using scratch memory at the same time.</dd>)^
  6597. **
  6598. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6599. ** <dd>This parameter returns the number of bytes of scratch memory
  6600. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6601. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6602. ** returned include overflows because the requested allocation was too
  6603. ** larger (that is, because the requested allocation was larger than the
  6604. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6605. ** slots were available.
  6606. ** </dd>)^
  6607. **
  6608. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6609. ** <dd>This parameter records the largest memory allocation request
  6610. ** handed to [scratch memory allocator]. Only the value returned in the
  6611. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6612. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6613. **
  6614. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6615. ** <dd>This parameter records the deepest parser stack. It is only
  6616. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6617. ** </dl>
  6618. **
  6619. ** New status parameters may be added from time to time.
  6620. */
  6621. #define SQLITE_STATUS_MEMORY_USED 0
  6622. #define SQLITE_STATUS_PAGECACHE_USED 1
  6623. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6624. #define SQLITE_STATUS_SCRATCH_USED 3
  6625. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6626. #define SQLITE_STATUS_MALLOC_SIZE 5
  6627. #define SQLITE_STATUS_PARSER_STACK 6
  6628. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6629. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6630. #define SQLITE_STATUS_MALLOC_COUNT 9
  6631. /*
  6632. ** CAPI3REF: Database Connection Status
  6633. ** METHOD: sqlite3
  6634. **
  6635. ** ^This interface is used to retrieve runtime status information
  6636. ** about a single [database connection]. ^The first argument is the
  6637. ** database connection object to be interrogated. ^The second argument
  6638. ** is an integer constant, taken from the set of
  6639. ** [SQLITE_DBSTATUS options], that
  6640. ** determines the parameter to interrogate. The set of
  6641. ** [SQLITE_DBSTATUS options] is likely
  6642. ** to grow in future releases of SQLite.
  6643. **
  6644. ** ^The current value of the requested parameter is written into *pCur
  6645. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6646. ** the resetFlg is true, then the highest instantaneous value is
  6647. ** reset back down to the current value.
  6648. **
  6649. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6650. ** non-zero [error code] on failure.
  6651. **
  6652. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6653. */
  6654. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6655. /*
  6656. ** CAPI3REF: Status Parameters for database connections
  6657. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6658. **
  6659. ** These constants are the available integer "verbs" that can be passed as
  6660. ** the second argument to the [sqlite3_db_status()] interface.
  6661. **
  6662. ** New verbs may be added in future releases of SQLite. Existing verbs
  6663. ** might be discontinued. Applications should check the return code from
  6664. ** [sqlite3_db_status()] to make sure that the call worked.
  6665. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6666. ** if a discontinued or unsupported verb is invoked.
  6667. **
  6668. ** <dl>
  6669. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6670. ** <dd>This parameter returns the number of lookaside memory slots currently
  6671. ** checked out.</dd>)^
  6672. **
  6673. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6674. ** <dd>This parameter returns the number malloc attempts that were
  6675. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6676. ** the current value is always zero.)^
  6677. **
  6678. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6679. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6680. ** <dd>This parameter returns the number malloc attempts that might have
  6681. ** been satisfied using lookaside memory but failed due to the amount of
  6682. ** memory requested being larger than the lookaside slot size.
  6683. ** Only the high-water value is meaningful;
  6684. ** the current value is always zero.)^
  6685. **
  6686. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6687. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6688. ** <dd>This parameter returns the number malloc attempts that might have
  6689. ** been satisfied using lookaside memory but failed due to all lookaside
  6690. ** memory already being in use.
  6691. ** Only the high-water value is meaningful;
  6692. ** the current value is always zero.)^
  6693. **
  6694. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6695. ** <dd>This parameter returns the approximate number of bytes of heap
  6696. ** memory used by all pager caches associated with the database connection.)^
  6697. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6698. **
  6699. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6700. ** <dd>This parameter returns the approximate number of bytes of heap
  6701. ** memory used to store the schema for all databases associated
  6702. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6703. ** ^The full amount of memory used by the schemas is reported, even if the
  6704. ** schema memory is shared with other database connections due to
  6705. ** [shared cache mode] being enabled.
  6706. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6707. **
  6708. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6709. ** <dd>This parameter returns the approximate number of bytes of heap
  6710. ** and lookaside memory used by all prepared statements associated with
  6711. ** the database connection.)^
  6712. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6713. ** </dd>
  6714. **
  6715. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6716. ** <dd>This parameter returns the number of pager cache hits that have
  6717. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6718. ** is always 0.
  6719. ** </dd>
  6720. **
  6721. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6722. ** <dd>This parameter returns the number of pager cache misses that have
  6723. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6724. ** is always 0.
  6725. ** </dd>
  6726. **
  6727. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6728. ** <dd>This parameter returns the number of dirty cache entries that have
  6729. ** been written to disk. Specifically, the number of pages written to the
  6730. ** wal file in wal mode databases, or the number of pages written to the
  6731. ** database file in rollback mode databases. Any pages written as part of
  6732. ** transaction rollback or database recovery operations are not included.
  6733. ** If an IO or other error occurs while writing a page to disk, the effect
  6734. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6735. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6736. ** </dd>
  6737. **
  6738. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6739. ** <dd>This parameter returns zero for the current value if and only if
  6740. ** all foreign key constraints (deferred or immediate) have been
  6741. ** resolved.)^ ^The highwater mark is always 0.
  6742. ** </dd>
  6743. ** </dl>
  6744. */
  6745. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6746. #define SQLITE_DBSTATUS_CACHE_USED 1
  6747. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6748. #define SQLITE_DBSTATUS_STMT_USED 3
  6749. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6750. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6751. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6752. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6753. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6754. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6755. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6756. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6757. /*
  6758. ** CAPI3REF: Prepared Statement Status
  6759. ** METHOD: sqlite3_stmt
  6760. **
  6761. ** ^(Each prepared statement maintains various
  6762. ** [SQLITE_STMTSTATUS counters] that measure the number
  6763. ** of times it has performed specific operations.)^ These counters can
  6764. ** be used to monitor the performance characteristics of the prepared
  6765. ** statements. For example, if the number of table steps greatly exceeds
  6766. ** the number of table searches or result rows, that would tend to indicate
  6767. ** that the prepared statement is using a full table scan rather than
  6768. ** an index.
  6769. **
  6770. ** ^(This interface is used to retrieve and reset counter values from
  6771. ** a [prepared statement]. The first argument is the prepared statement
  6772. ** object to be interrogated. The second argument
  6773. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6774. ** to be interrogated.)^
  6775. ** ^The current value of the requested counter is returned.
  6776. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6777. ** interface call returns.
  6778. **
  6779. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6780. */
  6781. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6782. /*
  6783. ** CAPI3REF: Status Parameters for prepared statements
  6784. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6785. **
  6786. ** These preprocessor macros define integer codes that name counter
  6787. ** values associated with the [sqlite3_stmt_status()] interface.
  6788. ** The meanings of the various counters are as follows:
  6789. **
  6790. ** <dl>
  6791. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6792. ** <dd>^This is the number of times that SQLite has stepped forward in
  6793. ** a table as part of a full table scan. Large numbers for this counter
  6794. ** may indicate opportunities for performance improvement through
  6795. ** careful use of indices.</dd>
  6796. **
  6797. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6798. ** <dd>^This is the number of sort operations that have occurred.
  6799. ** A non-zero value in this counter may indicate an opportunity to
  6800. ** improvement performance through careful use of indices.</dd>
  6801. **
  6802. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6803. ** <dd>^This is the number of rows inserted into transient indices that
  6804. ** were created automatically in order to help joins run faster.
  6805. ** A non-zero value in this counter may indicate an opportunity to
  6806. ** improvement performance by adding permanent indices that do not
  6807. ** need to be reinitialized each time the statement is run.</dd>
  6808. **
  6809. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6810. ** <dd>^This is the number of virtual machine operations executed
  6811. ** by the prepared statement if that number is less than or equal
  6812. ** to 2147483647. The number of virtual machine operations can be
  6813. ** used as a proxy for the total work done by the prepared statement.
  6814. ** If the number of virtual machine operations exceeds 2147483647
  6815. ** then the value returned by this statement status code is undefined.
  6816. ** </dd>
  6817. ** </dl>
  6818. */
  6819. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6820. #define SQLITE_STMTSTATUS_SORT 2
  6821. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6822. #define SQLITE_STMTSTATUS_VM_STEP 4
  6823. /*
  6824. ** CAPI3REF: Custom Page Cache Object
  6825. **
  6826. ** The sqlite3_pcache type is opaque. It is implemented by
  6827. ** the pluggable module. The SQLite core has no knowledge of
  6828. ** its size or internal structure and never deals with the
  6829. ** sqlite3_pcache object except by holding and passing pointers
  6830. ** to the object.
  6831. **
  6832. ** See [sqlite3_pcache_methods2] for additional information.
  6833. */
  6834. typedef struct sqlite3_pcache sqlite3_pcache;
  6835. /*
  6836. ** CAPI3REF: Custom Page Cache Object
  6837. **
  6838. ** The sqlite3_pcache_page object represents a single page in the
  6839. ** page cache. The page cache will allocate instances of this
  6840. ** object. Various methods of the page cache use pointers to instances
  6841. ** of this object as parameters or as their return value.
  6842. **
  6843. ** See [sqlite3_pcache_methods2] for additional information.
  6844. */
  6845. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6846. struct sqlite3_pcache_page {
  6847. void *pBuf; /* The content of the page */
  6848. void *pExtra; /* Extra information associated with the page */
  6849. };
  6850. /*
  6851. ** CAPI3REF: Application Defined Page Cache.
  6852. ** KEYWORDS: {page cache}
  6853. **
  6854. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6855. ** register an alternative page cache implementation by passing in an
  6856. ** instance of the sqlite3_pcache_methods2 structure.)^
  6857. ** In many applications, most of the heap memory allocated by
  6858. ** SQLite is used for the page cache.
  6859. ** By implementing a
  6860. ** custom page cache using this API, an application can better control
  6861. ** the amount of memory consumed by SQLite, the way in which
  6862. ** that memory is allocated and released, and the policies used to
  6863. ** determine exactly which parts of a database file are cached and for
  6864. ** how long.
  6865. **
  6866. ** The alternative page cache mechanism is an
  6867. ** extreme measure that is only needed by the most demanding applications.
  6868. ** The built-in page cache is recommended for most uses.
  6869. **
  6870. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6871. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6872. ** the application may discard the parameter after the call to
  6873. ** [sqlite3_config()] returns.)^
  6874. **
  6875. ** [[the xInit() page cache method]]
  6876. ** ^(The xInit() method is called once for each effective
  6877. ** call to [sqlite3_initialize()])^
  6878. ** (usually only once during the lifetime of the process). ^(The xInit()
  6879. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6880. ** The intent of the xInit() method is to set up global data structures
  6881. ** required by the custom page cache implementation.
  6882. ** ^(If the xInit() method is NULL, then the
  6883. ** built-in default page cache is used instead of the application defined
  6884. ** page cache.)^
  6885. **
  6886. ** [[the xShutdown() page cache method]]
  6887. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6888. ** It can be used to clean up
  6889. ** any outstanding resources before process shutdown, if required.
  6890. ** ^The xShutdown() method may be NULL.
  6891. **
  6892. ** ^SQLite automatically serializes calls to the xInit method,
  6893. ** so the xInit method need not be threadsafe. ^The
  6894. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6895. ** not need to be threadsafe either. All other methods must be threadsafe
  6896. ** in multithreaded applications.
  6897. **
  6898. ** ^SQLite will never invoke xInit() more than once without an intervening
  6899. ** call to xShutdown().
  6900. **
  6901. ** [[the xCreate() page cache methods]]
  6902. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6903. ** SQLite will typically create one cache instance for each open database file,
  6904. ** though this is not guaranteed. ^The
  6905. ** first parameter, szPage, is the size in bytes of the pages that must
  6906. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6907. ** second parameter szExtra is a number of bytes of extra storage
  6908. ** associated with each page cache entry. ^The szExtra parameter will
  6909. ** a number less than 250. SQLite will use the
  6910. ** extra szExtra bytes on each page to store metadata about the underlying
  6911. ** database page on disk. The value passed into szExtra depends
  6912. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6913. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6914. ** created will be used to cache database pages of a file stored on disk, or
  6915. ** false if it is used for an in-memory database. The cache implementation
  6916. ** does not have to do anything special based with the value of bPurgeable;
  6917. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6918. ** never invoke xUnpin() except to deliberately delete a page.
  6919. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6920. ** false will always have the "discard" flag set to true.
  6921. ** ^Hence, a cache created with bPurgeable false will
  6922. ** never contain any unpinned pages.
  6923. **
  6924. ** [[the xCachesize() page cache method]]
  6925. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6926. ** suggested maximum cache-size (number of pages stored by) the cache
  6927. ** instance passed as the first argument. This is the value configured using
  6928. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6929. ** parameter, the implementation is not required to do anything with this
  6930. ** value; it is advisory only.
  6931. **
  6932. ** [[the xPagecount() page cache methods]]
  6933. ** The xPagecount() method must return the number of pages currently
  6934. ** stored in the cache, both pinned and unpinned.
  6935. **
  6936. ** [[the xFetch() page cache methods]]
  6937. ** The xFetch() method locates a page in the cache and returns a pointer to
  6938. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6939. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6940. ** pointer to a buffer of szPage bytes used to store the content of a
  6941. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6942. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6943. ** for each entry in the page cache.
  6944. **
  6945. ** The page to be fetched is determined by the key. ^The minimum key value
  6946. ** is 1. After it has been retrieved using xFetch, the page is considered
  6947. ** to be "pinned".
  6948. **
  6949. ** If the requested page is already in the page cache, then the page cache
  6950. ** implementation must return a pointer to the page buffer with its content
  6951. ** intact. If the requested page is not already in the cache, then the
  6952. ** cache implementation should use the value of the createFlag
  6953. ** parameter to help it determined what action to take:
  6954. **
  6955. ** <table border=1 width=85% align=center>
  6956. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6957. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6958. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6959. ** Otherwise return NULL.
  6960. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6961. ** NULL if allocating a new page is effectively impossible.
  6962. ** </table>
  6963. **
  6964. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6965. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6966. ** failed.)^ In between the to xFetch() calls, SQLite may
  6967. ** attempt to unpin one or more cache pages by spilling the content of
  6968. ** pinned pages to disk and synching the operating system disk cache.
  6969. **
  6970. ** [[the xUnpin() page cache method]]
  6971. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6972. ** as its second argument. If the third parameter, discard, is non-zero,
  6973. ** then the page must be evicted from the cache.
  6974. ** ^If the discard parameter is
  6975. ** zero, then the page may be discarded or retained at the discretion of
  6976. ** page cache implementation. ^The page cache implementation
  6977. ** may choose to evict unpinned pages at any time.
  6978. **
  6979. ** The cache must not perform any reference counting. A single
  6980. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6981. ** to xFetch().
  6982. **
  6983. ** [[the xRekey() page cache methods]]
  6984. ** The xRekey() method is used to change the key value associated with the
  6985. ** page passed as the second argument. If the cache
  6986. ** previously contains an entry associated with newKey, it must be
  6987. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6988. ** to be pinned.
  6989. **
  6990. ** When SQLite calls the xTruncate() method, the cache must discard all
  6991. ** existing cache entries with page numbers (keys) greater than or equal
  6992. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6993. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6994. ** they can be safely discarded.
  6995. **
  6996. ** [[the xDestroy() page cache method]]
  6997. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6998. ** All resources associated with the specified cache should be freed. ^After
  6999. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7000. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  7001. ** functions.
  7002. **
  7003. ** [[the xShrink() page cache method]]
  7004. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  7005. ** free up as much of heap memory as possible. The page cache implementation
  7006. ** is not obligated to free any memory, but well-behaved implementations should
  7007. ** do their best.
  7008. */
  7009. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  7010. struct sqlite3_pcache_methods2 {
  7011. int iVersion;
  7012. void *pArg;
  7013. int (*xInit)(void*);
  7014. void (*xShutdown)(void*);
  7015. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  7016. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7017. int (*xPagecount)(sqlite3_pcache*);
  7018. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7019. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  7020. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  7021. unsigned oldKey, unsigned newKey);
  7022. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7023. void (*xDestroy)(sqlite3_pcache*);
  7024. void (*xShrink)(sqlite3_pcache*);
  7025. };
  7026. /*
  7027. ** This is the obsolete pcache_methods object that has now been replaced
  7028. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  7029. ** retained in the header file for backwards compatibility only.
  7030. */
  7031. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7032. struct sqlite3_pcache_methods {
  7033. void *pArg;
  7034. int (*xInit)(void*);
  7035. void (*xShutdown)(void*);
  7036. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7037. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7038. int (*xPagecount)(sqlite3_pcache*);
  7039. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7040. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7041. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7042. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7043. void (*xDestroy)(sqlite3_pcache*);
  7044. };
  7045. /*
  7046. ** CAPI3REF: Online Backup Object
  7047. **
  7048. ** The sqlite3_backup object records state information about an ongoing
  7049. ** online backup operation. ^The sqlite3_backup object is created by
  7050. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  7051. ** [sqlite3_backup_finish()].
  7052. **
  7053. ** See Also: [Using the SQLite Online Backup API]
  7054. */
  7055. typedef struct sqlite3_backup sqlite3_backup;
  7056. /*
  7057. ** CAPI3REF: Online Backup API.
  7058. **
  7059. ** The backup API copies the content of one database into another.
  7060. ** It is useful either for creating backups of databases or
  7061. ** for copying in-memory databases to or from persistent files.
  7062. **
  7063. ** See Also: [Using the SQLite Online Backup API]
  7064. **
  7065. ** ^SQLite holds a write transaction open on the destination database file
  7066. ** for the duration of the backup operation.
  7067. ** ^The source database is read-locked only while it is being read;
  7068. ** it is not locked continuously for the entire backup operation.
  7069. ** ^Thus, the backup may be performed on a live source database without
  7070. ** preventing other database connections from
  7071. ** reading or writing to the source database while the backup is underway.
  7072. **
  7073. ** ^(To perform a backup operation:
  7074. ** <ol>
  7075. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7076. ** backup,
  7077. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7078. ** the data between the two databases, and finally
  7079. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7080. ** associated with the backup operation.
  7081. ** </ol>)^
  7082. ** There should be exactly one call to sqlite3_backup_finish() for each
  7083. ** successful call to sqlite3_backup_init().
  7084. **
  7085. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7086. **
  7087. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7088. ** [database connection] associated with the destination database
  7089. ** and the database name, respectively.
  7090. ** ^The database name is "main" for the main database, "temp" for the
  7091. ** temporary database, or the name specified after the AS keyword in
  7092. ** an [ATTACH] statement for an attached database.
  7093. ** ^The S and M arguments passed to
  7094. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7095. ** and database name of the source database, respectively.
  7096. ** ^The source and destination [database connections] (parameters S and D)
  7097. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7098. ** an error.
  7099. **
  7100. ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
  7101. ** there is already a read or read-write transaction open on the
  7102. ** destination database.
  7103. **
  7104. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7105. ** returned and an error code and error message are stored in the
  7106. ** destination [database connection] D.
  7107. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7108. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7109. ** [sqlite3_errmsg16()] functions.
  7110. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7111. ** [sqlite3_backup] object.
  7112. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7113. ** sqlite3_backup_finish() functions to perform the specified backup
  7114. ** operation.
  7115. **
  7116. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7117. **
  7118. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7119. ** the source and destination databases specified by [sqlite3_backup] object B.
  7120. ** ^If N is negative, all remaining source pages are copied.
  7121. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7122. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7123. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7124. ** from source to destination, then it returns [SQLITE_DONE].
  7125. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7126. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7127. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7128. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7129. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7130. **
  7131. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7132. ** <ol>
  7133. ** <li> the destination database was opened read-only, or
  7134. ** <li> the destination database is using write-ahead-log journaling
  7135. ** and the destination and source page sizes differ, or
  7136. ** <li> the destination database is an in-memory database and the
  7137. ** destination and source page sizes differ.
  7138. ** </ol>)^
  7139. **
  7140. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7141. ** the [sqlite3_busy_handler | busy-handler function]
  7142. ** is invoked (if one is specified). ^If the
  7143. ** busy-handler returns non-zero before the lock is available, then
  7144. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7145. ** sqlite3_backup_step() can be retried later. ^If the source
  7146. ** [database connection]
  7147. ** is being used to write to the source database when sqlite3_backup_step()
  7148. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7149. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7150. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7151. ** [SQLITE_READONLY] is returned, then
  7152. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7153. ** errors are considered fatal.)^ The application must accept
  7154. ** that the backup operation has failed and pass the backup operation handle
  7155. ** to the sqlite3_backup_finish() to release associated resources.
  7156. **
  7157. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7158. ** on the destination file. ^The exclusive lock is not released until either
  7159. ** sqlite3_backup_finish() is called or the backup operation is complete
  7160. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7161. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7162. ** lasts for the duration of the sqlite3_backup_step() call.
  7163. ** ^Because the source database is not locked between calls to
  7164. ** sqlite3_backup_step(), the source database may be modified mid-way
  7165. ** through the backup process. ^If the source database is modified by an
  7166. ** external process or via a database connection other than the one being
  7167. ** used by the backup operation, then the backup will be automatically
  7168. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7169. ** database is modified by the using the same database connection as is used
  7170. ** by the backup operation, then the backup database is automatically
  7171. ** updated at the same time.
  7172. **
  7173. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7174. **
  7175. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7176. ** application wishes to abandon the backup operation, the application
  7177. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7178. ** ^The sqlite3_backup_finish() interfaces releases all
  7179. ** resources associated with the [sqlite3_backup] object.
  7180. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7181. ** active write-transaction on the destination database is rolled back.
  7182. ** The [sqlite3_backup] object is invalid
  7183. ** and may not be used following a call to sqlite3_backup_finish().
  7184. **
  7185. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7186. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7187. ** sqlite3_backup_step() completed.
  7188. ** ^If an out-of-memory condition or IO error occurred during any prior
  7189. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7190. ** sqlite3_backup_finish() returns the corresponding [error code].
  7191. **
  7192. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7193. ** is not a permanent error and does not affect the return value of
  7194. ** sqlite3_backup_finish().
  7195. **
  7196. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7197. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7198. **
  7199. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7200. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7201. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7202. ** in the source database at the conclusion of the most recent
  7203. ** sqlite3_backup_step().
  7204. ** ^(The values returned by these functions are only updated by
  7205. ** sqlite3_backup_step(). If the source database is modified in a way that
  7206. ** changes the size of the source database or the number of pages remaining,
  7207. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7208. ** and sqlite3_backup_remaining() until after the next
  7209. ** sqlite3_backup_step().)^
  7210. **
  7211. ** <b>Concurrent Usage of Database Handles</b>
  7212. **
  7213. ** ^The source [database connection] may be used by the application for other
  7214. ** purposes while a backup operation is underway or being initialized.
  7215. ** ^If SQLite is compiled and configured to support threadsafe database
  7216. ** connections, then the source database connection may be used concurrently
  7217. ** from within other threads.
  7218. **
  7219. ** However, the application must guarantee that the destination
  7220. ** [database connection] is not passed to any other API (by any thread) after
  7221. ** sqlite3_backup_init() is called and before the corresponding call to
  7222. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7223. ** if the application incorrectly accesses the destination [database connection]
  7224. ** and so no error code is reported, but the operations may malfunction
  7225. ** nevertheless. Use of the destination database connection while a
  7226. ** backup is in progress might also also cause a mutex deadlock.
  7227. **
  7228. ** If running in [shared cache mode], the application must
  7229. ** guarantee that the shared cache used by the destination database
  7230. ** is not accessed while the backup is running. In practice this means
  7231. ** that the application must guarantee that the disk file being
  7232. ** backed up to is not accessed by any connection within the process,
  7233. ** not just the specific connection that was passed to sqlite3_backup_init().
  7234. **
  7235. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7236. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7237. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7238. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7239. ** same time as another thread is invoking sqlite3_backup_step() it is
  7240. ** possible that they return invalid values.
  7241. */
  7242. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  7243. sqlite3 *pDest, /* Destination database handle */
  7244. const char *zDestName, /* Destination database name */
  7245. sqlite3 *pSource, /* Source database handle */
  7246. const char *zSourceName /* Source database name */
  7247. );
  7248. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7249. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
  7250. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
  7251. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
  7252. /*
  7253. ** CAPI3REF: Unlock Notification
  7254. ** METHOD: sqlite3
  7255. **
  7256. ** ^When running in shared-cache mode, a database operation may fail with
  7257. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7258. ** individual tables within the shared-cache cannot be obtained. See
  7259. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7260. ** ^This API may be used to register a callback that SQLite will invoke
  7261. ** when the connection currently holding the required lock relinquishes it.
  7262. ** ^This API is only available if the library was compiled with the
  7263. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7264. **
  7265. ** See Also: [Using the SQLite Unlock Notification Feature].
  7266. **
  7267. ** ^Shared-cache locks are released when a database connection concludes
  7268. ** its current transaction, either by committing it or rolling it back.
  7269. **
  7270. ** ^When a connection (known as the blocked connection) fails to obtain a
  7271. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7272. ** identity of the database connection (the blocking connection) that
  7273. ** has locked the required resource is stored internally. ^After an
  7274. ** application receives an SQLITE_LOCKED error, it may call the
  7275. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7276. ** the first argument to register for a callback that will be invoked
  7277. ** when the blocking connections current transaction is concluded. ^The
  7278. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7279. ** call that concludes the blocking connections transaction.
  7280. **
  7281. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7282. ** there is a chance that the blocking connection will have already
  7283. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7284. ** If this happens, then the specified callback is invoked immediately,
  7285. ** from within the call to sqlite3_unlock_notify().)^
  7286. **
  7287. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7288. ** shared-cache table, and more than one other connection currently holds
  7289. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7290. ** the other connections to use as the blocking connection.
  7291. **
  7292. ** ^(There may be at most one unlock-notify callback registered by a
  7293. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7294. ** blocked connection already has a registered unlock-notify callback,
  7295. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7296. ** called with a NULL pointer as its second argument, then any existing
  7297. ** unlock-notify callback is canceled. ^The blocked connections
  7298. ** unlock-notify callback may also be canceled by closing the blocked
  7299. ** connection using [sqlite3_close()].
  7300. **
  7301. ** The unlock-notify callback is not reentrant. If an application invokes
  7302. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7303. ** crash or deadlock may be the result.
  7304. **
  7305. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7306. ** returns SQLITE_OK.
  7307. **
  7308. ** <b>Callback Invocation Details</b>
  7309. **
  7310. ** When an unlock-notify callback is registered, the application provides a
  7311. ** single void* pointer that is passed to the callback when it is invoked.
  7312. ** However, the signature of the callback function allows SQLite to pass
  7313. ** it an array of void* context pointers. The first argument passed to
  7314. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7315. ** and the second is the number of entries in the array.
  7316. **
  7317. ** When a blocking connections transaction is concluded, there may be
  7318. ** more than one blocked connection that has registered for an unlock-notify
  7319. ** callback. ^If two or more such blocked connections have specified the
  7320. ** same callback function, then instead of invoking the callback function
  7321. ** multiple times, it is invoked once with the set of void* context pointers
  7322. ** specified by the blocked connections bundled together into an array.
  7323. ** This gives the application an opportunity to prioritize any actions
  7324. ** related to the set of unblocked database connections.
  7325. **
  7326. ** <b>Deadlock Detection</b>
  7327. **
  7328. ** Assuming that after registering for an unlock-notify callback a
  7329. ** database waits for the callback to be issued before taking any further
  7330. ** action (a reasonable assumption), then using this API may cause the
  7331. ** application to deadlock. For example, if connection X is waiting for
  7332. ** connection Y's transaction to be concluded, and similarly connection
  7333. ** Y is waiting on connection X's transaction, then neither connection
  7334. ** will proceed and the system may remain deadlocked indefinitely.
  7335. **
  7336. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7337. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7338. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7339. ** unlock-notify callback is registered. The system is said to be in
  7340. ** a deadlocked state if connection A has registered for an unlock-notify
  7341. ** callback on the conclusion of connection B's transaction, and connection
  7342. ** B has itself registered for an unlock-notify callback when connection
  7343. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7344. ** the system is also considered to be deadlocked if connection B has
  7345. ** registered for an unlock-notify callback on the conclusion of connection
  7346. ** C's transaction, where connection C is waiting on connection A. ^Any
  7347. ** number of levels of indirection are allowed.
  7348. **
  7349. ** <b>The "DROP TABLE" Exception</b>
  7350. **
  7351. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7352. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7353. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7354. ** SQLite checks if there are any currently executing SELECT statements
  7355. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7356. ** returned. In this case there is no "blocking connection", so invoking
  7357. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7358. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7359. ** or "DROP INDEX" query, an infinite loop might be the result.
  7360. **
  7361. ** One way around this problem is to check the extended error code returned
  7362. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7363. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7364. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7365. ** SQLITE_LOCKED.)^
  7366. */
  7367. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  7368. sqlite3 *pBlocked, /* Waiting connection */
  7369. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7370. void *pNotifyArg /* Argument to pass to xNotify */
  7371. );
  7372. /*
  7373. ** CAPI3REF: String Comparison
  7374. **
  7375. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7376. ** and extensions to compare the contents of two buffers containing UTF-8
  7377. ** strings in a case-independent fashion, using the same definition of "case
  7378. ** independence" that SQLite uses internally when comparing identifiers.
  7379. */
  7380. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
  7381. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
  7382. /*
  7383. ** CAPI3REF: String Globbing
  7384. *
  7385. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7386. ** the glob pattern P, and it returns non-zero if string X does not match
  7387. ** the glob pattern P. ^The definition of glob pattern matching used in
  7388. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7389. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7390. ** sensitive.
  7391. **
  7392. ** Note that this routine returns zero on a match and non-zero if the strings
  7393. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7394. */
  7395. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
  7396. /*
  7397. ** CAPI3REF: Error Logging Interface
  7398. **
  7399. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7400. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7401. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7402. ** used with [sqlite3_snprintf()] to generate the final output string.
  7403. **
  7404. ** The sqlite3_log() interface is intended for use by extensions such as
  7405. ** virtual tables, collating functions, and SQL functions. While there is
  7406. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7407. ** is considered bad form.
  7408. **
  7409. ** The zFormat string must not be NULL.
  7410. **
  7411. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7412. ** will not use dynamically allocated memory. The log message is stored in
  7413. ** a fixed-length buffer on the stack. If the log message is longer than
  7414. ** a few hundred characters, it will be truncated to the length of the
  7415. ** buffer.
  7416. */
  7417. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
  7418. /*
  7419. ** CAPI3REF: Write-Ahead Log Commit Hook
  7420. ** METHOD: sqlite3
  7421. **
  7422. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7423. ** is invoked each time data is committed to a database in wal mode.
  7424. **
  7425. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7426. ** the associated write-lock on the database released)^, so the implementation
  7427. ** may read, write or [checkpoint] the database as required.
  7428. **
  7429. ** ^The first parameter passed to the callback function when it is invoked
  7430. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7431. ** registering the callback. ^The second is a copy of the database handle.
  7432. ** ^The third parameter is the name of the database that was written to -
  7433. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7434. ** is the number of pages currently in the write-ahead log file,
  7435. ** including those that were just committed.
  7436. **
  7437. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7438. ** code is returned, that error will propagate back up through the
  7439. ** SQLite code base to cause the statement that provoked the callback
  7440. ** to report an error, though the commit will have still occurred. If the
  7441. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7442. ** that does not correspond to any valid SQLite error code, the results
  7443. ** are undefined.
  7444. **
  7445. ** A single database handle may have at most a single write-ahead log callback
  7446. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7447. ** previously registered write-ahead log callback. ^Note that the
  7448. ** [sqlite3_wal_autocheckpoint()] interface and the
  7449. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7450. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7451. */
  7452. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7453. sqlite3*,
  7454. int(*)(void *,sqlite3*,const char*,int),
  7455. void*
  7456. );
  7457. /*
  7458. ** CAPI3REF: Configure an auto-checkpoint
  7459. ** METHOD: sqlite3
  7460. **
  7461. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7462. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7463. ** to automatically [checkpoint]
  7464. ** after committing a transaction if there are N or
  7465. ** more frames in the [write-ahead log] file. ^Passing zero or
  7466. ** a negative value as the nFrame parameter disables automatic
  7467. ** checkpoints entirely.
  7468. **
  7469. ** ^The callback registered by this function replaces any existing callback
  7470. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7471. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7472. ** configured by this function.
  7473. **
  7474. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7475. ** from SQL.
  7476. **
  7477. ** ^Checkpoints initiated by this mechanism are
  7478. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7479. **
  7480. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7481. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7482. ** pages. The use of this interface
  7483. ** is only necessary if the default setting is found to be suboptimal
  7484. ** for a particular application.
  7485. */
  7486. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7487. /*
  7488. ** CAPI3REF: Checkpoint a database
  7489. ** METHOD: sqlite3
  7490. **
  7491. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7492. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7493. **
  7494. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7495. ** [write-ahead log] for database X on [database connection] D to be
  7496. ** transferred into the database file and for the write-ahead log to
  7497. ** be reset. See the [checkpointing] documentation for addition
  7498. ** information.
  7499. **
  7500. ** This interface used to be the only way to cause a checkpoint to
  7501. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7502. ** interface was added. This interface is retained for backwards
  7503. ** compatibility and as a convenience for applications that need to manually
  7504. ** start a callback but which do not need the full power (and corresponding
  7505. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7506. */
  7507. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7508. /*
  7509. ** CAPI3REF: Checkpoint a database
  7510. ** METHOD: sqlite3
  7511. **
  7512. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7513. ** operation on database X of [database connection] D in mode M. Status
  7514. ** information is written back into integers pointed to by L and C.)^
  7515. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7516. **
  7517. ** <dl>
  7518. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7519. ** ^Checkpoint as many frames as possible without waiting for any database
  7520. ** readers or writers to finish, then sync the database file if all frames
  7521. ** in the log were checkpointed. ^The [busy-handler callback]
  7522. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7523. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7524. ** if there are concurrent readers or writers.
  7525. **
  7526. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7527. ** ^This mode blocks (it invokes the
  7528. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7529. ** database writer and all readers are reading from the most recent database
  7530. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7531. ** database file. ^This mode blocks new database writers while it is pending,
  7532. ** but new database readers are allowed to continue unimpeded.
  7533. **
  7534. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7535. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7536. ** that after checkpointing the log file it blocks (calls the
  7537. ** [busy-handler callback])
  7538. ** until all readers are reading from the database file only. ^This ensures
  7539. ** that the next writer will restart the log file from the beginning.
  7540. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7541. ** database writer attempts while it is pending, but does not impede readers.
  7542. **
  7543. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7544. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7545. ** addition that it also truncates the log file to zero bytes just prior
  7546. ** to a successful return.
  7547. ** </dl>
  7548. **
  7549. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7550. ** the log file or to -1 if the checkpoint could not run because
  7551. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7552. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7553. ** log file (including any that were already checkpointed before the function
  7554. ** was called) or to -1 if the checkpoint could not run due to an error or
  7555. ** because the database is not in WAL mode. ^Note that upon successful
  7556. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7557. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7558. **
  7559. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7560. ** any other process is running a checkpoint operation at the same time, the
  7561. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7562. ** busy-handler configured, it will not be invoked in this case.
  7563. **
  7564. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7565. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  7566. ** obtained immediately, and a busy-handler is configured, it is invoked and
  7567. ** the writer lock retried until either the busy-handler returns 0 or the lock
  7568. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  7569. ** database readers as described above. ^If the busy-handler returns 0 before
  7570. ** the writer lock is obtained or while waiting for database readers, the
  7571. ** checkpoint operation proceeds from that point in the same way as
  7572. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7573. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  7574. **
  7575. ** ^If parameter zDb is NULL or points to a zero length string, then the
  7576. ** specified operation is attempted on all WAL databases [attached] to
  7577. ** [database connection] db. In this case the
  7578. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  7579. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7580. ** attached WAL databases, the operation is still attempted on any remaining
  7581. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  7582. ** error occurs while processing an attached database, processing is abandoned
  7583. ** and the error code is returned to the caller immediately. ^If no error
  7584. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7585. ** databases, SQLITE_OK is returned.
  7586. **
  7587. ** ^If database zDb is the name of an attached database that is not in WAL
  7588. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  7589. ** zDb is not NULL (or a zero length string) and is not the name of any
  7590. ** attached database, SQLITE_ERROR is returned to the caller.
  7591. **
  7592. ** ^Unless it returns SQLITE_MISUSE,
  7593. ** the sqlite3_wal_checkpoint_v2() interface
  7594. ** sets the error information that is queried by
  7595. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  7596. **
  7597. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  7598. ** from SQL.
  7599. */
  7600. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  7601. sqlite3 *db, /* Database handle */
  7602. const char *zDb, /* Name of attached database (or NULL) */
  7603. int eMode, /* SQLITE_CHECKPOINT_* value */
  7604. int *pnLog, /* OUT: Size of WAL log in frames */
  7605. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7606. );
  7607. /*
  7608. ** CAPI3REF: Checkpoint Mode Values
  7609. ** KEYWORDS: {checkpoint mode}
  7610. **
  7611. ** These constants define all valid values for the "checkpoint mode" passed
  7612. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  7613. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  7614. ** meaning of each of these checkpoint modes.
  7615. */
  7616. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  7617. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  7618. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  7619. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  7620. /*
  7621. ** CAPI3REF: Virtual Table Interface Configuration
  7622. **
  7623. ** This function may be called by either the [xConnect] or [xCreate] method
  7624. ** of a [virtual table] implementation to configure
  7625. ** various facets of the virtual table interface.
  7626. **
  7627. ** If this interface is invoked outside the context of an xConnect or
  7628. ** xCreate virtual table method then the behavior is undefined.
  7629. **
  7630. ** At present, there is only one option that may be configured using
  7631. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7632. ** may be added in the future.
  7633. */
  7634. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
  7635. /*
  7636. ** CAPI3REF: Virtual Table Configuration Options
  7637. **
  7638. ** These macros define the various options to the
  7639. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7640. ** can use to customize and optimize their behavior.
  7641. **
  7642. ** <dl>
  7643. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7644. ** <dd>Calls of the form
  7645. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7646. ** where X is an integer. If X is zero, then the [virtual table] whose
  7647. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7648. ** support constraints. In this configuration (which is the default) if
  7649. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7650. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7651. ** specified as part of the users SQL statement, regardless of the actual
  7652. ** ON CONFLICT mode specified.
  7653. **
  7654. ** If X is non-zero, then the virtual table implementation guarantees
  7655. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7656. ** any modifications to internal or persistent data structures have been made.
  7657. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7658. ** is able to roll back a statement or database transaction, and abandon
  7659. ** or continue processing the current SQL statement as appropriate.
  7660. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7661. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7662. ** had been ABORT.
  7663. **
  7664. ** Virtual table implementations that are required to handle OR REPLACE
  7665. ** must do so within the [xUpdate] method. If a call to the
  7666. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7667. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7668. ** silently replace the appropriate rows within the xUpdate callback and
  7669. ** return SQLITE_OK. Or, if this is not possible, it may return
  7670. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7671. ** constraint handling.
  7672. ** </dl>
  7673. */
  7674. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7675. /*
  7676. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7677. **
  7678. ** This function may only be called from within a call to the [xUpdate] method
  7679. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7680. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7681. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7682. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7683. ** [virtual table].
  7684. */
  7685. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
  7686. /*
  7687. ** CAPI3REF: Conflict resolution modes
  7688. ** KEYWORDS: {conflict resolution mode}
  7689. **
  7690. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7691. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7692. ** is for the SQL statement being evaluated.
  7693. **
  7694. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7695. ** return value from the [sqlite3_set_authorizer()] callback and that
  7696. ** [SQLITE_ABORT] is also a [result code].
  7697. */
  7698. #define SQLITE_ROLLBACK 1
  7699. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7700. #define SQLITE_FAIL 3
  7701. /* #define SQLITE_ABORT 4 // Also an error code */
  7702. #define SQLITE_REPLACE 5
  7703. /*
  7704. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  7705. ** KEYWORDS: {scanstatus options}
  7706. **
  7707. ** The following constants can be used for the T parameter to the
  7708. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  7709. ** different metric for sqlite3_stmt_scanstatus() to return.
  7710. **
  7711. ** When the value returned to V is a string, space to hold that string is
  7712. ** managed by the prepared statement S and will be automatically freed when
  7713. ** S is finalized.
  7714. **
  7715. ** <dl>
  7716. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  7717. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  7718. ** set to the total number of times that the X-th loop has run.</dd>
  7719. **
  7720. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  7721. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  7722. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  7723. **
  7724. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  7725. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  7726. ** query planner's estimate for the average number of rows output from each
  7727. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  7728. ** then this value will approximate the quotient NVISIT/NLOOP and the
  7729. ** product of this value for all prior loops with the same SELECTID will
  7730. ** be the NLOOP value for the current loop.
  7731. **
  7732. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  7733. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7734. ** to a zero-terminated UTF-8 string containing the name of the index or table
  7735. ** used for the X-th loop.
  7736. **
  7737. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  7738. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7739. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  7740. ** description for the X-th loop.
  7741. **
  7742. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  7743. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  7744. ** "select-id" for the X-th loop. The select-id identifies which query or
  7745. ** subquery the loop is part of. The main query has a select-id of zero.
  7746. ** The select-id is the same value as is output in the first column
  7747. ** of an [EXPLAIN QUERY PLAN] query.
  7748. ** </dl>
  7749. */
  7750. #define SQLITE_SCANSTAT_NLOOP 0
  7751. #define SQLITE_SCANSTAT_NVISIT 1
  7752. #define SQLITE_SCANSTAT_EST 2
  7753. #define SQLITE_SCANSTAT_NAME 3
  7754. #define SQLITE_SCANSTAT_EXPLAIN 4
  7755. #define SQLITE_SCANSTAT_SELECTID 5
  7756. /*
  7757. ** CAPI3REF: Prepared Statement Scan Status
  7758. ** METHOD: sqlite3_stmt
  7759. **
  7760. ** This interface returns information about the predicted and measured
  7761. ** performance for pStmt. Advanced applications can use this
  7762. ** interface to compare the predicted and the measured performance and
  7763. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  7764. **
  7765. ** Since this interface is expected to be rarely used, it is only
  7766. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  7767. ** compile-time option.
  7768. **
  7769. ** The "iScanStatusOp" parameter determines which status information to return.
  7770. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  7771. ** of this interface is undefined.
  7772. ** ^The requested measurement is written into a variable pointed to by
  7773. ** the "pOut" parameter.
  7774. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  7775. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  7776. ** zero or greater than or equal to the total number of loops used to implement
  7777. ** the statement - a non-zero value is returned and the variable that pOut
  7778. ** points to is unchanged.
  7779. **
  7780. ** ^Statistics might not be available for all loops in all statements. ^In cases
  7781. ** where there exist loops with no available statistics, this function behaves
  7782. ** as if the loop did not exist - it returns non-zero and leave the variable
  7783. ** that pOut points to unchanged.
  7784. **
  7785. ** See also: [sqlite3_stmt_scanstatus_reset()]
  7786. */
  7787. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  7788. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  7789. int idx, /* Index of loop to report on */
  7790. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  7791. void *pOut /* Result written here */
  7792. );
  7793. /*
  7794. ** CAPI3REF: Zero Scan-Status Counters
  7795. ** METHOD: sqlite3_stmt
  7796. **
  7797. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  7798. **
  7799. ** This API is only available if the library is built with pre-processor
  7800. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  7801. */
  7802. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  7803. /*
  7804. ** Undo the hack that converts floating point types to integer for
  7805. ** builds on processors without floating point support.
  7806. */
  7807. #ifdef SQLITE_OMIT_FLOATING_POINT
  7808. # undef double
  7809. #endif
  7810. #if 0
  7811. } /* End of the 'extern "C"' block */
  7812. #endif
  7813. #endif /* _SQLITE3_H_ */
  7814. /*
  7815. ** 2010 August 30
  7816. **
  7817. ** The author disclaims copyright to this source code. In place of
  7818. ** a legal notice, here is a blessing:
  7819. **
  7820. ** May you do good and not evil.
  7821. ** May you find forgiveness for yourself and forgive others.
  7822. ** May you share freely, never taking more than you give.
  7823. **
  7824. *************************************************************************
  7825. */
  7826. #ifndef _SQLITE3RTREE_H_
  7827. #define _SQLITE3RTREE_H_
  7828. #if 0
  7829. extern "C" {
  7830. #endif
  7831. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7832. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  7833. /* The double-precision datatype used by RTree depends on the
  7834. ** SQLITE_RTREE_INT_ONLY compile-time option.
  7835. */
  7836. #ifdef SQLITE_RTREE_INT_ONLY
  7837. typedef sqlite3_int64 sqlite3_rtree_dbl;
  7838. #else
  7839. typedef double sqlite3_rtree_dbl;
  7840. #endif
  7841. /*
  7842. ** Register a geometry callback named zGeom that can be used as part of an
  7843. ** R-Tree geometry query as follows:
  7844. **
  7845. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7846. */
  7847. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  7848. sqlite3 *db,
  7849. const char *zGeom,
  7850. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  7851. void *pContext
  7852. );
  7853. /*
  7854. ** A pointer to a structure of the following type is passed as the first
  7855. ** argument to callbacks registered using rtree_geometry_callback().
  7856. */
  7857. struct sqlite3_rtree_geometry {
  7858. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7859. int nParam; /* Size of array aParam[] */
  7860. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  7861. void *pUser; /* Callback implementation user data */
  7862. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7863. };
  7864. /*
  7865. ** Register a 2nd-generation geometry callback named zScore that can be
  7866. ** used as part of an R-Tree geometry query as follows:
  7867. **
  7868. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  7869. */
  7870. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  7871. sqlite3 *db,
  7872. const char *zQueryFunc,
  7873. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  7874. void *pContext,
  7875. void (*xDestructor)(void*)
  7876. );
  7877. /*
  7878. ** A pointer to a structure of the following type is passed as the
  7879. ** argument to scored geometry callback registered using
  7880. ** sqlite3_rtree_query_callback().
  7881. **
  7882. ** Note that the first 5 fields of this structure are identical to
  7883. ** sqlite3_rtree_geometry. This structure is a subclass of
  7884. ** sqlite3_rtree_geometry.
  7885. */
  7886. struct sqlite3_rtree_query_info {
  7887. void *pContext; /* pContext from when function registered */
  7888. int nParam; /* Number of function parameters */
  7889. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  7890. void *pUser; /* callback can use this, if desired */
  7891. void (*xDelUser)(void*); /* function to free pUser */
  7892. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  7893. unsigned int *anQueue; /* Number of pending entries in the queue */
  7894. int nCoord; /* Number of coordinates */
  7895. int iLevel; /* Level of current node or entry */
  7896. int mxLevel; /* The largest iLevel value in the tree */
  7897. sqlite3_int64 iRowid; /* Rowid for current entry */
  7898. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  7899. int eParentWithin; /* Visibility of parent node */
  7900. int eWithin; /* OUT: Visiblity */
  7901. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  7902. /* The following fields are only available in 3.8.11 and later */
  7903. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  7904. };
  7905. /*
  7906. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  7907. */
  7908. #define NOT_WITHIN 0 /* Object completely outside of query region */
  7909. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  7910. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  7911. #if 0
  7912. } /* end of the 'extern "C"' block */
  7913. #endif
  7914. #endif /* ifndef _SQLITE3RTREE_H_ */
  7915. /*
  7916. ** 2014 May 31
  7917. **
  7918. ** The author disclaims copyright to this source code. In place of
  7919. ** a legal notice, here is a blessing:
  7920. **
  7921. ** May you do good and not evil.
  7922. ** May you find forgiveness for yourself and forgive others.
  7923. ** May you share freely, never taking more than you give.
  7924. **
  7925. ******************************************************************************
  7926. **
  7927. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  7928. ** FTS5 may be extended with:
  7929. **
  7930. ** * custom tokenizers, and
  7931. ** * custom auxiliary functions.
  7932. */
  7933. #ifndef _FTS5_H
  7934. #define _FTS5_H
  7935. #if 0
  7936. extern "C" {
  7937. #endif
  7938. /*************************************************************************
  7939. ** CUSTOM AUXILIARY FUNCTIONS
  7940. **
  7941. ** Virtual table implementations may overload SQL functions by implementing
  7942. ** the sqlite3_module.xFindFunction() method.
  7943. */
  7944. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  7945. typedef struct Fts5Context Fts5Context;
  7946. typedef struct Fts5PhraseIter Fts5PhraseIter;
  7947. typedef void (*fts5_extension_function)(
  7948. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  7949. Fts5Context *pFts, /* First arg to pass to pApi functions */
  7950. sqlite3_context *pCtx, /* Context for returning result/error */
  7951. int nVal, /* Number of values in apVal[] array */
  7952. sqlite3_value **apVal /* Array of trailing arguments */
  7953. );
  7954. struct Fts5PhraseIter {
  7955. const unsigned char *a;
  7956. const unsigned char *b;
  7957. };
  7958. /*
  7959. ** EXTENSION API FUNCTIONS
  7960. **
  7961. ** xUserData(pFts):
  7962. ** Return a copy of the context pointer the extension function was
  7963. ** registered with.
  7964. **
  7965. ** xColumnTotalSize(pFts, iCol, pnToken):
  7966. ** If parameter iCol is less than zero, set output variable *pnToken
  7967. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  7968. ** non-negative but less than the number of columns in the table, return
  7969. ** the total number of tokens in column iCol, considering all rows in
  7970. ** the FTS5 table.
  7971. **
  7972. ** If parameter iCol is greater than or equal to the number of columns
  7973. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  7974. ** an OOM condition or IO error), an appropriate SQLite error code is
  7975. ** returned.
  7976. **
  7977. ** xColumnCount(pFts):
  7978. ** Return the number of columns in the table.
  7979. **
  7980. ** xColumnSize(pFts, iCol, pnToken):
  7981. ** If parameter iCol is less than zero, set output variable *pnToken
  7982. ** to the total number of tokens in the current row. Or, if iCol is
  7983. ** non-negative but less than the number of columns in the table, set
  7984. ** *pnToken to the number of tokens in column iCol of the current row.
  7985. **
  7986. ** If parameter iCol is greater than or equal to the number of columns
  7987. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  7988. ** an OOM condition or IO error), an appropriate SQLite error code is
  7989. ** returned.
  7990. **
  7991. ** xColumnText:
  7992. ** This function attempts to retrieve the text of column iCol of the
  7993. ** current document. If successful, (*pz) is set to point to a buffer
  7994. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  7995. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  7996. ** if an error occurs, an SQLite error code is returned and the final values
  7997. ** of (*pz) and (*pn) are undefined.
  7998. **
  7999. ** xPhraseCount:
  8000. ** Returns the number of phrases in the current query expression.
  8001. **
  8002. ** xPhraseSize:
  8003. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  8004. ** are numbered starting from zero.
  8005. **
  8006. ** xInstCount:
  8007. ** Set *pnInst to the total number of occurrences of all phrases within
  8008. ** the query within the current row. Return SQLITE_OK if successful, or
  8009. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  8010. **
  8011. ** xInst:
  8012. ** Query for the details of phrase match iIdx within the current row.
  8013. ** Phrase matches are numbered starting from zero, so the iIdx argument
  8014. ** should be greater than or equal to zero and smaller than the value
  8015. ** output by xInstCount().
  8016. **
  8017. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  8018. ** if an error occurs.
  8019. **
  8020. ** xRowid:
  8021. ** Returns the rowid of the current row.
  8022. **
  8023. ** xTokenize:
  8024. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  8025. **
  8026. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  8027. ** This API function is used to query the FTS table for phrase iPhrase
  8028. ** of the current query. Specifically, a query equivalent to:
  8029. **
  8030. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  8031. **
  8032. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  8033. ** current query is executed. For each row visited, the callback function
  8034. ** passed as the fourth argument is invoked. The context and API objects
  8035. ** passed to the callback function may be used to access the properties of
  8036. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  8037. ** passed as the third argument to pUserData.
  8038. **
  8039. ** If the callback function returns any value other than SQLITE_OK, the
  8040. ** query is abandoned and the xQueryPhrase function returns immediately.
  8041. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  8042. ** Otherwise, the error code is propagated upwards.
  8043. **
  8044. ** If the query runs to completion without incident, SQLITE_OK is returned.
  8045. ** Or, if some error occurs before the query completes or is aborted by
  8046. ** the callback, an SQLite error code is returned.
  8047. **
  8048. **
  8049. ** xSetAuxdata(pFts5, pAux, xDelete)
  8050. **
  8051. ** Save the pointer passed as the second argument as the extension functions
  8052. ** "auxiliary data". The pointer may then be retrieved by the current or any
  8053. ** future invocation of the same fts5 extension function made as part of
  8054. ** of the same MATCH query using the xGetAuxdata() API.
  8055. **
  8056. ** Each extension function is allocated a single auxiliary data slot for
  8057. ** each FTS query (MATCH expression). If the extension function is invoked
  8058. ** more than once for a single FTS query, then all invocations share a
  8059. ** single auxiliary data context.
  8060. **
  8061. ** If there is already an auxiliary data pointer when this function is
  8062. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  8063. ** was specified along with the original pointer, it is invoked at this
  8064. ** point.
  8065. **
  8066. ** The xDelete callback, if one is specified, is also invoked on the
  8067. ** auxiliary data pointer after the FTS5 query has finished.
  8068. **
  8069. ** If an error (e.g. an OOM condition) occurs within this function, an
  8070. ** the auxiliary data is set to NULL and an error code returned. If the
  8071. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  8072. ** pointer before returning.
  8073. **
  8074. **
  8075. ** xGetAuxdata(pFts5, bClear)
  8076. **
  8077. ** Returns the current auxiliary data pointer for the fts5 extension
  8078. ** function. See the xSetAuxdata() method for details.
  8079. **
  8080. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  8081. ** (set to NULL) before this function returns. In this case the xDelete,
  8082. ** if any, is not invoked.
  8083. **
  8084. **
  8085. ** xRowCount(pFts5, pnRow)
  8086. **
  8087. ** This function is used to retrieve the total number of rows in the table.
  8088. ** In other words, the same value that would be returned by:
  8089. **
  8090. ** SELECT count(*) FROM ftstable;
  8091. **
  8092. ** xPhraseFirst()
  8093. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  8094. ** method, to iterate through all instances of a single query phrase within
  8095. ** the current row. This is the same information as is accessible via the
  8096. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  8097. ** to use, this API may be faster under some circumstances. To iterate
  8098. ** through instances of phrase iPhrase, use the following code:
  8099. **
  8100. ** Fts5PhraseIter iter;
  8101. ** int iCol, iOff;
  8102. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  8103. ** iOff>=0;
  8104. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  8105. ** ){
  8106. ** // An instance of phrase iPhrase at offset iOff of column iCol
  8107. ** }
  8108. **
  8109. ** The Fts5PhraseIter structure is defined above. Applications should not
  8110. ** modify this structure directly - it should only be used as shown above
  8111. ** with the xPhraseFirst() and xPhraseNext() API methods.
  8112. **
  8113. ** xPhraseNext()
  8114. ** See xPhraseFirst above.
  8115. */
  8116. struct Fts5ExtensionApi {
  8117. int iVersion; /* Currently always set to 1 */
  8118. void *(*xUserData)(Fts5Context*);
  8119. int (*xColumnCount)(Fts5Context*);
  8120. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  8121. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  8122. int (*xTokenize)(Fts5Context*,
  8123. const char *pText, int nText, /* Text to tokenize */
  8124. void *pCtx, /* Context passed to xToken() */
  8125. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  8126. );
  8127. int (*xPhraseCount)(Fts5Context*);
  8128. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  8129. int (*xInstCount)(Fts5Context*, int *pnInst);
  8130. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  8131. sqlite3_int64 (*xRowid)(Fts5Context*);
  8132. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  8133. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  8134. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  8135. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  8136. );
  8137. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  8138. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  8139. void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  8140. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  8141. };
  8142. /*
  8143. ** CUSTOM AUXILIARY FUNCTIONS
  8144. *************************************************************************/
  8145. /*************************************************************************
  8146. ** CUSTOM TOKENIZERS
  8147. **
  8148. ** Applications may also register custom tokenizer types. A tokenizer
  8149. ** is registered by providing fts5 with a populated instance of the
  8150. ** following structure. All structure methods must be defined, setting
  8151. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  8152. ** behaviour. The structure methods are expected to function as follows:
  8153. **
  8154. ** xCreate:
  8155. ** This function is used to allocate and inititalize a tokenizer instance.
  8156. ** A tokenizer instance is required to actually tokenize text.
  8157. **
  8158. ** The first argument passed to this function is a copy of the (void*)
  8159. ** pointer provided by the application when the fts5_tokenizer object
  8160. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  8161. ** The second and third arguments are an array of nul-terminated strings
  8162. ** containing the tokenizer arguments, if any, specified following the
  8163. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  8164. ** to create the FTS5 table.
  8165. **
  8166. ** The final argument is an output variable. If successful, (*ppOut)
  8167. ** should be set to point to the new tokenizer handle and SQLITE_OK
  8168. ** returned. If an error occurs, some value other than SQLITE_OK should
  8169. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  8170. ** is undefined.
  8171. **
  8172. ** xDelete:
  8173. ** This function is invoked to delete a tokenizer handle previously
  8174. ** allocated using xCreate(). Fts5 guarantees that this function will
  8175. ** be invoked exactly once for each successful call to xCreate().
  8176. **
  8177. ** xTokenize:
  8178. ** This function is expected to tokenize the nText byte string indicated
  8179. ** by argument pText. pText may or may not be nul-terminated. The first
  8180. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  8181. ** returned by an earlier call to xCreate().
  8182. **
  8183. ** The second argument indicates the reason that FTS5 is requesting
  8184. ** tokenization of the supplied text. This is always one of the following
  8185. ** four values:
  8186. **
  8187. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  8188. ** or removed from the FTS table. The tokenizer is being invoked to
  8189. ** determine the set of tokens to add to (or delete from) the
  8190. ** FTS index.
  8191. **
  8192. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  8193. ** against the FTS index. The tokenizer is being called to tokenize
  8194. ** a bareword or quoted string specified as part of the query.
  8195. **
  8196. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  8197. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  8198. ** followed by a "*" character, indicating that the last token
  8199. ** returned by the tokenizer will be treated as a token prefix.
  8200. **
  8201. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  8202. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  8203. ** function. Or an fts5_api.xColumnSize() request made by the same
  8204. ** on a columnsize=0 database.
  8205. ** </ul>
  8206. **
  8207. ** For each token in the input string, the supplied callback xToken() must
  8208. ** be invoked. The first argument to it should be a copy of the pointer
  8209. ** passed as the second argument to xTokenize(). The third and fourth
  8210. ** arguments are a pointer to a buffer containing the token text, and the
  8211. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  8212. ** of the first byte of and first byte immediately following the text from
  8213. ** which the token is derived within the input.
  8214. **
  8215. ** The second argument passed to the xToken() callback ("tflags") should
  8216. ** normally be set to 0. The exception is if the tokenizer supports
  8217. ** synonyms. In this case see the discussion below for details.
  8218. **
  8219. ** FTS5 assumes the xToken() callback is invoked for each token in the
  8220. ** order that they occur within the input text.
  8221. **
  8222. ** If an xToken() callback returns any value other than SQLITE_OK, then
  8223. ** the tokenization should be abandoned and the xTokenize() method should
  8224. ** immediately return a copy of the xToken() return value. Or, if the
  8225. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  8226. ** if an error occurs with the xTokenize() implementation itself, it
  8227. ** may abandon the tokenization and return any error code other than
  8228. ** SQLITE_OK or SQLITE_DONE.
  8229. **
  8230. ** SYNONYM SUPPORT
  8231. **
  8232. ** Custom tokenizers may also support synonyms. Consider a case in which a
  8233. ** user wishes to query for a phrase such as "first place". Using the
  8234. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  8235. ** of "first place" within the document set, but not alternative forms
  8236. ** such as "1st place". In some applications, it would be better to match
  8237. ** all instances of "first place" or "1st place" regardless of which form
  8238. ** the user specified in the MATCH query text.
  8239. **
  8240. ** There are several ways to approach this in FTS5:
  8241. **
  8242. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  8243. ** In the above example, this means that the tokenizer returns the
  8244. ** same token for inputs "first" and "1st". Say that token is in
  8245. ** fact "first", so that when the user inserts the document "I won
  8246. ** 1st place" entries are added to the index for tokens "i", "won",
  8247. ** "first" and "place". If the user then queries for '1st + place',
  8248. ** the tokenizer substitutes "first" for "1st" and the query works
  8249. ** as expected.
  8250. **
  8251. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8252. ** In this case, when tokenizing query text, the tokenizer may
  8253. ** provide multiple synonyms for a single term within the document.
  8254. ** FTS5 then queries the index for each synonym individually. For
  8255. ** example, faced with the query:
  8256. **
  8257. ** <codeblock>
  8258. ** ... MATCH 'first place'</codeblock>
  8259. **
  8260. ** the tokenizer offers both "1st" and "first" as synonyms for the
  8261. ** first token in the MATCH query and FTS5 effectively runs a query
  8262. ** similar to:
  8263. **
  8264. ** <codeblock>
  8265. ** ... MATCH '(first OR 1st) place'</codeblock>
  8266. **
  8267. ** except that, for the purposes of auxiliary functions, the query
  8268. ** still appears to contain just two phrases - "(first OR 1st)"
  8269. ** being treated as a single phrase.
  8270. **
  8271. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8272. ** Using this method, when tokenizing document text, the tokenizer
  8273. ** provides multiple synonyms for each token. So that when a
  8274. ** document such as "I won first place" is tokenized, entries are
  8275. ** added to the FTS index for "i", "won", "first", "1st" and
  8276. ** "place".
  8277. **
  8278. ** This way, even if the tokenizer does not provide synonyms
  8279. ** when tokenizing query text (it should not - to do would be
  8280. ** inefficient), it doesn't matter if the user queries for
  8281. ** 'first + place' or '1st + place', as there are entires in the
  8282. ** FTS index corresponding to both forms of the first token.
  8283. ** </ol>
  8284. **
  8285. ** Whether it is parsing document or query text, any call to xToken that
  8286. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  8287. ** is considered to supply a synonym for the previous token. For example,
  8288. ** when parsing the document "I won first place", a tokenizer that supports
  8289. ** synonyms would call xToken() 5 times, as follows:
  8290. **
  8291. ** <codeblock>
  8292. ** xToken(pCtx, 0, "i", 1, 0, 1);
  8293. ** xToken(pCtx, 0, "won", 3, 2, 5);
  8294. ** xToken(pCtx, 0, "first", 5, 6, 11);
  8295. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  8296. ** xToken(pCtx, 0, "place", 5, 12, 17);
  8297. **</codeblock>
  8298. **
  8299. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  8300. ** xToken() is called. Multiple synonyms may be specified for a single token
  8301. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  8302. ** There is no limit to the number of synonyms that may be provided for a
  8303. ** single token.
  8304. **
  8305. ** In many cases, method (1) above is the best approach. It does not add
  8306. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  8307. ** so it is efficient in terms of disk space and query speed. However, it
  8308. ** does not support prefix queries very well. If, as suggested above, the
  8309. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  8310. **
  8311. ** <codeblock>
  8312. ** ... MATCH '1s*'</codeblock>
  8313. **
  8314. ** will not match documents that contain the token "1st" (as the tokenizer
  8315. ** will probably not map "1s" to any prefix of "first").
  8316. **
  8317. ** For full prefix support, method (3) may be preferred. In this case,
  8318. ** because the index contains entries for both "first" and "1st", prefix
  8319. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  8320. ** extra entries are added to the FTS index, this method uses more space
  8321. ** within the database.
  8322. **
  8323. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  8324. ** a query such as '1s*' will match documents that contain the literal
  8325. ** token "1st", but not "first" (assuming the tokenizer is not able to
  8326. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  8327. ** will match against "1st" and "first". This method does not require
  8328. ** extra disk space, as no extra entries are added to the FTS index.
  8329. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  8330. ** as separate queries of the FTS index are required for each synonym.
  8331. **
  8332. ** When using methods (2) or (3), it is important that the tokenizer only
  8333. ** provide synonyms when tokenizing document text (method (2)) or query
  8334. ** text (method (3)), not both. Doing so will not cause any errors, but is
  8335. ** inefficient.
  8336. */
  8337. typedef struct Fts5Tokenizer Fts5Tokenizer;
  8338. typedef struct fts5_tokenizer fts5_tokenizer;
  8339. struct fts5_tokenizer {
  8340. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  8341. void (*xDelete)(Fts5Tokenizer*);
  8342. int (*xTokenize)(Fts5Tokenizer*,
  8343. void *pCtx,
  8344. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  8345. const char *pText, int nText,
  8346. int (*xToken)(
  8347. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  8348. int tflags, /* Mask of FTS5_TOKEN_* flags */
  8349. const char *pToken, /* Pointer to buffer containing token */
  8350. int nToken, /* Size of token in bytes */
  8351. int iStart, /* Byte offset of token within input text */
  8352. int iEnd /* Byte offset of end of token within input text */
  8353. )
  8354. );
  8355. };
  8356. /* Flags that may be passed as the third argument to xTokenize() */
  8357. #define FTS5_TOKENIZE_QUERY 0x0001
  8358. #define FTS5_TOKENIZE_PREFIX 0x0002
  8359. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  8360. #define FTS5_TOKENIZE_AUX 0x0008
  8361. /* Flags that may be passed by the tokenizer implementation back to FTS5
  8362. ** as the third argument to the supplied xToken callback. */
  8363. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  8364. /*
  8365. ** END OF CUSTOM TOKENIZERS
  8366. *************************************************************************/
  8367. /*************************************************************************
  8368. ** FTS5 EXTENSION REGISTRATION API
  8369. */
  8370. typedef struct fts5_api fts5_api;
  8371. struct fts5_api {
  8372. int iVersion; /* Currently always set to 2 */
  8373. /* Create a new tokenizer */
  8374. int (*xCreateTokenizer)(
  8375. fts5_api *pApi,
  8376. const char *zName,
  8377. void *pContext,
  8378. fts5_tokenizer *pTokenizer,
  8379. void (*xDestroy)(void*)
  8380. );
  8381. /* Find an existing tokenizer */
  8382. int (*xFindTokenizer)(
  8383. fts5_api *pApi,
  8384. const char *zName,
  8385. void **ppContext,
  8386. fts5_tokenizer *pTokenizer
  8387. );
  8388. /* Create a new auxiliary function */
  8389. int (*xCreateFunction)(
  8390. fts5_api *pApi,
  8391. const char *zName,
  8392. void *pContext,
  8393. fts5_extension_function xFunction,
  8394. void (*xDestroy)(void*)
  8395. );
  8396. };
  8397. /*
  8398. ** END OF REGISTRATION API
  8399. *************************************************************************/
  8400. #if 0
  8401. } /* end of the 'extern "C"' block */
  8402. #endif
  8403. #endif /* _FTS5_H */
  8404. /************** End of sqlite3.h *********************************************/
  8405. /************** Continuing where we left off in sqliteInt.h ******************/
  8406. /*
  8407. ** Include the configuration header output by 'configure' if we're using the
  8408. ** autoconf-based build
  8409. */
  8410. #ifdef _HAVE_SQLITE_CONFIG_H
  8411. #include "config.h"
  8412. #endif
  8413. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  8414. /************** Begin file sqliteLimit.h *************************************/
  8415. /*
  8416. ** 2007 May 7
  8417. **
  8418. ** The author disclaims copyright to this source code. In place of
  8419. ** a legal notice, here is a blessing:
  8420. **
  8421. ** May you do good and not evil.
  8422. ** May you find forgiveness for yourself and forgive others.
  8423. ** May you share freely, never taking more than you give.
  8424. **
  8425. *************************************************************************
  8426. **
  8427. ** This file defines various limits of what SQLite can process.
  8428. */
  8429. /*
  8430. ** The maximum length of a TEXT or BLOB in bytes. This also
  8431. ** limits the size of a row in a table or index.
  8432. **
  8433. ** The hard limit is the ability of a 32-bit signed integer
  8434. ** to count the size: 2^31-1 or 2147483647.
  8435. */
  8436. #ifndef SQLITE_MAX_LENGTH
  8437. # define SQLITE_MAX_LENGTH 1000000000
  8438. #endif
  8439. /*
  8440. ** This is the maximum number of
  8441. **
  8442. ** * Columns in a table
  8443. ** * Columns in an index
  8444. ** * Columns in a view
  8445. ** * Terms in the SET clause of an UPDATE statement
  8446. ** * Terms in the result set of a SELECT statement
  8447. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  8448. ** * Terms in the VALUES clause of an INSERT statement
  8449. **
  8450. ** The hard upper limit here is 32676. Most database people will
  8451. ** tell you that in a well-normalized database, you usually should
  8452. ** not have more than a dozen or so columns in any table. And if
  8453. ** that is the case, there is no point in having more than a few
  8454. ** dozen values in any of the other situations described above.
  8455. */
  8456. #ifndef SQLITE_MAX_COLUMN
  8457. # define SQLITE_MAX_COLUMN 2000
  8458. #endif
  8459. /*
  8460. ** The maximum length of a single SQL statement in bytes.
  8461. **
  8462. ** It used to be the case that setting this value to zero would
  8463. ** turn the limit off. That is no longer true. It is not possible
  8464. ** to turn this limit off.
  8465. */
  8466. #ifndef SQLITE_MAX_SQL_LENGTH
  8467. # define SQLITE_MAX_SQL_LENGTH 1000000000
  8468. #endif
  8469. /*
  8470. ** The maximum depth of an expression tree. This is limited to
  8471. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  8472. ** want to place more severe limits on the complexity of an
  8473. ** expression.
  8474. **
  8475. ** A value of 0 used to mean that the limit was not enforced.
  8476. ** But that is no longer true. The limit is now strictly enforced
  8477. ** at all times.
  8478. */
  8479. #ifndef SQLITE_MAX_EXPR_DEPTH
  8480. # define SQLITE_MAX_EXPR_DEPTH 1000
  8481. #endif
  8482. /*
  8483. ** The maximum number of terms in a compound SELECT statement.
  8484. ** The code generator for compound SELECT statements does one
  8485. ** level of recursion for each term. A stack overflow can result
  8486. ** if the number of terms is too large. In practice, most SQL
  8487. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  8488. ** any limit on the number of terms in a compount SELECT.
  8489. */
  8490. #ifndef SQLITE_MAX_COMPOUND_SELECT
  8491. # define SQLITE_MAX_COMPOUND_SELECT 500
  8492. #endif
  8493. /*
  8494. ** The maximum number of opcodes in a VDBE program.
  8495. ** Not currently enforced.
  8496. */
  8497. #ifndef SQLITE_MAX_VDBE_OP
  8498. # define SQLITE_MAX_VDBE_OP 25000
  8499. #endif
  8500. /*
  8501. ** The maximum number of arguments to an SQL function.
  8502. */
  8503. #ifndef SQLITE_MAX_FUNCTION_ARG
  8504. # define SQLITE_MAX_FUNCTION_ARG 127
  8505. #endif
  8506. /*
  8507. ** The suggested maximum number of in-memory pages to use for
  8508. ** the main database table and for temporary tables.
  8509. **
  8510. ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
  8511. ** is 2000 pages.
  8512. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  8513. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  8514. */
  8515. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  8516. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  8517. #endif
  8518. /*
  8519. ** The default number of frames to accumulate in the log file before
  8520. ** checkpointing the database in WAL mode.
  8521. */
  8522. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  8523. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  8524. #endif
  8525. /*
  8526. ** The maximum number of attached databases. This must be between 0
  8527. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  8528. ** is used internally to track attached databases.
  8529. */
  8530. #ifndef SQLITE_MAX_ATTACHED
  8531. # define SQLITE_MAX_ATTACHED 10
  8532. #endif
  8533. /*
  8534. ** The maximum value of a ?nnn wildcard that the parser will accept.
  8535. */
  8536. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  8537. # define SQLITE_MAX_VARIABLE_NUMBER 999
  8538. #endif
  8539. /* Maximum page size. The upper bound on this value is 65536. This a limit
  8540. ** imposed by the use of 16-bit offsets within each page.
  8541. **
  8542. ** Earlier versions of SQLite allowed the user to change this value at
  8543. ** compile time. This is no longer permitted, on the grounds that it creates
  8544. ** a library that is technically incompatible with an SQLite library
  8545. ** compiled with a different limit. If a process operating on a database
  8546. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  8547. ** compiled with the default page-size limit will not be able to rollback
  8548. ** the aborted transaction. This could lead to database corruption.
  8549. */
  8550. #ifdef SQLITE_MAX_PAGE_SIZE
  8551. # undef SQLITE_MAX_PAGE_SIZE
  8552. #endif
  8553. #define SQLITE_MAX_PAGE_SIZE 65536
  8554. /*
  8555. ** The default size of a database page.
  8556. */
  8557. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  8558. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  8559. #endif
  8560. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8561. # undef SQLITE_DEFAULT_PAGE_SIZE
  8562. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8563. #endif
  8564. /*
  8565. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  8566. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  8567. ** device characteristics (sector-size and atomic write() support),
  8568. ** SQLite may choose a larger value. This constant is the maximum value
  8569. ** SQLite will choose on its own.
  8570. */
  8571. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8572. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  8573. #endif
  8574. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8575. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8576. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8577. #endif
  8578. /*
  8579. ** Maximum number of pages in one database file.
  8580. **
  8581. ** This is really just the default value for the max_page_count pragma.
  8582. ** This value can be lowered (or raised) at run-time using that the
  8583. ** max_page_count macro.
  8584. */
  8585. #ifndef SQLITE_MAX_PAGE_COUNT
  8586. # define SQLITE_MAX_PAGE_COUNT 1073741823
  8587. #endif
  8588. /*
  8589. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  8590. ** operator.
  8591. */
  8592. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  8593. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  8594. #endif
  8595. /*
  8596. ** Maximum depth of recursion for triggers.
  8597. **
  8598. ** A value of 1 means that a trigger program will not be able to itself
  8599. ** fire any triggers. A value of 0 means that no trigger programs at all
  8600. ** may be executed.
  8601. */
  8602. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  8603. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  8604. #endif
  8605. /************** End of sqliteLimit.h *****************************************/
  8606. /************** Continuing where we left off in sqliteInt.h ******************/
  8607. /* Disable nuisance warnings on Borland compilers */
  8608. #if defined(__BORLANDC__)
  8609. #pragma warn -rch /* unreachable code */
  8610. #pragma warn -ccc /* Condition is always true or false */
  8611. #pragma warn -aus /* Assigned value is never used */
  8612. #pragma warn -csu /* Comparing signed and unsigned */
  8613. #pragma warn -spa /* Suspicious pointer arithmetic */
  8614. #endif
  8615. /*
  8616. ** Include standard header files as necessary
  8617. */
  8618. #ifdef HAVE_STDINT_H
  8619. #include <stdint.h>
  8620. #endif
  8621. #ifdef HAVE_INTTYPES_H
  8622. #include <inttypes.h>
  8623. #endif
  8624. /*
  8625. ** The following macros are used to cast pointers to integers and
  8626. ** integers to pointers. The way you do this varies from one compiler
  8627. ** to the next, so we have developed the following set of #if statements
  8628. ** to generate appropriate macros for a wide range of compilers.
  8629. **
  8630. ** The correct "ANSI" way to do this is to use the intptr_t type.
  8631. ** Unfortunately, that typedef is not available on all compilers, or
  8632. ** if it is available, it requires an #include of specific headers
  8633. ** that vary from one machine to the next.
  8634. **
  8635. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  8636. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  8637. ** So we have to define the macros in different ways depending on the
  8638. ** compiler.
  8639. */
  8640. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  8641. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  8642. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  8643. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  8644. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  8645. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  8646. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  8647. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  8648. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  8649. #else /* Generates a warning - but it always works */
  8650. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  8651. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  8652. #endif
  8653. /*
  8654. ** A macro to hint to the compiler that a function should not be
  8655. ** inlined.
  8656. */
  8657. #if defined(__GNUC__)
  8658. # define SQLITE_NOINLINE __attribute__((noinline))
  8659. #elif defined(_MSC_VER) && _MSC_VER>=1310
  8660. # define SQLITE_NOINLINE __declspec(noinline)
  8661. #else
  8662. # define SQLITE_NOINLINE
  8663. #endif
  8664. /*
  8665. ** Make sure that the compiler intrinsics we desire are enabled when
  8666. ** compiling with an appropriate version of MSVC unless prevented by
  8667. ** the SQLITE_DISABLE_INTRINSIC define.
  8668. */
  8669. #if !defined(SQLITE_DISABLE_INTRINSIC)
  8670. # if defined(_MSC_VER) && _MSC_VER>=1300
  8671. # if !defined(_WIN32_WCE)
  8672. # include <intrin.h>
  8673. # pragma intrinsic(_byteswap_ushort)
  8674. # pragma intrinsic(_byteswap_ulong)
  8675. # pragma intrinsic(_ReadWriteBarrier)
  8676. # else
  8677. # include <cmnintrin.h>
  8678. # endif
  8679. # endif
  8680. #endif
  8681. /*
  8682. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  8683. ** 0 means mutexes are permanently disable and the library is never
  8684. ** threadsafe. 1 means the library is serialized which is the highest
  8685. ** level of threadsafety. 2 means the library is multithreaded - multiple
  8686. ** threads can use SQLite as long as no two threads try to use the same
  8687. ** database connection at the same time.
  8688. **
  8689. ** Older versions of SQLite used an optional THREADSAFE macro.
  8690. ** We support that for legacy.
  8691. */
  8692. #if !defined(SQLITE_THREADSAFE)
  8693. # if defined(THREADSAFE)
  8694. # define SQLITE_THREADSAFE THREADSAFE
  8695. # else
  8696. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  8697. # endif
  8698. #endif
  8699. /*
  8700. ** Powersafe overwrite is on by default. But can be turned off using
  8701. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  8702. */
  8703. #ifndef SQLITE_POWERSAFE_OVERWRITE
  8704. # define SQLITE_POWERSAFE_OVERWRITE 1
  8705. #endif
  8706. /*
  8707. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  8708. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  8709. ** which case memory allocation statistics are disabled by default.
  8710. */
  8711. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  8712. # define SQLITE_DEFAULT_MEMSTATUS 1
  8713. #endif
  8714. /*
  8715. ** Exactly one of the following macros must be defined in order to
  8716. ** specify which memory allocation subsystem to use.
  8717. **
  8718. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  8719. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  8720. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  8721. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  8722. **
  8723. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  8724. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  8725. ** will cause HeapValidate to be called. If heap validation should fail, an
  8726. ** assertion will be triggered.
  8727. **
  8728. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  8729. ** the default.
  8730. */
  8731. #if defined(SQLITE_SYSTEM_MALLOC) \
  8732. + defined(SQLITE_WIN32_MALLOC) \
  8733. + defined(SQLITE_ZERO_MALLOC) \
  8734. + defined(SQLITE_MEMDEBUG)>1
  8735. # error "Two or more of the following compile-time configuration options\
  8736. are defined but at most one is allowed:\
  8737. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  8738. SQLITE_ZERO_MALLOC"
  8739. #endif
  8740. #if defined(SQLITE_SYSTEM_MALLOC) \
  8741. + defined(SQLITE_WIN32_MALLOC) \
  8742. + defined(SQLITE_ZERO_MALLOC) \
  8743. + defined(SQLITE_MEMDEBUG)==0
  8744. # define SQLITE_SYSTEM_MALLOC 1
  8745. #endif
  8746. /*
  8747. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  8748. ** sizes of memory allocations below this value where possible.
  8749. */
  8750. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  8751. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  8752. #endif
  8753. /*
  8754. ** We need to define _XOPEN_SOURCE as follows in order to enable
  8755. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  8756. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  8757. ** it.
  8758. */
  8759. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  8760. # define _XOPEN_SOURCE 600
  8761. #endif
  8762. /*
  8763. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  8764. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  8765. ** make it true by defining or undefining NDEBUG.
  8766. **
  8767. ** Setting NDEBUG makes the code smaller and faster by disabling the
  8768. ** assert() statements in the code. So we want the default action
  8769. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  8770. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  8771. ** feature.
  8772. */
  8773. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  8774. # define NDEBUG 1
  8775. #endif
  8776. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  8777. # undef NDEBUG
  8778. #endif
  8779. /*
  8780. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  8781. */
  8782. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  8783. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  8784. #endif
  8785. /*
  8786. ** The testcase() macro is used to aid in coverage testing. When
  8787. ** doing coverage testing, the condition inside the argument to
  8788. ** testcase() must be evaluated both true and false in order to
  8789. ** get full branch coverage. The testcase() macro is inserted
  8790. ** to help ensure adequate test coverage in places where simple
  8791. ** condition/decision coverage is inadequate. For example, testcase()
  8792. ** can be used to make sure boundary values are tested. For
  8793. ** bitmask tests, testcase() can be used to make sure each bit
  8794. ** is significant and used at least once. On switch statements
  8795. ** where multiple cases go to the same block of code, testcase()
  8796. ** can insure that all cases are evaluated.
  8797. **
  8798. */
  8799. #ifdef SQLITE_COVERAGE_TEST
  8800. SQLITE_PRIVATE void sqlite3Coverage(int);
  8801. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  8802. #else
  8803. # define testcase(X)
  8804. #endif
  8805. /*
  8806. ** The TESTONLY macro is used to enclose variable declarations or
  8807. ** other bits of code that are needed to support the arguments
  8808. ** within testcase() and assert() macros.
  8809. */
  8810. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  8811. # define TESTONLY(X) X
  8812. #else
  8813. # define TESTONLY(X)
  8814. #endif
  8815. /*
  8816. ** Sometimes we need a small amount of code such as a variable initialization
  8817. ** to setup for a later assert() statement. We do not want this code to
  8818. ** appear when assert() is disabled. The following macro is therefore
  8819. ** used to contain that setup code. The "VVA" acronym stands for
  8820. ** "Verification, Validation, and Accreditation". In other words, the
  8821. ** code within VVA_ONLY() will only run during verification processes.
  8822. */
  8823. #ifndef NDEBUG
  8824. # define VVA_ONLY(X) X
  8825. #else
  8826. # define VVA_ONLY(X)
  8827. #endif
  8828. /*
  8829. ** The ALWAYS and NEVER macros surround boolean expressions which
  8830. ** are intended to always be true or false, respectively. Such
  8831. ** expressions could be omitted from the code completely. But they
  8832. ** are included in a few cases in order to enhance the resilience
  8833. ** of SQLite to unexpected behavior - to make the code "self-healing"
  8834. ** or "ductile" rather than being "brittle" and crashing at the first
  8835. ** hint of unplanned behavior.
  8836. **
  8837. ** In other words, ALWAYS and NEVER are added for defensive code.
  8838. **
  8839. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  8840. ** be true and false so that the unreachable code they specify will
  8841. ** not be counted as untested code.
  8842. */
  8843. #if defined(SQLITE_COVERAGE_TEST)
  8844. # define ALWAYS(X) (1)
  8845. # define NEVER(X) (0)
  8846. #elif !defined(NDEBUG)
  8847. # define ALWAYS(X) ((X)?1:(assert(0),0))
  8848. # define NEVER(X) ((X)?(assert(0),1):0)
  8849. #else
  8850. # define ALWAYS(X) (X)
  8851. # define NEVER(X) (X)
  8852. #endif
  8853. /*
  8854. ** Declarations used for tracing the operating system interfaces.
  8855. */
  8856. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  8857. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8858. extern int sqlite3OSTrace;
  8859. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  8860. # define SQLITE_HAVE_OS_TRACE
  8861. #else
  8862. # define OSTRACE(X)
  8863. # undef SQLITE_HAVE_OS_TRACE
  8864. #endif
  8865. /*
  8866. ** Is the sqlite3ErrName() function needed in the build? Currently,
  8867. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  8868. ** OSTRACE is enabled), and by several "test*.c" files (which are
  8869. ** compiled using SQLITE_TEST).
  8870. */
  8871. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  8872. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8873. # define SQLITE_NEED_ERR_NAME
  8874. #else
  8875. # undef SQLITE_NEED_ERR_NAME
  8876. #endif
  8877. /*
  8878. ** Return true (non-zero) if the input is an integer that is too large
  8879. ** to fit in 32-bits. This macro is used inside of various testcase()
  8880. ** macros to verify that we have tested SQLite for large-file support.
  8881. */
  8882. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  8883. /*
  8884. ** The macro unlikely() is a hint that surrounds a boolean
  8885. ** expression that is usually false. Macro likely() surrounds
  8886. ** a boolean expression that is usually true. These hints could,
  8887. ** in theory, be used by the compiler to generate better code, but
  8888. ** currently they are just comments for human readers.
  8889. */
  8890. #define likely(X) (X)
  8891. #define unlikely(X) (X)
  8892. /************** Include hash.h in the middle of sqliteInt.h ******************/
  8893. /************** Begin file hash.h ********************************************/
  8894. /*
  8895. ** 2001 September 22
  8896. **
  8897. ** The author disclaims copyright to this source code. In place of
  8898. ** a legal notice, here is a blessing:
  8899. **
  8900. ** May you do good and not evil.
  8901. ** May you find forgiveness for yourself and forgive others.
  8902. ** May you share freely, never taking more than you give.
  8903. **
  8904. *************************************************************************
  8905. ** This is the header file for the generic hash-table implementation
  8906. ** used in SQLite.
  8907. */
  8908. #ifndef _SQLITE_HASH_H_
  8909. #define _SQLITE_HASH_H_
  8910. /* Forward declarations of structures. */
  8911. typedef struct Hash Hash;
  8912. typedef struct HashElem HashElem;
  8913. /* A complete hash table is an instance of the following structure.
  8914. ** The internals of this structure are intended to be opaque -- client
  8915. ** code should not attempt to access or modify the fields of this structure
  8916. ** directly. Change this structure only by using the routines below.
  8917. ** However, some of the "procedures" and "functions" for modifying and
  8918. ** accessing this structure are really macros, so we can't really make
  8919. ** this structure opaque.
  8920. **
  8921. ** All elements of the hash table are on a single doubly-linked list.
  8922. ** Hash.first points to the head of this list.
  8923. **
  8924. ** There are Hash.htsize buckets. Each bucket points to a spot in
  8925. ** the global doubly-linked list. The contents of the bucket are the
  8926. ** element pointed to plus the next _ht.count-1 elements in the list.
  8927. **
  8928. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  8929. ** by a linear search of the global list. For small tables, the
  8930. ** Hash.ht table is never allocated because if there are few elements
  8931. ** in the table, it is faster to do a linear search than to manage
  8932. ** the hash table.
  8933. */
  8934. struct Hash {
  8935. unsigned int htsize; /* Number of buckets in the hash table */
  8936. unsigned int count; /* Number of entries in this table */
  8937. HashElem *first; /* The first element of the array */
  8938. struct _ht { /* the hash table */
  8939. int count; /* Number of entries with this hash */
  8940. HashElem *chain; /* Pointer to first entry with this hash */
  8941. } *ht;
  8942. };
  8943. /* Each element in the hash table is an instance of the following
  8944. ** structure. All elements are stored on a single doubly-linked list.
  8945. **
  8946. ** Again, this structure is intended to be opaque, but it can't really
  8947. ** be opaque because it is used by macros.
  8948. */
  8949. struct HashElem {
  8950. HashElem *next, *prev; /* Next and previous elements in the table */
  8951. void *data; /* Data associated with this element */
  8952. const char *pKey; /* Key associated with this element */
  8953. };
  8954. /*
  8955. ** Access routines. To delete, insert a NULL pointer.
  8956. */
  8957. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  8958. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  8959. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  8960. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  8961. /*
  8962. ** Macros for looping over all elements of a hash table. The idiom is
  8963. ** like this:
  8964. **
  8965. ** Hash h;
  8966. ** HashElem *p;
  8967. ** ...
  8968. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  8969. ** SomeStructure *pData = sqliteHashData(p);
  8970. ** // do something with pData
  8971. ** }
  8972. */
  8973. #define sqliteHashFirst(H) ((H)->first)
  8974. #define sqliteHashNext(E) ((E)->next)
  8975. #define sqliteHashData(E) ((E)->data)
  8976. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  8977. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  8978. /*
  8979. ** Number of entries in a hash table
  8980. */
  8981. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  8982. #endif /* _SQLITE_HASH_H_ */
  8983. /************** End of hash.h ************************************************/
  8984. /************** Continuing where we left off in sqliteInt.h ******************/
  8985. /************** Include parse.h in the middle of sqliteInt.h *****************/
  8986. /************** Begin file parse.h *******************************************/
  8987. #define TK_SEMI 1
  8988. #define TK_EXPLAIN 2
  8989. #define TK_QUERY 3
  8990. #define TK_PLAN 4
  8991. #define TK_BEGIN 5
  8992. #define TK_TRANSACTION 6
  8993. #define TK_DEFERRED 7
  8994. #define TK_IMMEDIATE 8
  8995. #define TK_EXCLUSIVE 9
  8996. #define TK_COMMIT 10
  8997. #define TK_END 11
  8998. #define TK_ROLLBACK 12
  8999. #define TK_SAVEPOINT 13
  9000. #define TK_RELEASE 14
  9001. #define TK_TO 15
  9002. #define TK_TABLE 16
  9003. #define TK_CREATE 17
  9004. #define TK_IF 18
  9005. #define TK_NOT 19
  9006. #define TK_EXISTS 20
  9007. #define TK_TEMP 21
  9008. #define TK_LP 22
  9009. #define TK_RP 23
  9010. #define TK_AS 24
  9011. #define TK_WITHOUT 25
  9012. #define TK_COMMA 26
  9013. #define TK_ID 27
  9014. #define TK_INDEXED 28
  9015. #define TK_ABORT 29
  9016. #define TK_ACTION 30
  9017. #define TK_AFTER 31
  9018. #define TK_ANALYZE 32
  9019. #define TK_ASC 33
  9020. #define TK_ATTACH 34
  9021. #define TK_BEFORE 35
  9022. #define TK_BY 36
  9023. #define TK_CASCADE 37
  9024. #define TK_CAST 38
  9025. #define TK_COLUMNKW 39
  9026. #define TK_CONFLICT 40
  9027. #define TK_DATABASE 41
  9028. #define TK_DESC 42
  9029. #define TK_DETACH 43
  9030. #define TK_EACH 44
  9031. #define TK_FAIL 45
  9032. #define TK_FOR 46
  9033. #define TK_IGNORE 47
  9034. #define TK_INITIALLY 48
  9035. #define TK_INSTEAD 49
  9036. #define TK_LIKE_KW 50
  9037. #define TK_MATCH 51
  9038. #define TK_NO 52
  9039. #define TK_KEY 53
  9040. #define TK_OF 54
  9041. #define TK_OFFSET 55
  9042. #define TK_PRAGMA 56
  9043. #define TK_RAISE 57
  9044. #define TK_RECURSIVE 58
  9045. #define TK_REPLACE 59
  9046. #define TK_RESTRICT 60
  9047. #define TK_ROW 61
  9048. #define TK_TRIGGER 62
  9049. #define TK_VACUUM 63
  9050. #define TK_VIEW 64
  9051. #define TK_VIRTUAL 65
  9052. #define TK_WITH 66
  9053. #define TK_REINDEX 67
  9054. #define TK_RENAME 68
  9055. #define TK_CTIME_KW 69
  9056. #define TK_ANY 70
  9057. #define TK_OR 71
  9058. #define TK_AND 72
  9059. #define TK_IS 73
  9060. #define TK_BETWEEN 74
  9061. #define TK_IN 75
  9062. #define TK_ISNULL 76
  9063. #define TK_NOTNULL 77
  9064. #define TK_NE 78
  9065. #define TK_EQ 79
  9066. #define TK_GT 80
  9067. #define TK_LE 81
  9068. #define TK_LT 82
  9069. #define TK_GE 83
  9070. #define TK_ESCAPE 84
  9071. #define TK_BITAND 85
  9072. #define TK_BITOR 86
  9073. #define TK_LSHIFT 87
  9074. #define TK_RSHIFT 88
  9075. #define TK_PLUS 89
  9076. #define TK_MINUS 90
  9077. #define TK_STAR 91
  9078. #define TK_SLASH 92
  9079. #define TK_REM 93
  9080. #define TK_CONCAT 94
  9081. #define TK_COLLATE 95
  9082. #define TK_BITNOT 96
  9083. #define TK_STRING 97
  9084. #define TK_JOIN_KW 98
  9085. #define TK_CONSTRAINT 99
  9086. #define TK_DEFAULT 100
  9087. #define TK_NULL 101
  9088. #define TK_PRIMARY 102
  9089. #define TK_UNIQUE 103
  9090. #define TK_CHECK 104
  9091. #define TK_REFERENCES 105
  9092. #define TK_AUTOINCR 106
  9093. #define TK_ON 107
  9094. #define TK_INSERT 108
  9095. #define TK_DELETE 109
  9096. #define TK_UPDATE 110
  9097. #define TK_SET 111
  9098. #define TK_DEFERRABLE 112
  9099. #define TK_FOREIGN 113
  9100. #define TK_DROP 114
  9101. #define TK_UNION 115
  9102. #define TK_ALL 116
  9103. #define TK_EXCEPT 117
  9104. #define TK_INTERSECT 118
  9105. #define TK_SELECT 119
  9106. #define TK_VALUES 120
  9107. #define TK_DISTINCT 121
  9108. #define TK_DOT 122
  9109. #define TK_FROM 123
  9110. #define TK_JOIN 124
  9111. #define TK_USING 125
  9112. #define TK_ORDER 126
  9113. #define TK_GROUP 127
  9114. #define TK_HAVING 128
  9115. #define TK_LIMIT 129
  9116. #define TK_WHERE 130
  9117. #define TK_INTO 131
  9118. #define TK_INTEGER 132
  9119. #define TK_FLOAT 133
  9120. #define TK_BLOB 134
  9121. #define TK_VARIABLE 135
  9122. #define TK_CASE 136
  9123. #define TK_WHEN 137
  9124. #define TK_THEN 138
  9125. #define TK_ELSE 139
  9126. #define TK_INDEX 140
  9127. #define TK_ALTER 141
  9128. #define TK_ADD 142
  9129. #define TK_TO_TEXT 143
  9130. #define TK_TO_BLOB 144
  9131. #define TK_TO_NUMERIC 145
  9132. #define TK_TO_INT 146
  9133. #define TK_TO_REAL 147
  9134. #define TK_ISNOT 148
  9135. #define TK_END_OF_FILE 149
  9136. #define TK_ILLEGAL 150
  9137. #define TK_SPACE 151
  9138. #define TK_UNCLOSED_STRING 152
  9139. #define TK_FUNCTION 153
  9140. #define TK_COLUMN 154
  9141. #define TK_AGG_FUNCTION 155
  9142. #define TK_AGG_COLUMN 156
  9143. #define TK_UMINUS 157
  9144. #define TK_UPLUS 158
  9145. #define TK_REGISTER 159
  9146. /************** End of parse.h ***********************************************/
  9147. /************** Continuing where we left off in sqliteInt.h ******************/
  9148. #include <stdio.h>
  9149. #include <stdlib.h>
  9150. #include <string.h>
  9151. #include <assert.h>
  9152. #include <stddef.h>
  9153. /*
  9154. ** If compiling for a processor that lacks floating point support,
  9155. ** substitute integer for floating-point
  9156. */
  9157. #ifdef SQLITE_OMIT_FLOATING_POINT
  9158. # define double sqlite_int64
  9159. # define float sqlite_int64
  9160. # define LONGDOUBLE_TYPE sqlite_int64
  9161. # ifndef SQLITE_BIG_DBL
  9162. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  9163. # endif
  9164. # define SQLITE_OMIT_DATETIME_FUNCS 1
  9165. # define SQLITE_OMIT_TRACE 1
  9166. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  9167. # undef SQLITE_HAVE_ISNAN
  9168. #endif
  9169. #ifndef SQLITE_BIG_DBL
  9170. # define SQLITE_BIG_DBL (1e99)
  9171. #endif
  9172. /*
  9173. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  9174. ** afterward. Having this macro allows us to cause the C compiler
  9175. ** to omit code used by TEMP tables without messy #ifndef statements.
  9176. */
  9177. #ifdef SQLITE_OMIT_TEMPDB
  9178. #define OMIT_TEMPDB 1
  9179. #else
  9180. #define OMIT_TEMPDB 0
  9181. #endif
  9182. /*
  9183. ** The "file format" number is an integer that is incremented whenever
  9184. ** the VDBE-level file format changes. The following macros define the
  9185. ** the default file format for new databases and the maximum file format
  9186. ** that the library can read.
  9187. */
  9188. #define SQLITE_MAX_FILE_FORMAT 4
  9189. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  9190. # define SQLITE_DEFAULT_FILE_FORMAT 4
  9191. #endif
  9192. /*
  9193. ** Determine whether triggers are recursive by default. This can be
  9194. ** changed at run-time using a pragma.
  9195. */
  9196. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  9197. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  9198. #endif
  9199. /*
  9200. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  9201. ** on the command-line
  9202. */
  9203. #ifndef SQLITE_TEMP_STORE
  9204. # define SQLITE_TEMP_STORE 1
  9205. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  9206. #endif
  9207. /*
  9208. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  9209. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  9210. ** to zero.
  9211. */
  9212. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  9213. # undef SQLITE_MAX_WORKER_THREADS
  9214. # define SQLITE_MAX_WORKER_THREADS 0
  9215. #endif
  9216. #ifndef SQLITE_MAX_WORKER_THREADS
  9217. # define SQLITE_MAX_WORKER_THREADS 8
  9218. #endif
  9219. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  9220. # define SQLITE_DEFAULT_WORKER_THREADS 0
  9221. #endif
  9222. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  9223. # undef SQLITE_MAX_WORKER_THREADS
  9224. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  9225. #endif
  9226. /*
  9227. ** The default initial allocation for the pagecache when using separate
  9228. ** pagecaches for each database connection. A positive number is the
  9229. ** number of pages. A negative number N translations means that a buffer
  9230. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  9231. */
  9232. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  9233. # define SQLITE_DEFAULT_PCACHE_INITSZ 100
  9234. #endif
  9235. /*
  9236. ** GCC does not define the offsetof() macro so we'll have to do it
  9237. ** ourselves.
  9238. */
  9239. #ifndef offsetof
  9240. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  9241. #endif
  9242. /*
  9243. ** Macros to compute minimum and maximum of two numbers.
  9244. */
  9245. #define MIN(A,B) ((A)<(B)?(A):(B))
  9246. #define MAX(A,B) ((A)>(B)?(A):(B))
  9247. /*
  9248. ** Swap two objects of type TYPE.
  9249. */
  9250. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  9251. /*
  9252. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  9253. ** not, there are still machines out there that use EBCDIC.)
  9254. */
  9255. #if 'A' == '\301'
  9256. # define SQLITE_EBCDIC 1
  9257. #else
  9258. # define SQLITE_ASCII 1
  9259. #endif
  9260. /*
  9261. ** Integers of known sizes. These typedefs might change for architectures
  9262. ** where the sizes very. Preprocessor macros are available so that the
  9263. ** types can be conveniently redefined at compile-type. Like this:
  9264. **
  9265. ** cc '-DUINTPTR_TYPE=long long int' ...
  9266. */
  9267. #ifndef UINT32_TYPE
  9268. # ifdef HAVE_UINT32_T
  9269. # define UINT32_TYPE uint32_t
  9270. # else
  9271. # define UINT32_TYPE unsigned int
  9272. # endif
  9273. #endif
  9274. #ifndef UINT16_TYPE
  9275. # ifdef HAVE_UINT16_T
  9276. # define UINT16_TYPE uint16_t
  9277. # else
  9278. # define UINT16_TYPE unsigned short int
  9279. # endif
  9280. #endif
  9281. #ifndef INT16_TYPE
  9282. # ifdef HAVE_INT16_T
  9283. # define INT16_TYPE int16_t
  9284. # else
  9285. # define INT16_TYPE short int
  9286. # endif
  9287. #endif
  9288. #ifndef UINT8_TYPE
  9289. # ifdef HAVE_UINT8_T
  9290. # define UINT8_TYPE uint8_t
  9291. # else
  9292. # define UINT8_TYPE unsigned char
  9293. # endif
  9294. #endif
  9295. #ifndef INT8_TYPE
  9296. # ifdef HAVE_INT8_T
  9297. # define INT8_TYPE int8_t
  9298. # else
  9299. # define INT8_TYPE signed char
  9300. # endif
  9301. #endif
  9302. #ifndef LONGDOUBLE_TYPE
  9303. # define LONGDOUBLE_TYPE long double
  9304. #endif
  9305. typedef sqlite_int64 i64; /* 8-byte signed integer */
  9306. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  9307. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  9308. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  9309. typedef INT16_TYPE i16; /* 2-byte signed integer */
  9310. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  9311. typedef INT8_TYPE i8; /* 1-byte signed integer */
  9312. /*
  9313. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  9314. ** that can be stored in a u32 without loss of data. The value
  9315. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  9316. ** have to specify the value in the less intuitive manner shown:
  9317. */
  9318. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  9319. /*
  9320. ** The datatype used to store estimates of the number of rows in a
  9321. ** table or index. This is an unsigned integer type. For 99.9% of
  9322. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  9323. ** can be used at compile-time if desired.
  9324. */
  9325. #ifdef SQLITE_64BIT_STATS
  9326. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  9327. #else
  9328. typedef u32 tRowcnt; /* 32-bit is the default */
  9329. #endif
  9330. /*
  9331. ** Estimated quantities used for query planning are stored as 16-bit
  9332. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  9333. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  9334. ** But the allowed values are "grainy". Not every value is representable.
  9335. ** For example, quantities 16 and 17 are both represented by a LogEst
  9336. ** of 40. However, since LogEst quantities are suppose to be estimates,
  9337. ** not exact values, this imprecision is not a problem.
  9338. **
  9339. ** "LogEst" is short for "Logarithmic Estimate".
  9340. **
  9341. ** Examples:
  9342. ** 1 -> 0 20 -> 43 10000 -> 132
  9343. ** 2 -> 10 25 -> 46 25000 -> 146
  9344. ** 3 -> 16 100 -> 66 1000000 -> 199
  9345. ** 4 -> 20 1000 -> 99 1048576 -> 200
  9346. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  9347. **
  9348. ** The LogEst can be negative to indicate fractional values.
  9349. ** Examples:
  9350. **
  9351. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  9352. */
  9353. typedef INT16_TYPE LogEst;
  9354. /*
  9355. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  9356. */
  9357. #ifndef SQLITE_PTRSIZE
  9358. # if defined(__SIZEOF_POINTER__)
  9359. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  9360. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9361. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  9362. # define SQLITE_PTRSIZE 4
  9363. # else
  9364. # define SQLITE_PTRSIZE 8
  9365. # endif
  9366. #endif
  9367. /*
  9368. ** Macros to determine whether the machine is big or little endian,
  9369. ** and whether or not that determination is run-time or compile-time.
  9370. **
  9371. ** For best performance, an attempt is made to guess at the byte-order
  9372. ** using C-preprocessor macros. If that is unsuccessful, or if
  9373. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  9374. ** at run-time.
  9375. */
  9376. #ifdef SQLITE_AMALGAMATION
  9377. SQLITE_PRIVATE const int sqlite3one = 1;
  9378. #else
  9379. SQLITE_PRIVATE const int sqlite3one;
  9380. #endif
  9381. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9382. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  9383. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  9384. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  9385. # define SQLITE_BYTEORDER 1234
  9386. # define SQLITE_BIGENDIAN 0
  9387. # define SQLITE_LITTLEENDIAN 1
  9388. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  9389. #endif
  9390. #if (defined(sparc) || defined(__ppc__)) \
  9391. && !defined(SQLITE_RUNTIME_BYTEORDER)
  9392. # define SQLITE_BYTEORDER 4321
  9393. # define SQLITE_BIGENDIAN 1
  9394. # define SQLITE_LITTLEENDIAN 0
  9395. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  9396. #endif
  9397. #if !defined(SQLITE_BYTEORDER)
  9398. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  9399. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  9400. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  9401. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  9402. #endif
  9403. /*
  9404. ** Constants for the largest and smallest possible 64-bit signed integers.
  9405. ** These macros are designed to work correctly on both 32-bit and 64-bit
  9406. ** compilers.
  9407. */
  9408. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  9409. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  9410. /*
  9411. ** Round up a number to the next larger multiple of 8. This is used
  9412. ** to force 8-byte alignment on 64-bit architectures.
  9413. */
  9414. #define ROUND8(x) (((x)+7)&~7)
  9415. /*
  9416. ** Round down to the nearest multiple of 8
  9417. */
  9418. #define ROUNDDOWN8(x) ((x)&~7)
  9419. /*
  9420. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  9421. ** macro is used only within assert() to verify that the code gets
  9422. ** all alignment restrictions correct.
  9423. **
  9424. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  9425. ** underlying malloc() implementation might return us 4-byte aligned
  9426. ** pointers. In that case, only verify 4-byte alignment.
  9427. */
  9428. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  9429. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  9430. #else
  9431. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  9432. #endif
  9433. /*
  9434. ** Disable MMAP on platforms where it is known to not work
  9435. */
  9436. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  9437. # undef SQLITE_MAX_MMAP_SIZE
  9438. # define SQLITE_MAX_MMAP_SIZE 0
  9439. #endif
  9440. /*
  9441. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  9442. */
  9443. #ifdef __APPLE__
  9444. # include <TargetConditionals.h>
  9445. # if TARGET_OS_IPHONE
  9446. # undef SQLITE_MAX_MMAP_SIZE
  9447. # define SQLITE_MAX_MMAP_SIZE 0
  9448. # endif
  9449. #endif
  9450. #ifndef SQLITE_MAX_MMAP_SIZE
  9451. # if defined(__linux__) \
  9452. || defined(_WIN32) \
  9453. || (defined(__APPLE__) && defined(__MACH__)) \
  9454. || defined(__sun) \
  9455. || defined(__FreeBSD__) \
  9456. || defined(__DragonFly__)
  9457. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  9458. # else
  9459. # define SQLITE_MAX_MMAP_SIZE 0
  9460. # endif
  9461. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  9462. #endif
  9463. /*
  9464. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  9465. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  9466. ** not exceed the maximum mmap size.
  9467. */
  9468. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  9469. # define SQLITE_DEFAULT_MMAP_SIZE 0
  9470. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  9471. #endif
  9472. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  9473. # undef SQLITE_DEFAULT_MMAP_SIZE
  9474. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  9475. #endif
  9476. /*
  9477. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  9478. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  9479. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  9480. */
  9481. #ifdef SQLITE_ENABLE_STAT4
  9482. # undef SQLITE_ENABLE_STAT3
  9483. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9484. #elif SQLITE_ENABLE_STAT3
  9485. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9486. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  9487. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  9488. #endif
  9489. /*
  9490. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  9491. ** the Select query generator tracing logic is turned on.
  9492. */
  9493. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  9494. # define SELECTTRACE_ENABLED 1
  9495. #else
  9496. # define SELECTTRACE_ENABLED 0
  9497. #endif
  9498. /*
  9499. ** An instance of the following structure is used to store the busy-handler
  9500. ** callback for a given sqlite handle.
  9501. **
  9502. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  9503. ** callback for the database handle. Each pager opened via the sqlite
  9504. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  9505. ** callback is currently invoked only from within pager.c.
  9506. */
  9507. typedef struct BusyHandler BusyHandler;
  9508. struct BusyHandler {
  9509. int (*xFunc)(void *,int); /* The busy callback */
  9510. void *pArg; /* First arg to busy callback */
  9511. int nBusy; /* Incremented with each busy call */
  9512. };
  9513. /*
  9514. ** Name of the master database table. The master database table
  9515. ** is a special table that holds the names and attributes of all
  9516. ** user tables and indices.
  9517. */
  9518. #define MASTER_NAME "sqlite_master"
  9519. #define TEMP_MASTER_NAME "sqlite_temp_master"
  9520. /*
  9521. ** The root-page of the master database table.
  9522. */
  9523. #define MASTER_ROOT 1
  9524. /*
  9525. ** The name of the schema table.
  9526. */
  9527. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  9528. /*
  9529. ** A convenience macro that returns the number of elements in
  9530. ** an array.
  9531. */
  9532. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  9533. /*
  9534. ** Determine if the argument is a power of two
  9535. */
  9536. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  9537. /*
  9538. ** The following value as a destructor means to use sqlite3DbFree().
  9539. ** The sqlite3DbFree() routine requires two parameters instead of the
  9540. ** one parameter that destructors normally want. So we have to introduce
  9541. ** this magic value that the code knows to handle differently. Any
  9542. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  9543. ** and SQLITE_TRANSIENT.
  9544. */
  9545. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  9546. /*
  9547. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  9548. ** not support Writable Static Data (WSD) such as global and static variables.
  9549. ** All variables must either be on the stack or dynamically allocated from
  9550. ** the heap. When WSD is unsupported, the variable declarations scattered
  9551. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  9552. ** macro is used for this purpose. And instead of referencing the variable
  9553. ** directly, we use its constant as a key to lookup the run-time allocated
  9554. ** buffer that holds real variable. The constant is also the initializer
  9555. ** for the run-time allocated buffer.
  9556. **
  9557. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  9558. ** macros become no-ops and have zero performance impact.
  9559. */
  9560. #ifdef SQLITE_OMIT_WSD
  9561. #define SQLITE_WSD const
  9562. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  9563. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  9564. SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
  9565. SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
  9566. #else
  9567. #define SQLITE_WSD
  9568. #define GLOBAL(t,v) v
  9569. #define sqlite3GlobalConfig sqlite3Config
  9570. #endif
  9571. /*
  9572. ** The following macros are used to suppress compiler warnings and to
  9573. ** make it clear to human readers when a function parameter is deliberately
  9574. ** left unused within the body of a function. This usually happens when
  9575. ** a function is called via a function pointer. For example the
  9576. ** implementation of an SQL aggregate step callback may not use the
  9577. ** parameter indicating the number of arguments passed to the aggregate,
  9578. ** if it knows that this is enforced elsewhere.
  9579. **
  9580. ** When a function parameter is not used at all within the body of a function,
  9581. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  9582. ** However, these macros may also be used to suppress warnings related to
  9583. ** parameters that may or may not be used depending on compilation options.
  9584. ** For example those parameters only used in assert() statements. In these
  9585. ** cases the parameters are named as per the usual conventions.
  9586. */
  9587. #define UNUSED_PARAMETER(x) (void)(x)
  9588. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  9589. /*
  9590. ** Forward references to structures
  9591. */
  9592. typedef struct AggInfo AggInfo;
  9593. typedef struct AuthContext AuthContext;
  9594. typedef struct AutoincInfo AutoincInfo;
  9595. typedef struct Bitvec Bitvec;
  9596. typedef struct CollSeq CollSeq;
  9597. typedef struct Column Column;
  9598. typedef struct Db Db;
  9599. typedef struct Schema Schema;
  9600. typedef struct Expr Expr;
  9601. typedef struct ExprList ExprList;
  9602. typedef struct ExprSpan ExprSpan;
  9603. typedef struct FKey FKey;
  9604. typedef struct FuncDestructor FuncDestructor;
  9605. typedef struct FuncDef FuncDef;
  9606. typedef struct FuncDefHash FuncDefHash;
  9607. typedef struct IdList IdList;
  9608. typedef struct Index Index;
  9609. typedef struct IndexSample IndexSample;
  9610. typedef struct KeyClass KeyClass;
  9611. typedef struct KeyInfo KeyInfo;
  9612. typedef struct Lookaside Lookaside;
  9613. typedef struct LookasideSlot LookasideSlot;
  9614. typedef struct Module Module;
  9615. typedef struct NameContext NameContext;
  9616. typedef struct Parse Parse;
  9617. typedef struct PrintfArguments PrintfArguments;
  9618. typedef struct RowSet RowSet;
  9619. typedef struct Savepoint Savepoint;
  9620. typedef struct Select Select;
  9621. typedef struct SQLiteThread SQLiteThread;
  9622. typedef struct SelectDest SelectDest;
  9623. typedef struct SrcList SrcList;
  9624. typedef struct StrAccum StrAccum;
  9625. typedef struct Table Table;
  9626. typedef struct TableLock TableLock;
  9627. typedef struct Token Token;
  9628. typedef struct TreeView TreeView;
  9629. typedef struct Trigger Trigger;
  9630. typedef struct TriggerPrg TriggerPrg;
  9631. typedef struct TriggerStep TriggerStep;
  9632. typedef struct UnpackedRecord UnpackedRecord;
  9633. typedef struct VTable VTable;
  9634. typedef struct VtabCtx VtabCtx;
  9635. typedef struct Walker Walker;
  9636. typedef struct WhereInfo WhereInfo;
  9637. typedef struct With With;
  9638. /*
  9639. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  9640. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  9641. ** pointer types (i.e. FuncDef) defined above.
  9642. */
  9643. /************** Include btree.h in the middle of sqliteInt.h *****************/
  9644. /************** Begin file btree.h *******************************************/
  9645. /*
  9646. ** 2001 September 15
  9647. **
  9648. ** The author disclaims copyright to this source code. In place of
  9649. ** a legal notice, here is a blessing:
  9650. **
  9651. ** May you do good and not evil.
  9652. ** May you find forgiveness for yourself and forgive others.
  9653. ** May you share freely, never taking more than you give.
  9654. **
  9655. *************************************************************************
  9656. ** This header file defines the interface that the sqlite B-Tree file
  9657. ** subsystem. See comments in the source code for a detailed description
  9658. ** of what each interface routine does.
  9659. */
  9660. #ifndef _BTREE_H_
  9661. #define _BTREE_H_
  9662. /* TODO: This definition is just included so other modules compile. It
  9663. ** needs to be revisited.
  9664. */
  9665. #define SQLITE_N_BTREE_META 16
  9666. /*
  9667. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  9668. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  9669. */
  9670. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  9671. #define SQLITE_DEFAULT_AUTOVACUUM 0
  9672. #endif
  9673. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  9674. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  9675. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  9676. /*
  9677. ** Forward declarations of structure
  9678. */
  9679. typedef struct Btree Btree;
  9680. typedef struct BtCursor BtCursor;
  9681. typedef struct BtShared BtShared;
  9682. SQLITE_PRIVATE int sqlite3BtreeOpen(
  9683. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  9684. const char *zFilename, /* Name of database file to open */
  9685. sqlite3 *db, /* Associated database connection */
  9686. Btree **ppBtree, /* Return open Btree* here */
  9687. int flags, /* Flags */
  9688. int vfsFlags /* Flags passed through to VFS open */
  9689. );
  9690. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  9691. ** following values.
  9692. **
  9693. ** NOTE: These values must match the corresponding PAGER_ values in
  9694. ** pager.h.
  9695. */
  9696. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  9697. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  9698. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  9699. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  9700. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  9701. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  9702. #if SQLITE_MAX_MMAP_SIZE>0
  9703. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  9704. #endif
  9705. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  9706. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  9707. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  9708. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  9709. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  9710. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  9711. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  9712. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  9713. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  9714. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  9715. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  9716. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  9717. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  9718. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  9719. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  9720. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  9721. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  9722. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  9723. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  9724. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  9725. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  9726. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  9727. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  9728. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  9729. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  9730. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  9731. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  9732. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  9733. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  9734. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  9735. ** of the flags shown below.
  9736. **
  9737. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  9738. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  9739. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  9740. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  9741. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  9742. ** indices.)
  9743. */
  9744. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  9745. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  9746. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  9747. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  9748. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  9749. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  9750. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  9751. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  9752. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  9753. /*
  9754. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  9755. ** should be one of the following values. The integer values are assigned
  9756. ** to constants so that the offset of the corresponding field in an
  9757. ** SQLite database header may be found using the following formula:
  9758. **
  9759. ** offset = 36 + (idx * 4)
  9760. **
  9761. ** For example, the free-page-count field is located at byte offset 36 of
  9762. ** the database file header. The incr-vacuum-flag field is located at
  9763. ** byte offset 64 (== 36+4*7).
  9764. **
  9765. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  9766. ** It is a read-only number computed by the pager. But we merge it with
  9767. ** the header value access routines since its access pattern is the same.
  9768. ** Call it a "virtual meta value".
  9769. */
  9770. #define BTREE_FREE_PAGE_COUNT 0
  9771. #define BTREE_SCHEMA_VERSION 1
  9772. #define BTREE_FILE_FORMAT 2
  9773. #define BTREE_DEFAULT_CACHE_SIZE 3
  9774. #define BTREE_LARGEST_ROOT_PAGE 4
  9775. #define BTREE_TEXT_ENCODING 5
  9776. #define BTREE_USER_VERSION 6
  9777. #define BTREE_INCR_VACUUM 7
  9778. #define BTREE_APPLICATION_ID 8
  9779. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  9780. /*
  9781. ** Values that may be OR'd together to form the second argument of an
  9782. ** sqlite3BtreeCursorHints() call.
  9783. **
  9784. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  9785. ** to be filled with content that is already in sorted order.
  9786. **
  9787. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  9788. ** OP_SeekLE opcodes for a range search, but where the range of entries
  9789. ** selected will all have the same key. In other words, the cursor will
  9790. ** be used only for equality key searches.
  9791. **
  9792. */
  9793. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  9794. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  9795. SQLITE_PRIVATE int sqlite3BtreeCursor(
  9796. Btree*, /* BTree containing table to open */
  9797. int iTable, /* Index of root page */
  9798. int wrFlag, /* 1 for writing. 0 for read-only */
  9799. struct KeyInfo*, /* First argument to compare function */
  9800. BtCursor *pCursor /* Space to write cursor structure */
  9801. );
  9802. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  9803. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  9804. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  9805. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  9806. BtCursor*,
  9807. UnpackedRecord *pUnKey,
  9808. i64 intKey,
  9809. int bias,
  9810. int *pRes
  9811. );
  9812. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  9813. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  9814. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, int);
  9815. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  9816. const void *pData, int nData,
  9817. int nZero, int bias, int seekResult);
  9818. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  9819. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  9820. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  9821. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  9822. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  9823. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  9824. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  9825. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  9826. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  9827. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  9828. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  9829. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  9830. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  9831. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  9832. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  9833. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  9834. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  9835. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  9836. #ifdef SQLITE_DEBUG
  9837. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  9838. #endif
  9839. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  9840. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  9841. #ifndef NDEBUG
  9842. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  9843. #endif
  9844. #ifndef SQLITE_OMIT_BTREECOUNT
  9845. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  9846. #endif
  9847. #ifdef SQLITE_TEST
  9848. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  9849. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  9850. #endif
  9851. #ifndef SQLITE_OMIT_WAL
  9852. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  9853. #endif
  9854. /*
  9855. ** If we are not using shared cache, then there is no need to
  9856. ** use mutexes to access the BtShared structures. So make the
  9857. ** Enter and Leave procedures no-ops.
  9858. */
  9859. #ifndef SQLITE_OMIT_SHARED_CACHE
  9860. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  9861. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  9862. #else
  9863. # define sqlite3BtreeEnter(X)
  9864. # define sqlite3BtreeEnterAll(X)
  9865. #endif
  9866. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  9867. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  9868. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  9869. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  9870. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  9871. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  9872. #ifndef NDEBUG
  9873. /* These routines are used inside assert() statements only. */
  9874. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  9875. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  9876. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  9877. #endif
  9878. #else
  9879. # define sqlite3BtreeSharable(X) 0
  9880. # define sqlite3BtreeLeave(X)
  9881. # define sqlite3BtreeEnterCursor(X)
  9882. # define sqlite3BtreeLeaveCursor(X)
  9883. # define sqlite3BtreeLeaveAll(X)
  9884. # define sqlite3BtreeHoldsMutex(X) 1
  9885. # define sqlite3BtreeHoldsAllMutexes(X) 1
  9886. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  9887. #endif
  9888. #endif /* _BTREE_H_ */
  9889. /************** End of btree.h ***********************************************/
  9890. /************** Continuing where we left off in sqliteInt.h ******************/
  9891. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  9892. /************** Begin file vdbe.h ********************************************/
  9893. /*
  9894. ** 2001 September 15
  9895. **
  9896. ** The author disclaims copyright to this source code. In place of
  9897. ** a legal notice, here is a blessing:
  9898. **
  9899. ** May you do good and not evil.
  9900. ** May you find forgiveness for yourself and forgive others.
  9901. ** May you share freely, never taking more than you give.
  9902. **
  9903. *************************************************************************
  9904. ** Header file for the Virtual DataBase Engine (VDBE)
  9905. **
  9906. ** This header defines the interface to the virtual database engine
  9907. ** or VDBE. The VDBE implements an abstract machine that runs a
  9908. ** simple program to access and modify the underlying database.
  9909. */
  9910. #ifndef _SQLITE_VDBE_H_
  9911. #define _SQLITE_VDBE_H_
  9912. /* #include <stdio.h> */
  9913. /*
  9914. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  9915. ** in the source file sqliteVdbe.c are allowed to see the insides
  9916. ** of this structure.
  9917. */
  9918. typedef struct Vdbe Vdbe;
  9919. /*
  9920. ** The names of the following types declared in vdbeInt.h are required
  9921. ** for the VdbeOp definition.
  9922. */
  9923. typedef struct Mem Mem;
  9924. typedef struct SubProgram SubProgram;
  9925. /*
  9926. ** A single instruction of the virtual machine has an opcode
  9927. ** and as many as three operands. The instruction is recorded
  9928. ** as an instance of the following structure:
  9929. */
  9930. struct VdbeOp {
  9931. u8 opcode; /* What operation to perform */
  9932. signed char p4type; /* One of the P4_xxx constants for p4 */
  9933. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  9934. u8 p5; /* Fifth parameter is an unsigned character */
  9935. int p1; /* First operand */
  9936. int p2; /* Second parameter (often the jump destination) */
  9937. int p3; /* The third parameter */
  9938. union p4union { /* fourth parameter */
  9939. int i; /* Integer value if p4type==P4_INT32 */
  9940. void *p; /* Generic pointer */
  9941. char *z; /* Pointer to data for string (char array) types */
  9942. i64 *pI64; /* Used when p4type is P4_INT64 */
  9943. double *pReal; /* Used when p4type is P4_REAL */
  9944. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  9945. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  9946. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  9947. Mem *pMem; /* Used when p4type is P4_MEM */
  9948. VTable *pVtab; /* Used when p4type is P4_VTAB */
  9949. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  9950. int *ai; /* Used when p4type is P4_INTARRAY */
  9951. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  9952. int (*xAdvance)(BtCursor *, int *);
  9953. } p4;
  9954. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9955. char *zComment; /* Comment to improve readability */
  9956. #endif
  9957. #ifdef VDBE_PROFILE
  9958. u32 cnt; /* Number of times this instruction was executed */
  9959. u64 cycles; /* Total time spent executing this instruction */
  9960. #endif
  9961. #ifdef SQLITE_VDBE_COVERAGE
  9962. int iSrcLine; /* Source-code line that generated this opcode */
  9963. #endif
  9964. };
  9965. typedef struct VdbeOp VdbeOp;
  9966. /*
  9967. ** A sub-routine used to implement a trigger program.
  9968. */
  9969. struct SubProgram {
  9970. VdbeOp *aOp; /* Array of opcodes for sub-program */
  9971. int nOp; /* Elements in aOp[] */
  9972. int nMem; /* Number of memory cells required */
  9973. int nCsr; /* Number of cursors required */
  9974. int nOnce; /* Number of OP_Once instructions */
  9975. void *token; /* id that may be used to recursive triggers */
  9976. SubProgram *pNext; /* Next sub-program already visited */
  9977. };
  9978. /*
  9979. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  9980. ** it takes up less space.
  9981. */
  9982. struct VdbeOpList {
  9983. u8 opcode; /* What operation to perform */
  9984. signed char p1; /* First operand */
  9985. signed char p2; /* Second parameter (often the jump destination) */
  9986. signed char p3; /* Third parameter */
  9987. };
  9988. typedef struct VdbeOpList VdbeOpList;
  9989. /*
  9990. ** Allowed values of VdbeOp.p4type
  9991. */
  9992. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  9993. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  9994. #define P4_STATIC (-2) /* Pointer to a static string */
  9995. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  9996. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  9997. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  9998. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  9999. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  10000. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  10001. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  10002. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  10003. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  10004. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  10005. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  10006. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  10007. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  10008. #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
  10009. /* Error message codes for OP_Halt */
  10010. #define P5_ConstraintNotNull 1
  10011. #define P5_ConstraintUnique 2
  10012. #define P5_ConstraintCheck 3
  10013. #define P5_ConstraintFK 4
  10014. /*
  10015. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  10016. ** number of columns of data returned by the statement.
  10017. */
  10018. #define COLNAME_NAME 0
  10019. #define COLNAME_DECLTYPE 1
  10020. #define COLNAME_DATABASE 2
  10021. #define COLNAME_TABLE 3
  10022. #define COLNAME_COLUMN 4
  10023. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  10024. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  10025. #else
  10026. # ifdef SQLITE_OMIT_DECLTYPE
  10027. # define COLNAME_N 1 /* Store only the name */
  10028. # else
  10029. # define COLNAME_N 2 /* Store the name and decltype */
  10030. # endif
  10031. #endif
  10032. /*
  10033. ** The following macro converts a relative address in the p2 field
  10034. ** of a VdbeOp structure into a negative number so that
  10035. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  10036. ** the macro again restores the address.
  10037. */
  10038. #define ADDR(X) (-1-(X))
  10039. /*
  10040. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  10041. ** header file that defines a number for each opcode used by the VDBE.
  10042. */
  10043. /************** Include opcodes.h in the middle of vdbe.h ********************/
  10044. /************** Begin file opcodes.h *****************************************/
  10045. /* Automatically generated. Do not edit */
  10046. /* See the mkopcodeh.awk script for details */
  10047. #define OP_Savepoint 1
  10048. #define OP_AutoCommit 2
  10049. #define OP_Transaction 3
  10050. #define OP_SorterNext 4
  10051. #define OP_PrevIfOpen 5
  10052. #define OP_NextIfOpen 6
  10053. #define OP_Prev 7
  10054. #define OP_Next 8
  10055. #define OP_Checkpoint 9
  10056. #define OP_JournalMode 10
  10057. #define OP_Vacuum 11
  10058. #define OP_VFilter 12 /* synopsis: iplan=r[P3] zplan='P4' */
  10059. #define OP_VUpdate 13 /* synopsis: data=r[P3@P2] */
  10060. #define OP_Goto 14
  10061. #define OP_Gosub 15
  10062. #define OP_Return 16
  10063. #define OP_InitCoroutine 17
  10064. #define OP_EndCoroutine 18
  10065. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  10066. #define OP_Yield 20
  10067. #define OP_HaltIfNull 21 /* synopsis: if r[P3]=null halt */
  10068. #define OP_Halt 22
  10069. #define OP_Integer 23 /* synopsis: r[P2]=P1 */
  10070. #define OP_Int64 24 /* synopsis: r[P2]=P4 */
  10071. #define OP_String 25 /* synopsis: r[P2]='P4' (len=P1) */
  10072. #define OP_Null 26 /* synopsis: r[P2..P3]=NULL */
  10073. #define OP_SoftNull 27 /* synopsis: r[P1]=NULL */
  10074. #define OP_Blob 28 /* synopsis: r[P2]=P4 (len=P1) */
  10075. #define OP_Variable 29 /* synopsis: r[P2]=parameter(P1,P4) */
  10076. #define OP_Move 30 /* synopsis: r[P2@P3]=r[P1@P3] */
  10077. #define OP_Copy 31 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  10078. #define OP_SCopy 32 /* synopsis: r[P2]=r[P1] */
  10079. #define OP_ResultRow 33 /* synopsis: output=r[P1@P2] */
  10080. #define OP_CollSeq 34
  10081. #define OP_Function0 35 /* synopsis: r[P3]=func(r[P2@P5]) */
  10082. #define OP_Function 36 /* synopsis: r[P3]=func(r[P2@P5]) */
  10083. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  10084. #define OP_MustBeInt 38
  10085. #define OP_RealAffinity 39
  10086. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  10087. #define OP_Permutation 41
  10088. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  10089. #define OP_Jump 43
  10090. #define OP_Once 44
  10091. #define OP_If 45
  10092. #define OP_IfNot 46
  10093. #define OP_Column 47 /* synopsis: r[P3]=PX */
  10094. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  10095. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  10096. #define OP_Count 50 /* synopsis: r[P2]=count() */
  10097. #define OP_ReadCookie 51
  10098. #define OP_SetCookie 52
  10099. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  10100. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  10101. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  10102. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  10103. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  10104. #define OP_SorterOpen 58
  10105. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  10106. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  10107. #define OP_Close 61
  10108. #define OP_ColumnsUsed 62
  10109. #define OP_SeekLT 63 /* synopsis: key=r[P3@P4] */
  10110. #define OP_SeekLE 64 /* synopsis: key=r[P3@P4] */
  10111. #define OP_SeekGE 65 /* synopsis: key=r[P3@P4] */
  10112. #define OP_SeekGT 66 /* synopsis: key=r[P3@P4] */
  10113. #define OP_Seek 67 /* synopsis: intkey=r[P2] */
  10114. #define OP_NoConflict 68 /* synopsis: key=r[P3@P4] */
  10115. #define OP_NotFound 69 /* synopsis: key=r[P3@P4] */
  10116. #define OP_Found 70 /* synopsis: key=r[P3@P4] */
  10117. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  10118. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  10119. #define OP_NotExists 73 /* synopsis: intkey=r[P3] */
  10120. #define OP_Sequence 74 /* synopsis: r[P2]=cursor[P1].ctr++ */
  10121. #define OP_NewRowid 75 /* synopsis: r[P2]=rowid */
  10122. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  10123. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  10124. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  10125. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  10126. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  10127. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  10128. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  10129. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  10130. #define OP_Insert 84 /* synopsis: intkey=r[P3] data=r[P2] */
  10131. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  10132. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  10133. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  10134. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  10135. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  10136. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  10137. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  10138. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  10139. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  10140. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  10141. #define OP_InsertInt 95 /* synopsis: intkey=P3 data=r[P2] */
  10142. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  10143. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  10144. #define OP_Delete 98
  10145. #define OP_ResetCount 99
  10146. #define OP_SorterCompare 100 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  10147. #define OP_SorterData 101 /* synopsis: r[P2]=data */
  10148. #define OP_RowKey 102 /* synopsis: r[P2]=key */
  10149. #define OP_RowData 103 /* synopsis: r[P2]=data */
  10150. #define OP_Rowid 104 /* synopsis: r[P2]=rowid */
  10151. #define OP_NullRow 105
  10152. #define OP_Last 106
  10153. #define OP_SorterSort 107
  10154. #define OP_Sort 108
  10155. #define OP_Rewind 109
  10156. #define OP_SorterInsert 110
  10157. #define OP_IdxInsert 111 /* synopsis: key=r[P2] */
  10158. #define OP_IdxDelete 112 /* synopsis: key=r[P2@P3] */
  10159. #define OP_IdxRowid 113 /* synopsis: r[P2]=rowid */
  10160. #define OP_IdxLE 114 /* synopsis: key=r[P3@P4] */
  10161. #define OP_IdxGT 115 /* synopsis: key=r[P3@P4] */
  10162. #define OP_IdxLT 116 /* synopsis: key=r[P3@P4] */
  10163. #define OP_IdxGE 117 /* synopsis: key=r[P3@P4] */
  10164. #define OP_Destroy 118
  10165. #define OP_Clear 119
  10166. #define OP_ResetSorter 120
  10167. #define OP_CreateIndex 121 /* synopsis: r[P2]=root iDb=P1 */
  10168. #define OP_CreateTable 122 /* synopsis: r[P2]=root iDb=P1 */
  10169. #define OP_ParseSchema 123
  10170. #define OP_LoadAnalysis 124
  10171. #define OP_DropTable 125
  10172. #define OP_DropIndex 126
  10173. #define OP_DropTrigger 127
  10174. #define OP_IntegrityCk 128
  10175. #define OP_RowSetAdd 129 /* synopsis: rowset(P1)=r[P2] */
  10176. #define OP_RowSetRead 130 /* synopsis: r[P3]=rowset(P1) */
  10177. #define OP_RowSetTest 131 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  10178. #define OP_Program 132
  10179. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  10180. #define OP_Param 134
  10181. #define OP_FkCounter 135 /* synopsis: fkctr[P1]+=P2 */
  10182. #define OP_FkIfZero 136 /* synopsis: if fkctr[P1]==0 goto P2 */
  10183. #define OP_MemMax 137 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  10184. #define OP_IfPos 138 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  10185. #define OP_SetIfNotPos 139 /* synopsis: if r[P1]<=0 then r[P2]=P3 */
  10186. #define OP_IfNotZero 140 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
  10187. #define OP_DecrJumpZero 141 /* synopsis: if (--r[P1])==0 goto P2 */
  10188. #define OP_JumpZeroIncr 142 /* synopsis: if (r[P1]++)==0 ) goto P2 */
  10189. #define OP_AggStep0 143 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10190. #define OP_AggStep 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10191. #define OP_AggFinal 145 /* synopsis: accum=r[P1] N=P2 */
  10192. #define OP_IncrVacuum 146
  10193. #define OP_Expire 147
  10194. #define OP_TableLock 148 /* synopsis: iDb=P1 root=P2 write=P3 */
  10195. #define OP_VBegin 149
  10196. #define OP_VCreate 150
  10197. #define OP_VDestroy 151
  10198. #define OP_VOpen 152
  10199. #define OP_VColumn 153 /* synopsis: r[P3]=vcolumn(P2) */
  10200. #define OP_VNext 154
  10201. #define OP_VRename 155
  10202. #define OP_Pagecount 156
  10203. #define OP_MaxPgcnt 157
  10204. #define OP_Init 158 /* synopsis: Start at P2 */
  10205. #define OP_Noop 159
  10206. #define OP_Explain 160
  10207. /* Properties such as "out2" or "jump" that are specified in
  10208. ** comments following the "case" for each opcode in the vdbe.c
  10209. ** are encoded into bitvectors as follows:
  10210. */
  10211. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  10212. #define OPFLG_IN1 0x0002 /* in1: P1 is an input */
  10213. #define OPFLG_IN2 0x0004 /* in2: P2 is an input */
  10214. #define OPFLG_IN3 0x0008 /* in3: P3 is an input */
  10215. #define OPFLG_OUT2 0x0010 /* out2: P2 is an output */
  10216. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  10217. #define OPFLG_INITIALIZER {\
  10218. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,\
  10219. /* 8 */ 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01,\
  10220. /* 16 */ 0x02, 0x01, 0x02, 0x12, 0x03, 0x08, 0x00, 0x10,\
  10221. /* 24 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
  10222. /* 32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
  10223. /* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
  10224. /* 48 */ 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00, 0x00,\
  10225. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
  10226. /* 64 */ 0x09, 0x09, 0x09, 0x04, 0x09, 0x09, 0x09, 0x26,\
  10227. /* 72 */ 0x26, 0x09, 0x10, 0x10, 0x03, 0x03, 0x0b, 0x0b,\
  10228. /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
  10229. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  10230. /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10231. /* 104 */ 0x10, 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04,\
  10232. /* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
  10233. /* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10234. /* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
  10235. /* 136 */ 0x01, 0x04, 0x03, 0x06, 0x03, 0x03, 0x03, 0x00,\
  10236. /* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10237. /* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
  10238. /* 160 */ 0x00,}
  10239. /************** End of opcodes.h *********************************************/
  10240. /************** Continuing where we left off in vdbe.h ***********************/
  10241. /*
  10242. ** Prototypes for the VDBE interface. See comments on the implementation
  10243. ** for a description of what each of these routines does.
  10244. */
  10245. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  10246. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  10247. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  10248. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  10249. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  10250. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  10251. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  10252. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  10253. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  10254. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  10255. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  10256. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  10257. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  10258. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  10259. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  10260. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  10261. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  10262. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  10263. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  10264. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  10265. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  10266. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  10267. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  10268. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  10269. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  10270. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  10271. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  10272. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  10273. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  10274. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  10275. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  10276. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  10277. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  10278. #ifdef SQLITE_DEBUG
  10279. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  10280. #endif
  10281. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  10282. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  10283. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  10284. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  10285. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  10286. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  10287. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  10288. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  10289. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  10290. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  10291. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  10292. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  10293. #ifndef SQLITE_OMIT_TRACE
  10294. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  10295. #endif
  10296. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  10297. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  10298. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  10299. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  10300. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  10301. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  10302. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  10303. #ifndef SQLITE_OMIT_TRIGGER
  10304. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  10305. #endif
  10306. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  10307. ** each VDBE opcode.
  10308. **
  10309. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  10310. ** comments in VDBE programs that show key decision points in the code
  10311. ** generator.
  10312. */
  10313. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10314. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  10315. # define VdbeComment(X) sqlite3VdbeComment X
  10316. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  10317. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  10318. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  10319. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  10320. # else
  10321. # define VdbeModuleComment(X)
  10322. # endif
  10323. #else
  10324. # define VdbeComment(X)
  10325. # define VdbeNoopComment(X)
  10326. # define VdbeModuleComment(X)
  10327. #endif
  10328. /*
  10329. ** The VdbeCoverage macros are used to set a coverage testing point
  10330. ** for VDBE branch instructions. The coverage testing points are line
  10331. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  10332. ** only works with an amalagmation build. That's ok since a VDBE branch
  10333. ** coverage build designed for testing the test suite only. No application
  10334. ** should ever ship with VDBE branch coverage measuring turned on.
  10335. **
  10336. ** VdbeCoverage(v) // Mark the previously coded instruction
  10337. ** // as a branch
  10338. **
  10339. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  10340. **
  10341. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  10342. **
  10343. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  10344. **
  10345. ** Every VDBE branch operation must be tagged with one of the macros above.
  10346. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  10347. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  10348. ** routine in vdbe.c, alerting the developer to the missed tag.
  10349. */
  10350. #ifdef SQLITE_VDBE_COVERAGE
  10351. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  10352. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  10353. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  10354. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  10355. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  10356. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  10357. #else
  10358. # define VdbeCoverage(v)
  10359. # define VdbeCoverageIf(v,x)
  10360. # define VdbeCoverageAlwaysTaken(v)
  10361. # define VdbeCoverageNeverTaken(v)
  10362. # define VDBE_OFFSET_LINENO(x) 0
  10363. #endif
  10364. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  10365. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  10366. #else
  10367. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  10368. #endif
  10369. #endif
  10370. /************** End of vdbe.h ************************************************/
  10371. /************** Continuing where we left off in sqliteInt.h ******************/
  10372. /************** Include pager.h in the middle of sqliteInt.h *****************/
  10373. /************** Begin file pager.h *******************************************/
  10374. /*
  10375. ** 2001 September 15
  10376. **
  10377. ** The author disclaims copyright to this source code. In place of
  10378. ** a legal notice, here is a blessing:
  10379. **
  10380. ** May you do good and not evil.
  10381. ** May you find forgiveness for yourself and forgive others.
  10382. ** May you share freely, never taking more than you give.
  10383. **
  10384. *************************************************************************
  10385. ** This header file defines the interface that the sqlite page cache
  10386. ** subsystem. The page cache subsystem reads and writes a file a page
  10387. ** at a time and provides a journal for rollback.
  10388. */
  10389. #ifndef _PAGER_H_
  10390. #define _PAGER_H_
  10391. /*
  10392. ** Default maximum size for persistent journal files. A negative
  10393. ** value means no limit. This value may be overridden using the
  10394. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  10395. */
  10396. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  10397. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  10398. #endif
  10399. /*
  10400. ** The type used to represent a page number. The first page in a file
  10401. ** is called page 1. 0 is used to represent "not a page".
  10402. */
  10403. typedef u32 Pgno;
  10404. /*
  10405. ** Each open file is managed by a separate instance of the "Pager" structure.
  10406. */
  10407. typedef struct Pager Pager;
  10408. /*
  10409. ** Handle type for pages.
  10410. */
  10411. typedef struct PgHdr DbPage;
  10412. /*
  10413. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  10414. ** reserved for working around a windows/posix incompatibility). It is
  10415. ** used in the journal to signify that the remainder of the journal file
  10416. ** is devoted to storing a master journal name - there are no more pages to
  10417. ** roll back. See comments for function writeMasterJournal() in pager.c
  10418. ** for details.
  10419. */
  10420. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  10421. /*
  10422. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  10423. **
  10424. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  10425. */
  10426. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  10427. #define PAGER_MEMORY 0x0002 /* In-memory database */
  10428. /*
  10429. ** Valid values for the second argument to sqlite3PagerLockingMode().
  10430. */
  10431. #define PAGER_LOCKINGMODE_QUERY -1
  10432. #define PAGER_LOCKINGMODE_NORMAL 0
  10433. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  10434. /*
  10435. ** Numeric constants that encode the journalmode.
  10436. */
  10437. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  10438. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  10439. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  10440. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  10441. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  10442. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  10443. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  10444. /*
  10445. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  10446. */
  10447. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  10448. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  10449. /*
  10450. ** Flags for sqlite3PagerSetFlags()
  10451. */
  10452. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  10453. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  10454. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  10455. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  10456. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  10457. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  10458. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  10459. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  10460. /*
  10461. ** The remainder of this file contains the declarations of the functions
  10462. ** that make up the Pager sub-system API. See source code comments for
  10463. ** a detailed description of each routine.
  10464. */
  10465. /* Open and close a Pager connection. */
  10466. SQLITE_PRIVATE int sqlite3PagerOpen(
  10467. sqlite3_vfs*,
  10468. Pager **ppPager,
  10469. const char*,
  10470. int,
  10471. int,
  10472. int,
  10473. void(*)(DbPage*)
  10474. );
  10475. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  10476. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  10477. /* Functions used to configure a Pager object. */
  10478. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  10479. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  10480. #ifdef SQLITE_HAS_CODEC
  10481. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  10482. #endif
  10483. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  10484. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  10485. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  10486. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  10487. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  10488. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  10489. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  10490. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  10491. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  10492. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  10493. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  10494. /* Functions used to obtain and release page references. */
  10495. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  10496. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  10497. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  10498. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  10499. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  10500. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  10501. /* Operations on page references. */
  10502. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  10503. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  10504. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  10505. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  10506. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  10507. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  10508. /* Functions used to manage pager transactions and savepoints. */
  10509. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  10510. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  10511. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  10512. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  10513. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  10514. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  10515. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  10516. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  10517. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  10518. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  10519. #ifndef SQLITE_OMIT_WAL
  10520. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  10521. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  10522. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  10523. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  10524. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  10525. #endif
  10526. #ifdef SQLITE_ENABLE_ZIPVFS
  10527. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  10528. #endif
  10529. /* Functions used to query pager state and configuration. */
  10530. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  10531. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  10532. #ifdef SQLITE_DEBUG
  10533. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  10534. #endif
  10535. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  10536. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  10537. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  10538. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  10539. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  10540. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  10541. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  10542. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  10543. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  10544. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  10545. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  10546. /* Functions used to truncate the database file. */
  10547. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  10548. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  10549. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  10550. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  10551. #endif
  10552. /* Functions to support testing and debugging. */
  10553. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  10554. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  10555. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  10556. #endif
  10557. #ifdef SQLITE_TEST
  10558. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  10559. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  10560. void disable_simulated_io_errors(void);
  10561. void enable_simulated_io_errors(void);
  10562. #else
  10563. # define disable_simulated_io_errors()
  10564. # define enable_simulated_io_errors()
  10565. #endif
  10566. #endif /* _PAGER_H_ */
  10567. /************** End of pager.h ***********************************************/
  10568. /************** Continuing where we left off in sqliteInt.h ******************/
  10569. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  10570. /************** Begin file pcache.h ******************************************/
  10571. /*
  10572. ** 2008 August 05
  10573. **
  10574. ** The author disclaims copyright to this source code. In place of
  10575. ** a legal notice, here is a blessing:
  10576. **
  10577. ** May you do good and not evil.
  10578. ** May you find forgiveness for yourself and forgive others.
  10579. ** May you share freely, never taking more than you give.
  10580. **
  10581. *************************************************************************
  10582. ** This header file defines the interface that the sqlite page cache
  10583. ** subsystem.
  10584. */
  10585. #ifndef _PCACHE_H_
  10586. typedef struct PgHdr PgHdr;
  10587. typedef struct PCache PCache;
  10588. /*
  10589. ** Every page in the cache is controlled by an instance of the following
  10590. ** structure.
  10591. */
  10592. struct PgHdr {
  10593. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  10594. void *pData; /* Page data */
  10595. void *pExtra; /* Extra content */
  10596. PgHdr *pDirty; /* Transient list of dirty pages */
  10597. Pager *pPager; /* The pager this page is part of */
  10598. Pgno pgno; /* Page number for this page */
  10599. #ifdef SQLITE_CHECK_PAGES
  10600. u32 pageHash; /* Hash of page content */
  10601. #endif
  10602. u16 flags; /* PGHDR flags defined below */
  10603. /**********************************************************************
  10604. ** Elements above are public. All that follows is private to pcache.c
  10605. ** and should not be accessed by other modules.
  10606. */
  10607. i16 nRef; /* Number of users of this page */
  10608. PCache *pCache; /* Cache that owns this page */
  10609. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  10610. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  10611. };
  10612. /* Bit values for PgHdr.flags */
  10613. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  10614. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  10615. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  10616. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  10617. ** writing this page to the database */
  10618. #define PGHDR_NEED_READ 0x010 /* Content is unread */
  10619. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  10620. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  10621. /* Initialize and shutdown the page cache subsystem */
  10622. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  10623. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  10624. /* Page cache buffer management:
  10625. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  10626. */
  10627. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  10628. /* Create a new pager cache.
  10629. ** Under memory stress, invoke xStress to try to make pages clean.
  10630. ** Only clean and unpinned pages can be reclaimed.
  10631. */
  10632. SQLITE_PRIVATE int sqlite3PcacheOpen(
  10633. int szPage, /* Size of every page */
  10634. int szExtra, /* Extra space associated with each page */
  10635. int bPurgeable, /* True if pages are on backing store */
  10636. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  10637. void *pStress, /* Argument to xStress */
  10638. PCache *pToInit /* Preallocated space for the PCache */
  10639. );
  10640. /* Modify the page-size after the cache has been created. */
  10641. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  10642. /* Return the size in bytes of a PCache object. Used to preallocate
  10643. ** storage space.
  10644. */
  10645. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  10646. /* One release per successful fetch. Page is pinned until released.
  10647. ** Reference counted.
  10648. */
  10649. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  10650. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  10651. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  10652. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  10653. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  10654. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  10655. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  10656. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  10657. /* Change a page number. Used by incr-vacuum. */
  10658. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  10659. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  10660. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  10661. /* Get a list of all dirty pages in the cache, sorted by page number */
  10662. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  10663. /* Reset and close the cache object */
  10664. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  10665. /* Clear flags from pages of the page cache */
  10666. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  10667. /* Discard the contents of the cache */
  10668. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  10669. /* Return the total number of outstanding page references */
  10670. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  10671. /* Increment the reference count of an existing page */
  10672. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  10673. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  10674. /* Return the total number of pages stored in the cache */
  10675. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  10676. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  10677. /* Iterate through all dirty pages currently stored in the cache. This
  10678. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  10679. ** library is built.
  10680. */
  10681. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  10682. #endif
  10683. /* Set and get the suggested cache-size for the specified pager-cache.
  10684. **
  10685. ** If no global maximum is configured, then the system attempts to limit
  10686. ** the total number of pages cached by purgeable pager-caches to the sum
  10687. ** of the suggested cache-sizes.
  10688. */
  10689. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  10690. #ifdef SQLITE_TEST
  10691. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  10692. #endif
  10693. /* Free up as much memory as possible from the page cache */
  10694. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  10695. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  10696. /* Try to return memory used by the pcache module to the main memory heap */
  10697. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  10698. #endif
  10699. #ifdef SQLITE_TEST
  10700. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  10701. #endif
  10702. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  10703. /* Return the header size */
  10704. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  10705. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  10706. #endif /* _PCACHE_H_ */
  10707. /************** End of pcache.h **********************************************/
  10708. /************** Continuing where we left off in sqliteInt.h ******************/
  10709. /************** Include os.h in the middle of sqliteInt.h ********************/
  10710. /************** Begin file os.h **********************************************/
  10711. /*
  10712. ** 2001 September 16
  10713. **
  10714. ** The author disclaims copyright to this source code. In place of
  10715. ** a legal notice, here is a blessing:
  10716. **
  10717. ** May you do good and not evil.
  10718. ** May you find forgiveness for yourself and forgive others.
  10719. ** May you share freely, never taking more than you give.
  10720. **
  10721. ******************************************************************************
  10722. **
  10723. ** This header file (together with is companion C source-code file
  10724. ** "os.c") attempt to abstract the underlying operating system so that
  10725. ** the SQLite library will work on both POSIX and windows systems.
  10726. **
  10727. ** This header file is #include-ed by sqliteInt.h and thus ends up
  10728. ** being included by every source file.
  10729. */
  10730. #ifndef _SQLITE_OS_H_
  10731. #define _SQLITE_OS_H_
  10732. /*
  10733. ** Attempt to automatically detect the operating system and setup the
  10734. ** necessary pre-processor macros for it.
  10735. */
  10736. /************** Include os_setup.h in the middle of os.h *********************/
  10737. /************** Begin file os_setup.h ****************************************/
  10738. /*
  10739. ** 2013 November 25
  10740. **
  10741. ** The author disclaims copyright to this source code. In place of
  10742. ** a legal notice, here is a blessing:
  10743. **
  10744. ** May you do good and not evil.
  10745. ** May you find forgiveness for yourself and forgive others.
  10746. ** May you share freely, never taking more than you give.
  10747. **
  10748. ******************************************************************************
  10749. **
  10750. ** This file contains pre-processor directives related to operating system
  10751. ** detection and/or setup.
  10752. */
  10753. #ifndef _OS_SETUP_H_
  10754. #define _OS_SETUP_H_
  10755. /*
  10756. ** Figure out if we are dealing with Unix, Windows, or some other operating
  10757. ** system.
  10758. **
  10759. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  10760. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  10761. ** the three will be 1. The other two will be 0.
  10762. */
  10763. #if defined(SQLITE_OS_OTHER)
  10764. # if SQLITE_OS_OTHER==1
  10765. # undef SQLITE_OS_UNIX
  10766. # define SQLITE_OS_UNIX 0
  10767. # undef SQLITE_OS_WIN
  10768. # define SQLITE_OS_WIN 0
  10769. # else
  10770. # undef SQLITE_OS_OTHER
  10771. # endif
  10772. #endif
  10773. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  10774. # define SQLITE_OS_OTHER 0
  10775. # ifndef SQLITE_OS_WIN
  10776. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  10777. defined(__MINGW32__) || defined(__BORLANDC__)
  10778. # define SQLITE_OS_WIN 1
  10779. # define SQLITE_OS_UNIX 0
  10780. # else
  10781. # define SQLITE_OS_WIN 0
  10782. # define SQLITE_OS_UNIX 1
  10783. # endif
  10784. # else
  10785. # define SQLITE_OS_UNIX 0
  10786. # endif
  10787. #else
  10788. # ifndef SQLITE_OS_WIN
  10789. # define SQLITE_OS_WIN 0
  10790. # endif
  10791. #endif
  10792. #endif /* _OS_SETUP_H_ */
  10793. /************** End of os_setup.h ********************************************/
  10794. /************** Continuing where we left off in os.h *************************/
  10795. /* If the SET_FULLSYNC macro is not defined above, then make it
  10796. ** a no-op
  10797. */
  10798. #ifndef SET_FULLSYNC
  10799. # define SET_FULLSYNC(x,y)
  10800. #endif
  10801. /*
  10802. ** The default size of a disk sector
  10803. */
  10804. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  10805. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  10806. #endif
  10807. /*
  10808. ** Temporary files are named starting with this prefix followed by 16 random
  10809. ** alphanumeric characters, and no file extension. They are stored in the
  10810. ** OS's standard temporary file directory, and are deleted prior to exit.
  10811. ** If sqlite is being embedded in another program, you may wish to change the
  10812. ** prefix to reflect your program's name, so that if your program exits
  10813. ** prematurely, old temporary files can be easily identified. This can be done
  10814. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  10815. **
  10816. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  10817. ** Mcafee started using SQLite in their anti-virus product and it
  10818. ** started putting files with the "sqlite" name in the c:/temp folder.
  10819. ** This annoyed many windows users. Those users would then do a
  10820. ** Google search for "sqlite", find the telephone numbers of the
  10821. ** developers and call to wake them up at night and complain.
  10822. ** For this reason, the default name prefix is changed to be "sqlite"
  10823. ** spelled backwards. So the temp files are still identified, but
  10824. ** anybody smart enough to figure out the code is also likely smart
  10825. ** enough to know that calling the developer will not help get rid
  10826. ** of the file.
  10827. */
  10828. #ifndef SQLITE_TEMP_FILE_PREFIX
  10829. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  10830. #endif
  10831. /*
  10832. ** The following values may be passed as the second argument to
  10833. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  10834. **
  10835. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  10836. ** RESERVED: A single process may hold a RESERVED lock on a file at
  10837. ** any time. Other processes may hold and obtain new SHARED locks.
  10838. ** PENDING: A single process may hold a PENDING lock on a file at
  10839. ** any one time. Existing SHARED locks may persist, but no new
  10840. ** SHARED locks may be obtained by other processes.
  10841. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  10842. **
  10843. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  10844. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  10845. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  10846. ** sqlite3OsLock().
  10847. */
  10848. #define NO_LOCK 0
  10849. #define SHARED_LOCK 1
  10850. #define RESERVED_LOCK 2
  10851. #define PENDING_LOCK 3
  10852. #define EXCLUSIVE_LOCK 4
  10853. /*
  10854. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  10855. **
  10856. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  10857. ** those functions are not available. So we use only LockFile() and
  10858. ** UnlockFile().
  10859. **
  10860. ** LockFile() prevents not just writing but also reading by other processes.
  10861. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  10862. ** byte out of a specific range of bytes. The lock byte is obtained at
  10863. ** random so two separate readers can probably access the file at the
  10864. ** same time, unless they are unlucky and choose the same lock byte.
  10865. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  10866. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  10867. ** a single byte of the file that is designated as the reserved lock byte.
  10868. ** A PENDING_LOCK is obtained by locking a designated byte different from
  10869. ** the RESERVED_LOCK byte.
  10870. **
  10871. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  10872. ** which means we can use reader/writer locks. When reader/writer locks
  10873. ** are used, the lock is placed on the same range of bytes that is used
  10874. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  10875. ** will support two or more Win95 readers or two or more WinNT readers.
  10876. ** But a single Win95 reader will lock out all WinNT readers and a single
  10877. ** WinNT reader will lock out all other Win95 readers.
  10878. **
  10879. ** The following #defines specify the range of bytes used for locking.
  10880. ** SHARED_SIZE is the number of bytes available in the pool from which
  10881. ** a random byte is selected for a shared lock. The pool of bytes for
  10882. ** shared locks begins at SHARED_FIRST.
  10883. **
  10884. ** The same locking strategy and
  10885. ** byte ranges are used for Unix. This leaves open the possibility of having
  10886. ** clients on win95, winNT, and unix all talking to the same shared file
  10887. ** and all locking correctly. To do so would require that samba (or whatever
  10888. ** tool is being used for file sharing) implements locks correctly between
  10889. ** windows and unix. I'm guessing that isn't likely to happen, but by
  10890. ** using the same locking range we are at least open to the possibility.
  10891. **
  10892. ** Locking in windows is manditory. For this reason, we cannot store
  10893. ** actual data in the bytes used for locking. The pager never allocates
  10894. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  10895. ** that all locks will fit on a single page even at the minimum page size.
  10896. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  10897. ** is set high so that we don't have to allocate an unused page except
  10898. ** for very large databases. But one should test the page skipping logic
  10899. ** by setting PENDING_BYTE low and running the entire regression suite.
  10900. **
  10901. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  10902. ** file format. Depending on how it is changed, you might not notice
  10903. ** the incompatibility right away, even running a full regression test.
  10904. ** The default location of PENDING_BYTE is the first byte past the
  10905. ** 1GB boundary.
  10906. **
  10907. */
  10908. #ifdef SQLITE_OMIT_WSD
  10909. # define PENDING_BYTE (0x40000000)
  10910. #else
  10911. # define PENDING_BYTE sqlite3PendingByte
  10912. #endif
  10913. #define RESERVED_BYTE (PENDING_BYTE+1)
  10914. #define SHARED_FIRST (PENDING_BYTE+2)
  10915. #define SHARED_SIZE 510
  10916. /*
  10917. ** Wrapper around OS specific sqlite3_os_init() function.
  10918. */
  10919. SQLITE_PRIVATE int sqlite3OsInit(void);
  10920. /*
  10921. ** Functions for accessing sqlite3_file methods
  10922. */
  10923. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  10924. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  10925. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  10926. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  10927. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  10928. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  10929. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  10930. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  10931. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  10932. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  10933. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  10934. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  10935. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  10936. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  10937. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  10938. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  10939. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  10940. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  10941. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  10942. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  10943. /*
  10944. ** Functions for accessing sqlite3_vfs methods
  10945. */
  10946. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  10947. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  10948. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  10949. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  10950. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10951. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  10952. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  10953. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  10954. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  10955. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  10956. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  10957. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  10958. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  10959. /*
  10960. ** Convenience functions for opening and closing files using
  10961. ** sqlite3_malloc() to obtain space for the file-handle structure.
  10962. */
  10963. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  10964. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  10965. #endif /* _SQLITE_OS_H_ */
  10966. /************** End of os.h **************************************************/
  10967. /************** Continuing where we left off in sqliteInt.h ******************/
  10968. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  10969. /************** Begin file mutex.h *******************************************/
  10970. /*
  10971. ** 2007 August 28
  10972. **
  10973. ** The author disclaims copyright to this source code. In place of
  10974. ** a legal notice, here is a blessing:
  10975. **
  10976. ** May you do good and not evil.
  10977. ** May you find forgiveness for yourself and forgive others.
  10978. ** May you share freely, never taking more than you give.
  10979. **
  10980. *************************************************************************
  10981. **
  10982. ** This file contains the common header for all mutex implementations.
  10983. ** The sqliteInt.h header #includes this file so that it is available
  10984. ** to all source files. We break it out in an effort to keep the code
  10985. ** better organized.
  10986. **
  10987. ** NOTE: source files should *not* #include this header file directly.
  10988. ** Source files should #include the sqliteInt.h file and let that file
  10989. ** include this one indirectly.
  10990. */
  10991. /*
  10992. ** Figure out what version of the code to use. The choices are
  10993. **
  10994. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  10995. ** mutexes implementation cannot be overridden
  10996. ** at start-time.
  10997. **
  10998. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  10999. ** mutual exclusion is provided. But this
  11000. ** implementation can be overridden at
  11001. ** start-time.
  11002. **
  11003. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  11004. **
  11005. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  11006. */
  11007. #if !SQLITE_THREADSAFE
  11008. # define SQLITE_MUTEX_OMIT
  11009. #endif
  11010. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  11011. # if SQLITE_OS_UNIX
  11012. # define SQLITE_MUTEX_PTHREADS
  11013. # elif SQLITE_OS_WIN
  11014. # define SQLITE_MUTEX_W32
  11015. # else
  11016. # define SQLITE_MUTEX_NOOP
  11017. # endif
  11018. #endif
  11019. #ifdef SQLITE_MUTEX_OMIT
  11020. /*
  11021. ** If this is a no-op implementation, implement everything as macros.
  11022. */
  11023. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  11024. #define sqlite3_mutex_free(X)
  11025. #define sqlite3_mutex_enter(X)
  11026. #define sqlite3_mutex_try(X) SQLITE_OK
  11027. #define sqlite3_mutex_leave(X)
  11028. #define sqlite3_mutex_held(X) ((void)(X),1)
  11029. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  11030. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  11031. #define sqlite3MutexInit() SQLITE_OK
  11032. #define sqlite3MutexEnd()
  11033. #define MUTEX_LOGIC(X)
  11034. #else
  11035. #define MUTEX_LOGIC(X) X
  11036. #endif /* defined(SQLITE_MUTEX_OMIT) */
  11037. /************** End of mutex.h ***********************************************/
  11038. /************** Continuing where we left off in sqliteInt.h ******************/
  11039. /*
  11040. ** Each database file to be accessed by the system is an instance
  11041. ** of the following structure. There are normally two of these structures
  11042. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  11043. ** aDb[1] is the database file used to hold temporary tables. Additional
  11044. ** databases may be attached.
  11045. */
  11046. struct Db {
  11047. char *zName; /* Name of this database */
  11048. Btree *pBt; /* The B*Tree structure for this database file */
  11049. u8 safety_level; /* How aggressive at syncing data to disk */
  11050. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  11051. };
  11052. /*
  11053. ** An instance of the following structure stores a database schema.
  11054. **
  11055. ** Most Schema objects are associated with a Btree. The exception is
  11056. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  11057. ** In shared cache mode, a single Schema object can be shared by multiple
  11058. ** Btrees that refer to the same underlying BtShared object.
  11059. **
  11060. ** Schema objects are automatically deallocated when the last Btree that
  11061. ** references them is destroyed. The TEMP Schema is manually freed by
  11062. ** sqlite3_close().
  11063. *
  11064. ** A thread must be holding a mutex on the corresponding Btree in order
  11065. ** to access Schema content. This implies that the thread must also be
  11066. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  11067. ** For a TEMP Schema, only the connection mutex is required.
  11068. */
  11069. struct Schema {
  11070. int schema_cookie; /* Database schema version number for this file */
  11071. int iGeneration; /* Generation counter. Incremented with each change */
  11072. Hash tblHash; /* All tables indexed by name */
  11073. Hash idxHash; /* All (named) indices indexed by name */
  11074. Hash trigHash; /* All triggers indexed by name */
  11075. Hash fkeyHash; /* All foreign keys by referenced table name */
  11076. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  11077. u8 file_format; /* Schema format version for this file */
  11078. u8 enc; /* Text encoding used by this database */
  11079. u16 schemaFlags; /* Flags associated with this schema */
  11080. int cache_size; /* Number of pages to use in the cache */
  11081. };
  11082. /*
  11083. ** These macros can be used to test, set, or clear bits in the
  11084. ** Db.pSchema->flags field.
  11085. */
  11086. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  11087. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  11088. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  11089. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  11090. /*
  11091. ** Allowed values for the DB.pSchema->flags field.
  11092. **
  11093. ** The DB_SchemaLoaded flag is set after the database schema has been
  11094. ** read into internal hash tables.
  11095. **
  11096. ** DB_UnresetViews means that one or more views have column names that
  11097. ** have been filled out. If the schema changes, these column names might
  11098. ** changes and so the view will need to be reset.
  11099. */
  11100. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  11101. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  11102. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  11103. /*
  11104. ** The number of different kinds of things that can be limited
  11105. ** using the sqlite3_limit() interface.
  11106. */
  11107. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  11108. /*
  11109. ** Lookaside malloc is a set of fixed-size buffers that can be used
  11110. ** to satisfy small transient memory allocation requests for objects
  11111. ** associated with a particular database connection. The use of
  11112. ** lookaside malloc provides a significant performance enhancement
  11113. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  11114. ** SQL statements.
  11115. **
  11116. ** The Lookaside structure holds configuration information about the
  11117. ** lookaside malloc subsystem. Each available memory allocation in
  11118. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  11119. ** objects.
  11120. **
  11121. ** Lookaside allocations are only allowed for objects that are associated
  11122. ** with a particular database connection. Hence, schema information cannot
  11123. ** be stored in lookaside because in shared cache mode the schema information
  11124. ** is shared by multiple database connections. Therefore, while parsing
  11125. ** schema information, the Lookaside.bEnabled flag is cleared so that
  11126. ** lookaside allocations are not used to construct the schema objects.
  11127. */
  11128. struct Lookaside {
  11129. u16 sz; /* Size of each buffer in bytes */
  11130. u8 bEnabled; /* False to disable new lookaside allocations */
  11131. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  11132. int nOut; /* Number of buffers currently checked out */
  11133. int mxOut; /* Highwater mark for nOut */
  11134. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  11135. LookasideSlot *pFree; /* List of available buffers */
  11136. void *pStart; /* First byte of available memory space */
  11137. void *pEnd; /* First byte past end of available space */
  11138. };
  11139. struct LookasideSlot {
  11140. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  11141. };
  11142. /*
  11143. ** A hash table for function definitions.
  11144. **
  11145. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  11146. ** Collisions are on the FuncDef.pHash chain.
  11147. */
  11148. struct FuncDefHash {
  11149. FuncDef *a[23]; /* Hash table for functions */
  11150. };
  11151. #ifdef SQLITE_USER_AUTHENTICATION
  11152. /*
  11153. ** Information held in the "sqlite3" database connection object and used
  11154. ** to manage user authentication.
  11155. */
  11156. typedef struct sqlite3_userauth sqlite3_userauth;
  11157. struct sqlite3_userauth {
  11158. u8 authLevel; /* Current authentication level */
  11159. int nAuthPW; /* Size of the zAuthPW in bytes */
  11160. char *zAuthPW; /* Password used to authenticate */
  11161. char *zAuthUser; /* User name used to authenticate */
  11162. };
  11163. /* Allowed values for sqlite3_userauth.authLevel */
  11164. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  11165. #define UAUTH_Fail 1 /* User authentication failed */
  11166. #define UAUTH_User 2 /* Authenticated as a normal user */
  11167. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  11168. /* Functions used only by user authorization logic */
  11169. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  11170. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  11171. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  11172. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  11173. #endif /* SQLITE_USER_AUTHENTICATION */
  11174. /*
  11175. ** typedef for the authorization callback function.
  11176. */
  11177. #ifdef SQLITE_USER_AUTHENTICATION
  11178. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11179. const char*, const char*);
  11180. #else
  11181. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11182. const char*);
  11183. #endif
  11184. /*
  11185. ** Each database connection is an instance of the following structure.
  11186. */
  11187. struct sqlite3 {
  11188. sqlite3_vfs *pVfs; /* OS Interface */
  11189. struct Vdbe *pVdbe; /* List of active virtual machines */
  11190. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  11191. sqlite3_mutex *mutex; /* Connection mutex */
  11192. Db *aDb; /* All backends */
  11193. int nDb; /* Number of backends currently in use */
  11194. int flags; /* Miscellaneous flags. See below */
  11195. i64 lastRowid; /* ROWID of most recent insert (see above) */
  11196. i64 szMmap; /* Default mmap_size setting */
  11197. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  11198. int errCode; /* Most recent error code (SQLITE_*) */
  11199. int errMask; /* & result codes with this before returning */
  11200. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  11201. u8 enc; /* Text encoding */
  11202. u8 autoCommit; /* The auto-commit flag. */
  11203. u8 temp_store; /* 1: file 2: memory 0: default */
  11204. u8 mallocFailed; /* True if we have seen a malloc failure */
  11205. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  11206. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  11207. u8 suppressErr; /* Do not issue error messages if true */
  11208. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  11209. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  11210. int nextPagesize; /* Pagesize after VACUUM if >0 */
  11211. u32 magic; /* Magic number for detect library misuse */
  11212. int nChange; /* Value returned by sqlite3_changes() */
  11213. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  11214. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  11215. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  11216. struct sqlite3InitInfo { /* Information used during initialization */
  11217. int newTnum; /* Rootpage of table being initialized */
  11218. u8 iDb; /* Which db file is being initialized */
  11219. u8 busy; /* TRUE if currently initializing */
  11220. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  11221. u8 imposterTable; /* Building an imposter table */
  11222. } init;
  11223. int nVdbeActive; /* Number of VDBEs currently running */
  11224. int nVdbeRead; /* Number of active VDBEs that read or write */
  11225. int nVdbeWrite; /* Number of active VDBEs that read and write */
  11226. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  11227. int nVDestroy; /* Number of active OP_VDestroy operations */
  11228. int nExtension; /* Number of loaded extensions */
  11229. void **aExtension; /* Array of shared library handles */
  11230. void (*xTrace)(void*,const char*); /* Trace function */
  11231. void *pTraceArg; /* Argument to the trace function */
  11232. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  11233. void *pProfileArg; /* Argument to profile function */
  11234. void *pCommitArg; /* Argument to xCommitCallback() */
  11235. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  11236. void *pRollbackArg; /* Argument to xRollbackCallback() */
  11237. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  11238. void *pUpdateArg;
  11239. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  11240. #ifndef SQLITE_OMIT_WAL
  11241. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  11242. void *pWalArg;
  11243. #endif
  11244. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  11245. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  11246. void *pCollNeededArg;
  11247. sqlite3_value *pErr; /* Most recent error message */
  11248. union {
  11249. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  11250. double notUsed1; /* Spacer */
  11251. } u1;
  11252. Lookaside lookaside; /* Lookaside malloc configuration */
  11253. #ifndef SQLITE_OMIT_AUTHORIZATION
  11254. sqlite3_xauth xAuth; /* Access authorization function */
  11255. void *pAuthArg; /* 1st argument to the access auth function */
  11256. #endif
  11257. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  11258. int (*xProgress)(void *); /* The progress callback */
  11259. void *pProgressArg; /* Argument to the progress callback */
  11260. unsigned nProgressOps; /* Number of opcodes for progress callback */
  11261. #endif
  11262. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11263. int nVTrans; /* Allocated size of aVTrans */
  11264. Hash aModule; /* populated by sqlite3_create_module() */
  11265. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  11266. VTable **aVTrans; /* Virtual tables with open transactions */
  11267. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  11268. #endif
  11269. FuncDefHash aFunc; /* Hash table of connection functions */
  11270. Hash aCollSeq; /* All collating sequences */
  11271. BusyHandler busyHandler; /* Busy callback */
  11272. Db aDbStatic[2]; /* Static space for the 2 default backends */
  11273. Savepoint *pSavepoint; /* List of active savepoints */
  11274. int busyTimeout; /* Busy handler timeout, in msec */
  11275. int nSavepoint; /* Number of non-transaction savepoints */
  11276. int nStatement; /* Number of nested statement-transactions */
  11277. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  11278. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  11279. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  11280. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11281. /* The following variables are all protected by the STATIC_MASTER
  11282. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  11283. **
  11284. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  11285. ** unlock so that it can proceed.
  11286. **
  11287. ** When X.pBlockingConnection==Y, that means that something that X tried
  11288. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  11289. ** held by Y.
  11290. */
  11291. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  11292. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  11293. void *pUnlockArg; /* Argument to xUnlockNotify */
  11294. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  11295. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  11296. #endif
  11297. #ifdef SQLITE_USER_AUTHENTICATION
  11298. sqlite3_userauth auth; /* User authentication information */
  11299. #endif
  11300. };
  11301. /*
  11302. ** A macro to discover the encoding of a database.
  11303. */
  11304. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  11305. #define ENC(db) ((db)->enc)
  11306. /*
  11307. ** Possible values for the sqlite3.flags.
  11308. */
  11309. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  11310. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  11311. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  11312. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  11313. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  11314. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  11315. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  11316. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  11317. /* DELETE, or UPDATE and return */
  11318. /* the count using a callback. */
  11319. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  11320. /* result set is empty */
  11321. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  11322. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  11323. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  11324. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  11325. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  11326. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  11327. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  11328. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  11329. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  11330. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  11331. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  11332. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  11333. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  11334. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  11335. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  11336. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  11337. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  11338. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  11339. #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
  11340. #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
  11341. /*
  11342. ** Bits of the sqlite3.dbOptFlags field that are used by the
  11343. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  11344. ** selectively disable various optimizations.
  11345. */
  11346. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  11347. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  11348. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  11349. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  11350. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  11351. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  11352. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  11353. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  11354. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  11355. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  11356. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  11357. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  11358. #define SQLITE_AllOpts 0xffff /* All optimizations */
  11359. /*
  11360. ** Macros for testing whether or not optimizations are enabled or disabled.
  11361. */
  11362. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11363. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  11364. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  11365. #else
  11366. #define OptimizationDisabled(db, mask) 0
  11367. #define OptimizationEnabled(db, mask) 1
  11368. #endif
  11369. /*
  11370. ** Return true if it OK to factor constant expressions into the initialization
  11371. ** code. The argument is a Parse object for the code generator.
  11372. */
  11373. #define ConstFactorOk(P) ((P)->okConstFactor)
  11374. /*
  11375. ** Possible values for the sqlite.magic field.
  11376. ** The numbers are obtained at random and have no special meaning, other
  11377. ** than being distinct from one another.
  11378. */
  11379. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  11380. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  11381. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  11382. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  11383. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  11384. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  11385. /*
  11386. ** Each SQL function is defined by an instance of the following
  11387. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  11388. ** hash table. When multiple functions have the same name, the hash table
  11389. ** points to a linked list of these structures.
  11390. */
  11391. struct FuncDef {
  11392. i16 nArg; /* Number of arguments. -1 means unlimited */
  11393. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  11394. void *pUserData; /* User data parameter */
  11395. FuncDef *pNext; /* Next function with same name */
  11396. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  11397. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  11398. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  11399. char *zName; /* SQL name of the function. */
  11400. FuncDef *pHash; /* Next with a different name but the same hash */
  11401. FuncDestructor *pDestructor; /* Reference counted destructor function */
  11402. };
  11403. /*
  11404. ** This structure encapsulates a user-function destructor callback (as
  11405. ** configured using create_function_v2()) and a reference counter. When
  11406. ** create_function_v2() is called to create a function with a destructor,
  11407. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  11408. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  11409. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  11410. ** member of each of the new FuncDef objects is set to point to the allocated
  11411. ** FuncDestructor.
  11412. **
  11413. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  11414. ** count on this object is decremented. When it reaches 0, the destructor
  11415. ** is invoked and the FuncDestructor structure freed.
  11416. */
  11417. struct FuncDestructor {
  11418. int nRef;
  11419. void (*xDestroy)(void *);
  11420. void *pUserData;
  11421. };
  11422. /*
  11423. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  11424. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  11425. ** are assert() statements in the code to verify this.
  11426. */
  11427. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  11428. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  11429. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  11430. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  11431. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  11432. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  11433. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  11434. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  11435. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  11436. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  11437. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  11438. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  11439. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  11440. ** single query - might change over time */
  11441. /*
  11442. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  11443. ** used to create the initializers for the FuncDef structures.
  11444. **
  11445. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  11446. ** Used to create a scalar function definition of a function zName
  11447. ** implemented by C function xFunc that accepts nArg arguments. The
  11448. ** value passed as iArg is cast to a (void*) and made available
  11449. ** as the user-data (sqlite3_user_data()) for the function. If
  11450. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  11451. **
  11452. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11453. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  11454. **
  11455. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11456. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  11457. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  11458. ** and functions like sqlite_version() that can change, but not during
  11459. ** a single query.
  11460. **
  11461. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  11462. ** Used to create an aggregate function definition implemented by
  11463. ** the C functions xStep and xFinal. The first four parameters
  11464. ** are interpreted in the same way as the first 4 parameters to
  11465. ** FUNCTION().
  11466. **
  11467. ** LIKEFUNC(zName, nArg, pArg, flags)
  11468. ** Used to create a scalar function definition of a function zName
  11469. ** that accepts nArg arguments and is implemented by a call to C
  11470. ** function likeFunc. Argument pArg is cast to a (void *) and made
  11471. ** available as the function user-data (sqlite3_user_data()). The
  11472. ** FuncDef.flags variable is set to the value passed as the flags
  11473. ** parameter.
  11474. */
  11475. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11476. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11477. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11478. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11479. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11480. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11481. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11482. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11483. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11484. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  11485. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  11486. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11487. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  11488. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11489. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  11490. #define LIKEFUNC(zName, nArg, arg, flags) \
  11491. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  11492. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  11493. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  11494. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  11495. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  11496. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  11497. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  11498. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  11499. /*
  11500. ** All current savepoints are stored in a linked list starting at
  11501. ** sqlite3.pSavepoint. The first element in the list is the most recently
  11502. ** opened savepoint. Savepoints are added to the list by the vdbe
  11503. ** OP_Savepoint instruction.
  11504. */
  11505. struct Savepoint {
  11506. char *zName; /* Savepoint name (nul-terminated) */
  11507. i64 nDeferredCons; /* Number of deferred fk violations */
  11508. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  11509. Savepoint *pNext; /* Parent savepoint (if any) */
  11510. };
  11511. /*
  11512. ** The following are used as the second parameter to sqlite3Savepoint(),
  11513. ** and as the P1 argument to the OP_Savepoint instruction.
  11514. */
  11515. #define SAVEPOINT_BEGIN 0
  11516. #define SAVEPOINT_RELEASE 1
  11517. #define SAVEPOINT_ROLLBACK 2
  11518. /*
  11519. ** Each SQLite module (virtual table definition) is defined by an
  11520. ** instance of the following structure, stored in the sqlite3.aModule
  11521. ** hash table.
  11522. */
  11523. struct Module {
  11524. const sqlite3_module *pModule; /* Callback pointers */
  11525. const char *zName; /* Name passed to create_module() */
  11526. void *pAux; /* pAux passed to create_module() */
  11527. void (*xDestroy)(void *); /* Module destructor function */
  11528. Table *pEpoTab; /* Eponymous table for this module */
  11529. };
  11530. /*
  11531. ** information about each column of an SQL table is held in an instance
  11532. ** of this structure.
  11533. */
  11534. struct Column {
  11535. char *zName; /* Name of this column */
  11536. Expr *pDflt; /* Default value of this column */
  11537. char *zDflt; /* Original text of the default value */
  11538. char *zType; /* Data type for this column */
  11539. char *zColl; /* Collating sequence. If NULL, use the default */
  11540. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  11541. char affinity; /* One of the SQLITE_AFF_... values */
  11542. u8 szEst; /* Estimated size of this column. INT==1 */
  11543. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  11544. };
  11545. /* Allowed values for Column.colFlags:
  11546. */
  11547. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  11548. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  11549. /*
  11550. ** A "Collating Sequence" is defined by an instance of the following
  11551. ** structure. Conceptually, a collating sequence consists of a name and
  11552. ** a comparison routine that defines the order of that sequence.
  11553. **
  11554. ** If CollSeq.xCmp is NULL, it means that the
  11555. ** collating sequence is undefined. Indices built on an undefined
  11556. ** collating sequence may not be read or written.
  11557. */
  11558. struct CollSeq {
  11559. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  11560. u8 enc; /* Text encoding handled by xCmp() */
  11561. void *pUser; /* First argument to xCmp() */
  11562. int (*xCmp)(void*,int, const void*, int, const void*);
  11563. void (*xDel)(void*); /* Destructor for pUser */
  11564. };
  11565. /*
  11566. ** A sort order can be either ASC or DESC.
  11567. */
  11568. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  11569. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  11570. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  11571. /*
  11572. ** Column affinity types.
  11573. **
  11574. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  11575. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  11576. ** the speed a little by numbering the values consecutively.
  11577. **
  11578. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  11579. ** when multiple affinity types are concatenated into a string and
  11580. ** used as the P4 operand, they will be more readable.
  11581. **
  11582. ** Note also that the numeric types are grouped together so that testing
  11583. ** for a numeric type is a single comparison. And the BLOB type is first.
  11584. */
  11585. #define SQLITE_AFF_BLOB 'A'
  11586. #define SQLITE_AFF_TEXT 'B'
  11587. #define SQLITE_AFF_NUMERIC 'C'
  11588. #define SQLITE_AFF_INTEGER 'D'
  11589. #define SQLITE_AFF_REAL 'E'
  11590. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  11591. /*
  11592. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  11593. ** affinity value.
  11594. */
  11595. #define SQLITE_AFF_MASK 0x47
  11596. /*
  11597. ** Additional bit values that can be ORed with an affinity without
  11598. ** changing the affinity.
  11599. **
  11600. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  11601. ** It causes an assert() to fire if either operand to a comparison
  11602. ** operator is NULL. It is added to certain comparison operators to
  11603. ** prove that the operands are always NOT NULL.
  11604. */
  11605. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  11606. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  11607. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  11608. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  11609. /*
  11610. ** An object of this type is created for each virtual table present in
  11611. ** the database schema.
  11612. **
  11613. ** If the database schema is shared, then there is one instance of this
  11614. ** structure for each database connection (sqlite3*) that uses the shared
  11615. ** schema. This is because each database connection requires its own unique
  11616. ** instance of the sqlite3_vtab* handle used to access the virtual table
  11617. ** implementation. sqlite3_vtab* handles can not be shared between
  11618. ** database connections, even when the rest of the in-memory database
  11619. ** schema is shared, as the implementation often stores the database
  11620. ** connection handle passed to it via the xConnect() or xCreate() method
  11621. ** during initialization internally. This database connection handle may
  11622. ** then be used by the virtual table implementation to access real tables
  11623. ** within the database. So that they appear as part of the callers
  11624. ** transaction, these accesses need to be made via the same database
  11625. ** connection as that used to execute SQL operations on the virtual table.
  11626. **
  11627. ** All VTable objects that correspond to a single table in a shared
  11628. ** database schema are initially stored in a linked-list pointed to by
  11629. ** the Table.pVTable member variable of the corresponding Table object.
  11630. ** When an sqlite3_prepare() operation is required to access the virtual
  11631. ** table, it searches the list for the VTable that corresponds to the
  11632. ** database connection doing the preparing so as to use the correct
  11633. ** sqlite3_vtab* handle in the compiled query.
  11634. **
  11635. ** When an in-memory Table object is deleted (for example when the
  11636. ** schema is being reloaded for some reason), the VTable objects are not
  11637. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  11638. ** immediately. Instead, they are moved from the Table.pVTable list to
  11639. ** another linked list headed by the sqlite3.pDisconnect member of the
  11640. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  11641. ** next time a statement is prepared using said sqlite3*. This is done
  11642. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  11643. ** Refer to comments above function sqlite3VtabUnlockList() for an
  11644. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  11645. ** list without holding the corresponding sqlite3.mutex mutex.
  11646. **
  11647. ** The memory for objects of this type is always allocated by
  11648. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  11649. ** the first argument.
  11650. */
  11651. struct VTable {
  11652. sqlite3 *db; /* Database connection associated with this table */
  11653. Module *pMod; /* Pointer to module implementation */
  11654. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  11655. int nRef; /* Number of pointers to this structure */
  11656. u8 bConstraint; /* True if constraints are supported */
  11657. int iSavepoint; /* Depth of the SAVEPOINT stack */
  11658. VTable *pNext; /* Next in linked list (see above) */
  11659. };
  11660. /*
  11661. ** The schema for each SQL table and view is represented in memory
  11662. ** by an instance of the following structure.
  11663. */
  11664. struct Table {
  11665. char *zName; /* Name of the table or view */
  11666. Column *aCol; /* Information about each column */
  11667. Index *pIndex; /* List of SQL indexes on this table. */
  11668. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  11669. FKey *pFKey; /* Linked list of all foreign keys in this table */
  11670. char *zColAff; /* String defining the affinity of each column */
  11671. ExprList *pCheck; /* All CHECK constraints */
  11672. /* ... also used as column name list in a VIEW */
  11673. int tnum; /* Root BTree page for this table */
  11674. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  11675. i16 nCol; /* Number of columns in this table */
  11676. u16 nRef; /* Number of pointers to this Table */
  11677. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  11678. LogEst szTabRow; /* Estimated size of each table row in bytes */
  11679. #ifdef SQLITE_ENABLE_COSTMULT
  11680. LogEst costMult; /* Cost multiplier for using this table */
  11681. #endif
  11682. u8 tabFlags; /* Mask of TF_* values */
  11683. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  11684. #ifndef SQLITE_OMIT_ALTERTABLE
  11685. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  11686. #endif
  11687. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11688. int nModuleArg; /* Number of arguments to the module */
  11689. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  11690. VTable *pVTable; /* List of VTable objects. */
  11691. #endif
  11692. Trigger *pTrigger; /* List of triggers stored in pSchema */
  11693. Schema *pSchema; /* Schema that contains this table */
  11694. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  11695. };
  11696. /*
  11697. ** Allowed values for Table.tabFlags.
  11698. **
  11699. ** TF_OOOHidden applies to virtual tables that have hidden columns that are
  11700. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  11701. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  11702. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  11703. ** special handling during INSERT processing.
  11704. */
  11705. #define TF_Readonly 0x01 /* Read-only system table */
  11706. #define TF_Ephemeral 0x02 /* An ephemeral table */
  11707. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  11708. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  11709. #define TF_Virtual 0x10 /* Is a virtual table */
  11710. #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
  11711. #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
  11712. #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
  11713. /*
  11714. ** Test to see whether or not a table is a virtual table. This is
  11715. ** done as a macro so that it will be optimized out when virtual
  11716. ** table support is omitted from the build.
  11717. */
  11718. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11719. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  11720. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  11721. #else
  11722. # define IsVirtual(X) 0
  11723. # define IsHiddenColumn(X) 0
  11724. #endif
  11725. /* Does the table have a rowid */
  11726. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  11727. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  11728. /*
  11729. ** Each foreign key constraint is an instance of the following structure.
  11730. **
  11731. ** A foreign key is associated with two tables. The "from" table is
  11732. ** the table that contains the REFERENCES clause that creates the foreign
  11733. ** key. The "to" table is the table that is named in the REFERENCES clause.
  11734. ** Consider this example:
  11735. **
  11736. ** CREATE TABLE ex1(
  11737. ** a INTEGER PRIMARY KEY,
  11738. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  11739. ** );
  11740. **
  11741. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  11742. ** Equivalent names:
  11743. **
  11744. ** from-table == child-table
  11745. ** to-table == parent-table
  11746. **
  11747. ** Each REFERENCES clause generates an instance of the following structure
  11748. ** which is attached to the from-table. The to-table need not exist when
  11749. ** the from-table is created. The existence of the to-table is not checked.
  11750. **
  11751. ** The list of all parents for child Table X is held at X.pFKey.
  11752. **
  11753. ** A list of all children for a table named Z (which might not even exist)
  11754. ** is held in Schema.fkeyHash with a hash key of Z.
  11755. */
  11756. struct FKey {
  11757. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  11758. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  11759. char *zTo; /* Name of table that the key points to (aka: Parent) */
  11760. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  11761. FKey *pPrevTo; /* Previous with the same zTo */
  11762. int nCol; /* Number of columns in this key */
  11763. /* EV: R-30323-21917 */
  11764. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  11765. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  11766. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  11767. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  11768. int iFrom; /* Index of column in pFrom */
  11769. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  11770. } aCol[1]; /* One entry for each of nCol columns */
  11771. };
  11772. /*
  11773. ** SQLite supports many different ways to resolve a constraint
  11774. ** error. ROLLBACK processing means that a constraint violation
  11775. ** causes the operation in process to fail and for the current transaction
  11776. ** to be rolled back. ABORT processing means the operation in process
  11777. ** fails and any prior changes from that one operation are backed out,
  11778. ** but the transaction is not rolled back. FAIL processing means that
  11779. ** the operation in progress stops and returns an error code. But prior
  11780. ** changes due to the same operation are not backed out and no rollback
  11781. ** occurs. IGNORE means that the particular row that caused the constraint
  11782. ** error is not inserted or updated. Processing continues and no error
  11783. ** is returned. REPLACE means that preexisting database rows that caused
  11784. ** a UNIQUE constraint violation are removed so that the new insert or
  11785. ** update can proceed. Processing continues and no error is reported.
  11786. **
  11787. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  11788. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  11789. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  11790. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  11791. ** referenced table row is propagated into the row that holds the
  11792. ** foreign key.
  11793. **
  11794. ** The following symbolic values are used to record which type
  11795. ** of action to take.
  11796. */
  11797. #define OE_None 0 /* There is no constraint to check */
  11798. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  11799. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  11800. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  11801. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  11802. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  11803. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  11804. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  11805. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  11806. #define OE_Cascade 9 /* Cascade the changes */
  11807. #define OE_Default 10 /* Do whatever the default action is */
  11808. /*
  11809. ** An instance of the following structure is passed as the first
  11810. ** argument to sqlite3VdbeKeyCompare and is used to control the
  11811. ** comparison of the two index keys.
  11812. **
  11813. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  11814. ** are nField slots for the columns of an index then one extra slot
  11815. ** for the rowid at the end.
  11816. */
  11817. struct KeyInfo {
  11818. u32 nRef; /* Number of references to this KeyInfo object */
  11819. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  11820. u16 nField; /* Number of key columns in the index */
  11821. u16 nXField; /* Number of columns beyond the key columns */
  11822. sqlite3 *db; /* The database connection */
  11823. u8 *aSortOrder; /* Sort order for each column. */
  11824. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  11825. };
  11826. /*
  11827. ** An instance of the following structure holds information about a
  11828. ** single index record that has already been parsed out into individual
  11829. ** values.
  11830. **
  11831. ** A record is an object that contains one or more fields of data.
  11832. ** Records are used to store the content of a table row and to store
  11833. ** the key of an index. A blob encoding of a record is created by
  11834. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  11835. ** OP_Column opcode.
  11836. **
  11837. ** This structure holds a record that has already been disassembled
  11838. ** into its constituent fields.
  11839. **
  11840. ** The r1 and r2 member variables are only used by the optimized comparison
  11841. ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  11842. */
  11843. struct UnpackedRecord {
  11844. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  11845. u16 nField; /* Number of entries in apMem[] */
  11846. i8 default_rc; /* Comparison result if keys are equal */
  11847. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  11848. Mem *aMem; /* Values */
  11849. int r1; /* Value to return if (lhs > rhs) */
  11850. int r2; /* Value to return if (rhs < lhs) */
  11851. };
  11852. /*
  11853. ** Each SQL index is represented in memory by an
  11854. ** instance of the following structure.
  11855. **
  11856. ** The columns of the table that are to be indexed are described
  11857. ** by the aiColumn[] field of this structure. For example, suppose
  11858. ** we have the following table and index:
  11859. **
  11860. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  11861. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  11862. **
  11863. ** In the Table structure describing Ex1, nCol==3 because there are
  11864. ** three columns in the table. In the Index structure describing
  11865. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  11866. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  11867. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  11868. ** The second column to be indexed (c1) has an index of 0 in
  11869. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  11870. **
  11871. ** The Index.onError field determines whether or not the indexed columns
  11872. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  11873. ** it means this is not a unique index. Otherwise it is a unique index
  11874. ** and the value of Index.onError indicate the which conflict resolution
  11875. ** algorithm to employ whenever an attempt is made to insert a non-unique
  11876. ** element.
  11877. **
  11878. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  11879. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  11880. ** table as part of parsing an existing database schema), transient instances
  11881. ** of this structure may be created. In this case the Index.tnum variable is
  11882. ** used to store the address of a VDBE instruction, not a database page
  11883. ** number (it cannot - the database page is not allocated until the VDBE
  11884. ** program is executed). See convertToWithoutRowidTable() for details.
  11885. */
  11886. struct Index {
  11887. char *zName; /* Name of this index */
  11888. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  11889. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  11890. Table *pTable; /* The SQL table being indexed */
  11891. char *zColAff; /* String defining the affinity of each column */
  11892. Index *pNext; /* The next index associated with the same table */
  11893. Schema *pSchema; /* Schema containing this index */
  11894. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  11895. char **azColl; /* Array of collation sequence names for index */
  11896. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  11897. ExprList *aColExpr; /* Column expressions */
  11898. int tnum; /* DB Page containing root of this index */
  11899. LogEst szIdxRow; /* Estimated average row size in bytes */
  11900. u16 nKeyCol; /* Number of columns forming the key */
  11901. u16 nColumn; /* Number of columns stored in the index */
  11902. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  11903. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  11904. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  11905. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  11906. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  11907. unsigned isCovering:1; /* True if this is a covering index */
  11908. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  11909. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11910. int nSample; /* Number of elements in aSample[] */
  11911. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  11912. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  11913. IndexSample *aSample; /* Samples of the left-most key */
  11914. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  11915. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  11916. #endif
  11917. };
  11918. /*
  11919. ** Allowed values for Index.idxType
  11920. */
  11921. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  11922. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  11923. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  11924. /* Return true if index X is a PRIMARY KEY index */
  11925. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  11926. /* Return true if index X is a UNIQUE index */
  11927. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  11928. /* The Index.aiColumn[] values are normally positive integer. But
  11929. ** there are some negative values that have special meaning:
  11930. */
  11931. #define XN_ROWID (-1) /* Indexed column is the rowid */
  11932. #define XN_EXPR (-2) /* Indexed column is an expression */
  11933. /*
  11934. ** Each sample stored in the sqlite_stat3 table is represented in memory
  11935. ** using a structure of this type. See documentation at the top of the
  11936. ** analyze.c source file for additional information.
  11937. */
  11938. struct IndexSample {
  11939. void *p; /* Pointer to sampled record */
  11940. int n; /* Size of record in bytes */
  11941. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  11942. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  11943. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  11944. };
  11945. /*
  11946. ** Each token coming out of the lexer is an instance of
  11947. ** this structure. Tokens are also used as part of an expression.
  11948. **
  11949. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  11950. ** may contain random values. Do not make any assumptions about Token.dyn
  11951. ** and Token.n when Token.z==0.
  11952. */
  11953. struct Token {
  11954. const char *z; /* Text of the token. Not NULL-terminated! */
  11955. unsigned int n; /* Number of characters in this token */
  11956. };
  11957. /*
  11958. ** An instance of this structure contains information needed to generate
  11959. ** code for a SELECT that contains aggregate functions.
  11960. **
  11961. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  11962. ** pointer to this structure. The Expr.iColumn field is the index in
  11963. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  11964. ** code for that node.
  11965. **
  11966. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  11967. ** original Select structure that describes the SELECT statement. These
  11968. ** fields do not need to be freed when deallocating the AggInfo structure.
  11969. */
  11970. struct AggInfo {
  11971. u8 directMode; /* Direct rendering mode means take data directly
  11972. ** from source tables rather than from accumulators */
  11973. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  11974. ** than the source table */
  11975. int sortingIdx; /* Cursor number of the sorting index */
  11976. int sortingIdxPTab; /* Cursor number of pseudo-table */
  11977. int nSortingColumn; /* Number of columns in the sorting index */
  11978. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  11979. ExprList *pGroupBy; /* The group by clause */
  11980. struct AggInfo_col { /* For each column used in source tables */
  11981. Table *pTab; /* Source table */
  11982. int iTable; /* Cursor number of the source table */
  11983. int iColumn; /* Column number within the source table */
  11984. int iSorterColumn; /* Column number in the sorting index */
  11985. int iMem; /* Memory location that acts as accumulator */
  11986. Expr *pExpr; /* The original expression */
  11987. } *aCol;
  11988. int nColumn; /* Number of used entries in aCol[] */
  11989. int nAccumulator; /* Number of columns that show through to the output.
  11990. ** Additional columns are used only as parameters to
  11991. ** aggregate functions */
  11992. struct AggInfo_func { /* For each aggregate function */
  11993. Expr *pExpr; /* Expression encoding the function */
  11994. FuncDef *pFunc; /* The aggregate function implementation */
  11995. int iMem; /* Memory location that acts as accumulator */
  11996. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  11997. } *aFunc;
  11998. int nFunc; /* Number of entries in aFunc[] */
  11999. };
  12000. /*
  12001. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  12002. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  12003. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  12004. ** it uses less memory in the Expr object, which is a big memory user
  12005. ** in systems with lots of prepared statements. And few applications
  12006. ** need more than about 10 or 20 variables. But some extreme users want
  12007. ** to have prepared statements with over 32767 variables, and for them
  12008. ** the option is available (at compile-time).
  12009. */
  12010. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  12011. typedef i16 ynVar;
  12012. #else
  12013. typedef int ynVar;
  12014. #endif
  12015. /*
  12016. ** Each node of an expression in the parse tree is an instance
  12017. ** of this structure.
  12018. **
  12019. ** Expr.op is the opcode. The integer parser token codes are reused
  12020. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  12021. ** code representing the ">=" operator. This same integer code is reused
  12022. ** to represent the greater-than-or-equal-to operator in the expression
  12023. ** tree.
  12024. **
  12025. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  12026. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  12027. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  12028. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  12029. ** then Expr.token contains the name of the function.
  12030. **
  12031. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  12032. ** binary operator. Either or both may be NULL.
  12033. **
  12034. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  12035. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  12036. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  12037. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  12038. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  12039. ** valid.
  12040. **
  12041. ** An expression of the form ID or ID.ID refers to a column in a table.
  12042. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  12043. ** the integer cursor number of a VDBE cursor pointing to that table and
  12044. ** Expr.iColumn is the column number for the specific column. If the
  12045. ** expression is used as a result in an aggregate SELECT, then the
  12046. ** value is also stored in the Expr.iAgg column in the aggregate so that
  12047. ** it can be accessed after all aggregates are computed.
  12048. **
  12049. ** If the expression is an unbound variable marker (a question mark
  12050. ** character '?' in the original SQL) then the Expr.iTable holds the index
  12051. ** number for that variable.
  12052. **
  12053. ** If the expression is a subquery then Expr.iColumn holds an integer
  12054. ** register number containing the result of the subquery. If the
  12055. ** subquery gives a constant result, then iTable is -1. If the subquery
  12056. ** gives a different answer at different times during statement processing
  12057. ** then iTable is the address of a subroutine that computes the subquery.
  12058. **
  12059. ** If the Expr is of type OP_Column, and the table it is selecting from
  12060. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  12061. ** corresponding table definition.
  12062. **
  12063. ** ALLOCATION NOTES:
  12064. **
  12065. ** Expr objects can use a lot of memory space in database schema. To
  12066. ** help reduce memory requirements, sometimes an Expr object will be
  12067. ** truncated. And to reduce the number of memory allocations, sometimes
  12068. ** two or more Expr objects will be stored in a single memory allocation,
  12069. ** together with Expr.zToken strings.
  12070. **
  12071. ** If the EP_Reduced and EP_TokenOnly flags are set when
  12072. ** an Expr object is truncated. When EP_Reduced is set, then all
  12073. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  12074. ** are contained within the same memory allocation. Note, however, that
  12075. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  12076. ** allocated, regardless of whether or not EP_Reduced is set.
  12077. */
  12078. struct Expr {
  12079. u8 op; /* Operation performed by this node */
  12080. char affinity; /* The affinity of the column or 0 if not a column */
  12081. u32 flags; /* Various flags. EP_* See below */
  12082. union {
  12083. char *zToken; /* Token value. Zero terminated and dequoted */
  12084. int iValue; /* Non-negative integer value if EP_IntValue */
  12085. } u;
  12086. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  12087. ** space is allocated for the fields below this point. An attempt to
  12088. ** access them will result in a segfault or malfunction.
  12089. *********************************************************************/
  12090. Expr *pLeft; /* Left subnode */
  12091. Expr *pRight; /* Right subnode */
  12092. union {
  12093. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  12094. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  12095. } x;
  12096. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  12097. ** space is allocated for the fields below this point. An attempt to
  12098. ** access them will result in a segfault or malfunction.
  12099. *********************************************************************/
  12100. #if SQLITE_MAX_EXPR_DEPTH>0
  12101. int nHeight; /* Height of the tree headed by this node */
  12102. #endif
  12103. int iTable; /* TK_COLUMN: cursor number of table holding column
  12104. ** TK_REGISTER: register number
  12105. ** TK_TRIGGER: 1 -> new, 0 -> old
  12106. ** EP_Unlikely: 134217728 times likelihood */
  12107. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  12108. ** TK_VARIABLE: variable number (always >= 1). */
  12109. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  12110. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  12111. u8 op2; /* TK_REGISTER: original value of Expr.op
  12112. ** TK_COLUMN: the value of p5 for OP_Column
  12113. ** TK_AGG_FUNCTION: nesting depth */
  12114. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  12115. Table *pTab; /* Table for TK_COLUMN expressions. */
  12116. };
  12117. /*
  12118. ** The following are the meanings of bits in the Expr.flags field.
  12119. */
  12120. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  12121. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  12122. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  12123. #define EP_Error 0x000008 /* Expression contains one or more errors */
  12124. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  12125. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  12126. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  12127. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  12128. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  12129. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  12130. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  12131. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  12132. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  12133. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  12134. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  12135. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  12136. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  12137. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  12138. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  12139. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  12140. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  12141. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  12142. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  12143. /*
  12144. ** Combinations of two or more EP_* flags
  12145. */
  12146. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  12147. /*
  12148. ** These macros can be used to test, set, or clear bits in the
  12149. ** Expr.flags field.
  12150. */
  12151. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  12152. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  12153. #define ExprSetProperty(E,P) (E)->flags|=(P)
  12154. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  12155. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  12156. ** and Accreditation only. It works like ExprSetProperty() during VVA
  12157. ** processes but is a no-op for delivery.
  12158. */
  12159. #ifdef SQLITE_DEBUG
  12160. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  12161. #else
  12162. # define ExprSetVVAProperty(E,P)
  12163. #endif
  12164. /*
  12165. ** Macros to determine the number of bytes required by a normal Expr
  12166. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  12167. ** and an Expr struct with the EP_TokenOnly flag set.
  12168. */
  12169. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  12170. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  12171. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  12172. /*
  12173. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  12174. ** above sqlite3ExprDup() for details.
  12175. */
  12176. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  12177. /*
  12178. ** A list of expressions. Each expression may optionally have a
  12179. ** name. An expr/name combination can be used in several ways, such
  12180. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  12181. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  12182. ** also be used as the argument to a function, in which case the a.zName
  12183. ** field is not used.
  12184. **
  12185. ** By default the Expr.zSpan field holds a human-readable description of
  12186. ** the expression that is used in the generation of error messages and
  12187. ** column labels. In this case, Expr.zSpan is typically the text of a
  12188. ** column expression as it exists in a SELECT statement. However, if
  12189. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  12190. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  12191. ** form is used for name resolution with nested FROM clauses.
  12192. */
  12193. struct ExprList {
  12194. int nExpr; /* Number of expressions on the list */
  12195. struct ExprList_item { /* For each expression in the list */
  12196. Expr *pExpr; /* The list of expressions */
  12197. char *zName; /* Token associated with this expression */
  12198. char *zSpan; /* Original text of the expression */
  12199. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  12200. unsigned done :1; /* A flag to indicate when processing is finished */
  12201. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  12202. unsigned reusable :1; /* Constant expression is reusable */
  12203. union {
  12204. struct {
  12205. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  12206. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  12207. } x;
  12208. int iConstExprReg; /* Register in which Expr value is cached */
  12209. } u;
  12210. } *a; /* Alloc a power of two greater or equal to nExpr */
  12211. };
  12212. /*
  12213. ** An instance of this structure is used by the parser to record both
  12214. ** the parse tree for an expression and the span of input text for an
  12215. ** expression.
  12216. */
  12217. struct ExprSpan {
  12218. Expr *pExpr; /* The expression parse tree */
  12219. const char *zStart; /* First character of input text */
  12220. const char *zEnd; /* One character past the end of input text */
  12221. };
  12222. /*
  12223. ** An instance of this structure can hold a simple list of identifiers,
  12224. ** such as the list "a,b,c" in the following statements:
  12225. **
  12226. ** INSERT INTO t(a,b,c) VALUES ...;
  12227. ** CREATE INDEX idx ON t(a,b,c);
  12228. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  12229. **
  12230. ** The IdList.a.idx field is used when the IdList represents the list of
  12231. ** column names after a table name in an INSERT statement. In the statement
  12232. **
  12233. ** INSERT INTO t(a,b,c) ...
  12234. **
  12235. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  12236. */
  12237. struct IdList {
  12238. struct IdList_item {
  12239. char *zName; /* Name of the identifier */
  12240. int idx; /* Index in some Table.aCol[] of a column named zName */
  12241. } *a;
  12242. int nId; /* Number of identifiers on the list */
  12243. };
  12244. /*
  12245. ** The bitmask datatype defined below is used for various optimizations.
  12246. **
  12247. ** Changing this from a 64-bit to a 32-bit type limits the number of
  12248. ** tables in a join to 32 instead of 64. But it also reduces the size
  12249. ** of the library by 738 bytes on ix86.
  12250. */
  12251. typedef u64 Bitmask;
  12252. /*
  12253. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  12254. */
  12255. #define BMS ((int)(sizeof(Bitmask)*8))
  12256. /*
  12257. ** A bit in a Bitmask
  12258. */
  12259. #define MASKBIT(n) (((Bitmask)1)<<(n))
  12260. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  12261. /*
  12262. ** The following structure describes the FROM clause of a SELECT statement.
  12263. ** Each table or subquery in the FROM clause is a separate element of
  12264. ** the SrcList.a[] array.
  12265. **
  12266. ** With the addition of multiple database support, the following structure
  12267. ** can also be used to describe a particular table such as the table that
  12268. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  12269. ** such a table must be a simple name: ID. But in SQLite, the table can
  12270. ** now be identified by a database name, a dot, then the table name: ID.ID.
  12271. **
  12272. ** The jointype starts out showing the join type between the current table
  12273. ** and the next table on the list. The parser builds the list this way.
  12274. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  12275. ** jointype expresses the join between the table and the previous table.
  12276. **
  12277. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  12278. ** contains more than 63 columns and the 64-th or later column is used.
  12279. */
  12280. struct SrcList {
  12281. int nSrc; /* Number of tables or subqueries in the FROM clause */
  12282. u32 nAlloc; /* Number of entries allocated in a[] below */
  12283. struct SrcList_item {
  12284. Schema *pSchema; /* Schema to which this item is fixed */
  12285. char *zDatabase; /* Name of database holding this table */
  12286. char *zName; /* Name of the table */
  12287. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  12288. Table *pTab; /* An SQL table corresponding to zName */
  12289. Select *pSelect; /* A SELECT statement used in place of a table name */
  12290. int addrFillSub; /* Address of subroutine to manifest a subquery */
  12291. int regReturn; /* Register holding return address of addrFillSub */
  12292. int regResult; /* Registers holding results of a co-routine */
  12293. struct {
  12294. u8 jointype; /* Type of join between this able and the previous */
  12295. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  12296. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  12297. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  12298. unsigned isCorrelated :1; /* True if sub-query is correlated */
  12299. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  12300. unsigned isRecursive :1; /* True for recursive reference in WITH */
  12301. } fg;
  12302. #ifndef SQLITE_OMIT_EXPLAIN
  12303. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  12304. #endif
  12305. int iCursor; /* The VDBE cursor number used to access this table */
  12306. Expr *pOn; /* The ON clause of a join */
  12307. IdList *pUsing; /* The USING clause of a join */
  12308. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  12309. union {
  12310. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  12311. ExprList *pFuncArg; /* Arguments to table-valued-function */
  12312. } u1;
  12313. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  12314. } a[1]; /* One entry for each identifier on the list */
  12315. };
  12316. /*
  12317. ** Permitted values of the SrcList.a.jointype field
  12318. */
  12319. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  12320. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  12321. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  12322. #define JT_LEFT 0x0008 /* Left outer join */
  12323. #define JT_RIGHT 0x0010 /* Right outer join */
  12324. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  12325. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  12326. /*
  12327. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  12328. ** and the WhereInfo.wctrlFlags member.
  12329. */
  12330. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  12331. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  12332. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  12333. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  12334. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  12335. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  12336. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  12337. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  12338. #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
  12339. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  12340. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  12341. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  12342. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  12343. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  12344. #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
  12345. /* Allowed return values from sqlite3WhereIsDistinct()
  12346. */
  12347. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  12348. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  12349. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  12350. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  12351. /*
  12352. ** A NameContext defines a context in which to resolve table and column
  12353. ** names. The context consists of a list of tables (the pSrcList) field and
  12354. ** a list of named expression (pEList). The named expression list may
  12355. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  12356. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  12357. ** pEList corresponds to the result set of a SELECT and is NULL for
  12358. ** other statements.
  12359. **
  12360. ** NameContexts can be nested. When resolving names, the inner-most
  12361. ** context is searched first. If no match is found, the next outer
  12362. ** context is checked. If there is still no match, the next context
  12363. ** is checked. This process continues until either a match is found
  12364. ** or all contexts are check. When a match is found, the nRef member of
  12365. ** the context containing the match is incremented.
  12366. **
  12367. ** Each subquery gets a new NameContext. The pNext field points to the
  12368. ** NameContext in the parent query. Thus the process of scanning the
  12369. ** NameContext list corresponds to searching through successively outer
  12370. ** subqueries looking for a match.
  12371. */
  12372. struct NameContext {
  12373. Parse *pParse; /* The parser */
  12374. SrcList *pSrcList; /* One or more tables used to resolve names */
  12375. ExprList *pEList; /* Optional list of result-set columns */
  12376. AggInfo *pAggInfo; /* Information about aggregates at this level */
  12377. NameContext *pNext; /* Next outer name context. NULL for outermost */
  12378. int nRef; /* Number of names resolved by this context */
  12379. int nErr; /* Number of errors encountered while resolving names */
  12380. u16 ncFlags; /* Zero or more NC_* flags defined below */
  12381. };
  12382. /*
  12383. ** Allowed values for the NameContext, ncFlags field.
  12384. **
  12385. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  12386. ** SQLITE_FUNC_MINMAX.
  12387. **
  12388. */
  12389. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  12390. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  12391. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  12392. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  12393. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  12394. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  12395. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  12396. /*
  12397. ** An instance of the following structure contains all information
  12398. ** needed to generate code for a single SELECT statement.
  12399. **
  12400. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  12401. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  12402. ** limit and nOffset to the value of the offset (or 0 if there is not
  12403. ** offset). But later on, nLimit and nOffset become the memory locations
  12404. ** in the VDBE that record the limit and offset counters.
  12405. **
  12406. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  12407. ** These addresses must be stored so that we can go back and fill in
  12408. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  12409. ** the number of columns in P2 can be computed at the same time
  12410. ** as the OP_OpenEphm instruction is coded because not
  12411. ** enough information about the compound query is known at that point.
  12412. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  12413. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  12414. ** sequences for the ORDER BY clause.
  12415. */
  12416. struct Select {
  12417. ExprList *pEList; /* The fields of the result */
  12418. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  12419. u16 selFlags; /* Various SF_* values */
  12420. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  12421. #if SELECTTRACE_ENABLED
  12422. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  12423. #endif
  12424. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  12425. u64 nSelectRow; /* Estimated number of result rows */
  12426. SrcList *pSrc; /* The FROM clause */
  12427. Expr *pWhere; /* The WHERE clause */
  12428. ExprList *pGroupBy; /* The GROUP BY clause */
  12429. Expr *pHaving; /* The HAVING clause */
  12430. ExprList *pOrderBy; /* The ORDER BY clause */
  12431. Select *pPrior; /* Prior select in a compound select statement */
  12432. Select *pNext; /* Next select to the left in a compound */
  12433. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  12434. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  12435. With *pWith; /* WITH clause attached to this select. Or NULL. */
  12436. };
  12437. /*
  12438. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  12439. ** "Select Flag".
  12440. */
  12441. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  12442. #define SF_All 0x0002 /* Includes the ALL keyword */
  12443. #define SF_Resolved 0x0004 /* Identifiers have been resolved */
  12444. #define SF_Aggregate 0x0008 /* Contains aggregate functions */
  12445. #define SF_UsesEphemeral 0x0010 /* Uses the OpenEphemeral opcode */
  12446. #define SF_Expanded 0x0020 /* sqlite3SelectExpand() called on this */
  12447. #define SF_HasTypeInfo 0x0040 /* FROM subqueries have Table metadata */
  12448. #define SF_Compound 0x0080 /* Part of a compound query */
  12449. #define SF_Values 0x0100 /* Synthesized from VALUES clause */
  12450. #define SF_MultiValue 0x0200 /* Single VALUES term with multiple rows */
  12451. #define SF_NestedFrom 0x0400 /* Part of a parenthesized FROM clause */
  12452. #define SF_MaybeConvert 0x0800 /* Need convertCompoundSelectToSubquery() */
  12453. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  12454. #define SF_Recursive 0x2000 /* The recursive part of a recursive CTE */
  12455. #define SF_Converted 0x4000 /* By convertCompoundSelectToSubquery() */
  12456. /*
  12457. ** The results of a SELECT can be distributed in several ways, as defined
  12458. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  12459. ** Type".
  12460. **
  12461. ** SRT_Union Store results as a key in a temporary index
  12462. ** identified by pDest->iSDParm.
  12463. **
  12464. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  12465. **
  12466. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  12467. ** set is not empty.
  12468. **
  12469. ** SRT_Discard Throw the results away. This is used by SELECT
  12470. ** statements within triggers whose only purpose is
  12471. ** the side-effects of functions.
  12472. **
  12473. ** All of the above are free to ignore their ORDER BY clause. Those that
  12474. ** follow must honor the ORDER BY clause.
  12475. **
  12476. ** SRT_Output Generate a row of output (using the OP_ResultRow
  12477. ** opcode) for each row in the result set.
  12478. **
  12479. ** SRT_Mem Only valid if the result is a single column.
  12480. ** Store the first column of the first result row
  12481. ** in register pDest->iSDParm then abandon the rest
  12482. ** of the query. This destination implies "LIMIT 1".
  12483. **
  12484. ** SRT_Set The result must be a single column. Store each
  12485. ** row of result as the key in table pDest->iSDParm.
  12486. ** Apply the affinity pDest->affSdst before storing
  12487. ** results. Used to implement "IN (SELECT ...)".
  12488. **
  12489. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  12490. ** the result there. The cursor is left open after
  12491. ** returning. This is like SRT_Table except that
  12492. ** this destination uses OP_OpenEphemeral to create
  12493. ** the table first.
  12494. **
  12495. ** SRT_Coroutine Generate a co-routine that returns a new row of
  12496. ** results each time it is invoked. The entry point
  12497. ** of the co-routine is stored in register pDest->iSDParm
  12498. ** and the result row is stored in pDest->nDest registers
  12499. ** starting with pDest->iSdst.
  12500. **
  12501. ** SRT_Table Store results in temporary table pDest->iSDParm.
  12502. ** SRT_Fifo This is like SRT_EphemTab except that the table
  12503. ** is assumed to already be open. SRT_Fifo has
  12504. ** the additional property of being able to ignore
  12505. ** the ORDER BY clause.
  12506. **
  12507. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  12508. ** But also use temporary table pDest->iSDParm+1 as
  12509. ** a record of all prior results and ignore any duplicate
  12510. ** rows. Name means: "Distinct Fifo".
  12511. **
  12512. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  12513. ** an index). Append a sequence number so that all entries
  12514. ** are distinct.
  12515. **
  12516. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  12517. ** the same record has never been stored before. The
  12518. ** index at pDest->iSDParm+1 hold all prior stores.
  12519. */
  12520. #define SRT_Union 1 /* Store result as keys in an index */
  12521. #define SRT_Except 2 /* Remove result from a UNION index */
  12522. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  12523. #define SRT_Discard 4 /* Do not save the results anywhere */
  12524. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  12525. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  12526. #define SRT_Queue 7 /* Store result in an queue */
  12527. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  12528. /* The ORDER BY clause is ignored for all of the above */
  12529. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  12530. #define SRT_Output 9 /* Output each row of result */
  12531. #define SRT_Mem 10 /* Store result in a memory cell */
  12532. #define SRT_Set 11 /* Store results as keys in an index */
  12533. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  12534. #define SRT_Coroutine 13 /* Generate a single row of result */
  12535. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  12536. /*
  12537. ** An instance of this object describes where to put of the results of
  12538. ** a SELECT statement.
  12539. */
  12540. struct SelectDest {
  12541. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  12542. char affSdst; /* Affinity used when eDest==SRT_Set */
  12543. int iSDParm; /* A parameter used by the eDest disposal method */
  12544. int iSdst; /* Base register where results are written */
  12545. int nSdst; /* Number of registers allocated */
  12546. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  12547. };
  12548. /*
  12549. ** During code generation of statements that do inserts into AUTOINCREMENT
  12550. ** tables, the following information is attached to the Table.u.autoInc.p
  12551. ** pointer of each autoincrement table to record some side information that
  12552. ** the code generator needs. We have to keep per-table autoincrement
  12553. ** information in case inserts are down within triggers. Triggers do not
  12554. ** normally coordinate their activities, but we do need to coordinate the
  12555. ** loading and saving of autoincrement information.
  12556. */
  12557. struct AutoincInfo {
  12558. AutoincInfo *pNext; /* Next info block in a list of them all */
  12559. Table *pTab; /* Table this info block refers to */
  12560. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  12561. int regCtr; /* Memory register holding the rowid counter */
  12562. };
  12563. /*
  12564. ** Size of the column cache
  12565. */
  12566. #ifndef SQLITE_N_COLCACHE
  12567. # define SQLITE_N_COLCACHE 10
  12568. #endif
  12569. /*
  12570. ** At least one instance of the following structure is created for each
  12571. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  12572. ** statement. All such objects are stored in the linked list headed at
  12573. ** Parse.pTriggerPrg and deleted once statement compilation has been
  12574. ** completed.
  12575. **
  12576. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  12577. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  12578. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  12579. ** The Parse.pTriggerPrg list never contains two entries with the same
  12580. ** values for both pTrigger and orconf.
  12581. **
  12582. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  12583. ** accessed (or set to 0 for triggers fired as a result of INSERT
  12584. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  12585. ** a mask of new.* columns used by the program.
  12586. */
  12587. struct TriggerPrg {
  12588. Trigger *pTrigger; /* Trigger this program was coded from */
  12589. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  12590. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  12591. int orconf; /* Default ON CONFLICT policy */
  12592. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  12593. };
  12594. /*
  12595. ** The yDbMask datatype for the bitmask of all attached databases.
  12596. */
  12597. #if SQLITE_MAX_ATTACHED>30
  12598. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  12599. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  12600. # define DbMaskZero(M) memset((M),0,sizeof(M))
  12601. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  12602. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  12603. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  12604. #else
  12605. typedef unsigned int yDbMask;
  12606. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  12607. # define DbMaskZero(M) (M)=0
  12608. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  12609. # define DbMaskAllZero(M) (M)==0
  12610. # define DbMaskNonZero(M) (M)!=0
  12611. #endif
  12612. /*
  12613. ** An SQL parser context. A copy of this structure is passed through
  12614. ** the parser and down into all the parser action routine in order to
  12615. ** carry around information that is global to the entire parse.
  12616. **
  12617. ** The structure is divided into two parts. When the parser and code
  12618. ** generate call themselves recursively, the first part of the structure
  12619. ** is constant but the second part is reset at the beginning and end of
  12620. ** each recursion.
  12621. **
  12622. ** The nTableLock and aTableLock variables are only used if the shared-cache
  12623. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  12624. ** used to store the set of table-locks required by the statement being
  12625. ** compiled. Function sqlite3TableLock() is used to add entries to the
  12626. ** list.
  12627. */
  12628. struct Parse {
  12629. sqlite3 *db; /* The main database structure */
  12630. char *zErrMsg; /* An error message */
  12631. Vdbe *pVdbe; /* An engine for executing database bytecode */
  12632. int rc; /* Return code from execution */
  12633. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  12634. u8 checkSchema; /* Causes schema cookie check after an error */
  12635. u8 nested; /* Number of nested calls to the parser/code generator */
  12636. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  12637. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  12638. u8 mayAbort; /* True if statement may throw an ABORT exception */
  12639. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  12640. u8 okConstFactor; /* OK to factor out constants */
  12641. int aTempReg[8]; /* Holding area for temporary registers */
  12642. int nRangeReg; /* Size of the temporary register block */
  12643. int iRangeReg; /* First register in temporary register block */
  12644. int nErr; /* Number of errors seen */
  12645. int nTab; /* Number of previously allocated VDBE cursors */
  12646. int nMem; /* Number of memory cells used so far */
  12647. int nSet; /* Number of sets used so far */
  12648. int nOnce; /* Number of OP_Once instructions so far */
  12649. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  12650. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  12651. int ckBase; /* Base register of data during check constraints */
  12652. int iSelfTab; /* Table of an index whose exprs are being coded */
  12653. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  12654. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  12655. int nLabel; /* Number of labels used */
  12656. int *aLabel; /* Space to hold the labels */
  12657. struct yColCache {
  12658. int iTable; /* Table cursor number */
  12659. i16 iColumn; /* Table column number */
  12660. u8 tempReg; /* iReg is a temp register that needs to be freed */
  12661. int iLevel; /* Nesting level */
  12662. int iReg; /* Reg with value of this column. 0 means none. */
  12663. int lru; /* Least recently used entry has the smallest value */
  12664. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  12665. ExprList *pConstExpr;/* Constant expressions */
  12666. Token constraintName;/* Name of the constraint currently being parsed */
  12667. yDbMask writeMask; /* Start a write transaction on these databases */
  12668. yDbMask cookieMask; /* Bitmask of schema verified databases */
  12669. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  12670. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  12671. int regRoot; /* Register holding root page number for new objects */
  12672. int nMaxArg; /* Max args passed to user function by sub-program */
  12673. #if SELECTTRACE_ENABLED
  12674. int nSelect; /* Number of SELECT statements seen */
  12675. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  12676. #endif
  12677. #ifndef SQLITE_OMIT_SHARED_CACHE
  12678. int nTableLock; /* Number of locks in aTableLock */
  12679. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  12680. #endif
  12681. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  12682. /* Information used while coding trigger programs. */
  12683. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  12684. Table *pTriggerTab; /* Table triggers are being coded for */
  12685. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  12686. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  12687. u32 oldmask; /* Mask of old.* columns referenced */
  12688. u32 newmask; /* Mask of new.* columns referenced */
  12689. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  12690. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  12691. u8 disableTriggers; /* True to disable triggers */
  12692. /************************************************************************
  12693. ** Above is constant between recursions. Below is reset before and after
  12694. ** each recursion. The boundary between these two regions is determined
  12695. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  12696. ** in the recursive region.
  12697. ************************************************************************/
  12698. int nVar; /* Number of '?' variables seen in the SQL so far */
  12699. int nzVar; /* Number of available slots in azVar[] */
  12700. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  12701. u8 bFreeWith; /* True if pWith should be freed with parser */
  12702. u8 explain; /* True if the EXPLAIN flag is found on the query */
  12703. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12704. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  12705. int nVtabLock; /* Number of virtual tables to lock */
  12706. #endif
  12707. int nAlias; /* Number of aliased result set columns */
  12708. int nHeight; /* Expression tree height of current sub-select */
  12709. #ifndef SQLITE_OMIT_EXPLAIN
  12710. int iSelectId; /* ID of current select for EXPLAIN output */
  12711. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  12712. #endif
  12713. char **azVar; /* Pointers to names of parameters */
  12714. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  12715. const char *zTail; /* All SQL text past the last semicolon parsed */
  12716. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  12717. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  12718. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  12719. Token sNameToken; /* Token with unqualified schema object name */
  12720. Token sLastToken; /* The last token parsed */
  12721. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12722. Token sArg; /* Complete text of a module argument */
  12723. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  12724. #endif
  12725. Table *pZombieTab; /* List of Table objects to delete after code gen */
  12726. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  12727. With *pWith; /* Current WITH clause, or NULL */
  12728. };
  12729. /*
  12730. ** Return true if currently inside an sqlite3_declare_vtab() call.
  12731. */
  12732. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12733. #define IN_DECLARE_VTAB 0
  12734. #else
  12735. #define IN_DECLARE_VTAB (pParse->declareVtab)
  12736. #endif
  12737. /*
  12738. ** An instance of the following structure can be declared on a stack and used
  12739. ** to save the Parse.zAuthContext value so that it can be restored later.
  12740. */
  12741. struct AuthContext {
  12742. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  12743. Parse *pParse; /* The Parse structure */
  12744. };
  12745. /*
  12746. ** Bitfield flags for P5 value in various opcodes.
  12747. */
  12748. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  12749. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  12750. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  12751. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  12752. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  12753. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  12754. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  12755. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  12756. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  12757. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  12758. #define OPFLAG_P2ISREG 0x04 /* P2 to OP_Open** is a register number */
  12759. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  12760. /*
  12761. * Each trigger present in the database schema is stored as an instance of
  12762. * struct Trigger.
  12763. *
  12764. * Pointers to instances of struct Trigger are stored in two ways.
  12765. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  12766. * database). This allows Trigger structures to be retrieved by name.
  12767. * 2. All triggers associated with a single table form a linked list, using the
  12768. * pNext member of struct Trigger. A pointer to the first element of the
  12769. * linked list is stored as the "pTrigger" member of the associated
  12770. * struct Table.
  12771. *
  12772. * The "step_list" member points to the first element of a linked list
  12773. * containing the SQL statements specified as the trigger program.
  12774. */
  12775. struct Trigger {
  12776. char *zName; /* The name of the trigger */
  12777. char *table; /* The table or view to which the trigger applies */
  12778. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  12779. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  12780. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  12781. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  12782. the <column-list> is stored here */
  12783. Schema *pSchema; /* Schema containing the trigger */
  12784. Schema *pTabSchema; /* Schema containing the table */
  12785. TriggerStep *step_list; /* Link list of trigger program steps */
  12786. Trigger *pNext; /* Next trigger associated with the table */
  12787. };
  12788. /*
  12789. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  12790. ** determine which.
  12791. **
  12792. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  12793. ** In that cases, the constants below can be ORed together.
  12794. */
  12795. #define TRIGGER_BEFORE 1
  12796. #define TRIGGER_AFTER 2
  12797. /*
  12798. * An instance of struct TriggerStep is used to store a single SQL statement
  12799. * that is a part of a trigger-program.
  12800. *
  12801. * Instances of struct TriggerStep are stored in a singly linked list (linked
  12802. * using the "pNext" member) referenced by the "step_list" member of the
  12803. * associated struct Trigger instance. The first element of the linked list is
  12804. * the first step of the trigger-program.
  12805. *
  12806. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  12807. * "SELECT" statement. The meanings of the other members is determined by the
  12808. * value of "op" as follows:
  12809. *
  12810. * (op == TK_INSERT)
  12811. * orconf -> stores the ON CONFLICT algorithm
  12812. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  12813. * this stores a pointer to the SELECT statement. Otherwise NULL.
  12814. * zTarget -> Dequoted name of the table to insert into.
  12815. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  12816. * this stores values to be inserted. Otherwise NULL.
  12817. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  12818. * statement, then this stores the column-names to be
  12819. * inserted into.
  12820. *
  12821. * (op == TK_DELETE)
  12822. * zTarget -> Dequoted name of the table to delete from.
  12823. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  12824. * Otherwise NULL.
  12825. *
  12826. * (op == TK_UPDATE)
  12827. * zTarget -> Dequoted name of the table to update.
  12828. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  12829. * Otherwise NULL.
  12830. * pExprList -> A list of the columns to update and the expressions to update
  12831. * them to. See sqlite3Update() documentation of "pChanges"
  12832. * argument.
  12833. *
  12834. */
  12835. struct TriggerStep {
  12836. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  12837. u8 orconf; /* OE_Rollback etc. */
  12838. Trigger *pTrig; /* The trigger that this step is a part of */
  12839. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  12840. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  12841. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  12842. ExprList *pExprList; /* SET clause for UPDATE. */
  12843. IdList *pIdList; /* Column names for INSERT */
  12844. TriggerStep *pNext; /* Next in the link-list */
  12845. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  12846. };
  12847. /*
  12848. ** The following structure contains information used by the sqliteFix...
  12849. ** routines as they walk the parse tree to make database references
  12850. ** explicit.
  12851. */
  12852. typedef struct DbFixer DbFixer;
  12853. struct DbFixer {
  12854. Parse *pParse; /* The parsing context. Error messages written here */
  12855. Schema *pSchema; /* Fix items to this schema */
  12856. int bVarOnly; /* Check for variable references only */
  12857. const char *zDb; /* Make sure all objects are contained in this database */
  12858. const char *zType; /* Type of the container - used for error messages */
  12859. const Token *pName; /* Name of the container - used for error messages */
  12860. };
  12861. /*
  12862. ** An objected used to accumulate the text of a string where we
  12863. ** do not necessarily know how big the string will be in the end.
  12864. */
  12865. struct StrAccum {
  12866. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  12867. char *zBase; /* A base allocation. Not from malloc. */
  12868. char *zText; /* The string collected so far */
  12869. int nChar; /* Length of the string so far */
  12870. int nAlloc; /* Amount of space allocated in zText */
  12871. int mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  12872. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  12873. };
  12874. #define STRACCUM_NOMEM 1
  12875. #define STRACCUM_TOOBIG 2
  12876. /*
  12877. ** A pointer to this structure is used to communicate information
  12878. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  12879. */
  12880. typedef struct {
  12881. sqlite3 *db; /* The database being initialized */
  12882. char **pzErrMsg; /* Error message stored here */
  12883. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  12884. int rc; /* Result code stored here */
  12885. } InitData;
  12886. /*
  12887. ** Structure containing global configuration data for the SQLite library.
  12888. **
  12889. ** This structure also contains some state information.
  12890. */
  12891. struct Sqlite3Config {
  12892. int bMemstat; /* True to enable memory status */
  12893. int bCoreMutex; /* True to enable core mutexing */
  12894. int bFullMutex; /* True to enable full mutexing */
  12895. int bOpenUri; /* True to interpret filenames as URIs */
  12896. int bUseCis; /* Use covering indices for full-scans */
  12897. int mxStrlen; /* Maximum string length */
  12898. int neverCorrupt; /* Database is always well-formed */
  12899. int szLookaside; /* Default lookaside buffer size */
  12900. int nLookaside; /* Default lookaside buffer count */
  12901. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  12902. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  12903. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  12904. void *pHeap; /* Heap storage space */
  12905. int nHeap; /* Size of pHeap[] */
  12906. int mnReq, mxReq; /* Min and max heap requests sizes */
  12907. sqlite3_int64 szMmap; /* mmap() space per open file */
  12908. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  12909. void *pScratch; /* Scratch memory */
  12910. int szScratch; /* Size of each scratch buffer */
  12911. int nScratch; /* Number of scratch buffers */
  12912. void *pPage; /* Page cache memory */
  12913. int szPage; /* Size of each page in pPage[] */
  12914. int nPage; /* Number of pages in pPage[] */
  12915. int mxParserStack; /* maximum depth of the parser stack */
  12916. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  12917. u32 szPma; /* Maximum Sorter PMA size */
  12918. /* The above might be initialized to non-zero. The following need to always
  12919. ** initially be zero, however. */
  12920. int isInit; /* True after initialization has finished */
  12921. int inProgress; /* True while initialization in progress */
  12922. int isMutexInit; /* True after mutexes are initialized */
  12923. int isMallocInit; /* True after malloc is initialized */
  12924. int isPCacheInit; /* True after malloc is initialized */
  12925. int nRefInitMutex; /* Number of users of pInitMutex */
  12926. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  12927. void (*xLog)(void*,int,const char*); /* Function for logging */
  12928. void *pLogArg; /* First argument to xLog() */
  12929. #ifdef SQLITE_ENABLE_SQLLOG
  12930. void(*xSqllog)(void*,sqlite3*,const char*, int);
  12931. void *pSqllogArg;
  12932. #endif
  12933. #ifdef SQLITE_VDBE_COVERAGE
  12934. /* The following callback (if not NULL) is invoked on every VDBE branch
  12935. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  12936. */
  12937. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  12938. void *pVdbeBranchArg; /* 1st argument */
  12939. #endif
  12940. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12941. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  12942. #endif
  12943. int bLocaltimeFault; /* True to fail localtime() calls */
  12944. };
  12945. /*
  12946. ** This macro is used inside of assert() statements to indicate that
  12947. ** the assert is only valid on a well-formed database. Instead of:
  12948. **
  12949. ** assert( X );
  12950. **
  12951. ** One writes:
  12952. **
  12953. ** assert( X || CORRUPT_DB );
  12954. **
  12955. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  12956. ** that the database is definitely corrupt, only that it might be corrupt.
  12957. ** For most test cases, CORRUPT_DB is set to false using a special
  12958. ** sqlite3_test_control(). This enables assert() statements to prove
  12959. ** things that are always true for well-formed databases.
  12960. */
  12961. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  12962. /*
  12963. ** Context pointer passed down through the tree-walk.
  12964. */
  12965. struct Walker {
  12966. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  12967. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  12968. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  12969. Parse *pParse; /* Parser context. */
  12970. int walkerDepth; /* Number of subqueries */
  12971. u8 eCode; /* A small processing code */
  12972. union { /* Extra data for callback */
  12973. NameContext *pNC; /* Naming context */
  12974. int n; /* A counter */
  12975. int iCur; /* A cursor number */
  12976. SrcList *pSrcList; /* FROM clause */
  12977. struct SrcCount *pSrcCount; /* Counting column references */
  12978. } u;
  12979. };
  12980. /* Forward declarations */
  12981. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  12982. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  12983. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  12984. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  12985. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  12986. /*
  12987. ** Return code from the parse-tree walking primitives and their
  12988. ** callbacks.
  12989. */
  12990. #define WRC_Continue 0 /* Continue down into children */
  12991. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  12992. #define WRC_Abort 2 /* Abandon the tree walk */
  12993. /*
  12994. ** An instance of this structure represents a set of one or more CTEs
  12995. ** (common table expressions) created by a single WITH clause.
  12996. */
  12997. struct With {
  12998. int nCte; /* Number of CTEs in the WITH clause */
  12999. With *pOuter; /* Containing WITH clause, or NULL */
  13000. struct Cte { /* For each CTE in the WITH clause.... */
  13001. char *zName; /* Name of this CTE */
  13002. ExprList *pCols; /* List of explicit column names, or NULL */
  13003. Select *pSelect; /* The definition of this CTE */
  13004. const char *zCteErr; /* Error message for circular references */
  13005. } a[1];
  13006. };
  13007. #ifdef SQLITE_DEBUG
  13008. /*
  13009. ** An instance of the TreeView object is used for printing the content of
  13010. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  13011. */
  13012. struct TreeView {
  13013. int iLevel; /* Which level of the tree we are on */
  13014. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  13015. };
  13016. #endif /* SQLITE_DEBUG */
  13017. /*
  13018. ** Assuming zIn points to the first byte of a UTF-8 character,
  13019. ** advance zIn to point to the first byte of the next UTF-8 character.
  13020. */
  13021. #define SQLITE_SKIP_UTF8(zIn) { \
  13022. if( (*(zIn++))>=0xc0 ){ \
  13023. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  13024. } \
  13025. }
  13026. /*
  13027. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  13028. ** the same name but without the _BKPT suffix. These macros invoke
  13029. ** routines that report the line-number on which the error originated
  13030. ** using sqlite3_log(). The routines also provide a convenient place
  13031. ** to set a debugger breakpoint.
  13032. */
  13033. SQLITE_PRIVATE int sqlite3CorruptError(int);
  13034. SQLITE_PRIVATE int sqlite3MisuseError(int);
  13035. SQLITE_PRIVATE int sqlite3CantopenError(int);
  13036. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  13037. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  13038. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  13039. /*
  13040. ** FTS4 is really an extension for FTS3. It is enabled using the
  13041. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  13042. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  13043. */
  13044. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  13045. # define SQLITE_ENABLE_FTS3 1
  13046. #endif
  13047. /*
  13048. ** The ctype.h header is needed for non-ASCII systems. It is also
  13049. ** needed by FTS3 when FTS3 is included in the amalgamation.
  13050. */
  13051. #if !defined(SQLITE_ASCII) || \
  13052. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  13053. # include <ctype.h>
  13054. #endif
  13055. /*
  13056. ** The following macros mimic the standard library functions toupper(),
  13057. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  13058. ** sqlite versions only work for ASCII characters, regardless of locale.
  13059. */
  13060. #ifdef SQLITE_ASCII
  13061. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  13062. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  13063. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  13064. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  13065. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  13066. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  13067. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  13068. #else
  13069. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  13070. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  13071. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  13072. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  13073. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  13074. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  13075. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  13076. #endif
  13077. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  13078. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  13079. #endif
  13080. /*
  13081. ** Internal function prototypes
  13082. */
  13083. #define sqlite3StrICmp sqlite3_stricmp
  13084. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  13085. #define sqlite3StrNICmp sqlite3_strnicmp
  13086. SQLITE_PRIVATE int sqlite3MallocInit(void);
  13087. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  13088. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  13089. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  13090. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  13091. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  13092. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  13093. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  13094. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  13095. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  13096. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  13097. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  13098. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  13099. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  13100. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  13101. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  13102. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  13103. SQLITE_PRIVATE void sqlite3PageFree(void*);
  13104. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  13105. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13106. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  13107. #endif
  13108. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  13109. /*
  13110. ** On systems with ample stack space and that support alloca(), make
  13111. ** use of alloca() to obtain space for large automatic objects. By default,
  13112. ** obtain space from malloc().
  13113. **
  13114. ** The alloca() routine never returns NULL. This will cause code paths
  13115. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  13116. */
  13117. #ifdef SQLITE_USE_ALLOCA
  13118. # define sqlite3StackAllocRaw(D,N) alloca(N)
  13119. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  13120. # define sqlite3StackFree(D,P)
  13121. #else
  13122. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  13123. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  13124. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  13125. #endif
  13126. #ifdef SQLITE_ENABLE_MEMSYS3
  13127. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  13128. #endif
  13129. #ifdef SQLITE_ENABLE_MEMSYS5
  13130. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  13131. #endif
  13132. #ifndef SQLITE_MUTEX_OMIT
  13133. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  13134. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  13135. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  13136. SQLITE_PRIVATE int sqlite3MutexInit(void);
  13137. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  13138. #endif
  13139. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  13140. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  13141. #else
  13142. # define sqlite3MemoryBarrier()
  13143. #endif
  13144. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  13145. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  13146. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  13147. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  13148. /* Access to mutexes used by sqlite3_status() */
  13149. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  13150. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  13151. #ifndef SQLITE_OMIT_FLOATING_POINT
  13152. SQLITE_PRIVATE int sqlite3IsNaN(double);
  13153. #else
  13154. # define sqlite3IsNaN(X) 0
  13155. #endif
  13156. /*
  13157. ** An instance of the following structure holds information about SQL
  13158. ** functions arguments that are the parameters to the printf() function.
  13159. */
  13160. struct PrintfArguments {
  13161. int nArg; /* Total number of arguments */
  13162. int nUsed; /* Number of arguments used so far */
  13163. sqlite3_value **apArg; /* The argument values */
  13164. };
  13165. #define SQLITE_PRINTF_INTERNAL 0x01
  13166. #define SQLITE_PRINTF_SQLFUNC 0x02
  13167. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  13168. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  13169. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  13170. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  13171. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  13172. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  13173. #endif
  13174. #if defined(SQLITE_TEST)
  13175. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  13176. #endif
  13177. #if defined(SQLITE_DEBUG)
  13178. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  13179. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  13180. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  13181. #endif
  13182. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  13183. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  13184. SQLITE_PRIVATE int sqlite3Dequote(char*);
  13185. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  13186. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  13187. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  13188. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  13189. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  13190. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  13191. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  13192. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  13193. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  13194. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  13195. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  13196. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  13197. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  13198. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  13199. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  13200. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  13201. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  13202. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  13203. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  13204. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  13205. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  13206. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  13207. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  13208. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  13209. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  13210. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  13211. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  13212. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  13213. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  13214. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  13215. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  13216. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  13217. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  13218. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  13219. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  13220. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  13221. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  13222. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  13223. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  13224. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  13225. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  13226. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  13227. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  13228. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  13229. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  13230. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  13231. sqlite3_vfs**,char**,char **);
  13232. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  13233. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  13234. #ifdef SQLITE_OMIT_BUILTIN_TEST
  13235. # define sqlite3FaultSim(X) SQLITE_OK
  13236. #else
  13237. SQLITE_PRIVATE int sqlite3FaultSim(int);
  13238. #endif
  13239. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  13240. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  13241. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  13242. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  13243. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  13244. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  13245. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  13246. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13247. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  13248. #endif
  13249. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  13250. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  13251. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  13252. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  13253. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  13254. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  13255. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  13256. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  13257. #else
  13258. # define sqlite3ViewGetColumnNames(A,B) 0
  13259. #endif
  13260. #if SQLITE_MAX_ATTACHED>30
  13261. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  13262. #endif
  13263. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  13264. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  13265. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  13266. #ifndef SQLITE_OMIT_AUTOINCREMENT
  13267. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  13268. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  13269. #else
  13270. # define sqlite3AutoincrementBegin(X)
  13271. # define sqlite3AutoincrementEnd(X)
  13272. #endif
  13273. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  13274. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  13275. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  13276. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  13277. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  13278. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  13279. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  13280. Token*, Select*, Expr*, IdList*);
  13281. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  13282. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  13283. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  13284. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  13285. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  13286. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  13287. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  13288. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  13289. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  13290. Expr*, int, int);
  13291. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  13292. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  13293. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  13294. Expr*,ExprList*,u16,Expr*,Expr*);
  13295. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  13296. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  13297. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  13298. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  13299. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  13300. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  13301. #endif
  13302. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  13303. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  13304. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  13305. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  13306. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  13307. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  13308. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  13309. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  13310. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  13311. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  13312. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  13313. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  13314. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  13315. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  13316. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  13317. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  13318. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  13319. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  13320. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  13321. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  13322. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  13323. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  13324. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  13325. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  13326. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  13327. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  13328. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  13329. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  13330. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  13331. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  13332. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  13333. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  13334. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  13335. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  13336. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  13337. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  13338. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  13339. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  13340. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  13341. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  13342. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  13343. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  13344. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  13345. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  13346. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  13347. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  13348. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  13349. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  13350. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  13351. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  13352. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  13353. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  13354. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  13355. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13356. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  13357. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  13358. #endif
  13359. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  13360. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  13361. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  13362. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  13363. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  13364. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  13365. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  13366. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  13367. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  13368. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  13369. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  13370. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  13371. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  13372. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  13373. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  13374. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  13375. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  13376. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  13377. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  13378. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  13379. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  13380. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  13381. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  13382. u8,u8,int,int*);
  13383. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  13384. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
  13385. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  13386. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  13387. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  13388. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  13389. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  13390. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  13391. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  13392. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  13393. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  13394. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  13395. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  13396. #if SELECTTRACE_ENABLED
  13397. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  13398. #else
  13399. # define sqlite3SelectSetName(A,B)
  13400. #endif
  13401. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  13402. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  13403. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  13404. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  13405. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  13406. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  13407. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  13408. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  13409. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  13410. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  13411. #endif
  13412. #ifndef SQLITE_OMIT_TRIGGER
  13413. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  13414. Expr*,int, int);
  13415. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  13416. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  13417. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  13418. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  13419. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  13420. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  13421. int, int, int);
  13422. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  13423. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  13424. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  13425. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  13426. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  13427. Select*,u8);
  13428. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  13429. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  13430. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  13431. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  13432. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  13433. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  13434. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  13435. #else
  13436. # define sqlite3TriggersExist(B,C,D,E,F) 0
  13437. # define sqlite3DeleteTrigger(A,B)
  13438. # define sqlite3DropTriggerPtr(A,B)
  13439. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  13440. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  13441. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  13442. # define sqlite3TriggerList(X, Y) 0
  13443. # define sqlite3ParseToplevel(p) p
  13444. # define sqlite3IsToplevel(p) 1
  13445. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  13446. #endif
  13447. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  13448. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  13449. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  13450. #ifndef SQLITE_OMIT_AUTHORIZATION
  13451. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  13452. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  13453. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  13454. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  13455. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  13456. #else
  13457. # define sqlite3AuthRead(a,b,c,d)
  13458. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  13459. # define sqlite3AuthContextPush(a,b,c)
  13460. # define sqlite3AuthContextPop(a) ((void)(a))
  13461. #endif
  13462. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  13463. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  13464. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  13465. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  13466. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  13467. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  13468. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  13469. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  13470. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  13471. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  13472. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  13473. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  13474. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  13475. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  13476. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  13477. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  13478. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13479. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  13480. #endif
  13481. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  13482. /*
  13483. ** Routines to read and write variable-length integers. These used to
  13484. ** be defined locally, but now we use the varint routines in the util.c
  13485. ** file.
  13486. */
  13487. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  13488. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  13489. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  13490. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  13491. /*
  13492. ** The common case is for a varint to be a single byte. They following
  13493. ** macros handle the common case without a procedure call, but then call
  13494. ** the procedure for larger varints.
  13495. */
  13496. #define getVarint32(A,B) \
  13497. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  13498. #define putVarint32(A,B) \
  13499. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  13500. sqlite3PutVarint((A),(B)))
  13501. #define getVarint sqlite3GetVarint
  13502. #define putVarint sqlite3PutVarint
  13503. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  13504. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  13505. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  13506. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  13507. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  13508. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  13509. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  13510. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  13511. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  13512. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  13513. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  13514. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  13515. #if defined(SQLITE_NEED_ERR_NAME)
  13516. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  13517. #endif
  13518. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  13519. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  13520. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  13521. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  13522. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  13523. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  13524. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  13525. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  13526. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  13527. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  13528. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  13529. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  13530. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  13531. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  13532. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  13533. #ifdef SQLITE_ENABLE_8_3_NAMES
  13534. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  13535. #else
  13536. # define sqlite3FileSuffix3(X,Y)
  13537. #endif
  13538. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  13539. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  13540. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  13541. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  13542. void(*)(void*));
  13543. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  13544. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  13545. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  13546. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  13547. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  13548. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  13549. #ifndef SQLITE_AMALGAMATION
  13550. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  13551. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  13552. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  13553. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  13554. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  13555. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  13556. #ifndef SQLITE_OMIT_WSD
  13557. SQLITE_PRIVATE int sqlite3PendingByte;
  13558. #endif
  13559. #endif
  13560. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  13561. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  13562. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  13563. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  13564. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  13565. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  13566. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  13567. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  13568. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  13569. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  13570. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  13571. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  13572. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  13573. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  13574. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  13575. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  13576. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  13577. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  13578. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  13579. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  13580. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  13581. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  13582. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  13583. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  13584. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  13585. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  13586. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  13587. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  13588. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  13589. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  13590. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  13591. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  13592. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  13593. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  13594. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  13595. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  13596. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  13597. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  13598. #ifdef SQLITE_DEBUG
  13599. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  13600. #endif
  13601. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  13602. void (*)(sqlite3_context*,int,sqlite3_value **),
  13603. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  13604. FuncDestructor *pDestructor
  13605. );
  13606. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  13607. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  13608. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  13609. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  13610. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  13611. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  13612. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  13613. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  13614. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  13615. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  13616. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  13617. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  13618. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  13619. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  13620. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  13621. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  13622. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  13623. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  13624. #endif
  13625. /*
  13626. ** The interface to the LEMON-generated parser
  13627. */
  13628. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  13629. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  13630. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  13631. #ifdef YYTRACKMAXSTACKDEPTH
  13632. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  13633. #endif
  13634. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  13635. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13636. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  13637. #else
  13638. # define sqlite3CloseExtensions(X)
  13639. #endif
  13640. #ifndef SQLITE_OMIT_SHARED_CACHE
  13641. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  13642. #else
  13643. #define sqlite3TableLock(v,w,x,y,z)
  13644. #endif
  13645. #ifdef SQLITE_TEST
  13646. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  13647. #endif
  13648. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13649. # define sqlite3VtabClear(Y)
  13650. # define sqlite3VtabSync(X,Y) SQLITE_OK
  13651. # define sqlite3VtabRollback(X)
  13652. # define sqlite3VtabCommit(X)
  13653. # define sqlite3VtabInSync(db) 0
  13654. # define sqlite3VtabLock(X)
  13655. # define sqlite3VtabUnlock(X)
  13656. # define sqlite3VtabUnlockList(X)
  13657. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  13658. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  13659. #else
  13660. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  13661. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  13662. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  13663. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  13664. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  13665. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  13666. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  13667. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  13668. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  13669. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  13670. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  13671. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  13672. #endif
  13673. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  13674. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  13675. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  13676. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  13677. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  13678. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  13679. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  13680. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  13681. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  13682. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  13683. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  13684. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  13685. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  13686. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  13687. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  13688. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  13689. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  13690. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  13691. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  13692. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  13693. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  13694. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  13695. #ifndef SQLITE_OMIT_WAL
  13696. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  13697. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  13698. #endif
  13699. #ifndef SQLITE_OMIT_CTE
  13700. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  13701. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  13702. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  13703. #else
  13704. #define sqlite3WithPush(x,y,z)
  13705. #define sqlite3WithDelete(x,y)
  13706. #endif
  13707. /* Declarations for functions in fkey.c. All of these are replaced by
  13708. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  13709. ** key functionality is available. If OMIT_TRIGGER is defined but
  13710. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  13711. ** this case foreign keys are parsed, but no other functionality is
  13712. ** provided (enforcement of FK constraints requires the triggers sub-system).
  13713. */
  13714. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  13715. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  13716. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  13717. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  13718. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  13719. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  13720. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  13721. #else
  13722. #define sqlite3FkActions(a,b,c,d,e,f)
  13723. #define sqlite3FkCheck(a,b,c,d,e,f)
  13724. #define sqlite3FkDropTable(a,b,c)
  13725. #define sqlite3FkOldmask(a,b) 0
  13726. #define sqlite3FkRequired(a,b,c,d) 0
  13727. #endif
  13728. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13729. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  13730. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  13731. #else
  13732. #define sqlite3FkDelete(a,b)
  13733. #define sqlite3FkLocateIndex(a,b,c,d,e)
  13734. #endif
  13735. /*
  13736. ** Available fault injectors. Should be numbered beginning with 0.
  13737. */
  13738. #define SQLITE_FAULTINJECTOR_MALLOC 0
  13739. #define SQLITE_FAULTINJECTOR_COUNT 1
  13740. /*
  13741. ** The interface to the code in fault.c used for identifying "benign"
  13742. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  13743. ** is not defined.
  13744. */
  13745. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13746. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  13747. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  13748. #else
  13749. #define sqlite3BeginBenignMalloc()
  13750. #define sqlite3EndBenignMalloc()
  13751. #endif
  13752. /*
  13753. ** Allowed return values from sqlite3FindInIndex()
  13754. */
  13755. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  13756. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  13757. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  13758. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  13759. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  13760. /*
  13761. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  13762. */
  13763. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  13764. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  13765. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  13766. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  13767. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  13768. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  13769. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  13770. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  13771. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  13772. #else
  13773. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  13774. #define sqlite3JournalExists(p) 1
  13775. #endif
  13776. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  13777. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  13778. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  13779. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  13780. #if SQLITE_MAX_EXPR_DEPTH>0
  13781. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  13782. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  13783. #else
  13784. #define sqlite3SelectExprHeight(x) 0
  13785. #define sqlite3ExprCheckHeight(x,y)
  13786. #endif
  13787. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  13788. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  13789. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13790. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  13791. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  13792. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  13793. #else
  13794. #define sqlite3ConnectionBlocked(x,y)
  13795. #define sqlite3ConnectionUnlocked(x)
  13796. #define sqlite3ConnectionClosed(x)
  13797. #endif
  13798. #ifdef SQLITE_DEBUG
  13799. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  13800. #endif
  13801. /*
  13802. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  13803. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  13804. ** print I/O tracing messages.
  13805. */
  13806. #ifdef SQLITE_ENABLE_IOTRACE
  13807. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  13808. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  13809. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  13810. #else
  13811. # define IOTRACE(A)
  13812. # define sqlite3VdbeIOTraceSql(X)
  13813. #endif
  13814. /*
  13815. ** These routines are available for the mem2.c debugging memory allocator
  13816. ** only. They are used to verify that different "types" of memory
  13817. ** allocations are properly tracked by the system.
  13818. **
  13819. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  13820. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  13821. ** a single bit set.
  13822. **
  13823. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  13824. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13825. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  13826. **
  13827. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  13828. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13829. **
  13830. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  13831. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  13832. ** it might have been allocated by lookaside, except the allocation was
  13833. ** too large or lookaside was already full. It is important to verify
  13834. ** that allocations that might have been satisfied by lookaside are not
  13835. ** passed back to non-lookaside free() routines. Asserts such as the
  13836. ** example above are placed on the non-lookaside free() routines to verify
  13837. ** this constraint.
  13838. **
  13839. ** All of this is no-op for a production build. It only comes into
  13840. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  13841. */
  13842. #ifdef SQLITE_MEMDEBUG
  13843. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  13844. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  13845. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  13846. #else
  13847. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  13848. # define sqlite3MemdebugHasType(X,Y) 1
  13849. # define sqlite3MemdebugNoType(X,Y) 1
  13850. #endif
  13851. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  13852. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  13853. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  13854. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  13855. /*
  13856. ** Threading interface
  13857. */
  13858. #if SQLITE_MAX_WORKER_THREADS>0
  13859. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  13860. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  13861. #endif
  13862. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  13863. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  13864. #endif
  13865. #endif /* _SQLITEINT_H_ */
  13866. /************** End of sqliteInt.h *******************************************/
  13867. /************** Begin file global.c ******************************************/
  13868. /*
  13869. ** 2008 June 13
  13870. **
  13871. ** The author disclaims copyright to this source code. In place of
  13872. ** a legal notice, here is a blessing:
  13873. **
  13874. ** May you do good and not evil.
  13875. ** May you find forgiveness for yourself and forgive others.
  13876. ** May you share freely, never taking more than you give.
  13877. **
  13878. *************************************************************************
  13879. **
  13880. ** This file contains definitions of global variables and constants.
  13881. */
  13882. /* #include "sqliteInt.h" */
  13883. /* An array to map all upper-case characters into their corresponding
  13884. ** lower-case character.
  13885. **
  13886. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  13887. ** handle case conversions for the UTF character set since the tables
  13888. ** involved are nearly as big or bigger than SQLite itself.
  13889. */
  13890. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  13891. #ifdef SQLITE_ASCII
  13892. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  13893. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  13894. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  13895. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  13896. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  13897. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  13898. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  13899. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  13900. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  13901. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  13902. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  13903. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  13904. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  13905. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  13906. 252,253,254,255
  13907. #endif
  13908. #ifdef SQLITE_EBCDIC
  13909. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  13910. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  13911. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  13912. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  13913. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  13914. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  13915. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  13916. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  13917. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  13918. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  13919. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  13920. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  13921. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  13922. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  13923. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  13924. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  13925. #endif
  13926. };
  13927. /*
  13928. ** The following 256 byte lookup table is used to support SQLites built-in
  13929. ** equivalents to the following standard library functions:
  13930. **
  13931. ** isspace() 0x01
  13932. ** isalpha() 0x02
  13933. ** isdigit() 0x04
  13934. ** isalnum() 0x06
  13935. ** isxdigit() 0x08
  13936. ** toupper() 0x20
  13937. ** SQLite identifier character 0x40
  13938. **
  13939. ** Bit 0x20 is set if the mapped character requires translation to upper
  13940. ** case. i.e. if the character is a lower-case ASCII character.
  13941. ** If x is a lower-case ASCII character, then its upper-case equivalent
  13942. ** is (x - 0x20). Therefore toupper() can be implemented as:
  13943. **
  13944. ** (x & ~(map[x]&0x20))
  13945. **
  13946. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  13947. ** array. tolower() is used more often than toupper() by SQLite.
  13948. **
  13949. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  13950. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  13951. ** non-ASCII UTF character. Hence the test for whether or not a character is
  13952. ** part of an identifier is 0x46.
  13953. **
  13954. ** SQLite's versions are identical to the standard versions assuming a
  13955. ** locale of "C". They are implemented as macros in sqliteInt.h.
  13956. */
  13957. #ifdef SQLITE_ASCII
  13958. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  13959. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  13960. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  13961. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  13962. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  13963. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  13964. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  13965. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  13966. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  13967. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  13968. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  13969. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  13970. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  13971. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  13972. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  13973. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  13974. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  13975. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  13976. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  13977. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  13978. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  13979. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  13980. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  13981. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  13982. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  13983. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  13984. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  13985. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  13986. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  13987. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  13988. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  13989. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  13990. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  13991. };
  13992. #endif
  13993. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  13994. ** compatibility for legacy applications, the URI filename capability is
  13995. ** disabled by default.
  13996. **
  13997. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  13998. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  13999. **
  14000. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  14001. ** disabled. The default value may be changed by compiling with the
  14002. ** SQLITE_USE_URI symbol defined.
  14003. */
  14004. #ifndef SQLITE_USE_URI
  14005. # define SQLITE_USE_URI 0
  14006. #endif
  14007. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  14008. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  14009. ** that compile-time option is omitted.
  14010. */
  14011. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  14012. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  14013. #endif
  14014. /* The minimum PMA size is set to this value multiplied by the database
  14015. ** page size in bytes.
  14016. */
  14017. #ifndef SQLITE_SORTER_PMASZ
  14018. # define SQLITE_SORTER_PMASZ 250
  14019. #endif
  14020. /*
  14021. ** The following singleton contains the global configuration for
  14022. ** the SQLite library.
  14023. */
  14024. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  14025. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  14026. 1, /* bCoreMutex */
  14027. SQLITE_THREADSAFE==1, /* bFullMutex */
  14028. SQLITE_USE_URI, /* bOpenUri */
  14029. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  14030. 0x7ffffffe, /* mxStrlen */
  14031. 0, /* neverCorrupt */
  14032. 128, /* szLookaside */
  14033. 500, /* nLookaside */
  14034. {0,0,0,0,0,0,0,0}, /* m */
  14035. {0,0,0,0,0,0,0,0,0}, /* mutex */
  14036. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  14037. (void*)0, /* pHeap */
  14038. 0, /* nHeap */
  14039. 0, 0, /* mnHeap, mxHeap */
  14040. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  14041. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  14042. (void*)0, /* pScratch */
  14043. 0, /* szScratch */
  14044. 0, /* nScratch */
  14045. (void*)0, /* pPage */
  14046. 0, /* szPage */
  14047. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  14048. 0, /* mxParserStack */
  14049. 0, /* sharedCacheEnabled */
  14050. SQLITE_SORTER_PMASZ, /* szPma */
  14051. /* All the rest should always be initialized to zero */
  14052. 0, /* isInit */
  14053. 0, /* inProgress */
  14054. 0, /* isMutexInit */
  14055. 0, /* isMallocInit */
  14056. 0, /* isPCacheInit */
  14057. 0, /* nRefInitMutex */
  14058. 0, /* pInitMutex */
  14059. 0, /* xLog */
  14060. 0, /* pLogArg */
  14061. #ifdef SQLITE_ENABLE_SQLLOG
  14062. 0, /* xSqllog */
  14063. 0, /* pSqllogArg */
  14064. #endif
  14065. #ifdef SQLITE_VDBE_COVERAGE
  14066. 0, /* xVdbeBranch */
  14067. 0, /* pVbeBranchArg */
  14068. #endif
  14069. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14070. 0, /* xTestCallback */
  14071. #endif
  14072. 0 /* bLocaltimeFault */
  14073. };
  14074. /*
  14075. ** Hash table for global functions - functions common to all
  14076. ** database connections. After initialization, this table is
  14077. ** read-only.
  14078. */
  14079. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  14080. /*
  14081. ** Constant tokens for values 0 and 1.
  14082. */
  14083. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  14084. { "0", 1 },
  14085. { "1", 1 }
  14086. };
  14087. /*
  14088. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  14089. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  14090. ** the database page that contains the pending byte. It never attempts
  14091. ** to read or write that page. The pending byte page is set assign
  14092. ** for use by the VFS layers as space for managing file locks.
  14093. **
  14094. ** During testing, it is often desirable to move the pending byte to
  14095. ** a different position in the file. This allows code that has to
  14096. ** deal with the pending byte to run on files that are much smaller
  14097. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  14098. ** move the pending byte.
  14099. **
  14100. ** IMPORTANT: Changing the pending byte to any value other than
  14101. ** 0x40000000 results in an incompatible database file format!
  14102. ** Changing the pending byte during operation will result in undefined
  14103. ** and incorrect behavior.
  14104. */
  14105. #ifndef SQLITE_OMIT_WSD
  14106. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  14107. #endif
  14108. /* #include "opcodes.h" */
  14109. /*
  14110. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  14111. ** created by mkopcodeh.awk during compilation. Data is obtained
  14112. ** from the comments following the "case OP_xxxx:" statements in
  14113. ** the vdbe.c file.
  14114. */
  14115. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  14116. /************** End of global.c **********************************************/
  14117. /************** Begin file ctime.c *******************************************/
  14118. /*
  14119. ** 2010 February 23
  14120. **
  14121. ** The author disclaims copyright to this source code. In place of
  14122. ** a legal notice, here is a blessing:
  14123. **
  14124. ** May you do good and not evil.
  14125. ** May you find forgiveness for yourself and forgive others.
  14126. ** May you share freely, never taking more than you give.
  14127. **
  14128. *************************************************************************
  14129. **
  14130. ** This file implements routines used to report what compile-time options
  14131. ** SQLite was built with.
  14132. */
  14133. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  14134. /* #include "sqliteInt.h" */
  14135. /*
  14136. ** An array of names of all compile-time options. This array should
  14137. ** be sorted A-Z.
  14138. **
  14139. ** This array looks large, but in a typical installation actually uses
  14140. ** only a handful of compile-time options, so most times this array is usually
  14141. ** rather short and uses little memory space.
  14142. */
  14143. static const char * const azCompileOpt[] = {
  14144. /* These macros are provided to "stringify" the value of the define
  14145. ** for those options in which the value is meaningful. */
  14146. #define CTIMEOPT_VAL_(opt) #opt
  14147. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  14148. #if SQLITE_32BIT_ROWID
  14149. "32BIT_ROWID",
  14150. #endif
  14151. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  14152. "4_BYTE_ALIGNED_MALLOC",
  14153. #endif
  14154. #if SQLITE_CASE_SENSITIVE_LIKE
  14155. "CASE_SENSITIVE_LIKE",
  14156. #endif
  14157. #if SQLITE_CHECK_PAGES
  14158. "CHECK_PAGES",
  14159. #endif
  14160. #if SQLITE_COVERAGE_TEST
  14161. "COVERAGE_TEST",
  14162. #endif
  14163. #if SQLITE_DEBUG
  14164. "DEBUG",
  14165. #endif
  14166. #if SQLITE_DEFAULT_LOCKING_MODE
  14167. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  14168. #endif
  14169. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  14170. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  14171. #endif
  14172. #if SQLITE_DISABLE_DIRSYNC
  14173. "DISABLE_DIRSYNC",
  14174. #endif
  14175. #if SQLITE_DISABLE_LFS
  14176. "DISABLE_LFS",
  14177. #endif
  14178. #if SQLITE_ENABLE_API_ARMOR
  14179. "ENABLE_API_ARMOR",
  14180. #endif
  14181. #if SQLITE_ENABLE_ATOMIC_WRITE
  14182. "ENABLE_ATOMIC_WRITE",
  14183. #endif
  14184. #if SQLITE_ENABLE_CEROD
  14185. "ENABLE_CEROD",
  14186. #endif
  14187. #if SQLITE_ENABLE_COLUMN_METADATA
  14188. "ENABLE_COLUMN_METADATA",
  14189. #endif
  14190. #if SQLITE_ENABLE_DBSTAT_VTAB
  14191. "ENABLE_DBSTAT_VTAB",
  14192. #endif
  14193. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  14194. "ENABLE_EXPENSIVE_ASSERT",
  14195. #endif
  14196. #if SQLITE_ENABLE_FTS1
  14197. "ENABLE_FTS1",
  14198. #endif
  14199. #if SQLITE_ENABLE_FTS2
  14200. "ENABLE_FTS2",
  14201. #endif
  14202. #if SQLITE_ENABLE_FTS3
  14203. "ENABLE_FTS3",
  14204. #endif
  14205. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  14206. "ENABLE_FTS3_PARENTHESIS",
  14207. #endif
  14208. #if SQLITE_ENABLE_FTS4
  14209. "ENABLE_FTS4",
  14210. #endif
  14211. #if SQLITE_ENABLE_FTS5
  14212. "ENABLE_FTS5",
  14213. #endif
  14214. #if SQLITE_ENABLE_ICU
  14215. "ENABLE_ICU",
  14216. #endif
  14217. #if SQLITE_ENABLE_IOTRACE
  14218. "ENABLE_IOTRACE",
  14219. #endif
  14220. #if SQLITE_ENABLE_JSON1
  14221. "ENABLE_JSON1",
  14222. #endif
  14223. #if SQLITE_ENABLE_LOAD_EXTENSION
  14224. "ENABLE_LOAD_EXTENSION",
  14225. #endif
  14226. #if SQLITE_ENABLE_LOCKING_STYLE
  14227. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  14228. #endif
  14229. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  14230. "ENABLE_MEMORY_MANAGEMENT",
  14231. #endif
  14232. #if SQLITE_ENABLE_MEMSYS3
  14233. "ENABLE_MEMSYS3",
  14234. #endif
  14235. #if SQLITE_ENABLE_MEMSYS5
  14236. "ENABLE_MEMSYS5",
  14237. #endif
  14238. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  14239. "ENABLE_OVERSIZE_CELL_CHECK",
  14240. #endif
  14241. #if SQLITE_ENABLE_RTREE
  14242. "ENABLE_RTREE",
  14243. #endif
  14244. #if defined(SQLITE_ENABLE_STAT4)
  14245. "ENABLE_STAT4",
  14246. #elif defined(SQLITE_ENABLE_STAT3)
  14247. "ENABLE_STAT3",
  14248. #endif
  14249. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  14250. "ENABLE_UNLOCK_NOTIFY",
  14251. #endif
  14252. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  14253. "ENABLE_UPDATE_DELETE_LIMIT",
  14254. #endif
  14255. #if SQLITE_HAS_CODEC
  14256. "HAS_CODEC",
  14257. #endif
  14258. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  14259. "HAVE_ISNAN",
  14260. #endif
  14261. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14262. "HOMEGROWN_RECURSIVE_MUTEX",
  14263. #endif
  14264. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  14265. "IGNORE_AFP_LOCK_ERRORS",
  14266. #endif
  14267. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  14268. "IGNORE_FLOCK_LOCK_ERRORS",
  14269. #endif
  14270. #ifdef SQLITE_INT64_TYPE
  14271. "INT64_TYPE",
  14272. #endif
  14273. #if SQLITE_LOCK_TRACE
  14274. "LOCK_TRACE",
  14275. #endif
  14276. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  14277. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  14278. #endif
  14279. #ifdef SQLITE_MAX_SCHEMA_RETRY
  14280. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  14281. #endif
  14282. #if SQLITE_MEMDEBUG
  14283. "MEMDEBUG",
  14284. #endif
  14285. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  14286. "MIXED_ENDIAN_64BIT_FLOAT",
  14287. #endif
  14288. #if SQLITE_NO_SYNC
  14289. "NO_SYNC",
  14290. #endif
  14291. #if SQLITE_OMIT_ALTERTABLE
  14292. "OMIT_ALTERTABLE",
  14293. #endif
  14294. #if SQLITE_OMIT_ANALYZE
  14295. "OMIT_ANALYZE",
  14296. #endif
  14297. #if SQLITE_OMIT_ATTACH
  14298. "OMIT_ATTACH",
  14299. #endif
  14300. #if SQLITE_OMIT_AUTHORIZATION
  14301. "OMIT_AUTHORIZATION",
  14302. #endif
  14303. #if SQLITE_OMIT_AUTOINCREMENT
  14304. "OMIT_AUTOINCREMENT",
  14305. #endif
  14306. #if SQLITE_OMIT_AUTOINIT
  14307. "OMIT_AUTOINIT",
  14308. #endif
  14309. #if SQLITE_OMIT_AUTOMATIC_INDEX
  14310. "OMIT_AUTOMATIC_INDEX",
  14311. #endif
  14312. #if SQLITE_OMIT_AUTORESET
  14313. "OMIT_AUTORESET",
  14314. #endif
  14315. #if SQLITE_OMIT_AUTOVACUUM
  14316. "OMIT_AUTOVACUUM",
  14317. #endif
  14318. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  14319. "OMIT_BETWEEN_OPTIMIZATION",
  14320. #endif
  14321. #if SQLITE_OMIT_BLOB_LITERAL
  14322. "OMIT_BLOB_LITERAL",
  14323. #endif
  14324. #if SQLITE_OMIT_BTREECOUNT
  14325. "OMIT_BTREECOUNT",
  14326. #endif
  14327. #if SQLITE_OMIT_BUILTIN_TEST
  14328. "OMIT_BUILTIN_TEST",
  14329. #endif
  14330. #if SQLITE_OMIT_CAST
  14331. "OMIT_CAST",
  14332. #endif
  14333. #if SQLITE_OMIT_CHECK
  14334. "OMIT_CHECK",
  14335. #endif
  14336. #if SQLITE_OMIT_COMPLETE
  14337. "OMIT_COMPLETE",
  14338. #endif
  14339. #if SQLITE_OMIT_COMPOUND_SELECT
  14340. "OMIT_COMPOUND_SELECT",
  14341. #endif
  14342. #if SQLITE_OMIT_CTE
  14343. "OMIT_CTE",
  14344. #endif
  14345. #if SQLITE_OMIT_DATETIME_FUNCS
  14346. "OMIT_DATETIME_FUNCS",
  14347. #endif
  14348. #if SQLITE_OMIT_DECLTYPE
  14349. "OMIT_DECLTYPE",
  14350. #endif
  14351. #if SQLITE_OMIT_DEPRECATED
  14352. "OMIT_DEPRECATED",
  14353. #endif
  14354. #if SQLITE_OMIT_DISKIO
  14355. "OMIT_DISKIO",
  14356. #endif
  14357. #if SQLITE_OMIT_EXPLAIN
  14358. "OMIT_EXPLAIN",
  14359. #endif
  14360. #if SQLITE_OMIT_FLAG_PRAGMAS
  14361. "OMIT_FLAG_PRAGMAS",
  14362. #endif
  14363. #if SQLITE_OMIT_FLOATING_POINT
  14364. "OMIT_FLOATING_POINT",
  14365. #endif
  14366. #if SQLITE_OMIT_FOREIGN_KEY
  14367. "OMIT_FOREIGN_KEY",
  14368. #endif
  14369. #if SQLITE_OMIT_GET_TABLE
  14370. "OMIT_GET_TABLE",
  14371. #endif
  14372. #if SQLITE_OMIT_INCRBLOB
  14373. "OMIT_INCRBLOB",
  14374. #endif
  14375. #if SQLITE_OMIT_INTEGRITY_CHECK
  14376. "OMIT_INTEGRITY_CHECK",
  14377. #endif
  14378. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  14379. "OMIT_LIKE_OPTIMIZATION",
  14380. #endif
  14381. #if SQLITE_OMIT_LOAD_EXTENSION
  14382. "OMIT_LOAD_EXTENSION",
  14383. #endif
  14384. #if SQLITE_OMIT_LOCALTIME
  14385. "OMIT_LOCALTIME",
  14386. #endif
  14387. #if SQLITE_OMIT_LOOKASIDE
  14388. "OMIT_LOOKASIDE",
  14389. #endif
  14390. #if SQLITE_OMIT_MEMORYDB
  14391. "OMIT_MEMORYDB",
  14392. #endif
  14393. #if SQLITE_OMIT_OR_OPTIMIZATION
  14394. "OMIT_OR_OPTIMIZATION",
  14395. #endif
  14396. #if SQLITE_OMIT_PAGER_PRAGMAS
  14397. "OMIT_PAGER_PRAGMAS",
  14398. #endif
  14399. #if SQLITE_OMIT_PRAGMA
  14400. "OMIT_PRAGMA",
  14401. #endif
  14402. #if SQLITE_OMIT_PROGRESS_CALLBACK
  14403. "OMIT_PROGRESS_CALLBACK",
  14404. #endif
  14405. #if SQLITE_OMIT_QUICKBALANCE
  14406. "OMIT_QUICKBALANCE",
  14407. #endif
  14408. #if SQLITE_OMIT_REINDEX
  14409. "OMIT_REINDEX",
  14410. #endif
  14411. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  14412. "OMIT_SCHEMA_PRAGMAS",
  14413. #endif
  14414. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  14415. "OMIT_SCHEMA_VERSION_PRAGMAS",
  14416. #endif
  14417. #if SQLITE_OMIT_SHARED_CACHE
  14418. "OMIT_SHARED_CACHE",
  14419. #endif
  14420. #if SQLITE_OMIT_SUBQUERY
  14421. "OMIT_SUBQUERY",
  14422. #endif
  14423. #if SQLITE_OMIT_TCL_VARIABLE
  14424. "OMIT_TCL_VARIABLE",
  14425. #endif
  14426. #if SQLITE_OMIT_TEMPDB
  14427. "OMIT_TEMPDB",
  14428. #endif
  14429. #if SQLITE_OMIT_TRACE
  14430. "OMIT_TRACE",
  14431. #endif
  14432. #if SQLITE_OMIT_TRIGGER
  14433. "OMIT_TRIGGER",
  14434. #endif
  14435. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  14436. "OMIT_TRUNCATE_OPTIMIZATION",
  14437. #endif
  14438. #if SQLITE_OMIT_UTF16
  14439. "OMIT_UTF16",
  14440. #endif
  14441. #if SQLITE_OMIT_VACUUM
  14442. "OMIT_VACUUM",
  14443. #endif
  14444. #if SQLITE_OMIT_VIEW
  14445. "OMIT_VIEW",
  14446. #endif
  14447. #if SQLITE_OMIT_VIRTUALTABLE
  14448. "OMIT_VIRTUALTABLE",
  14449. #endif
  14450. #if SQLITE_OMIT_WAL
  14451. "OMIT_WAL",
  14452. #endif
  14453. #if SQLITE_OMIT_WSD
  14454. "OMIT_WSD",
  14455. #endif
  14456. #if SQLITE_OMIT_XFER_OPT
  14457. "OMIT_XFER_OPT",
  14458. #endif
  14459. #if SQLITE_PERFORMANCE_TRACE
  14460. "PERFORMANCE_TRACE",
  14461. #endif
  14462. #if SQLITE_PROXY_DEBUG
  14463. "PROXY_DEBUG",
  14464. #endif
  14465. #if SQLITE_RTREE_INT_ONLY
  14466. "RTREE_INT_ONLY",
  14467. #endif
  14468. #if SQLITE_SECURE_DELETE
  14469. "SECURE_DELETE",
  14470. #endif
  14471. #if SQLITE_SMALL_STACK
  14472. "SMALL_STACK",
  14473. #endif
  14474. #if SQLITE_SOUNDEX
  14475. "SOUNDEX",
  14476. #endif
  14477. #if SQLITE_SYSTEM_MALLOC
  14478. "SYSTEM_MALLOC",
  14479. #endif
  14480. #if SQLITE_TCL
  14481. "TCL",
  14482. #endif
  14483. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  14484. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  14485. #endif
  14486. #if SQLITE_TEST
  14487. "TEST",
  14488. #endif
  14489. #if defined(SQLITE_THREADSAFE)
  14490. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  14491. #endif
  14492. #if SQLITE_USE_ALLOCA
  14493. "USE_ALLOCA",
  14494. #endif
  14495. #if SQLITE_USER_AUTHENTICATION
  14496. "USER_AUTHENTICATION",
  14497. #endif
  14498. #if SQLITE_WIN32_MALLOC
  14499. "WIN32_MALLOC",
  14500. #endif
  14501. #if SQLITE_ZERO_MALLOC
  14502. "ZERO_MALLOC"
  14503. #endif
  14504. };
  14505. /*
  14506. ** Given the name of a compile-time option, return true if that option
  14507. ** was used and false if not.
  14508. **
  14509. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  14510. ** is not required for a match.
  14511. */
  14512. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
  14513. int i, n;
  14514. #if SQLITE_ENABLE_API_ARMOR
  14515. if( zOptName==0 ){
  14516. (void)SQLITE_MISUSE_BKPT;
  14517. return 0;
  14518. }
  14519. #endif
  14520. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  14521. n = sqlite3Strlen30(zOptName);
  14522. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  14523. ** linear search is adequate. No need for a binary search. */
  14524. for(i=0; i<ArraySize(azCompileOpt); i++){
  14525. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  14526. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  14527. ){
  14528. return 1;
  14529. }
  14530. }
  14531. return 0;
  14532. }
  14533. /*
  14534. ** Return the N-th compile-time option string. If N is out of range,
  14535. ** return a NULL pointer.
  14536. */
  14537. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
  14538. if( N>=0 && N<ArraySize(azCompileOpt) ){
  14539. return azCompileOpt[N];
  14540. }
  14541. return 0;
  14542. }
  14543. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  14544. /************** End of ctime.c ***********************************************/
  14545. /************** Begin file status.c ******************************************/
  14546. /*
  14547. ** 2008 June 18
  14548. **
  14549. ** The author disclaims copyright to this source code. In place of
  14550. ** a legal notice, here is a blessing:
  14551. **
  14552. ** May you do good and not evil.
  14553. ** May you find forgiveness for yourself and forgive others.
  14554. ** May you share freely, never taking more than you give.
  14555. **
  14556. *************************************************************************
  14557. **
  14558. ** This module implements the sqlite3_status() interface and related
  14559. ** functionality.
  14560. */
  14561. /* #include "sqliteInt.h" */
  14562. /************** Include vdbeInt.h in the middle of status.c ******************/
  14563. /************** Begin file vdbeInt.h *****************************************/
  14564. /*
  14565. ** 2003 September 6
  14566. **
  14567. ** The author disclaims copyright to this source code. In place of
  14568. ** a legal notice, here is a blessing:
  14569. **
  14570. ** May you do good and not evil.
  14571. ** May you find forgiveness for yourself and forgive others.
  14572. ** May you share freely, never taking more than you give.
  14573. **
  14574. *************************************************************************
  14575. ** This is the header file for information that is private to the
  14576. ** VDBE. This information used to all be at the top of the single
  14577. ** source code file "vdbe.c". When that file became too big (over
  14578. ** 6000 lines long) it was split up into several smaller files and
  14579. ** this header information was factored out.
  14580. */
  14581. #ifndef _VDBEINT_H_
  14582. #define _VDBEINT_H_
  14583. /*
  14584. ** The maximum number of times that a statement will try to reparse
  14585. ** itself before giving up and returning SQLITE_SCHEMA.
  14586. */
  14587. #ifndef SQLITE_MAX_SCHEMA_RETRY
  14588. # define SQLITE_MAX_SCHEMA_RETRY 50
  14589. #endif
  14590. /*
  14591. ** SQL is translated into a sequence of instructions to be
  14592. ** executed by a virtual machine. Each instruction is an instance
  14593. ** of the following structure.
  14594. */
  14595. typedef struct VdbeOp Op;
  14596. /*
  14597. ** Boolean values
  14598. */
  14599. typedef unsigned Bool;
  14600. /* Opaque type used by code in vdbesort.c */
  14601. typedef struct VdbeSorter VdbeSorter;
  14602. /* Opaque type used by the explainer */
  14603. typedef struct Explain Explain;
  14604. /* Elements of the linked list at Vdbe.pAuxData */
  14605. typedef struct AuxData AuxData;
  14606. /*
  14607. ** A cursor is a pointer into a single BTree within a database file.
  14608. ** The cursor can seek to a BTree entry with a particular key, or
  14609. ** loop over all entries of the Btree. You can also insert new BTree
  14610. ** entries or retrieve the key or data from the entry that the cursor
  14611. ** is currently pointing to.
  14612. **
  14613. ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
  14614. ** A pseudo-table is a single-row table implemented by registers.
  14615. **
  14616. ** Every cursor that the virtual machine has open is represented by an
  14617. ** instance of the following structure.
  14618. */
  14619. struct VdbeCursor {
  14620. BtCursor *pCursor; /* The cursor structure of the backend */
  14621. Btree *pBt; /* Separate file holding temporary table */
  14622. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  14623. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  14624. int pseudoTableReg; /* Register holding pseudotable content. */
  14625. i16 nField; /* Number of fields in the header */
  14626. u16 nHdrParsed; /* Number of header fields parsed so far */
  14627. #ifdef SQLITE_DEBUG
  14628. u8 seekOp; /* Most recent seek operation on this cursor */
  14629. #endif
  14630. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  14631. u8 nullRow; /* True if pointing to a row with no data */
  14632. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  14633. Bool isEphemeral:1; /* True for an ephemeral table */
  14634. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  14635. Bool isTable:1; /* True if a table requiring integer keys */
  14636. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  14637. Pgno pgnoRoot; /* Root page of the open btree cursor */
  14638. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  14639. i64 seqCount; /* Sequence counter */
  14640. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  14641. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  14642. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  14643. u64 maskUsed; /* Mask of columns used by this cursor */
  14644. #endif
  14645. /* Cached information about the header for the data record that the
  14646. ** cursor is currently pointing to. Only valid if cacheStatus matches
  14647. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  14648. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  14649. ** the cache is out of date.
  14650. **
  14651. ** aRow might point to (ephemeral) data for the current row, or it might
  14652. ** be NULL.
  14653. */
  14654. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  14655. u32 payloadSize; /* Total number of bytes in the record */
  14656. u32 szRow; /* Byte available in aRow */
  14657. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  14658. const u8 *aRow; /* Data for the current row, if all on one page */
  14659. u32 *aOffset; /* Pointer to aType[nField] */
  14660. u32 aType[1]; /* Type values for all entries in the record */
  14661. /* 2*nField extra array elements allocated for aType[], beyond the one
  14662. ** static element declared in the structure. nField total array slots for
  14663. ** aType[] and nField+1 array slots for aOffset[] */
  14664. };
  14665. typedef struct VdbeCursor VdbeCursor;
  14666. /*
  14667. ** When a sub-program is executed (OP_Program), a structure of this type
  14668. ** is allocated to store the current value of the program counter, as
  14669. ** well as the current memory cell array and various other frame specific
  14670. ** values stored in the Vdbe struct. When the sub-program is finished,
  14671. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  14672. ** restoring the state of the VM to as it was before the sub-program
  14673. ** began executing.
  14674. **
  14675. ** The memory for a VdbeFrame object is allocated and managed by a memory
  14676. ** cell in the parent (calling) frame. When the memory cell is deleted or
  14677. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  14678. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  14679. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  14680. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  14681. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  14682. ** child frame are released.
  14683. **
  14684. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  14685. ** set to NULL if the currently executing frame is the main program.
  14686. */
  14687. typedef struct VdbeFrame VdbeFrame;
  14688. struct VdbeFrame {
  14689. Vdbe *v; /* VM this frame belongs to */
  14690. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  14691. Op *aOp; /* Program instructions for parent frame */
  14692. i64 *anExec; /* Event counters from parent frame */
  14693. Mem *aMem; /* Array of memory cells for parent frame */
  14694. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  14695. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  14696. void *token; /* Copy of SubProgram.token */
  14697. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  14698. int nCursor; /* Number of entries in apCsr */
  14699. int pc; /* Program Counter in parent (calling) frame */
  14700. int nOp; /* Size of aOp array */
  14701. int nMem; /* Number of entries in aMem */
  14702. int nOnceFlag; /* Number of entries in aOnceFlag */
  14703. int nChildMem; /* Number of memory cells for child frame */
  14704. int nChildCsr; /* Number of cursors for child frame */
  14705. int nChange; /* Statement changes (Vdbe.nChange) */
  14706. int nDbChange; /* Value of db->nChange */
  14707. };
  14708. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  14709. /*
  14710. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  14711. */
  14712. #define CACHE_STALE 0
  14713. /*
  14714. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  14715. ** structures. Each Mem struct may cache multiple representations (string,
  14716. ** integer etc.) of the same value.
  14717. */
  14718. struct Mem {
  14719. union MemValue {
  14720. double r; /* Real value used when MEM_Real is set in flags */
  14721. i64 i; /* Integer value used when MEM_Int is set in flags */
  14722. int nZero; /* Used when bit MEM_Zero is set in flags */
  14723. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  14724. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  14725. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  14726. } u;
  14727. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  14728. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  14729. u8 eSubtype; /* Subtype for this value */
  14730. int n; /* Number of characters in string value, excluding '\0' */
  14731. char *z; /* String or BLOB value */
  14732. /* ShallowCopy only needs to copy the information above */
  14733. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  14734. int szMalloc; /* Size of the zMalloc allocation */
  14735. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  14736. sqlite3 *db; /* The associated database connection */
  14737. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  14738. #ifdef SQLITE_DEBUG
  14739. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  14740. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  14741. #endif
  14742. };
  14743. /*
  14744. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  14745. ** follows.
  14746. */
  14747. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  14748. /* One or more of the following flags are set to indicate the validOK
  14749. ** representations of the value stored in the Mem struct.
  14750. **
  14751. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  14752. ** No other flags may be set in this case.
  14753. **
  14754. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  14755. ** Usually this is encoded in the same unicode encoding as the main
  14756. ** database (see below for exceptions). If the MEM_Term flag is also
  14757. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  14758. ** flags may coexist with the MEM_Str flag.
  14759. */
  14760. #define MEM_Null 0x0001 /* Value is NULL */
  14761. #define MEM_Str 0x0002 /* Value is a string */
  14762. #define MEM_Int 0x0004 /* Value is an integer */
  14763. #define MEM_Real 0x0008 /* Value is a real number */
  14764. #define MEM_Blob 0x0010 /* Value is a BLOB */
  14765. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  14766. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  14767. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  14768. #define MEM_Undefined 0x0080 /* Value is undefined */
  14769. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  14770. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  14771. /* Whenever Mem contains a valid string or blob representation, one of
  14772. ** the following flags must be set to determine the memory management
  14773. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  14774. ** string is \000 or \u0000 terminated
  14775. */
  14776. #define MEM_Term 0x0200 /* String rep is nul terminated */
  14777. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  14778. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  14779. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  14780. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  14781. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  14782. #ifdef SQLITE_OMIT_INCRBLOB
  14783. #undef MEM_Zero
  14784. #define MEM_Zero 0x0000
  14785. #endif
  14786. /*
  14787. ** Clear any existing type flags from a Mem and replace them with f
  14788. */
  14789. #define MemSetTypeFlag(p, f) \
  14790. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  14791. /*
  14792. ** Return true if a memory cell is not marked as invalid. This macro
  14793. ** is for use inside assert() statements only.
  14794. */
  14795. #ifdef SQLITE_DEBUG
  14796. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  14797. #endif
  14798. /*
  14799. ** Each auxiliary data pointer stored by a user defined function
  14800. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  14801. ** of this structure. All such structures associated with a single VM
  14802. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  14803. ** when the VM is halted (if not before).
  14804. */
  14805. struct AuxData {
  14806. int iOp; /* Instruction number of OP_Function opcode */
  14807. int iArg; /* Index of function argument. */
  14808. void *pAux; /* Aux data pointer */
  14809. void (*xDelete)(void *); /* Destructor for the aux data */
  14810. AuxData *pNext; /* Next element in list */
  14811. };
  14812. /*
  14813. ** The "context" argument for an installable function. A pointer to an
  14814. ** instance of this structure is the first argument to the routines used
  14815. ** implement the SQL functions.
  14816. **
  14817. ** There is a typedef for this structure in sqlite.h. So all routines,
  14818. ** even the public interface to SQLite, can use a pointer to this structure.
  14819. ** But this file is the only place where the internal details of this
  14820. ** structure are known.
  14821. **
  14822. ** This structure is defined inside of vdbeInt.h because it uses substructures
  14823. ** (Mem) which are only defined there.
  14824. */
  14825. struct sqlite3_context {
  14826. Mem *pOut; /* The return value is stored here */
  14827. FuncDef *pFunc; /* Pointer to function information */
  14828. Mem *pMem; /* Memory cell used to store aggregate context */
  14829. Vdbe *pVdbe; /* The VM that owns this context */
  14830. int iOp; /* Instruction number of OP_Function */
  14831. int isError; /* Error code returned by the function. */
  14832. u8 skipFlag; /* Skip accumulator loading if true */
  14833. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  14834. u8 argc; /* Number of arguments */
  14835. sqlite3_value *argv[1]; /* Argument set */
  14836. };
  14837. /*
  14838. ** An Explain object accumulates indented output which is helpful
  14839. ** in describing recursive data structures.
  14840. */
  14841. struct Explain {
  14842. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  14843. StrAccum str; /* The string being accumulated */
  14844. int nIndent; /* Number of elements in aIndent */
  14845. u16 aIndent[100]; /* Levels of indentation */
  14846. char zBase[100]; /* Initial space */
  14847. };
  14848. /* A bitfield type for use inside of structures. Always follow with :N where
  14849. ** N is the number of bits.
  14850. */
  14851. typedef unsigned bft; /* Bit Field Type */
  14852. typedef struct ScanStatus ScanStatus;
  14853. struct ScanStatus {
  14854. int addrExplain; /* OP_Explain for loop */
  14855. int addrLoop; /* Address of "loops" counter */
  14856. int addrVisit; /* Address of "rows visited" counter */
  14857. int iSelectID; /* The "Select-ID" for this loop */
  14858. LogEst nEst; /* Estimated output rows per loop */
  14859. char *zName; /* Name of table or index */
  14860. };
  14861. /*
  14862. ** An instance of the virtual machine. This structure contains the complete
  14863. ** state of the virtual machine.
  14864. **
  14865. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  14866. ** is really a pointer to an instance of this structure.
  14867. */
  14868. struct Vdbe {
  14869. sqlite3 *db; /* The database connection that owns this statement */
  14870. Op *aOp; /* Space to hold the virtual machine's program */
  14871. Mem *aMem; /* The memory locations */
  14872. Mem **apArg; /* Arguments to currently executing user function */
  14873. Mem *aColName; /* Column names to return */
  14874. Mem *pResultSet; /* Pointer to an array of results */
  14875. Parse *pParse; /* Parsing context used to create this Vdbe */
  14876. int nMem; /* Number of memory locations currently allocated */
  14877. int nOp; /* Number of instructions in the program */
  14878. int nCursor; /* Number of slots in apCsr[] */
  14879. u32 magic; /* Magic number for sanity checking */
  14880. char *zErrMsg; /* Error message written here */
  14881. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  14882. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  14883. Mem *aVar; /* Values for the OP_Variable opcode. */
  14884. char **azVar; /* Name of variables */
  14885. ynVar nVar; /* Number of entries in aVar[] */
  14886. ynVar nzVar; /* Number of entries in azVar[] */
  14887. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  14888. int pc; /* The program counter */
  14889. int rc; /* Value to return */
  14890. #ifdef SQLITE_DEBUG
  14891. int rcApp; /* errcode set by sqlite3_result_error_code() */
  14892. #endif
  14893. u16 nResColumn; /* Number of columns in one row of the result set */
  14894. u8 errorAction; /* Recovery action to do in case of an error */
  14895. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  14896. bft explain:2; /* True if EXPLAIN present on SQL command */
  14897. bft changeCntOn:1; /* True to update the change-counter */
  14898. bft expired:1; /* True if the VM needs to be recompiled */
  14899. bft runOnlyOnce:1; /* Automatically expire on reset */
  14900. bft usesStmtJournal:1; /* True if uses a statement journal */
  14901. bft readOnly:1; /* True for statements that do not write */
  14902. bft bIsReader:1; /* True for statements that read */
  14903. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  14904. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  14905. int nChange; /* Number of db changes made since last reset */
  14906. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  14907. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  14908. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  14909. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  14910. #ifndef SQLITE_OMIT_TRACE
  14911. i64 startTime; /* Time when query started - used for profiling */
  14912. #endif
  14913. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  14914. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  14915. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  14916. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  14917. char *zSql; /* Text of the SQL statement that generated this */
  14918. void *pFree; /* Free this when deleting the vdbe */
  14919. VdbeFrame *pFrame; /* Parent frame */
  14920. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  14921. int nFrame; /* Number of frames in pFrame list */
  14922. u32 expmask; /* Binding to these vars invalidates VM */
  14923. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  14924. int nOnceFlag; /* Size of array aOnceFlag[] */
  14925. u8 *aOnceFlag; /* Flags for OP_Once */
  14926. AuxData *pAuxData; /* Linked list of auxdata allocations */
  14927. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14928. i64 *anExec; /* Number of times each op has been executed */
  14929. int nScan; /* Entries in aScan[] */
  14930. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  14931. #endif
  14932. };
  14933. /*
  14934. ** The following are allowed values for Vdbe.magic
  14935. */
  14936. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  14937. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  14938. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  14939. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  14940. /*
  14941. ** Function prototypes
  14942. */
  14943. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  14944. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  14945. void sqliteVdbePopStack(Vdbe*,int);
  14946. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  14947. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  14948. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14949. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  14950. #endif
  14951. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  14952. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  14953. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  14954. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  14955. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  14956. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  14957. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  14958. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  14959. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  14960. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  14961. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  14962. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  14963. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  14964. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  14965. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  14966. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  14967. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  14968. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  14969. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  14970. #ifdef SQLITE_OMIT_FLOATING_POINT
  14971. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  14972. #else
  14973. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  14974. #endif
  14975. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  14976. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  14977. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  14978. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  14979. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  14980. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  14981. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  14982. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  14983. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  14984. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  14985. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  14986. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  14987. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  14988. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  14989. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  14990. #define VdbeMemDynamic(X) \
  14991. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  14992. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  14993. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  14994. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  14995. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  14996. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  14997. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  14998. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  14999. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  15000. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  15001. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  15002. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  15003. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  15004. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  15005. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  15006. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  15007. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  15008. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  15009. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  15010. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  15011. #else
  15012. # define sqlite3VdbeEnter(X)
  15013. # define sqlite3VdbeLeave(X)
  15014. #endif
  15015. #ifdef SQLITE_DEBUG
  15016. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  15017. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  15018. #endif
  15019. #ifndef SQLITE_OMIT_FOREIGN_KEY
  15020. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  15021. #else
  15022. # define sqlite3VdbeCheckFk(p,i) 0
  15023. #endif
  15024. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  15025. #ifdef SQLITE_DEBUG
  15026. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  15027. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  15028. #endif
  15029. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  15030. #ifndef SQLITE_OMIT_INCRBLOB
  15031. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  15032. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  15033. #else
  15034. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  15035. #define ExpandBlob(P) SQLITE_OK
  15036. #endif
  15037. #endif /* !defined(_VDBEINT_H_) */
  15038. /************** End of vdbeInt.h *********************************************/
  15039. /************** Continuing where we left off in status.c *********************/
  15040. /*
  15041. ** Variables in which to record status information.
  15042. */
  15043. typedef struct sqlite3StatType sqlite3StatType;
  15044. static SQLITE_WSD struct sqlite3StatType {
  15045. #if SQLITE_PTRSIZE>4
  15046. sqlite3_int64 nowValue[10]; /* Current value */
  15047. sqlite3_int64 mxValue[10]; /* Maximum value */
  15048. #else
  15049. u32 nowValue[10]; /* Current value */
  15050. u32 mxValue[10]; /* Maximum value */
  15051. #endif
  15052. } sqlite3Stat = { {0,}, {0,} };
  15053. /*
  15054. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  15055. ** mutex, or by the pcache1 mutex. The following array determines which.
  15056. */
  15057. static const char statMutex[] = {
  15058. 0, /* SQLITE_STATUS_MEMORY_USED */
  15059. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  15060. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  15061. 0, /* SQLITE_STATUS_SCRATCH_USED */
  15062. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  15063. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  15064. 0, /* SQLITE_STATUS_PARSER_STACK */
  15065. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  15066. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  15067. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  15068. };
  15069. /* The "wsdStat" macro will resolve to the status information
  15070. ** state vector. If writable static data is unsupported on the target,
  15071. ** we have to locate the state vector at run-time. In the more common
  15072. ** case where writable static data is supported, wsdStat can refer directly
  15073. ** to the "sqlite3Stat" state vector declared above.
  15074. */
  15075. #ifdef SQLITE_OMIT_WSD
  15076. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  15077. # define wsdStat x[0]
  15078. #else
  15079. # define wsdStatInit
  15080. # define wsdStat sqlite3Stat
  15081. #endif
  15082. /*
  15083. ** Return the current value of a status parameter. The caller must
  15084. ** be holding the appropriate mutex.
  15085. */
  15086. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  15087. wsdStatInit;
  15088. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15089. assert( op>=0 && op<ArraySize(statMutex) );
  15090. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15091. : sqlite3MallocMutex()) );
  15092. return wsdStat.nowValue[op];
  15093. }
  15094. /*
  15095. ** Add N to the value of a status record. The caller must hold the
  15096. ** appropriate mutex. (Locking is checked by assert()).
  15097. **
  15098. ** The StatusUp() routine can accept positive or negative values for N.
  15099. ** The value of N is added to the current status value and the high-water
  15100. ** mark is adjusted if necessary.
  15101. **
  15102. ** The StatusDown() routine lowers the current value by N. The highwater
  15103. ** mark is unchanged. N must be non-negative for StatusDown().
  15104. */
  15105. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  15106. wsdStatInit;
  15107. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15108. assert( op>=0 && op<ArraySize(statMutex) );
  15109. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15110. : sqlite3MallocMutex()) );
  15111. wsdStat.nowValue[op] += N;
  15112. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  15113. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15114. }
  15115. }
  15116. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  15117. wsdStatInit;
  15118. assert( N>=0 );
  15119. assert( op>=0 && op<ArraySize(statMutex) );
  15120. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15121. : sqlite3MallocMutex()) );
  15122. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15123. wsdStat.nowValue[op] -= N;
  15124. }
  15125. /*
  15126. ** Set the value of a status to X. The highwater mark is adjusted if
  15127. ** necessary. The caller must hold the appropriate mutex.
  15128. */
  15129. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  15130. wsdStatInit;
  15131. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15132. assert( op>=0 && op<ArraySize(statMutex) );
  15133. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15134. : sqlite3MallocMutex()) );
  15135. wsdStat.nowValue[op] = X;
  15136. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  15137. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15138. }
  15139. }
  15140. /*
  15141. ** Query status information.
  15142. */
  15143. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  15144. int op,
  15145. sqlite3_int64 *pCurrent,
  15146. sqlite3_int64 *pHighwater,
  15147. int resetFlag
  15148. ){
  15149. sqlite3_mutex *pMutex;
  15150. wsdStatInit;
  15151. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  15152. return SQLITE_MISUSE_BKPT;
  15153. }
  15154. #ifdef SQLITE_ENABLE_API_ARMOR
  15155. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15156. #endif
  15157. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  15158. sqlite3_mutex_enter(pMutex);
  15159. *pCurrent = wsdStat.nowValue[op];
  15160. *pHighwater = wsdStat.mxValue[op];
  15161. if( resetFlag ){
  15162. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15163. }
  15164. sqlite3_mutex_leave(pMutex);
  15165. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  15166. return SQLITE_OK;
  15167. }
  15168. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  15169. sqlite3_int64 iCur, iHwtr;
  15170. int rc;
  15171. #ifdef SQLITE_ENABLE_API_ARMOR
  15172. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15173. #endif
  15174. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  15175. if( rc==0 ){
  15176. *pCurrent = (int)iCur;
  15177. *pHighwater = (int)iHwtr;
  15178. }
  15179. return rc;
  15180. }
  15181. /*
  15182. ** Query status information for a single database connection
  15183. */
  15184. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
  15185. sqlite3 *db, /* The database connection whose status is desired */
  15186. int op, /* Status verb */
  15187. int *pCurrent, /* Write current value here */
  15188. int *pHighwater, /* Write high-water mark here */
  15189. int resetFlag /* Reset high-water mark if true */
  15190. ){
  15191. int rc = SQLITE_OK; /* Return code */
  15192. #ifdef SQLITE_ENABLE_API_ARMOR
  15193. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  15194. return SQLITE_MISUSE_BKPT;
  15195. }
  15196. #endif
  15197. sqlite3_mutex_enter(db->mutex);
  15198. switch( op ){
  15199. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  15200. *pCurrent = db->lookaside.nOut;
  15201. *pHighwater = db->lookaside.mxOut;
  15202. if( resetFlag ){
  15203. db->lookaside.mxOut = db->lookaside.nOut;
  15204. }
  15205. break;
  15206. }
  15207. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  15208. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  15209. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  15210. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  15211. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  15212. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  15213. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  15214. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  15215. *pCurrent = 0;
  15216. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  15217. if( resetFlag ){
  15218. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  15219. }
  15220. break;
  15221. }
  15222. /*
  15223. ** Return an approximation for the amount of memory currently used
  15224. ** by all pagers associated with the given database connection. The
  15225. ** highwater mark is meaningless and is returned as zero.
  15226. */
  15227. case SQLITE_DBSTATUS_CACHE_USED: {
  15228. int totalUsed = 0;
  15229. int i;
  15230. sqlite3BtreeEnterAll(db);
  15231. for(i=0; i<db->nDb; i++){
  15232. Btree *pBt = db->aDb[i].pBt;
  15233. if( pBt ){
  15234. Pager *pPager = sqlite3BtreePager(pBt);
  15235. totalUsed += sqlite3PagerMemUsed(pPager);
  15236. }
  15237. }
  15238. sqlite3BtreeLeaveAll(db);
  15239. *pCurrent = totalUsed;
  15240. *pHighwater = 0;
  15241. break;
  15242. }
  15243. /*
  15244. ** *pCurrent gets an accurate estimate of the amount of memory used
  15245. ** to store the schema for all databases (main, temp, and any ATTACHed
  15246. ** databases. *pHighwater is set to zero.
  15247. */
  15248. case SQLITE_DBSTATUS_SCHEMA_USED: {
  15249. int i; /* Used to iterate through schemas */
  15250. int nByte = 0; /* Used to accumulate return value */
  15251. sqlite3BtreeEnterAll(db);
  15252. db->pnBytesFreed = &nByte;
  15253. for(i=0; i<db->nDb; i++){
  15254. Schema *pSchema = db->aDb[i].pSchema;
  15255. if( ALWAYS(pSchema!=0) ){
  15256. HashElem *p;
  15257. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  15258. pSchema->tblHash.count
  15259. + pSchema->trigHash.count
  15260. + pSchema->idxHash.count
  15261. + pSchema->fkeyHash.count
  15262. );
  15263. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  15264. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  15265. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  15266. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  15267. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  15268. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  15269. }
  15270. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  15271. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  15272. }
  15273. }
  15274. }
  15275. db->pnBytesFreed = 0;
  15276. sqlite3BtreeLeaveAll(db);
  15277. *pHighwater = 0;
  15278. *pCurrent = nByte;
  15279. break;
  15280. }
  15281. /*
  15282. ** *pCurrent gets an accurate estimate of the amount of memory used
  15283. ** to store all prepared statements.
  15284. ** *pHighwater is set to zero.
  15285. */
  15286. case SQLITE_DBSTATUS_STMT_USED: {
  15287. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  15288. int nByte = 0; /* Used to accumulate return value */
  15289. db->pnBytesFreed = &nByte;
  15290. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  15291. sqlite3VdbeClearObject(db, pVdbe);
  15292. sqlite3DbFree(db, pVdbe);
  15293. }
  15294. db->pnBytesFreed = 0;
  15295. *pHighwater = 0; /* IMP: R-64479-57858 */
  15296. *pCurrent = nByte;
  15297. break;
  15298. }
  15299. /*
  15300. ** Set *pCurrent to the total cache hits or misses encountered by all
  15301. ** pagers the database handle is connected to. *pHighwater is always set
  15302. ** to zero.
  15303. */
  15304. case SQLITE_DBSTATUS_CACHE_HIT:
  15305. case SQLITE_DBSTATUS_CACHE_MISS:
  15306. case SQLITE_DBSTATUS_CACHE_WRITE:{
  15307. int i;
  15308. int nRet = 0;
  15309. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  15310. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  15311. for(i=0; i<db->nDb; i++){
  15312. if( db->aDb[i].pBt ){
  15313. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  15314. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  15315. }
  15316. }
  15317. *pHighwater = 0; /* IMP: R-42420-56072 */
  15318. /* IMP: R-54100-20147 */
  15319. /* IMP: R-29431-39229 */
  15320. *pCurrent = nRet;
  15321. break;
  15322. }
  15323. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  15324. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  15325. ** have been satisfied. The *pHighwater is always set to zero.
  15326. */
  15327. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  15328. *pHighwater = 0; /* IMP: R-11967-56545 */
  15329. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  15330. break;
  15331. }
  15332. default: {
  15333. rc = SQLITE_ERROR;
  15334. }
  15335. }
  15336. sqlite3_mutex_leave(db->mutex);
  15337. return rc;
  15338. }
  15339. /************** End of status.c **********************************************/
  15340. /************** Begin file date.c ********************************************/
  15341. /*
  15342. ** 2003 October 31
  15343. **
  15344. ** The author disclaims copyright to this source code. In place of
  15345. ** a legal notice, here is a blessing:
  15346. **
  15347. ** May you do good and not evil.
  15348. ** May you find forgiveness for yourself and forgive others.
  15349. ** May you share freely, never taking more than you give.
  15350. **
  15351. *************************************************************************
  15352. ** This file contains the C functions that implement date and time
  15353. ** functions for SQLite.
  15354. **
  15355. ** There is only one exported symbol in this file - the function
  15356. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  15357. ** All other code has file scope.
  15358. **
  15359. ** SQLite processes all times and dates as julian day numbers. The
  15360. ** dates and times are stored as the number of days since noon
  15361. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  15362. ** calendar system.
  15363. **
  15364. ** 1970-01-01 00:00:00 is JD 2440587.5
  15365. ** 2000-01-01 00:00:00 is JD 2451544.5
  15366. **
  15367. ** This implementation requires years to be expressed as a 4-digit number
  15368. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  15369. ** be represented, even though julian day numbers allow a much wider
  15370. ** range of dates.
  15371. **
  15372. ** The Gregorian calendar system is used for all dates and times,
  15373. ** even those that predate the Gregorian calendar. Historians usually
  15374. ** use the julian calendar for dates prior to 1582-10-15 and for some
  15375. ** dates afterwards, depending on locale. Beware of this difference.
  15376. **
  15377. ** The conversion algorithms are implemented based on descriptions
  15378. ** in the following text:
  15379. **
  15380. ** Jean Meeus
  15381. ** Astronomical Algorithms, 2nd Edition, 1998
  15382. ** ISBM 0-943396-61-1
  15383. ** Willmann-Bell, Inc
  15384. ** Richmond, Virginia (USA)
  15385. */
  15386. /* #include "sqliteInt.h" */
  15387. /* #include <stdlib.h> */
  15388. /* #include <assert.h> */
  15389. #include <time.h>
  15390. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15391. /*
  15392. ** A structure for holding a single date and time.
  15393. */
  15394. typedef struct DateTime DateTime;
  15395. struct DateTime {
  15396. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  15397. int Y, M, D; /* Year, month, and day */
  15398. int h, m; /* Hour and minutes */
  15399. int tz; /* Timezone offset in minutes */
  15400. double s; /* Seconds */
  15401. char validYMD; /* True (1) if Y,M,D are valid */
  15402. char validHMS; /* True (1) if h,m,s are valid */
  15403. char validJD; /* True (1) if iJD is valid */
  15404. char validTZ; /* True (1) if tz is valid */
  15405. };
  15406. /*
  15407. ** Convert zDate into one or more integers. Additional arguments
  15408. ** come in groups of 5 as follows:
  15409. **
  15410. ** N number of digits in the integer
  15411. ** min minimum allowed value of the integer
  15412. ** max maximum allowed value of the integer
  15413. ** nextC first character after the integer
  15414. ** pVal where to write the integers value.
  15415. **
  15416. ** Conversions continue until one with nextC==0 is encountered.
  15417. ** The function returns the number of successful conversions.
  15418. */
  15419. static int getDigits(const char *zDate, ...){
  15420. va_list ap;
  15421. int val;
  15422. int N;
  15423. int min;
  15424. int max;
  15425. int nextC;
  15426. int *pVal;
  15427. int cnt = 0;
  15428. va_start(ap, zDate);
  15429. do{
  15430. N = va_arg(ap, int);
  15431. min = va_arg(ap, int);
  15432. max = va_arg(ap, int);
  15433. nextC = va_arg(ap, int);
  15434. pVal = va_arg(ap, int*);
  15435. val = 0;
  15436. while( N-- ){
  15437. if( !sqlite3Isdigit(*zDate) ){
  15438. goto end_getDigits;
  15439. }
  15440. val = val*10 + *zDate - '0';
  15441. zDate++;
  15442. }
  15443. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  15444. goto end_getDigits;
  15445. }
  15446. *pVal = val;
  15447. zDate++;
  15448. cnt++;
  15449. }while( nextC );
  15450. end_getDigits:
  15451. va_end(ap);
  15452. return cnt;
  15453. }
  15454. /*
  15455. ** Parse a timezone extension on the end of a date-time.
  15456. ** The extension is of the form:
  15457. **
  15458. ** (+/-)HH:MM
  15459. **
  15460. ** Or the "zulu" notation:
  15461. **
  15462. ** Z
  15463. **
  15464. ** If the parse is successful, write the number of minutes
  15465. ** of change in p->tz and return 0. If a parser error occurs,
  15466. ** return non-zero.
  15467. **
  15468. ** A missing specifier is not considered an error.
  15469. */
  15470. static int parseTimezone(const char *zDate, DateTime *p){
  15471. int sgn = 0;
  15472. int nHr, nMn;
  15473. int c;
  15474. while( sqlite3Isspace(*zDate) ){ zDate++; }
  15475. p->tz = 0;
  15476. c = *zDate;
  15477. if( c=='-' ){
  15478. sgn = -1;
  15479. }else if( c=='+' ){
  15480. sgn = +1;
  15481. }else if( c=='Z' || c=='z' ){
  15482. zDate++;
  15483. goto zulu_time;
  15484. }else{
  15485. return c!=0;
  15486. }
  15487. zDate++;
  15488. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  15489. return 1;
  15490. }
  15491. zDate += 5;
  15492. p->tz = sgn*(nMn + nHr*60);
  15493. zulu_time:
  15494. while( sqlite3Isspace(*zDate) ){ zDate++; }
  15495. return *zDate!=0;
  15496. }
  15497. /*
  15498. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  15499. ** The HH, MM, and SS must each be exactly 2 digits. The
  15500. ** fractional seconds FFFF can be one or more digits.
  15501. **
  15502. ** Return 1 if there is a parsing error and 0 on success.
  15503. */
  15504. static int parseHhMmSs(const char *zDate, DateTime *p){
  15505. int h, m, s;
  15506. double ms = 0.0;
  15507. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  15508. return 1;
  15509. }
  15510. zDate += 5;
  15511. if( *zDate==':' ){
  15512. zDate++;
  15513. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  15514. return 1;
  15515. }
  15516. zDate += 2;
  15517. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  15518. double rScale = 1.0;
  15519. zDate++;
  15520. while( sqlite3Isdigit(*zDate) ){
  15521. ms = ms*10.0 + *zDate - '0';
  15522. rScale *= 10.0;
  15523. zDate++;
  15524. }
  15525. ms /= rScale;
  15526. }
  15527. }else{
  15528. s = 0;
  15529. }
  15530. p->validJD = 0;
  15531. p->validHMS = 1;
  15532. p->h = h;
  15533. p->m = m;
  15534. p->s = s + ms;
  15535. if( parseTimezone(zDate, p) ) return 1;
  15536. p->validTZ = (p->tz!=0)?1:0;
  15537. return 0;
  15538. }
  15539. /*
  15540. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  15541. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  15542. **
  15543. ** Reference: Meeus page 61
  15544. */
  15545. static void computeJD(DateTime *p){
  15546. int Y, M, D, A, B, X1, X2;
  15547. if( p->validJD ) return;
  15548. if( p->validYMD ){
  15549. Y = p->Y;
  15550. M = p->M;
  15551. D = p->D;
  15552. }else{
  15553. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  15554. M = 1;
  15555. D = 1;
  15556. }
  15557. if( M<=2 ){
  15558. Y--;
  15559. M += 12;
  15560. }
  15561. A = Y/100;
  15562. B = 2 - A + (A/4);
  15563. X1 = 36525*(Y+4716)/100;
  15564. X2 = 306001*(M+1)/10000;
  15565. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  15566. p->validJD = 1;
  15567. if( p->validHMS ){
  15568. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  15569. if( p->validTZ ){
  15570. p->iJD -= p->tz*60000;
  15571. p->validYMD = 0;
  15572. p->validHMS = 0;
  15573. p->validTZ = 0;
  15574. }
  15575. }
  15576. }
  15577. /*
  15578. ** Parse dates of the form
  15579. **
  15580. ** YYYY-MM-DD HH:MM:SS.FFF
  15581. ** YYYY-MM-DD HH:MM:SS
  15582. ** YYYY-MM-DD HH:MM
  15583. ** YYYY-MM-DD
  15584. **
  15585. ** Write the result into the DateTime structure and return 0
  15586. ** on success and 1 if the input string is not a well-formed
  15587. ** date.
  15588. */
  15589. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  15590. int Y, M, D, neg;
  15591. if( zDate[0]=='-' ){
  15592. zDate++;
  15593. neg = 1;
  15594. }else{
  15595. neg = 0;
  15596. }
  15597. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  15598. return 1;
  15599. }
  15600. zDate += 10;
  15601. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  15602. if( parseHhMmSs(zDate, p)==0 ){
  15603. /* We got the time */
  15604. }else if( *zDate==0 ){
  15605. p->validHMS = 0;
  15606. }else{
  15607. return 1;
  15608. }
  15609. p->validJD = 0;
  15610. p->validYMD = 1;
  15611. p->Y = neg ? -Y : Y;
  15612. p->M = M;
  15613. p->D = D;
  15614. if( p->validTZ ){
  15615. computeJD(p);
  15616. }
  15617. return 0;
  15618. }
  15619. /*
  15620. ** Set the time to the current time reported by the VFS.
  15621. **
  15622. ** Return the number of errors.
  15623. */
  15624. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  15625. p->iJD = sqlite3StmtCurrentTime(context);
  15626. if( p->iJD>0 ){
  15627. p->validJD = 1;
  15628. return 0;
  15629. }else{
  15630. return 1;
  15631. }
  15632. }
  15633. /*
  15634. ** Attempt to parse the given string into a julian day number. Return
  15635. ** the number of errors.
  15636. **
  15637. ** The following are acceptable forms for the input string:
  15638. **
  15639. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  15640. ** DDDD.DD
  15641. ** now
  15642. **
  15643. ** In the first form, the +/-HH:MM is always optional. The fractional
  15644. ** seconds extension (the ".FFF") is optional. The seconds portion
  15645. ** (":SS.FFF") is option. The year and date can be omitted as long
  15646. ** as there is a time string. The time string can be omitted as long
  15647. ** as there is a year and date.
  15648. */
  15649. static int parseDateOrTime(
  15650. sqlite3_context *context,
  15651. const char *zDate,
  15652. DateTime *p
  15653. ){
  15654. double r;
  15655. if( parseYyyyMmDd(zDate,p)==0 ){
  15656. return 0;
  15657. }else if( parseHhMmSs(zDate, p)==0 ){
  15658. return 0;
  15659. }else if( sqlite3StrICmp(zDate,"now")==0){
  15660. return setDateTimeToCurrent(context, p);
  15661. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  15662. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  15663. p->validJD = 1;
  15664. return 0;
  15665. }
  15666. return 1;
  15667. }
  15668. /*
  15669. ** Compute the Year, Month, and Day from the julian day number.
  15670. */
  15671. static void computeYMD(DateTime *p){
  15672. int Z, A, B, C, D, E, X1;
  15673. if( p->validYMD ) return;
  15674. if( !p->validJD ){
  15675. p->Y = 2000;
  15676. p->M = 1;
  15677. p->D = 1;
  15678. }else{
  15679. Z = (int)((p->iJD + 43200000)/86400000);
  15680. A = (int)((Z - 1867216.25)/36524.25);
  15681. A = Z + 1 + A - (A/4);
  15682. B = A + 1524;
  15683. C = (int)((B - 122.1)/365.25);
  15684. D = (36525*(C&32767))/100;
  15685. E = (int)((B-D)/30.6001);
  15686. X1 = (int)(30.6001*E);
  15687. p->D = B - D - X1;
  15688. p->M = E<14 ? E-1 : E-13;
  15689. p->Y = p->M>2 ? C - 4716 : C - 4715;
  15690. }
  15691. p->validYMD = 1;
  15692. }
  15693. /*
  15694. ** Compute the Hour, Minute, and Seconds from the julian day number.
  15695. */
  15696. static void computeHMS(DateTime *p){
  15697. int s;
  15698. if( p->validHMS ) return;
  15699. computeJD(p);
  15700. s = (int)((p->iJD + 43200000) % 86400000);
  15701. p->s = s/1000.0;
  15702. s = (int)p->s;
  15703. p->s -= s;
  15704. p->h = s/3600;
  15705. s -= p->h*3600;
  15706. p->m = s/60;
  15707. p->s += s - p->m*60;
  15708. p->validHMS = 1;
  15709. }
  15710. /*
  15711. ** Compute both YMD and HMS
  15712. */
  15713. static void computeYMD_HMS(DateTime *p){
  15714. computeYMD(p);
  15715. computeHMS(p);
  15716. }
  15717. /*
  15718. ** Clear the YMD and HMS and the TZ
  15719. */
  15720. static void clearYMD_HMS_TZ(DateTime *p){
  15721. p->validYMD = 0;
  15722. p->validHMS = 0;
  15723. p->validTZ = 0;
  15724. }
  15725. /*
  15726. ** On recent Windows platforms, the localtime_s() function is available
  15727. ** as part of the "Secure CRT". It is essentially equivalent to
  15728. ** localtime_r() available under most POSIX platforms, except that the
  15729. ** order of the parameters is reversed.
  15730. **
  15731. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  15732. **
  15733. ** If the user has not indicated to use localtime_r() or localtime_s()
  15734. ** already, check for an MSVC build environment that provides
  15735. ** localtime_s().
  15736. */
  15737. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  15738. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  15739. #undef HAVE_LOCALTIME_S
  15740. #define HAVE_LOCALTIME_S 1
  15741. #endif
  15742. #ifndef SQLITE_OMIT_LOCALTIME
  15743. /*
  15744. ** The following routine implements the rough equivalent of localtime_r()
  15745. ** using whatever operating-system specific localtime facility that
  15746. ** is available. This routine returns 0 on success and
  15747. ** non-zero on any kind of error.
  15748. **
  15749. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  15750. ** routine will always fail.
  15751. **
  15752. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  15753. ** library function localtime_r() is used to assist in the calculation of
  15754. ** local time.
  15755. */
  15756. static int osLocaltime(time_t *t, struct tm *pTm){
  15757. int rc;
  15758. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  15759. struct tm *pX;
  15760. #if SQLITE_THREADSAFE>0
  15761. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15762. #endif
  15763. sqlite3_mutex_enter(mutex);
  15764. pX = localtime(t);
  15765. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15766. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  15767. #endif
  15768. if( pX ) *pTm = *pX;
  15769. sqlite3_mutex_leave(mutex);
  15770. rc = pX==0;
  15771. #else
  15772. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15773. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  15774. #endif
  15775. #if HAVE_LOCALTIME_R
  15776. rc = localtime_r(t, pTm)==0;
  15777. #else
  15778. rc = localtime_s(pTm, t);
  15779. #endif /* HAVE_LOCALTIME_R */
  15780. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  15781. return rc;
  15782. }
  15783. #endif /* SQLITE_OMIT_LOCALTIME */
  15784. #ifndef SQLITE_OMIT_LOCALTIME
  15785. /*
  15786. ** Compute the difference (in milliseconds) between localtime and UTC
  15787. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  15788. ** return this value and set *pRc to SQLITE_OK.
  15789. **
  15790. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  15791. ** is undefined in this case.
  15792. */
  15793. static sqlite3_int64 localtimeOffset(
  15794. DateTime *p, /* Date at which to calculate offset */
  15795. sqlite3_context *pCtx, /* Write error here if one occurs */
  15796. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  15797. ){
  15798. DateTime x, y;
  15799. time_t t;
  15800. struct tm sLocal;
  15801. /* Initialize the contents of sLocal to avoid a compiler warning. */
  15802. memset(&sLocal, 0, sizeof(sLocal));
  15803. x = *p;
  15804. computeYMD_HMS(&x);
  15805. if( x.Y<1971 || x.Y>=2038 ){
  15806. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  15807. ** works for years between 1970 and 2037. For dates outside this range,
  15808. ** SQLite attempts to map the year into an equivalent year within this
  15809. ** range, do the calculation, then map the year back.
  15810. */
  15811. x.Y = 2000;
  15812. x.M = 1;
  15813. x.D = 1;
  15814. x.h = 0;
  15815. x.m = 0;
  15816. x.s = 0.0;
  15817. } else {
  15818. int s = (int)(x.s + 0.5);
  15819. x.s = s;
  15820. }
  15821. x.tz = 0;
  15822. x.validJD = 0;
  15823. computeJD(&x);
  15824. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  15825. if( osLocaltime(&t, &sLocal) ){
  15826. sqlite3_result_error(pCtx, "local time unavailable", -1);
  15827. *pRc = SQLITE_ERROR;
  15828. return 0;
  15829. }
  15830. y.Y = sLocal.tm_year + 1900;
  15831. y.M = sLocal.tm_mon + 1;
  15832. y.D = sLocal.tm_mday;
  15833. y.h = sLocal.tm_hour;
  15834. y.m = sLocal.tm_min;
  15835. y.s = sLocal.tm_sec;
  15836. y.validYMD = 1;
  15837. y.validHMS = 1;
  15838. y.validJD = 0;
  15839. y.validTZ = 0;
  15840. computeJD(&y);
  15841. *pRc = SQLITE_OK;
  15842. return y.iJD - x.iJD;
  15843. }
  15844. #endif /* SQLITE_OMIT_LOCALTIME */
  15845. /*
  15846. ** Process a modifier to a date-time stamp. The modifiers are
  15847. ** as follows:
  15848. **
  15849. ** NNN days
  15850. ** NNN hours
  15851. ** NNN minutes
  15852. ** NNN.NNNN seconds
  15853. ** NNN months
  15854. ** NNN years
  15855. ** start of month
  15856. ** start of year
  15857. ** start of week
  15858. ** start of day
  15859. ** weekday N
  15860. ** unixepoch
  15861. ** localtime
  15862. ** utc
  15863. **
  15864. ** Return 0 on success and 1 if there is any kind of error. If the error
  15865. ** is in a system call (i.e. localtime()), then an error message is written
  15866. ** to context pCtx. If the error is an unrecognized modifier, no error is
  15867. ** written to pCtx.
  15868. */
  15869. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  15870. int rc = 1;
  15871. int n;
  15872. double r;
  15873. char *z, zBuf[30];
  15874. z = zBuf;
  15875. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  15876. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  15877. }
  15878. z[n] = 0;
  15879. switch( z[0] ){
  15880. #ifndef SQLITE_OMIT_LOCALTIME
  15881. case 'l': {
  15882. /* localtime
  15883. **
  15884. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  15885. ** show local time.
  15886. */
  15887. if( strcmp(z, "localtime")==0 ){
  15888. computeJD(p);
  15889. p->iJD += localtimeOffset(p, pCtx, &rc);
  15890. clearYMD_HMS_TZ(p);
  15891. }
  15892. break;
  15893. }
  15894. #endif
  15895. case 'u': {
  15896. /*
  15897. ** unixepoch
  15898. **
  15899. ** Treat the current value of p->iJD as the number of
  15900. ** seconds since 1970. Convert to a real julian day number.
  15901. */
  15902. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  15903. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  15904. clearYMD_HMS_TZ(p);
  15905. rc = 0;
  15906. }
  15907. #ifndef SQLITE_OMIT_LOCALTIME
  15908. else if( strcmp(z, "utc")==0 ){
  15909. sqlite3_int64 c1;
  15910. computeJD(p);
  15911. c1 = localtimeOffset(p, pCtx, &rc);
  15912. if( rc==SQLITE_OK ){
  15913. p->iJD -= c1;
  15914. clearYMD_HMS_TZ(p);
  15915. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  15916. }
  15917. }
  15918. #endif
  15919. break;
  15920. }
  15921. case 'w': {
  15922. /*
  15923. ** weekday N
  15924. **
  15925. ** Move the date to the same time on the next occurrence of
  15926. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  15927. ** date is already on the appropriate weekday, this is a no-op.
  15928. */
  15929. if( strncmp(z, "weekday ", 8)==0
  15930. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  15931. && (n=(int)r)==r && n>=0 && r<7 ){
  15932. sqlite3_int64 Z;
  15933. computeYMD_HMS(p);
  15934. p->validTZ = 0;
  15935. p->validJD = 0;
  15936. computeJD(p);
  15937. Z = ((p->iJD + 129600000)/86400000) % 7;
  15938. if( Z>n ) Z -= 7;
  15939. p->iJD += (n - Z)*86400000;
  15940. clearYMD_HMS_TZ(p);
  15941. rc = 0;
  15942. }
  15943. break;
  15944. }
  15945. case 's': {
  15946. /*
  15947. ** start of TTTTT
  15948. **
  15949. ** Move the date backwards to the beginning of the current day,
  15950. ** or month or year.
  15951. */
  15952. if( strncmp(z, "start of ", 9)!=0 ) break;
  15953. z += 9;
  15954. computeYMD(p);
  15955. p->validHMS = 1;
  15956. p->h = p->m = 0;
  15957. p->s = 0.0;
  15958. p->validTZ = 0;
  15959. p->validJD = 0;
  15960. if( strcmp(z,"month")==0 ){
  15961. p->D = 1;
  15962. rc = 0;
  15963. }else if( strcmp(z,"year")==0 ){
  15964. computeYMD(p);
  15965. p->M = 1;
  15966. p->D = 1;
  15967. rc = 0;
  15968. }else if( strcmp(z,"day")==0 ){
  15969. rc = 0;
  15970. }
  15971. break;
  15972. }
  15973. case '+':
  15974. case '-':
  15975. case '0':
  15976. case '1':
  15977. case '2':
  15978. case '3':
  15979. case '4':
  15980. case '5':
  15981. case '6':
  15982. case '7':
  15983. case '8':
  15984. case '9': {
  15985. double rRounder;
  15986. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  15987. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  15988. rc = 1;
  15989. break;
  15990. }
  15991. if( z[n]==':' ){
  15992. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  15993. ** specified number of hours, minutes, seconds, and fractional seconds
  15994. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  15995. ** omitted.
  15996. */
  15997. const char *z2 = z;
  15998. DateTime tx;
  15999. sqlite3_int64 day;
  16000. if( !sqlite3Isdigit(*z2) ) z2++;
  16001. memset(&tx, 0, sizeof(tx));
  16002. if( parseHhMmSs(z2, &tx) ) break;
  16003. computeJD(&tx);
  16004. tx.iJD -= 43200000;
  16005. day = tx.iJD/86400000;
  16006. tx.iJD -= day*86400000;
  16007. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  16008. computeJD(p);
  16009. clearYMD_HMS_TZ(p);
  16010. p->iJD += tx.iJD;
  16011. rc = 0;
  16012. break;
  16013. }
  16014. z += n;
  16015. while( sqlite3Isspace(*z) ) z++;
  16016. n = sqlite3Strlen30(z);
  16017. if( n>10 || n<3 ) break;
  16018. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  16019. computeJD(p);
  16020. rc = 0;
  16021. rRounder = r<0 ? -0.5 : +0.5;
  16022. if( n==3 && strcmp(z,"day")==0 ){
  16023. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  16024. }else if( n==4 && strcmp(z,"hour")==0 ){
  16025. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  16026. }else if( n==6 && strcmp(z,"minute")==0 ){
  16027. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  16028. }else if( n==6 && strcmp(z,"second")==0 ){
  16029. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  16030. }else if( n==5 && strcmp(z,"month")==0 ){
  16031. int x, y;
  16032. computeYMD_HMS(p);
  16033. p->M += (int)r;
  16034. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  16035. p->Y += x;
  16036. p->M -= x*12;
  16037. p->validJD = 0;
  16038. computeJD(p);
  16039. y = (int)r;
  16040. if( y!=r ){
  16041. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  16042. }
  16043. }else if( n==4 && strcmp(z,"year")==0 ){
  16044. int y = (int)r;
  16045. computeYMD_HMS(p);
  16046. p->Y += y;
  16047. p->validJD = 0;
  16048. computeJD(p);
  16049. if( y!=r ){
  16050. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  16051. }
  16052. }else{
  16053. rc = 1;
  16054. }
  16055. clearYMD_HMS_TZ(p);
  16056. break;
  16057. }
  16058. default: {
  16059. break;
  16060. }
  16061. }
  16062. return rc;
  16063. }
  16064. /*
  16065. ** Process time function arguments. argv[0] is a date-time stamp.
  16066. ** argv[1] and following are modifiers. Parse them all and write
  16067. ** the resulting time into the DateTime structure p. Return 0
  16068. ** on success and 1 if there are any errors.
  16069. **
  16070. ** If there are zero parameters (if even argv[0] is undefined)
  16071. ** then assume a default value of "now" for argv[0].
  16072. */
  16073. static int isDate(
  16074. sqlite3_context *context,
  16075. int argc,
  16076. sqlite3_value **argv,
  16077. DateTime *p
  16078. ){
  16079. int i;
  16080. const unsigned char *z;
  16081. int eType;
  16082. memset(p, 0, sizeof(*p));
  16083. if( argc==0 ){
  16084. return setDateTimeToCurrent(context, p);
  16085. }
  16086. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  16087. || eType==SQLITE_INTEGER ){
  16088. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  16089. p->validJD = 1;
  16090. }else{
  16091. z = sqlite3_value_text(argv[0]);
  16092. if( !z || parseDateOrTime(context, (char*)z, p) ){
  16093. return 1;
  16094. }
  16095. }
  16096. for(i=1; i<argc; i++){
  16097. z = sqlite3_value_text(argv[i]);
  16098. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  16099. }
  16100. return 0;
  16101. }
  16102. /*
  16103. ** The following routines implement the various date and time functions
  16104. ** of SQLite.
  16105. */
  16106. /*
  16107. ** julianday( TIMESTRING, MOD, MOD, ...)
  16108. **
  16109. ** Return the julian day number of the date specified in the arguments
  16110. */
  16111. static void juliandayFunc(
  16112. sqlite3_context *context,
  16113. int argc,
  16114. sqlite3_value **argv
  16115. ){
  16116. DateTime x;
  16117. if( isDate(context, argc, argv, &x)==0 ){
  16118. computeJD(&x);
  16119. sqlite3_result_double(context, x.iJD/86400000.0);
  16120. }
  16121. }
  16122. /*
  16123. ** datetime( TIMESTRING, MOD, MOD, ...)
  16124. **
  16125. ** Return YYYY-MM-DD HH:MM:SS
  16126. */
  16127. static void datetimeFunc(
  16128. sqlite3_context *context,
  16129. int argc,
  16130. sqlite3_value **argv
  16131. ){
  16132. DateTime x;
  16133. if( isDate(context, argc, argv, &x)==0 ){
  16134. char zBuf[100];
  16135. computeYMD_HMS(&x);
  16136. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  16137. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  16138. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16139. }
  16140. }
  16141. /*
  16142. ** time( TIMESTRING, MOD, MOD, ...)
  16143. **
  16144. ** Return HH:MM:SS
  16145. */
  16146. static void timeFunc(
  16147. sqlite3_context *context,
  16148. int argc,
  16149. sqlite3_value **argv
  16150. ){
  16151. DateTime x;
  16152. if( isDate(context, argc, argv, &x)==0 ){
  16153. char zBuf[100];
  16154. computeHMS(&x);
  16155. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  16156. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16157. }
  16158. }
  16159. /*
  16160. ** date( TIMESTRING, MOD, MOD, ...)
  16161. **
  16162. ** Return YYYY-MM-DD
  16163. */
  16164. static void dateFunc(
  16165. sqlite3_context *context,
  16166. int argc,
  16167. sqlite3_value **argv
  16168. ){
  16169. DateTime x;
  16170. if( isDate(context, argc, argv, &x)==0 ){
  16171. char zBuf[100];
  16172. computeYMD(&x);
  16173. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  16174. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16175. }
  16176. }
  16177. /*
  16178. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  16179. **
  16180. ** Return a string described by FORMAT. Conversions as follows:
  16181. **
  16182. ** %d day of month
  16183. ** %f ** fractional seconds SS.SSS
  16184. ** %H hour 00-24
  16185. ** %j day of year 000-366
  16186. ** %J ** julian day number
  16187. ** %m month 01-12
  16188. ** %M minute 00-59
  16189. ** %s seconds since 1970-01-01
  16190. ** %S seconds 00-59
  16191. ** %w day of week 0-6 sunday==0
  16192. ** %W week of year 00-53
  16193. ** %Y year 0000-9999
  16194. ** %% %
  16195. */
  16196. static void strftimeFunc(
  16197. sqlite3_context *context,
  16198. int argc,
  16199. sqlite3_value **argv
  16200. ){
  16201. DateTime x;
  16202. u64 n;
  16203. size_t i,j;
  16204. char *z;
  16205. sqlite3 *db;
  16206. const char *zFmt;
  16207. char zBuf[100];
  16208. if( argc==0 ) return;
  16209. zFmt = (const char*)sqlite3_value_text(argv[0]);
  16210. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  16211. db = sqlite3_context_db_handle(context);
  16212. for(i=0, n=1; zFmt[i]; i++, n++){
  16213. if( zFmt[i]=='%' ){
  16214. switch( zFmt[i+1] ){
  16215. case 'd':
  16216. case 'H':
  16217. case 'm':
  16218. case 'M':
  16219. case 'S':
  16220. case 'W':
  16221. n++;
  16222. /* fall thru */
  16223. case 'w':
  16224. case '%':
  16225. break;
  16226. case 'f':
  16227. n += 8;
  16228. break;
  16229. case 'j':
  16230. n += 3;
  16231. break;
  16232. case 'Y':
  16233. n += 8;
  16234. break;
  16235. case 's':
  16236. case 'J':
  16237. n += 50;
  16238. break;
  16239. default:
  16240. return; /* ERROR. return a NULL */
  16241. }
  16242. i++;
  16243. }
  16244. }
  16245. testcase( n==sizeof(zBuf)-1 );
  16246. testcase( n==sizeof(zBuf) );
  16247. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  16248. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  16249. if( n<sizeof(zBuf) ){
  16250. z = zBuf;
  16251. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  16252. sqlite3_result_error_toobig(context);
  16253. return;
  16254. }else{
  16255. z = sqlite3DbMallocRaw(db, (int)n);
  16256. if( z==0 ){
  16257. sqlite3_result_error_nomem(context);
  16258. return;
  16259. }
  16260. }
  16261. computeJD(&x);
  16262. computeYMD_HMS(&x);
  16263. for(i=j=0; zFmt[i]; i++){
  16264. if( zFmt[i]!='%' ){
  16265. z[j++] = zFmt[i];
  16266. }else{
  16267. i++;
  16268. switch( zFmt[i] ){
  16269. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  16270. case 'f': {
  16271. double s = x.s;
  16272. if( s>59.999 ) s = 59.999;
  16273. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  16274. j += sqlite3Strlen30(&z[j]);
  16275. break;
  16276. }
  16277. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  16278. case 'W': /* Fall thru */
  16279. case 'j': {
  16280. int nDay; /* Number of days since 1st day of year */
  16281. DateTime y = x;
  16282. y.validJD = 0;
  16283. y.M = 1;
  16284. y.D = 1;
  16285. computeJD(&y);
  16286. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  16287. if( zFmt[i]=='W' ){
  16288. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  16289. wd = (int)(((x.iJD+43200000)/86400000)%7);
  16290. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  16291. j += 2;
  16292. }else{
  16293. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  16294. j += 3;
  16295. }
  16296. break;
  16297. }
  16298. case 'J': {
  16299. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  16300. j+=sqlite3Strlen30(&z[j]);
  16301. break;
  16302. }
  16303. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  16304. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  16305. case 's': {
  16306. sqlite3_snprintf(30,&z[j],"%lld",
  16307. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  16308. j += sqlite3Strlen30(&z[j]);
  16309. break;
  16310. }
  16311. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  16312. case 'w': {
  16313. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  16314. break;
  16315. }
  16316. case 'Y': {
  16317. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  16318. break;
  16319. }
  16320. default: z[j++] = '%'; break;
  16321. }
  16322. }
  16323. }
  16324. z[j] = 0;
  16325. sqlite3_result_text(context, z, -1,
  16326. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  16327. }
  16328. /*
  16329. ** current_time()
  16330. **
  16331. ** This function returns the same value as time('now').
  16332. */
  16333. static void ctimeFunc(
  16334. sqlite3_context *context,
  16335. int NotUsed,
  16336. sqlite3_value **NotUsed2
  16337. ){
  16338. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16339. timeFunc(context, 0, 0);
  16340. }
  16341. /*
  16342. ** current_date()
  16343. **
  16344. ** This function returns the same value as date('now').
  16345. */
  16346. static void cdateFunc(
  16347. sqlite3_context *context,
  16348. int NotUsed,
  16349. sqlite3_value **NotUsed2
  16350. ){
  16351. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16352. dateFunc(context, 0, 0);
  16353. }
  16354. /*
  16355. ** current_timestamp()
  16356. **
  16357. ** This function returns the same value as datetime('now').
  16358. */
  16359. static void ctimestampFunc(
  16360. sqlite3_context *context,
  16361. int NotUsed,
  16362. sqlite3_value **NotUsed2
  16363. ){
  16364. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16365. datetimeFunc(context, 0, 0);
  16366. }
  16367. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  16368. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  16369. /*
  16370. ** If the library is compiled to omit the full-scale date and time
  16371. ** handling (to get a smaller binary), the following minimal version
  16372. ** of the functions current_time(), current_date() and current_timestamp()
  16373. ** are included instead. This is to support column declarations that
  16374. ** include "DEFAULT CURRENT_TIME" etc.
  16375. **
  16376. ** This function uses the C-library functions time(), gmtime()
  16377. ** and strftime(). The format string to pass to strftime() is supplied
  16378. ** as the user-data for the function.
  16379. */
  16380. static void currentTimeFunc(
  16381. sqlite3_context *context,
  16382. int argc,
  16383. sqlite3_value **argv
  16384. ){
  16385. time_t t;
  16386. char *zFormat = (char *)sqlite3_user_data(context);
  16387. sqlite3 *db;
  16388. sqlite3_int64 iT;
  16389. struct tm *pTm;
  16390. struct tm sNow;
  16391. char zBuf[20];
  16392. UNUSED_PARAMETER(argc);
  16393. UNUSED_PARAMETER(argv);
  16394. iT = sqlite3StmtCurrentTime(context);
  16395. if( iT<=0 ) return;
  16396. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  16397. #if HAVE_GMTIME_R
  16398. pTm = gmtime_r(&t, &sNow);
  16399. #else
  16400. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  16401. pTm = gmtime(&t);
  16402. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  16403. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  16404. #endif
  16405. if( pTm ){
  16406. strftime(zBuf, 20, zFormat, &sNow);
  16407. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16408. }
  16409. }
  16410. #endif
  16411. /*
  16412. ** This function registered all of the above C functions as SQL
  16413. ** functions. This should be the only routine in this file with
  16414. ** external linkage.
  16415. */
  16416. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  16417. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  16418. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  16419. DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  16420. DFUNCTION(date, -1, 0, 0, dateFunc ),
  16421. DFUNCTION(time, -1, 0, 0, timeFunc ),
  16422. DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  16423. DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  16424. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  16425. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  16426. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  16427. #else
  16428. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  16429. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  16430. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  16431. #endif
  16432. };
  16433. int i;
  16434. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  16435. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  16436. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  16437. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  16438. }
  16439. }
  16440. /************** End of date.c ************************************************/
  16441. /************** Begin file os.c **********************************************/
  16442. /*
  16443. ** 2005 November 29
  16444. **
  16445. ** The author disclaims copyright to this source code. In place of
  16446. ** a legal notice, here is a blessing:
  16447. **
  16448. ** May you do good and not evil.
  16449. ** May you find forgiveness for yourself and forgive others.
  16450. ** May you share freely, never taking more than you give.
  16451. **
  16452. ******************************************************************************
  16453. **
  16454. ** This file contains OS interface code that is common to all
  16455. ** architectures.
  16456. */
  16457. #define _SQLITE_OS_C_ 1
  16458. /* #include "sqliteInt.h" */
  16459. #undef _SQLITE_OS_C_
  16460. /*
  16461. ** The default SQLite sqlite3_vfs implementations do not allocate
  16462. ** memory (actually, os_unix.c allocates a small amount of memory
  16463. ** from within OsOpen()), but some third-party implementations may.
  16464. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  16465. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  16466. **
  16467. ** The following functions are instrumented for malloc() failure
  16468. ** testing:
  16469. **
  16470. ** sqlite3OsRead()
  16471. ** sqlite3OsWrite()
  16472. ** sqlite3OsSync()
  16473. ** sqlite3OsFileSize()
  16474. ** sqlite3OsLock()
  16475. ** sqlite3OsCheckReservedLock()
  16476. ** sqlite3OsFileControl()
  16477. ** sqlite3OsShmMap()
  16478. ** sqlite3OsOpen()
  16479. ** sqlite3OsDelete()
  16480. ** sqlite3OsAccess()
  16481. ** sqlite3OsFullPathname()
  16482. **
  16483. */
  16484. #if defined(SQLITE_TEST)
  16485. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  16486. #define DO_OS_MALLOC_TEST(x) \
  16487. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  16488. void *pTstAlloc = sqlite3Malloc(10); \
  16489. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  16490. sqlite3_free(pTstAlloc); \
  16491. }
  16492. #else
  16493. #define DO_OS_MALLOC_TEST(x)
  16494. #endif
  16495. /*
  16496. ** The following routines are convenience wrappers around methods
  16497. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  16498. ** of this would be completely automatic if SQLite were coded using
  16499. ** C++ instead of plain old C.
  16500. */
  16501. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  16502. int rc = SQLITE_OK;
  16503. if( pId->pMethods ){
  16504. rc = pId->pMethods->xClose(pId);
  16505. pId->pMethods = 0;
  16506. }
  16507. return rc;
  16508. }
  16509. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  16510. DO_OS_MALLOC_TEST(id);
  16511. return id->pMethods->xRead(id, pBuf, amt, offset);
  16512. }
  16513. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  16514. DO_OS_MALLOC_TEST(id);
  16515. return id->pMethods->xWrite(id, pBuf, amt, offset);
  16516. }
  16517. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  16518. return id->pMethods->xTruncate(id, size);
  16519. }
  16520. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  16521. DO_OS_MALLOC_TEST(id);
  16522. return id->pMethods->xSync(id, flags);
  16523. }
  16524. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  16525. DO_OS_MALLOC_TEST(id);
  16526. return id->pMethods->xFileSize(id, pSize);
  16527. }
  16528. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  16529. DO_OS_MALLOC_TEST(id);
  16530. return id->pMethods->xLock(id, lockType);
  16531. }
  16532. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  16533. return id->pMethods->xUnlock(id, lockType);
  16534. }
  16535. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  16536. DO_OS_MALLOC_TEST(id);
  16537. return id->pMethods->xCheckReservedLock(id, pResOut);
  16538. }
  16539. /*
  16540. ** Use sqlite3OsFileControl() when we are doing something that might fail
  16541. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  16542. ** when simply tossing information over the wall to the VFS and we do not
  16543. ** really care if the VFS receives and understands the information since it
  16544. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  16545. ** routine has no return value since the return value would be meaningless.
  16546. */
  16547. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  16548. #ifdef SQLITE_TEST
  16549. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  16550. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  16551. ** is using a regular VFS, it is called after the corresponding
  16552. ** transaction has been committed. Injecting a fault at this point
  16553. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  16554. ** but the transaction is committed anyway.
  16555. **
  16556. ** The core must call OsFileControl() though, not OsFileControlHint(),
  16557. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  16558. ** means the commit really has failed and an error should be returned
  16559. ** to the user. */
  16560. DO_OS_MALLOC_TEST(id);
  16561. }
  16562. #endif
  16563. return id->pMethods->xFileControl(id, op, pArg);
  16564. }
  16565. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  16566. (void)id->pMethods->xFileControl(id, op, pArg);
  16567. }
  16568. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  16569. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  16570. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  16571. }
  16572. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  16573. return id->pMethods->xDeviceCharacteristics(id);
  16574. }
  16575. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  16576. return id->pMethods->xShmLock(id, offset, n, flags);
  16577. }
  16578. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  16579. id->pMethods->xShmBarrier(id);
  16580. }
  16581. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  16582. return id->pMethods->xShmUnmap(id, deleteFlag);
  16583. }
  16584. SQLITE_PRIVATE int sqlite3OsShmMap(
  16585. sqlite3_file *id, /* Database file handle */
  16586. int iPage,
  16587. int pgsz,
  16588. int bExtend, /* True to extend file if necessary */
  16589. void volatile **pp /* OUT: Pointer to mapping */
  16590. ){
  16591. DO_OS_MALLOC_TEST(id);
  16592. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  16593. }
  16594. #if SQLITE_MAX_MMAP_SIZE>0
  16595. /* The real implementation of xFetch and xUnfetch */
  16596. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  16597. DO_OS_MALLOC_TEST(id);
  16598. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  16599. }
  16600. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  16601. return id->pMethods->xUnfetch(id, iOff, p);
  16602. }
  16603. #else
  16604. /* No-op stubs to use when memory-mapped I/O is disabled */
  16605. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  16606. *pp = 0;
  16607. return SQLITE_OK;
  16608. }
  16609. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  16610. return SQLITE_OK;
  16611. }
  16612. #endif
  16613. /*
  16614. ** The next group of routines are convenience wrappers around the
  16615. ** VFS methods.
  16616. */
  16617. SQLITE_PRIVATE int sqlite3OsOpen(
  16618. sqlite3_vfs *pVfs,
  16619. const char *zPath,
  16620. sqlite3_file *pFile,
  16621. int flags,
  16622. int *pFlagsOut
  16623. ){
  16624. int rc;
  16625. DO_OS_MALLOC_TEST(0);
  16626. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  16627. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  16628. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  16629. ** reaching the VFS. */
  16630. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  16631. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  16632. return rc;
  16633. }
  16634. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  16635. DO_OS_MALLOC_TEST(0);
  16636. assert( dirSync==0 || dirSync==1 );
  16637. return pVfs->xDelete(pVfs, zPath, dirSync);
  16638. }
  16639. SQLITE_PRIVATE int sqlite3OsAccess(
  16640. sqlite3_vfs *pVfs,
  16641. const char *zPath,
  16642. int flags,
  16643. int *pResOut
  16644. ){
  16645. DO_OS_MALLOC_TEST(0);
  16646. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  16647. }
  16648. SQLITE_PRIVATE int sqlite3OsFullPathname(
  16649. sqlite3_vfs *pVfs,
  16650. const char *zPath,
  16651. int nPathOut,
  16652. char *zPathOut
  16653. ){
  16654. DO_OS_MALLOC_TEST(0);
  16655. zPathOut[0] = 0;
  16656. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  16657. }
  16658. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  16659. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  16660. return pVfs->xDlOpen(pVfs, zPath);
  16661. }
  16662. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  16663. pVfs->xDlError(pVfs, nByte, zBufOut);
  16664. }
  16665. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  16666. return pVfs->xDlSym(pVfs, pHdle, zSym);
  16667. }
  16668. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  16669. pVfs->xDlClose(pVfs, pHandle);
  16670. }
  16671. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  16672. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  16673. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  16674. }
  16675. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  16676. return pVfs->xSleep(pVfs, nMicro);
  16677. }
  16678. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  16679. int rc;
  16680. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  16681. ** method to get the current date and time if that method is available
  16682. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  16683. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  16684. ** unavailable.
  16685. */
  16686. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  16687. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  16688. }else{
  16689. double r;
  16690. rc = pVfs->xCurrentTime(pVfs, &r);
  16691. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  16692. }
  16693. return rc;
  16694. }
  16695. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  16696. sqlite3_vfs *pVfs,
  16697. const char *zFile,
  16698. sqlite3_file **ppFile,
  16699. int flags,
  16700. int *pOutFlags
  16701. ){
  16702. int rc = SQLITE_NOMEM;
  16703. sqlite3_file *pFile;
  16704. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  16705. if( pFile ){
  16706. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  16707. if( rc!=SQLITE_OK ){
  16708. sqlite3_free(pFile);
  16709. }else{
  16710. *ppFile = pFile;
  16711. }
  16712. }
  16713. return rc;
  16714. }
  16715. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  16716. int rc = SQLITE_OK;
  16717. assert( pFile );
  16718. rc = sqlite3OsClose(pFile);
  16719. sqlite3_free(pFile);
  16720. return rc;
  16721. }
  16722. /*
  16723. ** This function is a wrapper around the OS specific implementation of
  16724. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  16725. ** ability to simulate a malloc failure, so that the handling of an
  16726. ** error in sqlite3_os_init() by the upper layers can be tested.
  16727. */
  16728. SQLITE_PRIVATE int sqlite3OsInit(void){
  16729. void *p = sqlite3_malloc(10);
  16730. if( p==0 ) return SQLITE_NOMEM;
  16731. sqlite3_free(p);
  16732. return sqlite3_os_init();
  16733. }
  16734. /*
  16735. ** The list of all registered VFS implementations.
  16736. */
  16737. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  16738. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  16739. /*
  16740. ** Locate a VFS by name. If no name is given, simply return the
  16741. ** first VFS on the list.
  16742. */
  16743. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
  16744. sqlite3_vfs *pVfs = 0;
  16745. #if SQLITE_THREADSAFE
  16746. sqlite3_mutex *mutex;
  16747. #endif
  16748. #ifndef SQLITE_OMIT_AUTOINIT
  16749. int rc = sqlite3_initialize();
  16750. if( rc ) return 0;
  16751. #endif
  16752. #if SQLITE_THREADSAFE
  16753. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16754. #endif
  16755. sqlite3_mutex_enter(mutex);
  16756. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  16757. if( zVfs==0 ) break;
  16758. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  16759. }
  16760. sqlite3_mutex_leave(mutex);
  16761. return pVfs;
  16762. }
  16763. /*
  16764. ** Unlink a VFS from the linked list
  16765. */
  16766. static void vfsUnlink(sqlite3_vfs *pVfs){
  16767. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  16768. if( pVfs==0 ){
  16769. /* No-op */
  16770. }else if( vfsList==pVfs ){
  16771. vfsList = pVfs->pNext;
  16772. }else if( vfsList ){
  16773. sqlite3_vfs *p = vfsList;
  16774. while( p->pNext && p->pNext!=pVfs ){
  16775. p = p->pNext;
  16776. }
  16777. if( p->pNext==pVfs ){
  16778. p->pNext = pVfs->pNext;
  16779. }
  16780. }
  16781. }
  16782. /*
  16783. ** Register a VFS with the system. It is harmless to register the same
  16784. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  16785. ** true.
  16786. */
  16787. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  16788. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  16789. #ifndef SQLITE_OMIT_AUTOINIT
  16790. int rc = sqlite3_initialize();
  16791. if( rc ) return rc;
  16792. #endif
  16793. #ifdef SQLITE_ENABLE_API_ARMOR
  16794. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  16795. #endif
  16796. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  16797. sqlite3_mutex_enter(mutex);
  16798. vfsUnlink(pVfs);
  16799. if( makeDflt || vfsList==0 ){
  16800. pVfs->pNext = vfsList;
  16801. vfsList = pVfs;
  16802. }else{
  16803. pVfs->pNext = vfsList->pNext;
  16804. vfsList->pNext = pVfs;
  16805. }
  16806. assert(vfsList);
  16807. sqlite3_mutex_leave(mutex);
  16808. return SQLITE_OK;
  16809. }
  16810. /*
  16811. ** Unregister a VFS so that it is no longer accessible.
  16812. */
  16813. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  16814. #if SQLITE_THREADSAFE
  16815. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16816. #endif
  16817. sqlite3_mutex_enter(mutex);
  16818. vfsUnlink(pVfs);
  16819. sqlite3_mutex_leave(mutex);
  16820. return SQLITE_OK;
  16821. }
  16822. /************** End of os.c **************************************************/
  16823. /************** Begin file fault.c *******************************************/
  16824. /*
  16825. ** 2008 Jan 22
  16826. **
  16827. ** The author disclaims copyright to this source code. In place of
  16828. ** a legal notice, here is a blessing:
  16829. **
  16830. ** May you do good and not evil.
  16831. ** May you find forgiveness for yourself and forgive others.
  16832. ** May you share freely, never taking more than you give.
  16833. **
  16834. *************************************************************************
  16835. **
  16836. ** This file contains code to support the concept of "benign"
  16837. ** malloc failures (when the xMalloc() or xRealloc() method of the
  16838. ** sqlite3_mem_methods structure fails to allocate a block of memory
  16839. ** and returns 0).
  16840. **
  16841. ** Most malloc failures are non-benign. After they occur, SQLite
  16842. ** abandons the current operation and returns an error code (usually
  16843. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  16844. ** fatal. For example, if a malloc fails while resizing a hash table, this
  16845. ** is completely recoverable simply by not carrying out the resize. The
  16846. ** hash table will continue to function normally. So a malloc failure
  16847. ** during a hash table resize is a benign fault.
  16848. */
  16849. /* #include "sqliteInt.h" */
  16850. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16851. /*
  16852. ** Global variables.
  16853. */
  16854. typedef struct BenignMallocHooks BenignMallocHooks;
  16855. static SQLITE_WSD struct BenignMallocHooks {
  16856. void (*xBenignBegin)(void);
  16857. void (*xBenignEnd)(void);
  16858. } sqlite3Hooks = { 0, 0 };
  16859. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  16860. ** structure. If writable static data is unsupported on the target,
  16861. ** we have to locate the state vector at run-time. In the more common
  16862. ** case where writable static data is supported, wsdHooks can refer directly
  16863. ** to the "sqlite3Hooks" state vector declared above.
  16864. */
  16865. #ifdef SQLITE_OMIT_WSD
  16866. # define wsdHooksInit \
  16867. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  16868. # define wsdHooks x[0]
  16869. #else
  16870. # define wsdHooksInit
  16871. # define wsdHooks sqlite3Hooks
  16872. #endif
  16873. /*
  16874. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  16875. ** sqlite3EndBenignMalloc() are called, respectively.
  16876. */
  16877. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  16878. void (*xBenignBegin)(void),
  16879. void (*xBenignEnd)(void)
  16880. ){
  16881. wsdHooksInit;
  16882. wsdHooks.xBenignBegin = xBenignBegin;
  16883. wsdHooks.xBenignEnd = xBenignEnd;
  16884. }
  16885. /*
  16886. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  16887. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  16888. ** indicates that subsequent malloc failures are non-benign.
  16889. */
  16890. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  16891. wsdHooksInit;
  16892. if( wsdHooks.xBenignBegin ){
  16893. wsdHooks.xBenignBegin();
  16894. }
  16895. }
  16896. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  16897. wsdHooksInit;
  16898. if( wsdHooks.xBenignEnd ){
  16899. wsdHooks.xBenignEnd();
  16900. }
  16901. }
  16902. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  16903. /************** End of fault.c ***********************************************/
  16904. /************** Begin file mem0.c ********************************************/
  16905. /*
  16906. ** 2008 October 28
  16907. **
  16908. ** The author disclaims copyright to this source code. In place of
  16909. ** a legal notice, here is a blessing:
  16910. **
  16911. ** May you do good and not evil.
  16912. ** May you find forgiveness for yourself and forgive others.
  16913. ** May you share freely, never taking more than you give.
  16914. **
  16915. *************************************************************************
  16916. **
  16917. ** This file contains a no-op memory allocation drivers for use when
  16918. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  16919. ** here always fail. SQLite will not operate with these drivers. These
  16920. ** are merely placeholders. Real drivers must be substituted using
  16921. ** sqlite3_config() before SQLite will operate.
  16922. */
  16923. /* #include "sqliteInt.h" */
  16924. /*
  16925. ** This version of the memory allocator is the default. It is
  16926. ** used when no other memory allocator is specified using compile-time
  16927. ** macros.
  16928. */
  16929. #ifdef SQLITE_ZERO_MALLOC
  16930. /*
  16931. ** No-op versions of all memory allocation routines
  16932. */
  16933. static void *sqlite3MemMalloc(int nByte){ return 0; }
  16934. static void sqlite3MemFree(void *pPrior){ return; }
  16935. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  16936. static int sqlite3MemSize(void *pPrior){ return 0; }
  16937. static int sqlite3MemRoundup(int n){ return n; }
  16938. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  16939. static void sqlite3MemShutdown(void *NotUsed){ return; }
  16940. /*
  16941. ** This routine is the only routine in this file with external linkage.
  16942. **
  16943. ** Populate the low-level memory allocation function pointers in
  16944. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16945. */
  16946. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16947. static const sqlite3_mem_methods defaultMethods = {
  16948. sqlite3MemMalloc,
  16949. sqlite3MemFree,
  16950. sqlite3MemRealloc,
  16951. sqlite3MemSize,
  16952. sqlite3MemRoundup,
  16953. sqlite3MemInit,
  16954. sqlite3MemShutdown,
  16955. 0
  16956. };
  16957. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16958. }
  16959. #endif /* SQLITE_ZERO_MALLOC */
  16960. /************** End of mem0.c ************************************************/
  16961. /************** Begin file mem1.c ********************************************/
  16962. /*
  16963. ** 2007 August 14
  16964. **
  16965. ** The author disclaims copyright to this source code. In place of
  16966. ** a legal notice, here is a blessing:
  16967. **
  16968. ** May you do good and not evil.
  16969. ** May you find forgiveness for yourself and forgive others.
  16970. ** May you share freely, never taking more than you give.
  16971. **
  16972. *************************************************************************
  16973. **
  16974. ** This file contains low-level memory allocation drivers for when
  16975. ** SQLite will use the standard C-library malloc/realloc/free interface
  16976. ** to obtain the memory it needs.
  16977. **
  16978. ** This file contains implementations of the low-level memory allocation
  16979. ** routines specified in the sqlite3_mem_methods object. The content of
  16980. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  16981. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  16982. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  16983. ** default configuration is to use memory allocation routines in this
  16984. ** file.
  16985. **
  16986. ** C-preprocessor macro summary:
  16987. **
  16988. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  16989. ** the malloc_usable_size() interface exists
  16990. ** on the target platform. Or, this symbol
  16991. ** can be set manually, if desired.
  16992. ** If an equivalent interface exists by
  16993. ** a different name, using a separate -D
  16994. ** option to rename it.
  16995. **
  16996. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  16997. ** memory allocator. Set this symbol to enable
  16998. ** building on older macs.
  16999. **
  17000. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  17001. ** _msize() on windows systems. This might
  17002. ** be necessary when compiling for Delphi,
  17003. ** for example.
  17004. */
  17005. /* #include "sqliteInt.h" */
  17006. /*
  17007. ** This version of the memory allocator is the default. It is
  17008. ** used when no other memory allocator is specified using compile-time
  17009. ** macros.
  17010. */
  17011. #ifdef SQLITE_SYSTEM_MALLOC
  17012. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17013. /*
  17014. ** Use the zone allocator available on apple products unless the
  17015. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  17016. */
  17017. #include <sys/sysctl.h>
  17018. #include <malloc/malloc.h>
  17019. #include <libkern/OSAtomic.h>
  17020. static malloc_zone_t* _sqliteZone_;
  17021. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  17022. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  17023. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  17024. #define SQLITE_MALLOCSIZE(x) \
  17025. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  17026. #else /* if not __APPLE__ */
  17027. /*
  17028. ** Use standard C library malloc and free on non-Apple systems.
  17029. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  17030. */
  17031. #define SQLITE_MALLOC(x) malloc(x)
  17032. #define SQLITE_FREE(x) free(x)
  17033. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  17034. /*
  17035. ** The malloc.h header file is needed for malloc_usable_size() function
  17036. ** on some systems (e.g. Linux).
  17037. */
  17038. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  17039. # define SQLITE_USE_MALLOC_H 1
  17040. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  17041. /*
  17042. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  17043. ** use of _msize() is automatic, but can be disabled by compiling with
  17044. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  17045. ** the malloc.h header file.
  17046. */
  17047. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  17048. # define SQLITE_USE_MALLOC_H
  17049. # define SQLITE_USE_MSIZE
  17050. #endif
  17051. /*
  17052. ** Include the malloc.h header file, if necessary. Also set define macro
  17053. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  17054. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  17055. ** The memory size function can always be overridden manually by defining
  17056. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  17057. */
  17058. #if defined(SQLITE_USE_MALLOC_H)
  17059. # include <malloc.h>
  17060. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  17061. # if !defined(SQLITE_MALLOCSIZE)
  17062. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  17063. # endif
  17064. # elif defined(SQLITE_USE_MSIZE)
  17065. # if !defined(SQLITE_MALLOCSIZE)
  17066. # define SQLITE_MALLOCSIZE _msize
  17067. # endif
  17068. # endif
  17069. #endif /* defined(SQLITE_USE_MALLOC_H) */
  17070. #endif /* __APPLE__ or not __APPLE__ */
  17071. /*
  17072. ** Like malloc(), but remember the size of the allocation
  17073. ** so that we can find it later using sqlite3MemSize().
  17074. **
  17075. ** For this low-level routine, we are guaranteed that nByte>0 because
  17076. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  17077. ** routines.
  17078. */
  17079. static void *sqlite3MemMalloc(int nByte){
  17080. #ifdef SQLITE_MALLOCSIZE
  17081. void *p = SQLITE_MALLOC( nByte );
  17082. if( p==0 ){
  17083. testcase( sqlite3GlobalConfig.xLog!=0 );
  17084. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17085. }
  17086. return p;
  17087. #else
  17088. sqlite3_int64 *p;
  17089. assert( nByte>0 );
  17090. nByte = ROUND8(nByte);
  17091. p = SQLITE_MALLOC( nByte+8 );
  17092. if( p ){
  17093. p[0] = nByte;
  17094. p++;
  17095. }else{
  17096. testcase( sqlite3GlobalConfig.xLog!=0 );
  17097. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17098. }
  17099. return (void *)p;
  17100. #endif
  17101. }
  17102. /*
  17103. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  17104. ** or sqlite3MemRealloc().
  17105. **
  17106. ** For this low-level routine, we already know that pPrior!=0 since
  17107. ** cases where pPrior==0 will have been intecepted and dealt with
  17108. ** by higher-level routines.
  17109. */
  17110. static void sqlite3MemFree(void *pPrior){
  17111. #ifdef SQLITE_MALLOCSIZE
  17112. SQLITE_FREE(pPrior);
  17113. #else
  17114. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17115. assert( pPrior!=0 );
  17116. p--;
  17117. SQLITE_FREE(p);
  17118. #endif
  17119. }
  17120. /*
  17121. ** Report the allocated size of a prior return from xMalloc()
  17122. ** or xRealloc().
  17123. */
  17124. static int sqlite3MemSize(void *pPrior){
  17125. #ifdef SQLITE_MALLOCSIZE
  17126. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  17127. #else
  17128. sqlite3_int64 *p;
  17129. if( pPrior==0 ) return 0;
  17130. p = (sqlite3_int64*)pPrior;
  17131. p--;
  17132. return (int)p[0];
  17133. #endif
  17134. }
  17135. /*
  17136. ** Like realloc(). Resize an allocation previously obtained from
  17137. ** sqlite3MemMalloc().
  17138. **
  17139. ** For this low-level interface, we know that pPrior!=0. Cases where
  17140. ** pPrior==0 while have been intercepted by higher-level routine and
  17141. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  17142. ** cases where nByte<=0 will have been intercepted by higher-level
  17143. ** routines and redirected to xFree.
  17144. */
  17145. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  17146. #ifdef SQLITE_MALLOCSIZE
  17147. void *p = SQLITE_REALLOC(pPrior, nByte);
  17148. if( p==0 ){
  17149. testcase( sqlite3GlobalConfig.xLog!=0 );
  17150. sqlite3_log(SQLITE_NOMEM,
  17151. "failed memory resize %u to %u bytes",
  17152. SQLITE_MALLOCSIZE(pPrior), nByte);
  17153. }
  17154. return p;
  17155. #else
  17156. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17157. assert( pPrior!=0 && nByte>0 );
  17158. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  17159. p--;
  17160. p = SQLITE_REALLOC(p, nByte+8 );
  17161. if( p ){
  17162. p[0] = nByte;
  17163. p++;
  17164. }else{
  17165. testcase( sqlite3GlobalConfig.xLog!=0 );
  17166. sqlite3_log(SQLITE_NOMEM,
  17167. "failed memory resize %u to %u bytes",
  17168. sqlite3MemSize(pPrior), nByte);
  17169. }
  17170. return (void*)p;
  17171. #endif
  17172. }
  17173. /*
  17174. ** Round up a request size to the next valid allocation size.
  17175. */
  17176. static int sqlite3MemRoundup(int n){
  17177. return ROUND8(n);
  17178. }
  17179. /*
  17180. ** Initialize this module.
  17181. */
  17182. static int sqlite3MemInit(void *NotUsed){
  17183. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17184. int cpuCount;
  17185. size_t len;
  17186. if( _sqliteZone_ ){
  17187. return SQLITE_OK;
  17188. }
  17189. len = sizeof(cpuCount);
  17190. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  17191. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  17192. if( cpuCount>1 ){
  17193. /* defer MT decisions to system malloc */
  17194. _sqliteZone_ = malloc_default_zone();
  17195. }else{
  17196. /* only 1 core, use our own zone to contention over global locks,
  17197. ** e.g. we have our own dedicated locks */
  17198. bool success;
  17199. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  17200. malloc_set_zone_name(newzone, "Sqlite_Heap");
  17201. do{
  17202. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  17203. (void * volatile *)&_sqliteZone_);
  17204. }while(!_sqliteZone_);
  17205. if( !success ){
  17206. /* somebody registered a zone first */
  17207. malloc_destroy_zone(newzone);
  17208. }
  17209. }
  17210. #endif
  17211. UNUSED_PARAMETER(NotUsed);
  17212. return SQLITE_OK;
  17213. }
  17214. /*
  17215. ** Deinitialize this module.
  17216. */
  17217. static void sqlite3MemShutdown(void *NotUsed){
  17218. UNUSED_PARAMETER(NotUsed);
  17219. return;
  17220. }
  17221. /*
  17222. ** This routine is the only routine in this file with external linkage.
  17223. **
  17224. ** Populate the low-level memory allocation function pointers in
  17225. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17226. */
  17227. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17228. static const sqlite3_mem_methods defaultMethods = {
  17229. sqlite3MemMalloc,
  17230. sqlite3MemFree,
  17231. sqlite3MemRealloc,
  17232. sqlite3MemSize,
  17233. sqlite3MemRoundup,
  17234. sqlite3MemInit,
  17235. sqlite3MemShutdown,
  17236. 0
  17237. };
  17238. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17239. }
  17240. #endif /* SQLITE_SYSTEM_MALLOC */
  17241. /************** End of mem1.c ************************************************/
  17242. /************** Begin file mem2.c ********************************************/
  17243. /*
  17244. ** 2007 August 15
  17245. **
  17246. ** The author disclaims copyright to this source code. In place of
  17247. ** a legal notice, here is a blessing:
  17248. **
  17249. ** May you do good and not evil.
  17250. ** May you find forgiveness for yourself and forgive others.
  17251. ** May you share freely, never taking more than you give.
  17252. **
  17253. *************************************************************************
  17254. **
  17255. ** This file contains low-level memory allocation drivers for when
  17256. ** SQLite will use the standard C-library malloc/realloc/free interface
  17257. ** to obtain the memory it needs while adding lots of additional debugging
  17258. ** information to each allocation in order to help detect and fix memory
  17259. ** leaks and memory usage errors.
  17260. **
  17261. ** This file contains implementations of the low-level memory allocation
  17262. ** routines specified in the sqlite3_mem_methods object.
  17263. */
  17264. /* #include "sqliteInt.h" */
  17265. /*
  17266. ** This version of the memory allocator is used only if the
  17267. ** SQLITE_MEMDEBUG macro is defined
  17268. */
  17269. #ifdef SQLITE_MEMDEBUG
  17270. /*
  17271. ** The backtrace functionality is only available with GLIBC
  17272. */
  17273. #ifdef __GLIBC__
  17274. extern int backtrace(void**,int);
  17275. extern void backtrace_symbols_fd(void*const*,int,int);
  17276. #else
  17277. # define backtrace(A,B) 1
  17278. # define backtrace_symbols_fd(A,B,C)
  17279. #endif
  17280. /* #include <stdio.h> */
  17281. /*
  17282. ** Each memory allocation looks like this:
  17283. **
  17284. ** ------------------------------------------------------------------------
  17285. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  17286. ** ------------------------------------------------------------------------
  17287. **
  17288. ** The application code sees only a pointer to the allocation. We have
  17289. ** to back up from the allocation pointer to find the MemBlockHdr. The
  17290. ** MemBlockHdr tells us the size of the allocation and the number of
  17291. ** backtrace pointers. There is also a guard word at the end of the
  17292. ** MemBlockHdr.
  17293. */
  17294. struct MemBlockHdr {
  17295. i64 iSize; /* Size of this allocation */
  17296. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  17297. char nBacktrace; /* Number of backtraces on this alloc */
  17298. char nBacktraceSlots; /* Available backtrace slots */
  17299. u8 nTitle; /* Bytes of title; includes '\0' */
  17300. u8 eType; /* Allocation type code */
  17301. int iForeGuard; /* Guard word for sanity */
  17302. };
  17303. /*
  17304. ** Guard words
  17305. */
  17306. #define FOREGUARD 0x80F5E153
  17307. #define REARGUARD 0xE4676B53
  17308. /*
  17309. ** Number of malloc size increments to track.
  17310. */
  17311. #define NCSIZE 1000
  17312. /*
  17313. ** All of the static variables used by this module are collected
  17314. ** into a single structure named "mem". This is to keep the
  17315. ** static variables organized and to reduce namespace pollution
  17316. ** when this module is combined with other in the amalgamation.
  17317. */
  17318. static struct {
  17319. /*
  17320. ** Mutex to control access to the memory allocation subsystem.
  17321. */
  17322. sqlite3_mutex *mutex;
  17323. /*
  17324. ** Head and tail of a linked list of all outstanding allocations
  17325. */
  17326. struct MemBlockHdr *pFirst;
  17327. struct MemBlockHdr *pLast;
  17328. /*
  17329. ** The number of levels of backtrace to save in new allocations.
  17330. */
  17331. int nBacktrace;
  17332. void (*xBacktrace)(int, int, void **);
  17333. /*
  17334. ** Title text to insert in front of each block
  17335. */
  17336. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  17337. char zTitle[100]; /* The title text */
  17338. /*
  17339. ** sqlite3MallocDisallow() increments the following counter.
  17340. ** sqlite3MallocAllow() decrements it.
  17341. */
  17342. int disallow; /* Do not allow memory allocation */
  17343. /*
  17344. ** Gather statistics on the sizes of memory allocations.
  17345. ** nAlloc[i] is the number of allocation attempts of i*8
  17346. ** bytes. i==NCSIZE is the number of allocation attempts for
  17347. ** sizes more than NCSIZE*8 bytes.
  17348. */
  17349. int nAlloc[NCSIZE]; /* Total number of allocations */
  17350. int nCurrent[NCSIZE]; /* Current number of allocations */
  17351. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  17352. } mem;
  17353. /*
  17354. ** Adjust memory usage statistics
  17355. */
  17356. static void adjustStats(int iSize, int increment){
  17357. int i = ROUND8(iSize)/8;
  17358. if( i>NCSIZE-1 ){
  17359. i = NCSIZE - 1;
  17360. }
  17361. if( increment>0 ){
  17362. mem.nAlloc[i]++;
  17363. mem.nCurrent[i]++;
  17364. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  17365. mem.mxCurrent[i] = mem.nCurrent[i];
  17366. }
  17367. }else{
  17368. mem.nCurrent[i]--;
  17369. assert( mem.nCurrent[i]>=0 );
  17370. }
  17371. }
  17372. /*
  17373. ** Given an allocation, find the MemBlockHdr for that allocation.
  17374. **
  17375. ** This routine checks the guards at either end of the allocation and
  17376. ** if they are incorrect it asserts.
  17377. */
  17378. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  17379. struct MemBlockHdr *p;
  17380. int *pInt;
  17381. u8 *pU8;
  17382. int nReserve;
  17383. p = (struct MemBlockHdr*)pAllocation;
  17384. p--;
  17385. assert( p->iForeGuard==(int)FOREGUARD );
  17386. nReserve = ROUND8(p->iSize);
  17387. pInt = (int*)pAllocation;
  17388. pU8 = (u8*)pAllocation;
  17389. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  17390. /* This checks any of the "extra" bytes allocated due
  17391. ** to rounding up to an 8 byte boundary to ensure
  17392. ** they haven't been overwritten.
  17393. */
  17394. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  17395. return p;
  17396. }
  17397. /*
  17398. ** Return the number of bytes currently allocated at address p.
  17399. */
  17400. static int sqlite3MemSize(void *p){
  17401. struct MemBlockHdr *pHdr;
  17402. if( !p ){
  17403. return 0;
  17404. }
  17405. pHdr = sqlite3MemsysGetHeader(p);
  17406. return (int)pHdr->iSize;
  17407. }
  17408. /*
  17409. ** Initialize the memory allocation subsystem.
  17410. */
  17411. static int sqlite3MemInit(void *NotUsed){
  17412. UNUSED_PARAMETER(NotUsed);
  17413. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  17414. if( !sqlite3GlobalConfig.bMemstat ){
  17415. /* If memory status is enabled, then the malloc.c wrapper will already
  17416. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  17417. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17418. }
  17419. return SQLITE_OK;
  17420. }
  17421. /*
  17422. ** Deinitialize the memory allocation subsystem.
  17423. */
  17424. static void sqlite3MemShutdown(void *NotUsed){
  17425. UNUSED_PARAMETER(NotUsed);
  17426. mem.mutex = 0;
  17427. }
  17428. /*
  17429. ** Round up a request size to the next valid allocation size.
  17430. */
  17431. static int sqlite3MemRoundup(int n){
  17432. return ROUND8(n);
  17433. }
  17434. /*
  17435. ** Fill a buffer with pseudo-random bytes. This is used to preset
  17436. ** the content of a new memory allocation to unpredictable values and
  17437. ** to clear the content of a freed allocation to unpredictable values.
  17438. */
  17439. static void randomFill(char *pBuf, int nByte){
  17440. unsigned int x, y, r;
  17441. x = SQLITE_PTR_TO_INT(pBuf);
  17442. y = nByte | 1;
  17443. while( nByte >= 4 ){
  17444. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  17445. y = y*1103515245 + 12345;
  17446. r = x ^ y;
  17447. *(int*)pBuf = r;
  17448. pBuf += 4;
  17449. nByte -= 4;
  17450. }
  17451. while( nByte-- > 0 ){
  17452. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  17453. y = y*1103515245 + 12345;
  17454. r = x ^ y;
  17455. *(pBuf++) = r & 0xff;
  17456. }
  17457. }
  17458. /*
  17459. ** Allocate nByte bytes of memory.
  17460. */
  17461. static void *sqlite3MemMalloc(int nByte){
  17462. struct MemBlockHdr *pHdr;
  17463. void **pBt;
  17464. char *z;
  17465. int *pInt;
  17466. void *p = 0;
  17467. int totalSize;
  17468. int nReserve;
  17469. sqlite3_mutex_enter(mem.mutex);
  17470. assert( mem.disallow==0 );
  17471. nReserve = ROUND8(nByte);
  17472. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  17473. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  17474. p = malloc(totalSize);
  17475. if( p ){
  17476. z = p;
  17477. pBt = (void**)&z[mem.nTitle];
  17478. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  17479. pHdr->pNext = 0;
  17480. pHdr->pPrev = mem.pLast;
  17481. if( mem.pLast ){
  17482. mem.pLast->pNext = pHdr;
  17483. }else{
  17484. mem.pFirst = pHdr;
  17485. }
  17486. mem.pLast = pHdr;
  17487. pHdr->iForeGuard = FOREGUARD;
  17488. pHdr->eType = MEMTYPE_HEAP;
  17489. pHdr->nBacktraceSlots = mem.nBacktrace;
  17490. pHdr->nTitle = mem.nTitle;
  17491. if( mem.nBacktrace ){
  17492. void *aAddr[40];
  17493. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  17494. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  17495. assert(pBt[0]);
  17496. if( mem.xBacktrace ){
  17497. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  17498. }
  17499. }else{
  17500. pHdr->nBacktrace = 0;
  17501. }
  17502. if( mem.nTitle ){
  17503. memcpy(z, mem.zTitle, mem.nTitle);
  17504. }
  17505. pHdr->iSize = nByte;
  17506. adjustStats(nByte, +1);
  17507. pInt = (int*)&pHdr[1];
  17508. pInt[nReserve/sizeof(int)] = REARGUARD;
  17509. randomFill((char*)pInt, nByte);
  17510. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  17511. p = (void*)pInt;
  17512. }
  17513. sqlite3_mutex_leave(mem.mutex);
  17514. return p;
  17515. }
  17516. /*
  17517. ** Free memory.
  17518. */
  17519. static void sqlite3MemFree(void *pPrior){
  17520. struct MemBlockHdr *pHdr;
  17521. void **pBt;
  17522. char *z;
  17523. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  17524. || mem.mutex!=0 );
  17525. pHdr = sqlite3MemsysGetHeader(pPrior);
  17526. pBt = (void**)pHdr;
  17527. pBt -= pHdr->nBacktraceSlots;
  17528. sqlite3_mutex_enter(mem.mutex);
  17529. if( pHdr->pPrev ){
  17530. assert( pHdr->pPrev->pNext==pHdr );
  17531. pHdr->pPrev->pNext = pHdr->pNext;
  17532. }else{
  17533. assert( mem.pFirst==pHdr );
  17534. mem.pFirst = pHdr->pNext;
  17535. }
  17536. if( pHdr->pNext ){
  17537. assert( pHdr->pNext->pPrev==pHdr );
  17538. pHdr->pNext->pPrev = pHdr->pPrev;
  17539. }else{
  17540. assert( mem.pLast==pHdr );
  17541. mem.pLast = pHdr->pPrev;
  17542. }
  17543. z = (char*)pBt;
  17544. z -= pHdr->nTitle;
  17545. adjustStats((int)pHdr->iSize, -1);
  17546. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  17547. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  17548. free(z);
  17549. sqlite3_mutex_leave(mem.mutex);
  17550. }
  17551. /*
  17552. ** Change the size of an existing memory allocation.
  17553. **
  17554. ** For this debugging implementation, we *always* make a copy of the
  17555. ** allocation into a new place in memory. In this way, if the
  17556. ** higher level code is using pointer to the old allocation, it is
  17557. ** much more likely to break and we are much more liking to find
  17558. ** the error.
  17559. */
  17560. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  17561. struct MemBlockHdr *pOldHdr;
  17562. void *pNew;
  17563. assert( mem.disallow==0 );
  17564. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  17565. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  17566. pNew = sqlite3MemMalloc(nByte);
  17567. if( pNew ){
  17568. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  17569. if( nByte>pOldHdr->iSize ){
  17570. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  17571. }
  17572. sqlite3MemFree(pPrior);
  17573. }
  17574. return pNew;
  17575. }
  17576. /*
  17577. ** Populate the low-level memory allocation function pointers in
  17578. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17579. */
  17580. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17581. static const sqlite3_mem_methods defaultMethods = {
  17582. sqlite3MemMalloc,
  17583. sqlite3MemFree,
  17584. sqlite3MemRealloc,
  17585. sqlite3MemSize,
  17586. sqlite3MemRoundup,
  17587. sqlite3MemInit,
  17588. sqlite3MemShutdown,
  17589. 0
  17590. };
  17591. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17592. }
  17593. /*
  17594. ** Set the "type" of an allocation.
  17595. */
  17596. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  17597. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17598. struct MemBlockHdr *pHdr;
  17599. pHdr = sqlite3MemsysGetHeader(p);
  17600. assert( pHdr->iForeGuard==FOREGUARD );
  17601. pHdr->eType = eType;
  17602. }
  17603. }
  17604. /*
  17605. ** Return TRUE if the mask of type in eType matches the type of the
  17606. ** allocation p. Also return true if p==NULL.
  17607. **
  17608. ** This routine is designed for use within an assert() statement, to
  17609. ** verify the type of an allocation. For example:
  17610. **
  17611. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  17612. */
  17613. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  17614. int rc = 1;
  17615. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17616. struct MemBlockHdr *pHdr;
  17617. pHdr = sqlite3MemsysGetHeader(p);
  17618. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17619. if( (pHdr->eType&eType)==0 ){
  17620. rc = 0;
  17621. }
  17622. }
  17623. return rc;
  17624. }
  17625. /*
  17626. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  17627. ** allocation p. Also return true if p==NULL.
  17628. **
  17629. ** This routine is designed for use within an assert() statement, to
  17630. ** verify the type of an allocation. For example:
  17631. **
  17632. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17633. */
  17634. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  17635. int rc = 1;
  17636. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17637. struct MemBlockHdr *pHdr;
  17638. pHdr = sqlite3MemsysGetHeader(p);
  17639. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17640. if( (pHdr->eType&eType)!=0 ){
  17641. rc = 0;
  17642. }
  17643. }
  17644. return rc;
  17645. }
  17646. /*
  17647. ** Set the number of backtrace levels kept for each allocation.
  17648. ** A value of zero turns off backtracing. The number is always rounded
  17649. ** up to a multiple of 2.
  17650. */
  17651. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  17652. if( depth<0 ){ depth = 0; }
  17653. if( depth>20 ){ depth = 20; }
  17654. depth = (depth+1)&0xfe;
  17655. mem.nBacktrace = depth;
  17656. }
  17657. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  17658. mem.xBacktrace = xBacktrace;
  17659. }
  17660. /*
  17661. ** Set the title string for subsequent allocations.
  17662. */
  17663. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  17664. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  17665. sqlite3_mutex_enter(mem.mutex);
  17666. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  17667. memcpy(mem.zTitle, zTitle, n);
  17668. mem.zTitle[n] = 0;
  17669. mem.nTitle = ROUND8(n);
  17670. sqlite3_mutex_leave(mem.mutex);
  17671. }
  17672. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  17673. struct MemBlockHdr *pHdr;
  17674. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  17675. void **pBt = (void**)pHdr;
  17676. pBt -= pHdr->nBacktraceSlots;
  17677. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  17678. }
  17679. }
  17680. /*
  17681. ** Open the file indicated and write a log of all unfreed memory
  17682. ** allocations into that log.
  17683. */
  17684. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  17685. FILE *out;
  17686. struct MemBlockHdr *pHdr;
  17687. void **pBt;
  17688. int i;
  17689. out = fopen(zFilename, "w");
  17690. if( out==0 ){
  17691. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17692. zFilename);
  17693. return;
  17694. }
  17695. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  17696. char *z = (char*)pHdr;
  17697. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  17698. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  17699. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  17700. if( pHdr->nBacktrace ){
  17701. fflush(out);
  17702. pBt = (void**)pHdr;
  17703. pBt -= pHdr->nBacktraceSlots;
  17704. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  17705. fprintf(out, "\n");
  17706. }
  17707. }
  17708. fprintf(out, "COUNTS:\n");
  17709. for(i=0; i<NCSIZE-1; i++){
  17710. if( mem.nAlloc[i] ){
  17711. fprintf(out, " %5d: %10d %10d %10d\n",
  17712. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  17713. }
  17714. }
  17715. if( mem.nAlloc[NCSIZE-1] ){
  17716. fprintf(out, " %5d: %10d %10d %10d\n",
  17717. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  17718. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  17719. }
  17720. fclose(out);
  17721. }
  17722. /*
  17723. ** Return the number of times sqlite3MemMalloc() has been called.
  17724. */
  17725. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  17726. int i;
  17727. int nTotal = 0;
  17728. for(i=0; i<NCSIZE; i++){
  17729. nTotal += mem.nAlloc[i];
  17730. }
  17731. return nTotal;
  17732. }
  17733. #endif /* SQLITE_MEMDEBUG */
  17734. /************** End of mem2.c ************************************************/
  17735. /************** Begin file mem3.c ********************************************/
  17736. /*
  17737. ** 2007 October 14
  17738. **
  17739. ** The author disclaims copyright to this source code. In place of
  17740. ** a legal notice, here is a blessing:
  17741. **
  17742. ** May you do good and not evil.
  17743. ** May you find forgiveness for yourself and forgive others.
  17744. ** May you share freely, never taking more than you give.
  17745. **
  17746. *************************************************************************
  17747. ** This file contains the C functions that implement a memory
  17748. ** allocation subsystem for use by SQLite.
  17749. **
  17750. ** This version of the memory allocation subsystem omits all
  17751. ** use of malloc(). The SQLite user supplies a block of memory
  17752. ** before calling sqlite3_initialize() from which allocations
  17753. ** are made and returned by the xMalloc() and xRealloc()
  17754. ** implementations. Once sqlite3_initialize() has been called,
  17755. ** the amount of memory available to SQLite is fixed and cannot
  17756. ** be changed.
  17757. **
  17758. ** This version of the memory allocation subsystem is included
  17759. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  17760. */
  17761. /* #include "sqliteInt.h" */
  17762. /*
  17763. ** This version of the memory allocator is only built into the library
  17764. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  17765. ** mean that the library will use a memory-pool by default, just that
  17766. ** it is available. The mempool allocator is activated by calling
  17767. ** sqlite3_config().
  17768. */
  17769. #ifdef SQLITE_ENABLE_MEMSYS3
  17770. /*
  17771. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  17772. */
  17773. #define MX_SMALL 10
  17774. /*
  17775. ** Number of freelist hash slots
  17776. */
  17777. #define N_HASH 61
  17778. /*
  17779. ** A memory allocation (also called a "chunk") consists of two or
  17780. ** more blocks where each block is 8 bytes. The first 8 bytes are
  17781. ** a header that is not returned to the user.
  17782. **
  17783. ** A chunk is two or more blocks that is either checked out or
  17784. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  17785. ** size of the allocation in blocks if the allocation is free.
  17786. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  17787. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  17788. ** is true if the previous chunk is checked out and false if the
  17789. ** previous chunk is free. The u.hdr.prevSize field is the size of
  17790. ** the previous chunk in blocks if the previous chunk is on the
  17791. ** freelist. If the previous chunk is checked out, then
  17792. ** u.hdr.prevSize can be part of the data for that chunk and should
  17793. ** not be read or written.
  17794. **
  17795. ** We often identify a chunk by its index in mem3.aPool[]. When
  17796. ** this is done, the chunk index refers to the second block of
  17797. ** the chunk. In this way, the first chunk has an index of 1.
  17798. ** A chunk index of 0 means "no such chunk" and is the equivalent
  17799. ** of a NULL pointer.
  17800. **
  17801. ** The second block of free chunks is of the form u.list. The
  17802. ** two fields form a double-linked list of chunks of related sizes.
  17803. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  17804. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  17805. **
  17806. ** The second block of a chunk is user data if the chunk is checked
  17807. ** out. If a chunk is checked out, the user data may extend into
  17808. ** the u.hdr.prevSize value of the following chunk.
  17809. */
  17810. typedef struct Mem3Block Mem3Block;
  17811. struct Mem3Block {
  17812. union {
  17813. struct {
  17814. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  17815. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  17816. } hdr;
  17817. struct {
  17818. u32 next; /* Index in mem3.aPool[] of next free chunk */
  17819. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  17820. } list;
  17821. } u;
  17822. };
  17823. /*
  17824. ** All of the static variables used by this module are collected
  17825. ** into a single structure named "mem3". This is to keep the
  17826. ** static variables organized and to reduce namespace pollution
  17827. ** when this module is combined with other in the amalgamation.
  17828. */
  17829. static SQLITE_WSD struct Mem3Global {
  17830. /*
  17831. ** Memory available for allocation. nPool is the size of the array
  17832. ** (in Mem3Blocks) pointed to by aPool less 2.
  17833. */
  17834. u32 nPool;
  17835. Mem3Block *aPool;
  17836. /*
  17837. ** True if we are evaluating an out-of-memory callback.
  17838. */
  17839. int alarmBusy;
  17840. /*
  17841. ** Mutex to control access to the memory allocation subsystem.
  17842. */
  17843. sqlite3_mutex *mutex;
  17844. /*
  17845. ** The minimum amount of free space that we have seen.
  17846. */
  17847. u32 mnMaster;
  17848. /*
  17849. ** iMaster is the index of the master chunk. Most new allocations
  17850. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  17851. ** of the current master. iMaster is 0 if there is not master chunk.
  17852. ** The master chunk is not in either the aiHash[] or aiSmall[].
  17853. */
  17854. u32 iMaster;
  17855. u32 szMaster;
  17856. /*
  17857. ** Array of lists of free blocks according to the block size
  17858. ** for smaller chunks, or a hash on the block size for larger
  17859. ** chunks.
  17860. */
  17861. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  17862. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  17863. } mem3 = { 97535575 };
  17864. #define mem3 GLOBAL(struct Mem3Global, mem3)
  17865. /*
  17866. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  17867. ** on. *pRoot is the list that i is a member of.
  17868. */
  17869. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  17870. u32 next = mem3.aPool[i].u.list.next;
  17871. u32 prev = mem3.aPool[i].u.list.prev;
  17872. assert( sqlite3_mutex_held(mem3.mutex) );
  17873. if( prev==0 ){
  17874. *pRoot = next;
  17875. }else{
  17876. mem3.aPool[prev].u.list.next = next;
  17877. }
  17878. if( next ){
  17879. mem3.aPool[next].u.list.prev = prev;
  17880. }
  17881. mem3.aPool[i].u.list.next = 0;
  17882. mem3.aPool[i].u.list.prev = 0;
  17883. }
  17884. /*
  17885. ** Unlink the chunk at index i from
  17886. ** whatever list is currently a member of.
  17887. */
  17888. static void memsys3Unlink(u32 i){
  17889. u32 size, hash;
  17890. assert( sqlite3_mutex_held(mem3.mutex) );
  17891. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17892. assert( i>=1 );
  17893. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17894. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17895. assert( size>=2 );
  17896. if( size <= MX_SMALL ){
  17897. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  17898. }else{
  17899. hash = size % N_HASH;
  17900. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  17901. }
  17902. }
  17903. /*
  17904. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  17905. ** at *pRoot.
  17906. */
  17907. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  17908. assert( sqlite3_mutex_held(mem3.mutex) );
  17909. mem3.aPool[i].u.list.next = *pRoot;
  17910. mem3.aPool[i].u.list.prev = 0;
  17911. if( *pRoot ){
  17912. mem3.aPool[*pRoot].u.list.prev = i;
  17913. }
  17914. *pRoot = i;
  17915. }
  17916. /*
  17917. ** Link the chunk at index i into either the appropriate
  17918. ** small chunk list, or into the large chunk hash table.
  17919. */
  17920. static void memsys3Link(u32 i){
  17921. u32 size, hash;
  17922. assert( sqlite3_mutex_held(mem3.mutex) );
  17923. assert( i>=1 );
  17924. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17925. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17926. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17927. assert( size>=2 );
  17928. if( size <= MX_SMALL ){
  17929. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  17930. }else{
  17931. hash = size % N_HASH;
  17932. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  17933. }
  17934. }
  17935. /*
  17936. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17937. ** will already be held (obtained by code in malloc.c) if
  17938. ** sqlite3GlobalConfig.bMemStat is true.
  17939. */
  17940. static void memsys3Enter(void){
  17941. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  17942. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17943. }
  17944. sqlite3_mutex_enter(mem3.mutex);
  17945. }
  17946. static void memsys3Leave(void){
  17947. sqlite3_mutex_leave(mem3.mutex);
  17948. }
  17949. /*
  17950. ** Called when we are unable to satisfy an allocation of nBytes.
  17951. */
  17952. static void memsys3OutOfMemory(int nByte){
  17953. if( !mem3.alarmBusy ){
  17954. mem3.alarmBusy = 1;
  17955. assert( sqlite3_mutex_held(mem3.mutex) );
  17956. sqlite3_mutex_leave(mem3.mutex);
  17957. sqlite3_release_memory(nByte);
  17958. sqlite3_mutex_enter(mem3.mutex);
  17959. mem3.alarmBusy = 0;
  17960. }
  17961. }
  17962. /*
  17963. ** Chunk i is a free chunk that has been unlinked. Adjust its
  17964. ** size parameters for check-out and return a pointer to the
  17965. ** user portion of the chunk.
  17966. */
  17967. static void *memsys3Checkout(u32 i, u32 nBlock){
  17968. u32 x;
  17969. assert( sqlite3_mutex_held(mem3.mutex) );
  17970. assert( i>=1 );
  17971. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  17972. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  17973. x = mem3.aPool[i-1].u.hdr.size4x;
  17974. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  17975. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  17976. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  17977. return &mem3.aPool[i];
  17978. }
  17979. /*
  17980. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  17981. ** Return a pointer to the new allocation. Or, if the master chunk
  17982. ** is not large enough, return 0.
  17983. */
  17984. static void *memsys3FromMaster(u32 nBlock){
  17985. assert( sqlite3_mutex_held(mem3.mutex) );
  17986. assert( mem3.szMaster>=nBlock );
  17987. if( nBlock>=mem3.szMaster-1 ){
  17988. /* Use the entire master */
  17989. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  17990. mem3.iMaster = 0;
  17991. mem3.szMaster = 0;
  17992. mem3.mnMaster = 0;
  17993. return p;
  17994. }else{
  17995. /* Split the master block. Return the tail. */
  17996. u32 newi, x;
  17997. newi = mem3.iMaster + mem3.szMaster - nBlock;
  17998. assert( newi > mem3.iMaster+1 );
  17999. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  18000. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  18001. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  18002. mem3.szMaster -= nBlock;
  18003. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  18004. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18005. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18006. if( mem3.szMaster < mem3.mnMaster ){
  18007. mem3.mnMaster = mem3.szMaster;
  18008. }
  18009. return (void*)&mem3.aPool[newi];
  18010. }
  18011. }
  18012. /*
  18013. ** *pRoot is the head of a list of free chunks of the same size
  18014. ** or same size hash. In other words, *pRoot is an entry in either
  18015. ** mem3.aiSmall[] or mem3.aiHash[].
  18016. **
  18017. ** This routine examines all entries on the given list and tries
  18018. ** to coalesce each entries with adjacent free chunks.
  18019. **
  18020. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  18021. ** the current mem3.iMaster with the new larger chunk. In order for
  18022. ** this mem3.iMaster replacement to work, the master chunk must be
  18023. ** linked into the hash tables. That is not the normal state of
  18024. ** affairs, of course. The calling routine must link the master
  18025. ** chunk before invoking this routine, then must unlink the (possibly
  18026. ** changed) master chunk once this routine has finished.
  18027. */
  18028. static void memsys3Merge(u32 *pRoot){
  18029. u32 iNext, prev, size, i, x;
  18030. assert( sqlite3_mutex_held(mem3.mutex) );
  18031. for(i=*pRoot; i>0; i=iNext){
  18032. iNext = mem3.aPool[i].u.list.next;
  18033. size = mem3.aPool[i-1].u.hdr.size4x;
  18034. assert( (size&1)==0 );
  18035. if( (size&2)==0 ){
  18036. memsys3UnlinkFromList(i, pRoot);
  18037. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  18038. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  18039. if( prev==iNext ){
  18040. iNext = mem3.aPool[prev].u.list.next;
  18041. }
  18042. memsys3Unlink(prev);
  18043. size = i + size/4 - prev;
  18044. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  18045. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  18046. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  18047. memsys3Link(prev);
  18048. i = prev;
  18049. }else{
  18050. size /= 4;
  18051. }
  18052. if( size>mem3.szMaster ){
  18053. mem3.iMaster = i;
  18054. mem3.szMaster = size;
  18055. }
  18056. }
  18057. }
  18058. /*
  18059. ** Return a block of memory of at least nBytes in size.
  18060. ** Return NULL if unable.
  18061. **
  18062. ** This function assumes that the necessary mutexes, if any, are
  18063. ** already held by the caller. Hence "Unsafe".
  18064. */
  18065. static void *memsys3MallocUnsafe(int nByte){
  18066. u32 i;
  18067. u32 nBlock;
  18068. u32 toFree;
  18069. assert( sqlite3_mutex_held(mem3.mutex) );
  18070. assert( sizeof(Mem3Block)==8 );
  18071. if( nByte<=12 ){
  18072. nBlock = 2;
  18073. }else{
  18074. nBlock = (nByte + 11)/8;
  18075. }
  18076. assert( nBlock>=2 );
  18077. /* STEP 1:
  18078. ** Look for an entry of the correct size in either the small
  18079. ** chunk table or in the large chunk hash table. This is
  18080. ** successful most of the time (about 9 times out of 10).
  18081. */
  18082. if( nBlock <= MX_SMALL ){
  18083. i = mem3.aiSmall[nBlock-2];
  18084. if( i>0 ){
  18085. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  18086. return memsys3Checkout(i, nBlock);
  18087. }
  18088. }else{
  18089. int hash = nBlock % N_HASH;
  18090. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  18091. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  18092. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  18093. return memsys3Checkout(i, nBlock);
  18094. }
  18095. }
  18096. }
  18097. /* STEP 2:
  18098. ** Try to satisfy the allocation by carving a piece off of the end
  18099. ** of the master chunk. This step usually works if step 1 fails.
  18100. */
  18101. if( mem3.szMaster>=nBlock ){
  18102. return memsys3FromMaster(nBlock);
  18103. }
  18104. /* STEP 3:
  18105. ** Loop through the entire memory pool. Coalesce adjacent free
  18106. ** chunks. Recompute the master chunk as the largest free chunk.
  18107. ** Then try again to satisfy the allocation by carving a piece off
  18108. ** of the end of the master chunk. This step happens very
  18109. ** rarely (we hope!)
  18110. */
  18111. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  18112. memsys3OutOfMemory(toFree);
  18113. if( mem3.iMaster ){
  18114. memsys3Link(mem3.iMaster);
  18115. mem3.iMaster = 0;
  18116. mem3.szMaster = 0;
  18117. }
  18118. for(i=0; i<N_HASH; i++){
  18119. memsys3Merge(&mem3.aiHash[i]);
  18120. }
  18121. for(i=0; i<MX_SMALL-1; i++){
  18122. memsys3Merge(&mem3.aiSmall[i]);
  18123. }
  18124. if( mem3.szMaster ){
  18125. memsys3Unlink(mem3.iMaster);
  18126. if( mem3.szMaster>=nBlock ){
  18127. return memsys3FromMaster(nBlock);
  18128. }
  18129. }
  18130. }
  18131. /* If none of the above worked, then we fail. */
  18132. return 0;
  18133. }
  18134. /*
  18135. ** Free an outstanding memory allocation.
  18136. **
  18137. ** This function assumes that the necessary mutexes, if any, are
  18138. ** already held by the caller. Hence "Unsafe".
  18139. */
  18140. static void memsys3FreeUnsafe(void *pOld){
  18141. Mem3Block *p = (Mem3Block*)pOld;
  18142. int i;
  18143. u32 size, x;
  18144. assert( sqlite3_mutex_held(mem3.mutex) );
  18145. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  18146. i = p - mem3.aPool;
  18147. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  18148. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18149. assert( i+size<=mem3.nPool+1 );
  18150. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  18151. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  18152. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  18153. memsys3Link(i);
  18154. /* Try to expand the master using the newly freed chunk */
  18155. if( mem3.iMaster ){
  18156. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  18157. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  18158. mem3.iMaster -= size;
  18159. mem3.szMaster += size;
  18160. memsys3Unlink(mem3.iMaster);
  18161. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18162. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18163. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18164. }
  18165. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18166. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  18167. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  18168. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  18169. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18170. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18171. }
  18172. }
  18173. }
  18174. /*
  18175. ** Return the size of an outstanding allocation, in bytes. The
  18176. ** size returned omits the 8-byte header overhead. This only
  18177. ** works for chunks that are currently checked out.
  18178. */
  18179. static int memsys3Size(void *p){
  18180. Mem3Block *pBlock;
  18181. if( p==0 ) return 0;
  18182. pBlock = (Mem3Block*)p;
  18183. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  18184. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  18185. }
  18186. /*
  18187. ** Round up a request size to the next valid allocation size.
  18188. */
  18189. static int memsys3Roundup(int n){
  18190. if( n<=12 ){
  18191. return 12;
  18192. }else{
  18193. return ((n+11)&~7) - 4;
  18194. }
  18195. }
  18196. /*
  18197. ** Allocate nBytes of memory.
  18198. */
  18199. static void *memsys3Malloc(int nBytes){
  18200. sqlite3_int64 *p;
  18201. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  18202. memsys3Enter();
  18203. p = memsys3MallocUnsafe(nBytes);
  18204. memsys3Leave();
  18205. return (void*)p;
  18206. }
  18207. /*
  18208. ** Free memory.
  18209. */
  18210. static void memsys3Free(void *pPrior){
  18211. assert( pPrior );
  18212. memsys3Enter();
  18213. memsys3FreeUnsafe(pPrior);
  18214. memsys3Leave();
  18215. }
  18216. /*
  18217. ** Change the size of an existing memory allocation
  18218. */
  18219. static void *memsys3Realloc(void *pPrior, int nBytes){
  18220. int nOld;
  18221. void *p;
  18222. if( pPrior==0 ){
  18223. return sqlite3_malloc(nBytes);
  18224. }
  18225. if( nBytes<=0 ){
  18226. sqlite3_free(pPrior);
  18227. return 0;
  18228. }
  18229. nOld = memsys3Size(pPrior);
  18230. if( nBytes<=nOld && nBytes>=nOld-128 ){
  18231. return pPrior;
  18232. }
  18233. memsys3Enter();
  18234. p = memsys3MallocUnsafe(nBytes);
  18235. if( p ){
  18236. if( nOld<nBytes ){
  18237. memcpy(p, pPrior, nOld);
  18238. }else{
  18239. memcpy(p, pPrior, nBytes);
  18240. }
  18241. memsys3FreeUnsafe(pPrior);
  18242. }
  18243. memsys3Leave();
  18244. return p;
  18245. }
  18246. /*
  18247. ** Initialize this module.
  18248. */
  18249. static int memsys3Init(void *NotUsed){
  18250. UNUSED_PARAMETER(NotUsed);
  18251. if( !sqlite3GlobalConfig.pHeap ){
  18252. return SQLITE_ERROR;
  18253. }
  18254. /* Store a pointer to the memory block in global structure mem3. */
  18255. assert( sizeof(Mem3Block)==8 );
  18256. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  18257. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  18258. /* Initialize the master block. */
  18259. mem3.szMaster = mem3.nPool;
  18260. mem3.mnMaster = mem3.szMaster;
  18261. mem3.iMaster = 1;
  18262. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  18263. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  18264. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  18265. return SQLITE_OK;
  18266. }
  18267. /*
  18268. ** Deinitialize this module.
  18269. */
  18270. static void memsys3Shutdown(void *NotUsed){
  18271. UNUSED_PARAMETER(NotUsed);
  18272. mem3.mutex = 0;
  18273. return;
  18274. }
  18275. /*
  18276. ** Open the file indicated and write a log of all unfreed memory
  18277. ** allocations into that log.
  18278. */
  18279. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  18280. #ifdef SQLITE_DEBUG
  18281. FILE *out;
  18282. u32 i, j;
  18283. u32 size;
  18284. if( zFilename==0 || zFilename[0]==0 ){
  18285. out = stdout;
  18286. }else{
  18287. out = fopen(zFilename, "w");
  18288. if( out==0 ){
  18289. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18290. zFilename);
  18291. return;
  18292. }
  18293. }
  18294. memsys3Enter();
  18295. fprintf(out, "CHUNKS:\n");
  18296. for(i=1; i<=mem3.nPool; i+=size/4){
  18297. size = mem3.aPool[i-1].u.hdr.size4x;
  18298. if( size/4<=1 ){
  18299. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  18300. assert( 0 );
  18301. break;
  18302. }
  18303. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  18304. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  18305. assert( 0 );
  18306. break;
  18307. }
  18308. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  18309. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  18310. assert( 0 );
  18311. break;
  18312. }
  18313. if( size&1 ){
  18314. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  18315. }else{
  18316. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  18317. i==mem3.iMaster ? " **master**" : "");
  18318. }
  18319. }
  18320. for(i=0; i<MX_SMALL-1; i++){
  18321. if( mem3.aiSmall[i]==0 ) continue;
  18322. fprintf(out, "small(%2d):", i);
  18323. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  18324. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18325. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18326. }
  18327. fprintf(out, "\n");
  18328. }
  18329. for(i=0; i<N_HASH; i++){
  18330. if( mem3.aiHash[i]==0 ) continue;
  18331. fprintf(out, "hash(%2d):", i);
  18332. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  18333. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18334. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18335. }
  18336. fprintf(out, "\n");
  18337. }
  18338. fprintf(out, "master=%d\n", mem3.iMaster);
  18339. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  18340. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  18341. sqlite3_mutex_leave(mem3.mutex);
  18342. if( out==stdout ){
  18343. fflush(stdout);
  18344. }else{
  18345. fclose(out);
  18346. }
  18347. #else
  18348. UNUSED_PARAMETER(zFilename);
  18349. #endif
  18350. }
  18351. /*
  18352. ** This routine is the only routine in this file with external
  18353. ** linkage.
  18354. **
  18355. ** Populate the low-level memory allocation function pointers in
  18356. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  18357. ** arguments specify the block of memory to manage.
  18358. **
  18359. ** This routine is only called by sqlite3_config(), and therefore
  18360. ** is not required to be threadsafe (it is not).
  18361. */
  18362. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  18363. static const sqlite3_mem_methods mempoolMethods = {
  18364. memsys3Malloc,
  18365. memsys3Free,
  18366. memsys3Realloc,
  18367. memsys3Size,
  18368. memsys3Roundup,
  18369. memsys3Init,
  18370. memsys3Shutdown,
  18371. 0
  18372. };
  18373. return &mempoolMethods;
  18374. }
  18375. #endif /* SQLITE_ENABLE_MEMSYS3 */
  18376. /************** End of mem3.c ************************************************/
  18377. /************** Begin file mem5.c ********************************************/
  18378. /*
  18379. ** 2007 October 14
  18380. **
  18381. ** The author disclaims copyright to this source code. In place of
  18382. ** a legal notice, here is a blessing:
  18383. **
  18384. ** May you do good and not evil.
  18385. ** May you find forgiveness for yourself and forgive others.
  18386. ** May you share freely, never taking more than you give.
  18387. **
  18388. *************************************************************************
  18389. ** This file contains the C functions that implement a memory
  18390. ** allocation subsystem for use by SQLite.
  18391. **
  18392. ** This version of the memory allocation subsystem omits all
  18393. ** use of malloc(). The application gives SQLite a block of memory
  18394. ** before calling sqlite3_initialize() from which allocations
  18395. ** are made and returned by the xMalloc() and xRealloc()
  18396. ** implementations. Once sqlite3_initialize() has been called,
  18397. ** the amount of memory available to SQLite is fixed and cannot
  18398. ** be changed.
  18399. **
  18400. ** This version of the memory allocation subsystem is included
  18401. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  18402. **
  18403. ** This memory allocator uses the following algorithm:
  18404. **
  18405. ** 1. All memory allocations sizes are rounded up to a power of 2.
  18406. **
  18407. ** 2. If two adjacent free blocks are the halves of a larger block,
  18408. ** then the two blocks are coalesced into the single larger block.
  18409. **
  18410. ** 3. New memory is allocated from the first available free block.
  18411. **
  18412. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  18413. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  18414. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  18415. **
  18416. ** Let n be the size of the largest allocation divided by the minimum
  18417. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  18418. ** be the maximum amount of memory ever outstanding at one time. Let
  18419. ** N be the total amount of memory available for allocation. Robson
  18420. ** proved that this memory allocator will never breakdown due to
  18421. ** fragmentation as long as the following constraint holds:
  18422. **
  18423. ** N >= M*(1 + log2(n)/2) - n + 1
  18424. **
  18425. ** The sqlite3_status() logic tracks the maximum values of n and M so
  18426. ** that an application can, at any time, verify this constraint.
  18427. */
  18428. /* #include "sqliteInt.h" */
  18429. /*
  18430. ** This version of the memory allocator is used only when
  18431. ** SQLITE_ENABLE_MEMSYS5 is defined.
  18432. */
  18433. #ifdef SQLITE_ENABLE_MEMSYS5
  18434. /*
  18435. ** A minimum allocation is an instance of the following structure.
  18436. ** Larger allocations are an array of these structures where the
  18437. ** size of the array is a power of 2.
  18438. **
  18439. ** The size of this object must be a power of two. That fact is
  18440. ** verified in memsys5Init().
  18441. */
  18442. typedef struct Mem5Link Mem5Link;
  18443. struct Mem5Link {
  18444. int next; /* Index of next free chunk */
  18445. int prev; /* Index of previous free chunk */
  18446. };
  18447. /*
  18448. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  18449. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  18450. ** it is not actually possible to reach this limit.
  18451. */
  18452. #define LOGMAX 30
  18453. /*
  18454. ** Masks used for mem5.aCtrl[] elements.
  18455. */
  18456. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  18457. #define CTRL_FREE 0x20 /* True if not checked out */
  18458. /*
  18459. ** All of the static variables used by this module are collected
  18460. ** into a single structure named "mem5". This is to keep the
  18461. ** static variables organized and to reduce namespace pollution
  18462. ** when this module is combined with other in the amalgamation.
  18463. */
  18464. static SQLITE_WSD struct Mem5Global {
  18465. /*
  18466. ** Memory available for allocation
  18467. */
  18468. int szAtom; /* Smallest possible allocation in bytes */
  18469. int nBlock; /* Number of szAtom sized blocks in zPool */
  18470. u8 *zPool; /* Memory available to be allocated */
  18471. /*
  18472. ** Mutex to control access to the memory allocation subsystem.
  18473. */
  18474. sqlite3_mutex *mutex;
  18475. /*
  18476. ** Performance statistics
  18477. */
  18478. u64 nAlloc; /* Total number of calls to malloc */
  18479. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  18480. u64 totalExcess; /* Total internal fragmentation */
  18481. u32 currentOut; /* Current checkout, including internal fragmentation */
  18482. u32 currentCount; /* Current number of distinct checkouts */
  18483. u32 maxOut; /* Maximum instantaneous currentOut */
  18484. u32 maxCount; /* Maximum instantaneous currentCount */
  18485. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  18486. /*
  18487. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  18488. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  18489. ** and so forth.
  18490. */
  18491. int aiFreelist[LOGMAX+1];
  18492. /*
  18493. ** Space for tracking which blocks are checked out and the size
  18494. ** of each block. One byte per block.
  18495. */
  18496. u8 *aCtrl;
  18497. } mem5;
  18498. /*
  18499. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  18500. */
  18501. #define mem5 GLOBAL(struct Mem5Global, mem5)
  18502. /*
  18503. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  18504. ** structures, return a pointer to the idx-th such link.
  18505. */
  18506. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  18507. /*
  18508. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  18509. ** on. It should be found on mem5.aiFreelist[iLogsize].
  18510. */
  18511. static void memsys5Unlink(int i, int iLogsize){
  18512. int next, prev;
  18513. assert( i>=0 && i<mem5.nBlock );
  18514. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  18515. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  18516. next = MEM5LINK(i)->next;
  18517. prev = MEM5LINK(i)->prev;
  18518. if( prev<0 ){
  18519. mem5.aiFreelist[iLogsize] = next;
  18520. }else{
  18521. MEM5LINK(prev)->next = next;
  18522. }
  18523. if( next>=0 ){
  18524. MEM5LINK(next)->prev = prev;
  18525. }
  18526. }
  18527. /*
  18528. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  18529. ** free list.
  18530. */
  18531. static void memsys5Link(int i, int iLogsize){
  18532. int x;
  18533. assert( sqlite3_mutex_held(mem5.mutex) );
  18534. assert( i>=0 && i<mem5.nBlock );
  18535. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  18536. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  18537. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  18538. MEM5LINK(i)->prev = -1;
  18539. if( x>=0 ){
  18540. assert( x<mem5.nBlock );
  18541. MEM5LINK(x)->prev = i;
  18542. }
  18543. mem5.aiFreelist[iLogsize] = i;
  18544. }
  18545. /*
  18546. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  18547. ** will already be held (obtained by code in malloc.c) if
  18548. ** sqlite3GlobalConfig.bMemStat is true.
  18549. */
  18550. static void memsys5Enter(void){
  18551. sqlite3_mutex_enter(mem5.mutex);
  18552. }
  18553. static void memsys5Leave(void){
  18554. sqlite3_mutex_leave(mem5.mutex);
  18555. }
  18556. /*
  18557. ** Return the size of an outstanding allocation, in bytes. The
  18558. ** size returned omits the 8-byte header overhead. This only
  18559. ** works for chunks that are currently checked out.
  18560. */
  18561. static int memsys5Size(void *p){
  18562. int iSize = 0;
  18563. if( p ){
  18564. int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  18565. assert( i>=0 && i<mem5.nBlock );
  18566. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  18567. }
  18568. return iSize;
  18569. }
  18570. /*
  18571. ** Return a block of memory of at least nBytes in size.
  18572. ** Return NULL if unable. Return NULL if nBytes==0.
  18573. **
  18574. ** The caller guarantees that nByte is positive.
  18575. **
  18576. ** The caller has obtained a mutex prior to invoking this
  18577. ** routine so there is never any chance that two or more
  18578. ** threads can be in this routine at the same time.
  18579. */
  18580. static void *memsys5MallocUnsafe(int nByte){
  18581. int i; /* Index of a mem5.aPool[] slot */
  18582. int iBin; /* Index into mem5.aiFreelist[] */
  18583. int iFullSz; /* Size of allocation rounded up to power of 2 */
  18584. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  18585. /* nByte must be a positive */
  18586. assert( nByte>0 );
  18587. /* Keep track of the maximum allocation request. Even unfulfilled
  18588. ** requests are counted */
  18589. if( (u32)nByte>mem5.maxRequest ){
  18590. mem5.maxRequest = nByte;
  18591. }
  18592. /* Abort if the requested allocation size is larger than the largest
  18593. ** power of two that we can represent using 32-bit signed integers.
  18594. */
  18595. if( nByte > 0x40000000 ){
  18596. return 0;
  18597. }
  18598. /* Round nByte up to the next valid power of two */
  18599. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  18600. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  18601. ** block. If not, then split a block of the next larger power of
  18602. ** two in order to create a new free block of size iLogsize.
  18603. */
  18604. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  18605. if( iBin>LOGMAX ){
  18606. testcase( sqlite3GlobalConfig.xLog!=0 );
  18607. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  18608. return 0;
  18609. }
  18610. i = mem5.aiFreelist[iBin];
  18611. memsys5Unlink(i, iBin);
  18612. while( iBin>iLogsize ){
  18613. int newSize;
  18614. iBin--;
  18615. newSize = 1 << iBin;
  18616. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  18617. memsys5Link(i+newSize, iBin);
  18618. }
  18619. mem5.aCtrl[i] = iLogsize;
  18620. /* Update allocator performance statistics. */
  18621. mem5.nAlloc++;
  18622. mem5.totalAlloc += iFullSz;
  18623. mem5.totalExcess += iFullSz - nByte;
  18624. mem5.currentCount++;
  18625. mem5.currentOut += iFullSz;
  18626. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  18627. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  18628. #ifdef SQLITE_DEBUG
  18629. /* Make sure the allocated memory does not assume that it is set to zero
  18630. ** or retains a value from a previous allocation */
  18631. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  18632. #endif
  18633. /* Return a pointer to the allocated memory. */
  18634. return (void*)&mem5.zPool[i*mem5.szAtom];
  18635. }
  18636. /*
  18637. ** Free an outstanding memory allocation.
  18638. */
  18639. static void memsys5FreeUnsafe(void *pOld){
  18640. u32 size, iLogsize;
  18641. int iBlock;
  18642. /* Set iBlock to the index of the block pointed to by pOld in
  18643. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  18644. */
  18645. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  18646. /* Check that the pointer pOld points to a valid, non-free block. */
  18647. assert( iBlock>=0 && iBlock<mem5.nBlock );
  18648. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  18649. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  18650. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  18651. size = 1<<iLogsize;
  18652. assert( iBlock+size-1<(u32)mem5.nBlock );
  18653. mem5.aCtrl[iBlock] |= CTRL_FREE;
  18654. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  18655. assert( mem5.currentCount>0 );
  18656. assert( mem5.currentOut>=(size*mem5.szAtom) );
  18657. mem5.currentCount--;
  18658. mem5.currentOut -= size*mem5.szAtom;
  18659. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  18660. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  18661. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  18662. while( ALWAYS(iLogsize<LOGMAX) ){
  18663. int iBuddy;
  18664. if( (iBlock>>iLogsize) & 1 ){
  18665. iBuddy = iBlock - size;
  18666. }else{
  18667. iBuddy = iBlock + size;
  18668. }
  18669. assert( iBuddy>=0 );
  18670. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  18671. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  18672. memsys5Unlink(iBuddy, iLogsize);
  18673. iLogsize++;
  18674. if( iBuddy<iBlock ){
  18675. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  18676. mem5.aCtrl[iBlock] = 0;
  18677. iBlock = iBuddy;
  18678. }else{
  18679. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  18680. mem5.aCtrl[iBuddy] = 0;
  18681. }
  18682. size *= 2;
  18683. }
  18684. #ifdef SQLITE_DEBUG
  18685. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  18686. ** not used after being freed */
  18687. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  18688. #endif
  18689. memsys5Link(iBlock, iLogsize);
  18690. }
  18691. /*
  18692. ** Allocate nBytes of memory.
  18693. */
  18694. static void *memsys5Malloc(int nBytes){
  18695. sqlite3_int64 *p = 0;
  18696. if( nBytes>0 ){
  18697. memsys5Enter();
  18698. p = memsys5MallocUnsafe(nBytes);
  18699. memsys5Leave();
  18700. }
  18701. return (void*)p;
  18702. }
  18703. /*
  18704. ** Free memory.
  18705. **
  18706. ** The outer layer memory allocator prevents this routine from
  18707. ** being called with pPrior==0.
  18708. */
  18709. static void memsys5Free(void *pPrior){
  18710. assert( pPrior!=0 );
  18711. memsys5Enter();
  18712. memsys5FreeUnsafe(pPrior);
  18713. memsys5Leave();
  18714. }
  18715. /*
  18716. ** Change the size of an existing memory allocation.
  18717. **
  18718. ** The outer layer memory allocator prevents this routine from
  18719. ** being called with pPrior==0.
  18720. **
  18721. ** nBytes is always a value obtained from a prior call to
  18722. ** memsys5Round(). Hence nBytes is always a non-negative power
  18723. ** of two. If nBytes==0 that means that an oversize allocation
  18724. ** (an allocation larger than 0x40000000) was requested and this
  18725. ** routine should return 0 without freeing pPrior.
  18726. */
  18727. static void *memsys5Realloc(void *pPrior, int nBytes){
  18728. int nOld;
  18729. void *p;
  18730. assert( pPrior!=0 );
  18731. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  18732. assert( nBytes>=0 );
  18733. if( nBytes==0 ){
  18734. return 0;
  18735. }
  18736. nOld = memsys5Size(pPrior);
  18737. if( nBytes<=nOld ){
  18738. return pPrior;
  18739. }
  18740. memsys5Enter();
  18741. p = memsys5MallocUnsafe(nBytes);
  18742. if( p ){
  18743. memcpy(p, pPrior, nOld);
  18744. memsys5FreeUnsafe(pPrior);
  18745. }
  18746. memsys5Leave();
  18747. return p;
  18748. }
  18749. /*
  18750. ** Round up a request size to the next valid allocation size. If
  18751. ** the allocation is too large to be handled by this allocation system,
  18752. ** return 0.
  18753. **
  18754. ** All allocations must be a power of two and must be expressed by a
  18755. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  18756. ** or 1073741824 bytes.
  18757. */
  18758. static int memsys5Roundup(int n){
  18759. int iFullSz;
  18760. if( n > 0x40000000 ) return 0;
  18761. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  18762. return iFullSz;
  18763. }
  18764. /*
  18765. ** Return the ceiling of the logarithm base 2 of iValue.
  18766. **
  18767. ** Examples: memsys5Log(1) -> 0
  18768. ** memsys5Log(2) -> 1
  18769. ** memsys5Log(4) -> 2
  18770. ** memsys5Log(5) -> 3
  18771. ** memsys5Log(8) -> 3
  18772. ** memsys5Log(9) -> 4
  18773. */
  18774. static int memsys5Log(int iValue){
  18775. int iLog;
  18776. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  18777. return iLog;
  18778. }
  18779. /*
  18780. ** Initialize the memory allocator.
  18781. **
  18782. ** This routine is not threadsafe. The caller must be holding a mutex
  18783. ** to prevent multiple threads from entering at the same time.
  18784. */
  18785. static int memsys5Init(void *NotUsed){
  18786. int ii; /* Loop counter */
  18787. int nByte; /* Number of bytes of memory available to this allocator */
  18788. u8 *zByte; /* Memory usable by this allocator */
  18789. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  18790. int iOffset; /* An offset into mem5.aCtrl[] */
  18791. UNUSED_PARAMETER(NotUsed);
  18792. /* For the purposes of this routine, disable the mutex */
  18793. mem5.mutex = 0;
  18794. /* The size of a Mem5Link object must be a power of two. Verify that
  18795. ** this is case.
  18796. */
  18797. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  18798. nByte = sqlite3GlobalConfig.nHeap;
  18799. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  18800. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  18801. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  18802. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  18803. mem5.szAtom = (1<<nMinLog);
  18804. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  18805. mem5.szAtom = mem5.szAtom << 1;
  18806. }
  18807. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  18808. mem5.zPool = zByte;
  18809. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  18810. for(ii=0; ii<=LOGMAX; ii++){
  18811. mem5.aiFreelist[ii] = -1;
  18812. }
  18813. iOffset = 0;
  18814. for(ii=LOGMAX; ii>=0; ii--){
  18815. int nAlloc = (1<<ii);
  18816. if( (iOffset+nAlloc)<=mem5.nBlock ){
  18817. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  18818. memsys5Link(iOffset, ii);
  18819. iOffset += nAlloc;
  18820. }
  18821. assert((iOffset+nAlloc)>mem5.nBlock);
  18822. }
  18823. /* If a mutex is required for normal operation, allocate one */
  18824. if( sqlite3GlobalConfig.bMemstat==0 ){
  18825. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18826. }
  18827. return SQLITE_OK;
  18828. }
  18829. /*
  18830. ** Deinitialize this module.
  18831. */
  18832. static void memsys5Shutdown(void *NotUsed){
  18833. UNUSED_PARAMETER(NotUsed);
  18834. mem5.mutex = 0;
  18835. return;
  18836. }
  18837. #ifdef SQLITE_TEST
  18838. /*
  18839. ** Open the file indicated and write a log of all unfreed memory
  18840. ** allocations into that log.
  18841. */
  18842. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  18843. FILE *out;
  18844. int i, j, n;
  18845. int nMinLog;
  18846. if( zFilename==0 || zFilename[0]==0 ){
  18847. out = stdout;
  18848. }else{
  18849. out = fopen(zFilename, "w");
  18850. if( out==0 ){
  18851. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18852. zFilename);
  18853. return;
  18854. }
  18855. }
  18856. memsys5Enter();
  18857. nMinLog = memsys5Log(mem5.szAtom);
  18858. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  18859. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  18860. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  18861. }
  18862. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  18863. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  18864. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  18865. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  18866. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  18867. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  18868. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  18869. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  18870. memsys5Leave();
  18871. if( out==stdout ){
  18872. fflush(stdout);
  18873. }else{
  18874. fclose(out);
  18875. }
  18876. }
  18877. #endif
  18878. /*
  18879. ** This routine is the only routine in this file with external
  18880. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  18881. ** struct populated with the memsys5 methods.
  18882. */
  18883. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  18884. static const sqlite3_mem_methods memsys5Methods = {
  18885. memsys5Malloc,
  18886. memsys5Free,
  18887. memsys5Realloc,
  18888. memsys5Size,
  18889. memsys5Roundup,
  18890. memsys5Init,
  18891. memsys5Shutdown,
  18892. 0
  18893. };
  18894. return &memsys5Methods;
  18895. }
  18896. #endif /* SQLITE_ENABLE_MEMSYS5 */
  18897. /************** End of mem5.c ************************************************/
  18898. /************** Begin file mutex.c *******************************************/
  18899. /*
  18900. ** 2007 August 14
  18901. **
  18902. ** The author disclaims copyright to this source code. In place of
  18903. ** a legal notice, here is a blessing:
  18904. **
  18905. ** May you do good and not evil.
  18906. ** May you find forgiveness for yourself and forgive others.
  18907. ** May you share freely, never taking more than you give.
  18908. **
  18909. *************************************************************************
  18910. ** This file contains the C functions that implement mutexes.
  18911. **
  18912. ** This file contains code that is common across all mutex implementations.
  18913. */
  18914. /* #include "sqliteInt.h" */
  18915. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  18916. /*
  18917. ** For debugging purposes, record when the mutex subsystem is initialized
  18918. ** and uninitialized so that we can assert() if there is an attempt to
  18919. ** allocate a mutex while the system is uninitialized.
  18920. */
  18921. static SQLITE_WSD int mutexIsInit = 0;
  18922. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  18923. #ifndef SQLITE_MUTEX_OMIT
  18924. /*
  18925. ** Initialize the mutex system.
  18926. */
  18927. SQLITE_PRIVATE int sqlite3MutexInit(void){
  18928. int rc = SQLITE_OK;
  18929. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  18930. /* If the xMutexAlloc method has not been set, then the user did not
  18931. ** install a mutex implementation via sqlite3_config() prior to
  18932. ** sqlite3_initialize() being called. This block copies pointers to
  18933. ** the default implementation into the sqlite3GlobalConfig structure.
  18934. */
  18935. sqlite3_mutex_methods const *pFrom;
  18936. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  18937. if( sqlite3GlobalConfig.bCoreMutex ){
  18938. pFrom = sqlite3DefaultMutex();
  18939. }else{
  18940. pFrom = sqlite3NoopMutex();
  18941. }
  18942. pTo->xMutexInit = pFrom->xMutexInit;
  18943. pTo->xMutexEnd = pFrom->xMutexEnd;
  18944. pTo->xMutexFree = pFrom->xMutexFree;
  18945. pTo->xMutexEnter = pFrom->xMutexEnter;
  18946. pTo->xMutexTry = pFrom->xMutexTry;
  18947. pTo->xMutexLeave = pFrom->xMutexLeave;
  18948. pTo->xMutexHeld = pFrom->xMutexHeld;
  18949. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  18950. sqlite3MemoryBarrier();
  18951. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  18952. }
  18953. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  18954. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  18955. #ifdef SQLITE_DEBUG
  18956. GLOBAL(int, mutexIsInit) = 1;
  18957. #endif
  18958. return rc;
  18959. }
  18960. /*
  18961. ** Shutdown the mutex system. This call frees resources allocated by
  18962. ** sqlite3MutexInit().
  18963. */
  18964. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  18965. int rc = SQLITE_OK;
  18966. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  18967. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  18968. }
  18969. #ifdef SQLITE_DEBUG
  18970. GLOBAL(int, mutexIsInit) = 0;
  18971. #endif
  18972. return rc;
  18973. }
  18974. /*
  18975. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  18976. */
  18977. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
  18978. #ifndef SQLITE_OMIT_AUTOINIT
  18979. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  18980. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  18981. #endif
  18982. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  18983. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18984. }
  18985. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  18986. if( !sqlite3GlobalConfig.bCoreMutex ){
  18987. return 0;
  18988. }
  18989. assert( GLOBAL(int, mutexIsInit) );
  18990. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  18991. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18992. }
  18993. /*
  18994. ** Free a dynamic mutex.
  18995. */
  18996. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
  18997. if( p ){
  18998. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  18999. sqlite3GlobalConfig.mutex.xMutexFree(p);
  19000. }
  19001. }
  19002. /*
  19003. ** Obtain the mutex p. If some other thread already has the mutex, block
  19004. ** until it can be obtained.
  19005. */
  19006. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
  19007. if( p ){
  19008. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  19009. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  19010. }
  19011. }
  19012. /*
  19013. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  19014. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  19015. */
  19016. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
  19017. int rc = SQLITE_OK;
  19018. if( p ){
  19019. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  19020. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  19021. }
  19022. return rc;
  19023. }
  19024. /*
  19025. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  19026. ** entered by the same thread. The behavior is undefined if the mutex
  19027. ** is not currently entered. If a NULL pointer is passed as an argument
  19028. ** this function is a no-op.
  19029. */
  19030. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
  19031. if( p ){
  19032. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  19033. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  19034. }
  19035. }
  19036. #ifndef NDEBUG
  19037. /*
  19038. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19039. ** intended for use inside assert() statements.
  19040. */
  19041. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
  19042. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  19043. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  19044. }
  19045. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
  19046. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  19047. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  19048. }
  19049. #endif
  19050. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19051. /************** End of mutex.c ***********************************************/
  19052. /************** Begin file mutex_noop.c **************************************/
  19053. /*
  19054. ** 2008 October 07
  19055. **
  19056. ** The author disclaims copyright to this source code. In place of
  19057. ** a legal notice, here is a blessing:
  19058. **
  19059. ** May you do good and not evil.
  19060. ** May you find forgiveness for yourself and forgive others.
  19061. ** May you share freely, never taking more than you give.
  19062. **
  19063. *************************************************************************
  19064. ** This file contains the C functions that implement mutexes.
  19065. **
  19066. ** This implementation in this file does not provide any mutual
  19067. ** exclusion and is thus suitable for use only in applications
  19068. ** that use SQLite in a single thread. The routines defined
  19069. ** here are place-holders. Applications can substitute working
  19070. ** mutex routines at start-time using the
  19071. **
  19072. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  19073. **
  19074. ** interface.
  19075. **
  19076. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  19077. ** that does error checking on mutexes to make sure they are being
  19078. ** called correctly.
  19079. */
  19080. /* #include "sqliteInt.h" */
  19081. #ifndef SQLITE_MUTEX_OMIT
  19082. #ifndef SQLITE_DEBUG
  19083. /*
  19084. ** Stub routines for all mutex methods.
  19085. **
  19086. ** This routines provide no mutual exclusion or error checking.
  19087. */
  19088. static int noopMutexInit(void){ return SQLITE_OK; }
  19089. static int noopMutexEnd(void){ return SQLITE_OK; }
  19090. static sqlite3_mutex *noopMutexAlloc(int id){
  19091. UNUSED_PARAMETER(id);
  19092. return (sqlite3_mutex*)8;
  19093. }
  19094. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19095. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19096. static int noopMutexTry(sqlite3_mutex *p){
  19097. UNUSED_PARAMETER(p);
  19098. return SQLITE_OK;
  19099. }
  19100. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19101. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19102. static const sqlite3_mutex_methods sMutex = {
  19103. noopMutexInit,
  19104. noopMutexEnd,
  19105. noopMutexAlloc,
  19106. noopMutexFree,
  19107. noopMutexEnter,
  19108. noopMutexTry,
  19109. noopMutexLeave,
  19110. 0,
  19111. 0,
  19112. };
  19113. return &sMutex;
  19114. }
  19115. #endif /* !SQLITE_DEBUG */
  19116. #ifdef SQLITE_DEBUG
  19117. /*
  19118. ** In this implementation, error checking is provided for testing
  19119. ** and debugging purposes. The mutexes still do not provide any
  19120. ** mutual exclusion.
  19121. */
  19122. /*
  19123. ** The mutex object
  19124. */
  19125. typedef struct sqlite3_debug_mutex {
  19126. int id; /* The mutex type */
  19127. int cnt; /* Number of entries without a matching leave */
  19128. } sqlite3_debug_mutex;
  19129. /*
  19130. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19131. ** intended for use inside assert() statements.
  19132. */
  19133. static int debugMutexHeld(sqlite3_mutex *pX){
  19134. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19135. return p==0 || p->cnt>0;
  19136. }
  19137. static int debugMutexNotheld(sqlite3_mutex *pX){
  19138. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19139. return p==0 || p->cnt==0;
  19140. }
  19141. /*
  19142. ** Initialize and deinitialize the mutex subsystem.
  19143. */
  19144. static int debugMutexInit(void){ return SQLITE_OK; }
  19145. static int debugMutexEnd(void){ return SQLITE_OK; }
  19146. /*
  19147. ** The sqlite3_mutex_alloc() routine allocates a new
  19148. ** mutex and returns a pointer to it. If it returns NULL
  19149. ** that means that a mutex could not be allocated.
  19150. */
  19151. static sqlite3_mutex *debugMutexAlloc(int id){
  19152. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  19153. sqlite3_debug_mutex *pNew = 0;
  19154. switch( id ){
  19155. case SQLITE_MUTEX_FAST:
  19156. case SQLITE_MUTEX_RECURSIVE: {
  19157. pNew = sqlite3Malloc(sizeof(*pNew));
  19158. if( pNew ){
  19159. pNew->id = id;
  19160. pNew->cnt = 0;
  19161. }
  19162. break;
  19163. }
  19164. default: {
  19165. #ifdef SQLITE_ENABLE_API_ARMOR
  19166. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  19167. (void)SQLITE_MISUSE_BKPT;
  19168. return 0;
  19169. }
  19170. #endif
  19171. pNew = &aStatic[id-2];
  19172. pNew->id = id;
  19173. break;
  19174. }
  19175. }
  19176. return (sqlite3_mutex*)pNew;
  19177. }
  19178. /*
  19179. ** This routine deallocates a previously allocated mutex.
  19180. */
  19181. static void debugMutexFree(sqlite3_mutex *pX){
  19182. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19183. assert( p->cnt==0 );
  19184. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  19185. sqlite3_free(p);
  19186. }else{
  19187. #ifdef SQLITE_ENABLE_API_ARMOR
  19188. (void)SQLITE_MISUSE_BKPT;
  19189. #endif
  19190. }
  19191. }
  19192. /*
  19193. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19194. ** to enter a mutex. If another thread is already within the mutex,
  19195. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19196. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19197. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19198. ** be entered multiple times by the same thread. In such cases the,
  19199. ** mutex must be exited an equal number of times before another thread
  19200. ** can enter. If the same thread tries to enter any other kind of mutex
  19201. ** more than once, the behavior is undefined.
  19202. */
  19203. static void debugMutexEnter(sqlite3_mutex *pX){
  19204. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19205. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19206. p->cnt++;
  19207. }
  19208. static int debugMutexTry(sqlite3_mutex *pX){
  19209. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19210. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19211. p->cnt++;
  19212. return SQLITE_OK;
  19213. }
  19214. /*
  19215. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19216. ** previously entered by the same thread. The behavior
  19217. ** is undefined if the mutex is not currently entered or
  19218. ** is not currently allocated. SQLite will never do either.
  19219. */
  19220. static void debugMutexLeave(sqlite3_mutex *pX){
  19221. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19222. assert( debugMutexHeld(pX) );
  19223. p->cnt--;
  19224. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19225. }
  19226. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19227. static const sqlite3_mutex_methods sMutex = {
  19228. debugMutexInit,
  19229. debugMutexEnd,
  19230. debugMutexAlloc,
  19231. debugMutexFree,
  19232. debugMutexEnter,
  19233. debugMutexTry,
  19234. debugMutexLeave,
  19235. debugMutexHeld,
  19236. debugMutexNotheld
  19237. };
  19238. return &sMutex;
  19239. }
  19240. #endif /* SQLITE_DEBUG */
  19241. /*
  19242. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  19243. ** is used regardless of the run-time threadsafety setting.
  19244. */
  19245. #ifdef SQLITE_MUTEX_NOOP
  19246. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19247. return sqlite3NoopMutex();
  19248. }
  19249. #endif /* defined(SQLITE_MUTEX_NOOP) */
  19250. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19251. /************** End of mutex_noop.c ******************************************/
  19252. /************** Begin file mutex_unix.c **************************************/
  19253. /*
  19254. ** 2007 August 28
  19255. **
  19256. ** The author disclaims copyright to this source code. In place of
  19257. ** a legal notice, here is a blessing:
  19258. **
  19259. ** May you do good and not evil.
  19260. ** May you find forgiveness for yourself and forgive others.
  19261. ** May you share freely, never taking more than you give.
  19262. **
  19263. *************************************************************************
  19264. ** This file contains the C functions that implement mutexes for pthreads
  19265. */
  19266. /* #include "sqliteInt.h" */
  19267. /*
  19268. ** The code in this file is only used if we are compiling threadsafe
  19269. ** under unix with pthreads.
  19270. **
  19271. ** Note that this implementation requires a version of pthreads that
  19272. ** supports recursive mutexes.
  19273. */
  19274. #ifdef SQLITE_MUTEX_PTHREADS
  19275. #include <pthread.h>
  19276. /*
  19277. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  19278. ** are necessary under two condidtions: (1) Debug builds and (2) using
  19279. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  19280. */
  19281. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  19282. # define SQLITE_MUTEX_NREF 1
  19283. #else
  19284. # define SQLITE_MUTEX_NREF 0
  19285. #endif
  19286. /*
  19287. ** Each recursive mutex is an instance of the following structure.
  19288. */
  19289. struct sqlite3_mutex {
  19290. pthread_mutex_t mutex; /* Mutex controlling the lock */
  19291. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  19292. int id; /* Mutex type */
  19293. #endif
  19294. #if SQLITE_MUTEX_NREF
  19295. volatile int nRef; /* Number of entrances */
  19296. volatile pthread_t owner; /* Thread that is within this mutex */
  19297. int trace; /* True to trace changes */
  19298. #endif
  19299. };
  19300. #if SQLITE_MUTEX_NREF
  19301. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  19302. #else
  19303. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  19304. #endif
  19305. /*
  19306. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19307. ** intended for use only inside assert() statements. On some platforms,
  19308. ** there might be race conditions that can cause these routines to
  19309. ** deliver incorrect results. In particular, if pthread_equal() is
  19310. ** not an atomic operation, then these routines might delivery
  19311. ** incorrect results. On most platforms, pthread_equal() is a
  19312. ** comparison of two integers and is therefore atomic. But we are
  19313. ** told that HPUX is not such a platform. If so, then these routines
  19314. ** will not always work correctly on HPUX.
  19315. **
  19316. ** On those platforms where pthread_equal() is not atomic, SQLite
  19317. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  19318. ** make sure no assert() statements are evaluated and hence these
  19319. ** routines are never called.
  19320. */
  19321. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  19322. static int pthreadMutexHeld(sqlite3_mutex *p){
  19323. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  19324. }
  19325. static int pthreadMutexNotheld(sqlite3_mutex *p){
  19326. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  19327. }
  19328. #endif
  19329. /*
  19330. ** Try to provide a memory barrier operation, needed for initialization
  19331. ** and also for the implementation of xShmBarrier in the VFS in cases
  19332. ** where SQLite is compiled without mutexes.
  19333. */
  19334. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  19335. #if defined(SQLITE_MEMORY_BARRIER)
  19336. SQLITE_MEMORY_BARRIER;
  19337. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  19338. __sync_synchronize();
  19339. #endif
  19340. }
  19341. /*
  19342. ** Initialize and deinitialize the mutex subsystem.
  19343. */
  19344. static int pthreadMutexInit(void){ return SQLITE_OK; }
  19345. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  19346. /*
  19347. ** The sqlite3_mutex_alloc() routine allocates a new
  19348. ** mutex and returns a pointer to it. If it returns NULL
  19349. ** that means that a mutex could not be allocated. SQLite
  19350. ** will unwind its stack and return an error. The argument
  19351. ** to sqlite3_mutex_alloc() is one of these integer constants:
  19352. **
  19353. ** <ul>
  19354. ** <li> SQLITE_MUTEX_FAST
  19355. ** <li> SQLITE_MUTEX_RECURSIVE
  19356. ** <li> SQLITE_MUTEX_STATIC_MASTER
  19357. ** <li> SQLITE_MUTEX_STATIC_MEM
  19358. ** <li> SQLITE_MUTEX_STATIC_OPEN
  19359. ** <li> SQLITE_MUTEX_STATIC_PRNG
  19360. ** <li> SQLITE_MUTEX_STATIC_LRU
  19361. ** <li> SQLITE_MUTEX_STATIC_PMEM
  19362. ** <li> SQLITE_MUTEX_STATIC_APP1
  19363. ** <li> SQLITE_MUTEX_STATIC_APP2
  19364. ** <li> SQLITE_MUTEX_STATIC_APP3
  19365. ** <li> SQLITE_MUTEX_STATIC_VFS1
  19366. ** <li> SQLITE_MUTEX_STATIC_VFS2
  19367. ** <li> SQLITE_MUTEX_STATIC_VFS3
  19368. ** </ul>
  19369. **
  19370. ** The first two constants cause sqlite3_mutex_alloc() to create
  19371. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  19372. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  19373. ** The mutex implementation does not need to make a distinction
  19374. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  19375. ** not want to. But SQLite will only request a recursive mutex in
  19376. ** cases where it really needs one. If a faster non-recursive mutex
  19377. ** implementation is available on the host platform, the mutex subsystem
  19378. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  19379. **
  19380. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  19381. ** a pointer to a static preexisting mutex. Six static mutexes are
  19382. ** used by the current version of SQLite. Future versions of SQLite
  19383. ** may add additional static mutexes. Static mutexes are for internal
  19384. ** use by SQLite only. Applications that use SQLite mutexes should
  19385. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  19386. ** SQLITE_MUTEX_RECURSIVE.
  19387. **
  19388. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  19389. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  19390. ** returns a different mutex on every call. But for the static
  19391. ** mutex types, the same mutex is returned on every call that has
  19392. ** the same type number.
  19393. */
  19394. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  19395. static sqlite3_mutex staticMutexes[] = {
  19396. SQLITE3_MUTEX_INITIALIZER,
  19397. SQLITE3_MUTEX_INITIALIZER,
  19398. SQLITE3_MUTEX_INITIALIZER,
  19399. SQLITE3_MUTEX_INITIALIZER,
  19400. SQLITE3_MUTEX_INITIALIZER,
  19401. SQLITE3_MUTEX_INITIALIZER,
  19402. SQLITE3_MUTEX_INITIALIZER,
  19403. SQLITE3_MUTEX_INITIALIZER,
  19404. SQLITE3_MUTEX_INITIALIZER,
  19405. SQLITE3_MUTEX_INITIALIZER,
  19406. SQLITE3_MUTEX_INITIALIZER,
  19407. SQLITE3_MUTEX_INITIALIZER
  19408. };
  19409. sqlite3_mutex *p;
  19410. switch( iType ){
  19411. case SQLITE_MUTEX_RECURSIVE: {
  19412. p = sqlite3MallocZero( sizeof(*p) );
  19413. if( p ){
  19414. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19415. /* If recursive mutexes are not available, we will have to
  19416. ** build our own. See below. */
  19417. pthread_mutex_init(&p->mutex, 0);
  19418. #else
  19419. /* Use a recursive mutex if it is available */
  19420. pthread_mutexattr_t recursiveAttr;
  19421. pthread_mutexattr_init(&recursiveAttr);
  19422. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  19423. pthread_mutex_init(&p->mutex, &recursiveAttr);
  19424. pthread_mutexattr_destroy(&recursiveAttr);
  19425. #endif
  19426. }
  19427. break;
  19428. }
  19429. case SQLITE_MUTEX_FAST: {
  19430. p = sqlite3MallocZero( sizeof(*p) );
  19431. if( p ){
  19432. pthread_mutex_init(&p->mutex, 0);
  19433. }
  19434. break;
  19435. }
  19436. default: {
  19437. #ifdef SQLITE_ENABLE_API_ARMOR
  19438. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  19439. (void)SQLITE_MISUSE_BKPT;
  19440. return 0;
  19441. }
  19442. #endif
  19443. p = &staticMutexes[iType-2];
  19444. break;
  19445. }
  19446. }
  19447. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  19448. if( p ) p->id = iType;
  19449. #endif
  19450. return p;
  19451. }
  19452. /*
  19453. ** This routine deallocates a previously
  19454. ** allocated mutex. SQLite is careful to deallocate every
  19455. ** mutex that it allocates.
  19456. */
  19457. static void pthreadMutexFree(sqlite3_mutex *p){
  19458. assert( p->nRef==0 );
  19459. #if SQLITE_ENABLE_API_ARMOR
  19460. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  19461. #endif
  19462. {
  19463. pthread_mutex_destroy(&p->mutex);
  19464. sqlite3_free(p);
  19465. }
  19466. #ifdef SQLITE_ENABLE_API_ARMOR
  19467. else{
  19468. (void)SQLITE_MISUSE_BKPT;
  19469. }
  19470. #endif
  19471. }
  19472. /*
  19473. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19474. ** to enter a mutex. If another thread is already within the mutex,
  19475. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19476. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19477. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19478. ** be entered multiple times by the same thread. In such cases the,
  19479. ** mutex must be exited an equal number of times before another thread
  19480. ** can enter. If the same thread tries to enter any other kind of mutex
  19481. ** more than once, the behavior is undefined.
  19482. */
  19483. static void pthreadMutexEnter(sqlite3_mutex *p){
  19484. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  19485. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19486. /* If recursive mutexes are not available, then we have to grow
  19487. ** our own. This implementation assumes that pthread_equal()
  19488. ** is atomic - that it cannot be deceived into thinking self
  19489. ** and p->owner are equal if p->owner changes between two values
  19490. ** that are not equal to self while the comparison is taking place.
  19491. ** This implementation also assumes a coherent cache - that
  19492. ** separate processes cannot read different values from the same
  19493. ** address at the same time. If either of these two conditions
  19494. ** are not met, then the mutexes will fail and problems will result.
  19495. */
  19496. {
  19497. pthread_t self = pthread_self();
  19498. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  19499. p->nRef++;
  19500. }else{
  19501. pthread_mutex_lock(&p->mutex);
  19502. assert( p->nRef==0 );
  19503. p->owner = self;
  19504. p->nRef = 1;
  19505. }
  19506. }
  19507. #else
  19508. /* Use the built-in recursive mutexes if they are available.
  19509. */
  19510. pthread_mutex_lock(&p->mutex);
  19511. #if SQLITE_MUTEX_NREF
  19512. assert( p->nRef>0 || p->owner==0 );
  19513. p->owner = pthread_self();
  19514. p->nRef++;
  19515. #endif
  19516. #endif
  19517. #ifdef SQLITE_DEBUG
  19518. if( p->trace ){
  19519. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19520. }
  19521. #endif
  19522. }
  19523. static int pthreadMutexTry(sqlite3_mutex *p){
  19524. int rc;
  19525. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  19526. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19527. /* If recursive mutexes are not available, then we have to grow
  19528. ** our own. This implementation assumes that pthread_equal()
  19529. ** is atomic - that it cannot be deceived into thinking self
  19530. ** and p->owner are equal if p->owner changes between two values
  19531. ** that are not equal to self while the comparison is taking place.
  19532. ** This implementation also assumes a coherent cache - that
  19533. ** separate processes cannot read different values from the same
  19534. ** address at the same time. If either of these two conditions
  19535. ** are not met, then the mutexes will fail and problems will result.
  19536. */
  19537. {
  19538. pthread_t self = pthread_self();
  19539. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  19540. p->nRef++;
  19541. rc = SQLITE_OK;
  19542. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  19543. assert( p->nRef==0 );
  19544. p->owner = self;
  19545. p->nRef = 1;
  19546. rc = SQLITE_OK;
  19547. }else{
  19548. rc = SQLITE_BUSY;
  19549. }
  19550. }
  19551. #else
  19552. /* Use the built-in recursive mutexes if they are available.
  19553. */
  19554. if( pthread_mutex_trylock(&p->mutex)==0 ){
  19555. #if SQLITE_MUTEX_NREF
  19556. p->owner = pthread_self();
  19557. p->nRef++;
  19558. #endif
  19559. rc = SQLITE_OK;
  19560. }else{
  19561. rc = SQLITE_BUSY;
  19562. }
  19563. #endif
  19564. #ifdef SQLITE_DEBUG
  19565. if( rc==SQLITE_OK && p->trace ){
  19566. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19567. }
  19568. #endif
  19569. return rc;
  19570. }
  19571. /*
  19572. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19573. ** previously entered by the same thread. The behavior
  19574. ** is undefined if the mutex is not currently entered or
  19575. ** is not currently allocated. SQLite will never do either.
  19576. */
  19577. static void pthreadMutexLeave(sqlite3_mutex *p){
  19578. assert( pthreadMutexHeld(p) );
  19579. #if SQLITE_MUTEX_NREF
  19580. p->nRef--;
  19581. if( p->nRef==0 ) p->owner = 0;
  19582. #endif
  19583. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  19584. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19585. if( p->nRef==0 ){
  19586. pthread_mutex_unlock(&p->mutex);
  19587. }
  19588. #else
  19589. pthread_mutex_unlock(&p->mutex);
  19590. #endif
  19591. #ifdef SQLITE_DEBUG
  19592. if( p->trace ){
  19593. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19594. }
  19595. #endif
  19596. }
  19597. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19598. static const sqlite3_mutex_methods sMutex = {
  19599. pthreadMutexInit,
  19600. pthreadMutexEnd,
  19601. pthreadMutexAlloc,
  19602. pthreadMutexFree,
  19603. pthreadMutexEnter,
  19604. pthreadMutexTry,
  19605. pthreadMutexLeave,
  19606. #ifdef SQLITE_DEBUG
  19607. pthreadMutexHeld,
  19608. pthreadMutexNotheld
  19609. #else
  19610. 0,
  19611. 0
  19612. #endif
  19613. };
  19614. return &sMutex;
  19615. }
  19616. #endif /* SQLITE_MUTEX_PTHREADS */
  19617. /************** End of mutex_unix.c ******************************************/
  19618. /************** Begin file mutex_w32.c ***************************************/
  19619. /*
  19620. ** 2007 August 14
  19621. **
  19622. ** The author disclaims copyright to this source code. In place of
  19623. ** a legal notice, here is a blessing:
  19624. **
  19625. ** May you do good and not evil.
  19626. ** May you find forgiveness for yourself and forgive others.
  19627. ** May you share freely, never taking more than you give.
  19628. **
  19629. *************************************************************************
  19630. ** This file contains the C functions that implement mutexes for Win32.
  19631. */
  19632. /* #include "sqliteInt.h" */
  19633. #if SQLITE_OS_WIN
  19634. /*
  19635. ** Include code that is common to all os_*.c files
  19636. */
  19637. /************** Include os_common.h in the middle of mutex_w32.c *************/
  19638. /************** Begin file os_common.h ***************************************/
  19639. /*
  19640. ** 2004 May 22
  19641. **
  19642. ** The author disclaims copyright to this source code. In place of
  19643. ** a legal notice, here is a blessing:
  19644. **
  19645. ** May you do good and not evil.
  19646. ** May you find forgiveness for yourself and forgive others.
  19647. ** May you share freely, never taking more than you give.
  19648. **
  19649. ******************************************************************************
  19650. **
  19651. ** This file contains macros and a little bit of code that is common to
  19652. ** all of the platform-specific files (os_*.c) and is #included into those
  19653. ** files.
  19654. **
  19655. ** This file should be #included by the os_*.c files only. It is not a
  19656. ** general purpose header file.
  19657. */
  19658. #ifndef _OS_COMMON_H_
  19659. #define _OS_COMMON_H_
  19660. /*
  19661. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  19662. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  19663. ** switch. The following code should catch this problem at compile-time.
  19664. */
  19665. #ifdef MEMORY_DEBUG
  19666. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  19667. #endif
  19668. /*
  19669. ** Macros for performance tracing. Normally turned off. Only works
  19670. ** on i486 hardware.
  19671. */
  19672. #ifdef SQLITE_PERFORMANCE_TRACE
  19673. /*
  19674. ** hwtime.h contains inline assembler code for implementing
  19675. ** high-performance timing routines.
  19676. */
  19677. /************** Include hwtime.h in the middle of os_common.h ****************/
  19678. /************** Begin file hwtime.h ******************************************/
  19679. /*
  19680. ** 2008 May 27
  19681. **
  19682. ** The author disclaims copyright to this source code. In place of
  19683. ** a legal notice, here is a blessing:
  19684. **
  19685. ** May you do good and not evil.
  19686. ** May you find forgiveness for yourself and forgive others.
  19687. ** May you share freely, never taking more than you give.
  19688. **
  19689. ******************************************************************************
  19690. **
  19691. ** This file contains inline asm code for retrieving "high-performance"
  19692. ** counters for x86 class CPUs.
  19693. */
  19694. #ifndef _HWTIME_H_
  19695. #define _HWTIME_H_
  19696. /*
  19697. ** The following routine only works on pentium-class (or newer) processors.
  19698. ** It uses the RDTSC opcode to read the cycle count value out of the
  19699. ** processor and returns that value. This can be used for high-res
  19700. ** profiling.
  19701. */
  19702. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  19703. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  19704. #if defined(__GNUC__)
  19705. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19706. unsigned int lo, hi;
  19707. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  19708. return (sqlite_uint64)hi << 32 | lo;
  19709. }
  19710. #elif defined(_MSC_VER)
  19711. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  19712. __asm {
  19713. rdtsc
  19714. ret ; return value at EDX:EAX
  19715. }
  19716. }
  19717. #endif
  19718. #elif (defined(__GNUC__) && defined(__x86_64__))
  19719. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19720. unsigned long val;
  19721. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  19722. return val;
  19723. }
  19724. #elif (defined(__GNUC__) && defined(__ppc__))
  19725. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19726. unsigned long long retval;
  19727. unsigned long junk;
  19728. __asm__ __volatile__ ("\n\
  19729. 1: mftbu %1\n\
  19730. mftb %L0\n\
  19731. mftbu %0\n\
  19732. cmpw %0,%1\n\
  19733. bne 1b"
  19734. : "=r" (retval), "=r" (junk));
  19735. return retval;
  19736. }
  19737. #else
  19738. #error Need implementation of sqlite3Hwtime() for your platform.
  19739. /*
  19740. ** To compile without implementing sqlite3Hwtime() for your platform,
  19741. ** you can remove the above #error and use the following
  19742. ** stub function. You will lose timing support for many
  19743. ** of the debugging and testing utilities, but it should at
  19744. ** least compile and run.
  19745. */
  19746. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  19747. #endif
  19748. #endif /* !defined(_HWTIME_H_) */
  19749. /************** End of hwtime.h **********************************************/
  19750. /************** Continuing where we left off in os_common.h ******************/
  19751. static sqlite_uint64 g_start;
  19752. static sqlite_uint64 g_elapsed;
  19753. #define TIMER_START g_start=sqlite3Hwtime()
  19754. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  19755. #define TIMER_ELAPSED g_elapsed
  19756. #else
  19757. #define TIMER_START
  19758. #define TIMER_END
  19759. #define TIMER_ELAPSED ((sqlite_uint64)0)
  19760. #endif
  19761. /*
  19762. ** If we compile with the SQLITE_TEST macro set, then the following block
  19763. ** of code will give us the ability to simulate a disk I/O error. This
  19764. ** is used for testing the I/O recovery logic.
  19765. */
  19766. #ifdef SQLITE_TEST
  19767. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19768. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19769. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19770. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19771. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19772. SQLITE_API int sqlite3_diskfull_pending = 0;
  19773. SQLITE_API int sqlite3_diskfull = 0;
  19774. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  19775. #define SimulateIOError(CODE) \
  19776. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  19777. || sqlite3_io_error_pending-- == 1 ) \
  19778. { local_ioerr(); CODE; }
  19779. static void local_ioerr(){
  19780. IOTRACE(("IOERR\n"));
  19781. sqlite3_io_error_hit++;
  19782. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  19783. }
  19784. #define SimulateDiskfullError(CODE) \
  19785. if( sqlite3_diskfull_pending ){ \
  19786. if( sqlite3_diskfull_pending == 1 ){ \
  19787. local_ioerr(); \
  19788. sqlite3_diskfull = 1; \
  19789. sqlite3_io_error_hit = 1; \
  19790. CODE; \
  19791. }else{ \
  19792. sqlite3_diskfull_pending--; \
  19793. } \
  19794. }
  19795. #else
  19796. #define SimulateIOErrorBenign(X)
  19797. #define SimulateIOError(A)
  19798. #define SimulateDiskfullError(A)
  19799. #endif
  19800. /*
  19801. ** When testing, keep a count of the number of open files.
  19802. */
  19803. #ifdef SQLITE_TEST
  19804. SQLITE_API int sqlite3_open_file_count = 0;
  19805. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  19806. #else
  19807. #define OpenCounter(X)
  19808. #endif
  19809. #endif /* !defined(_OS_COMMON_H_) */
  19810. /************** End of os_common.h *******************************************/
  19811. /************** Continuing where we left off in mutex_w32.c ******************/
  19812. /*
  19813. ** Include the header file for the Windows VFS.
  19814. */
  19815. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  19816. /************** Begin file os_win.h ******************************************/
  19817. /*
  19818. ** 2013 November 25
  19819. **
  19820. ** The author disclaims copyright to this source code. In place of
  19821. ** a legal notice, here is a blessing:
  19822. **
  19823. ** May you do good and not evil.
  19824. ** May you find forgiveness for yourself and forgive others.
  19825. ** May you share freely, never taking more than you give.
  19826. **
  19827. ******************************************************************************
  19828. **
  19829. ** This file contains code that is specific to Windows.
  19830. */
  19831. #ifndef _OS_WIN_H_
  19832. #define _OS_WIN_H_
  19833. /*
  19834. ** Include the primary Windows SDK header file.
  19835. */
  19836. #include "windows.h"
  19837. #ifdef __CYGWIN__
  19838. # include <sys/cygwin.h>
  19839. # include <errno.h> /* amalgamator: dontcache */
  19840. #endif
  19841. /*
  19842. ** Determine if we are dealing with Windows NT.
  19843. **
  19844. ** We ought to be able to determine if we are compiling for Windows 9x or
  19845. ** Windows NT using the _WIN32_WINNT macro as follows:
  19846. **
  19847. ** #if defined(_WIN32_WINNT)
  19848. ** # define SQLITE_OS_WINNT 1
  19849. ** #else
  19850. ** # define SQLITE_OS_WINNT 0
  19851. ** #endif
  19852. **
  19853. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  19854. ** it ought to, so the above test does not work. We'll just assume that
  19855. ** everything is Windows NT unless the programmer explicitly says otherwise
  19856. ** by setting SQLITE_OS_WINNT to 0.
  19857. */
  19858. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  19859. # define SQLITE_OS_WINNT 1
  19860. #endif
  19861. /*
  19862. ** Determine if we are dealing with Windows CE - which has a much reduced
  19863. ** API.
  19864. */
  19865. #if defined(_WIN32_WCE)
  19866. # define SQLITE_OS_WINCE 1
  19867. #else
  19868. # define SQLITE_OS_WINCE 0
  19869. #endif
  19870. /*
  19871. ** Determine if we are dealing with WinRT, which provides only a subset of
  19872. ** the full Win32 API.
  19873. */
  19874. #if !defined(SQLITE_OS_WINRT)
  19875. # define SQLITE_OS_WINRT 0
  19876. #endif
  19877. /*
  19878. ** For WinCE, some API function parameters do not appear to be declared as
  19879. ** volatile.
  19880. */
  19881. #if SQLITE_OS_WINCE
  19882. # define SQLITE_WIN32_VOLATILE
  19883. #else
  19884. # define SQLITE_WIN32_VOLATILE volatile
  19885. #endif
  19886. /*
  19887. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  19888. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  19889. */
  19890. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  19891. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  19892. # define SQLITE_OS_WIN_THREADS 1
  19893. #else
  19894. # define SQLITE_OS_WIN_THREADS 0
  19895. #endif
  19896. #endif /* _OS_WIN_H_ */
  19897. /************** End of os_win.h **********************************************/
  19898. /************** Continuing where we left off in mutex_w32.c ******************/
  19899. #endif
  19900. /*
  19901. ** The code in this file is only used if we are compiling multithreaded
  19902. ** on a Win32 system.
  19903. */
  19904. #ifdef SQLITE_MUTEX_W32
  19905. /*
  19906. ** Each recursive mutex is an instance of the following structure.
  19907. */
  19908. struct sqlite3_mutex {
  19909. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  19910. int id; /* Mutex type */
  19911. #ifdef SQLITE_DEBUG
  19912. volatile int nRef; /* Number of enterances */
  19913. volatile DWORD owner; /* Thread holding this mutex */
  19914. volatile int trace; /* True to trace changes */
  19915. #endif
  19916. };
  19917. /*
  19918. ** These are the initializer values used when declaring a "static" mutex
  19919. ** on Win32. It should be noted that all mutexes require initialization
  19920. ** on the Win32 platform.
  19921. */
  19922. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  19923. #ifdef SQLITE_DEBUG
  19924. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  19925. 0L, (DWORD)0, 0 }
  19926. #else
  19927. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  19928. #endif
  19929. #ifdef SQLITE_DEBUG
  19930. /*
  19931. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19932. ** intended for use only inside assert() statements.
  19933. */
  19934. static int winMutexHeld(sqlite3_mutex *p){
  19935. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  19936. }
  19937. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  19938. return p->nRef==0 || p->owner!=tid;
  19939. }
  19940. static int winMutexNotheld(sqlite3_mutex *p){
  19941. DWORD tid = GetCurrentThreadId();
  19942. return winMutexNotheld2(p, tid);
  19943. }
  19944. #endif
  19945. /*
  19946. ** Try to provide a memory barrier operation, needed for initialization
  19947. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  19948. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  19949. */
  19950. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  19951. #if defined(SQLITE_MEMORY_BARRIER)
  19952. SQLITE_MEMORY_BARRIER;
  19953. #elif defined(__GNUC__)
  19954. __sync_synchronize();
  19955. #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
  19956. defined(_MSC_VER) && _MSC_VER>=1300
  19957. _ReadWriteBarrier();
  19958. #elif defined(MemoryBarrier)
  19959. MemoryBarrier();
  19960. #endif
  19961. }
  19962. /*
  19963. ** Initialize and deinitialize the mutex subsystem.
  19964. */
  19965. static sqlite3_mutex winMutex_staticMutexes[] = {
  19966. SQLITE3_MUTEX_INITIALIZER,
  19967. SQLITE3_MUTEX_INITIALIZER,
  19968. SQLITE3_MUTEX_INITIALIZER,
  19969. SQLITE3_MUTEX_INITIALIZER,
  19970. SQLITE3_MUTEX_INITIALIZER,
  19971. SQLITE3_MUTEX_INITIALIZER,
  19972. SQLITE3_MUTEX_INITIALIZER,
  19973. SQLITE3_MUTEX_INITIALIZER,
  19974. SQLITE3_MUTEX_INITIALIZER,
  19975. SQLITE3_MUTEX_INITIALIZER,
  19976. SQLITE3_MUTEX_INITIALIZER,
  19977. SQLITE3_MUTEX_INITIALIZER
  19978. };
  19979. static int winMutex_isInit = 0;
  19980. static int winMutex_isNt = -1; /* <0 means "need to query" */
  19981. /* As the winMutexInit() and winMutexEnd() functions are called as part
  19982. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  19983. ** "interlocked" magic used here is probably not strictly necessary.
  19984. */
  19985. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  19986. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
  19987. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  19988. static int winMutexInit(void){
  19989. /* The first to increment to 1 does actual initialization */
  19990. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  19991. int i;
  19992. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  19993. #if SQLITE_OS_WINRT
  19994. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  19995. #else
  19996. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  19997. #endif
  19998. }
  19999. winMutex_isInit = 1;
  20000. }else{
  20001. /* Another thread is (in the process of) initializing the static
  20002. ** mutexes */
  20003. while( !winMutex_isInit ){
  20004. sqlite3_win32_sleep(1);
  20005. }
  20006. }
  20007. return SQLITE_OK;
  20008. }
  20009. static int winMutexEnd(void){
  20010. /* The first to decrement to 0 does actual shutdown
  20011. ** (which should be the last to shutdown.) */
  20012. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  20013. if( winMutex_isInit==1 ){
  20014. int i;
  20015. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  20016. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  20017. }
  20018. winMutex_isInit = 0;
  20019. }
  20020. }
  20021. return SQLITE_OK;
  20022. }
  20023. /*
  20024. ** The sqlite3_mutex_alloc() routine allocates a new
  20025. ** mutex and returns a pointer to it. If it returns NULL
  20026. ** that means that a mutex could not be allocated. SQLite
  20027. ** will unwind its stack and return an error. The argument
  20028. ** to sqlite3_mutex_alloc() is one of these integer constants:
  20029. **
  20030. ** <ul>
  20031. ** <li> SQLITE_MUTEX_FAST
  20032. ** <li> SQLITE_MUTEX_RECURSIVE
  20033. ** <li> SQLITE_MUTEX_STATIC_MASTER
  20034. ** <li> SQLITE_MUTEX_STATIC_MEM
  20035. ** <li> SQLITE_MUTEX_STATIC_OPEN
  20036. ** <li> SQLITE_MUTEX_STATIC_PRNG
  20037. ** <li> SQLITE_MUTEX_STATIC_LRU
  20038. ** <li> SQLITE_MUTEX_STATIC_PMEM
  20039. ** <li> SQLITE_MUTEX_STATIC_APP1
  20040. ** <li> SQLITE_MUTEX_STATIC_APP2
  20041. ** <li> SQLITE_MUTEX_STATIC_APP3
  20042. ** <li> SQLITE_MUTEX_STATIC_VFS1
  20043. ** <li> SQLITE_MUTEX_STATIC_VFS2
  20044. ** <li> SQLITE_MUTEX_STATIC_VFS3
  20045. ** </ul>
  20046. **
  20047. ** The first two constants cause sqlite3_mutex_alloc() to create
  20048. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  20049. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  20050. ** The mutex implementation does not need to make a distinction
  20051. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  20052. ** not want to. But SQLite will only request a recursive mutex in
  20053. ** cases where it really needs one. If a faster non-recursive mutex
  20054. ** implementation is available on the host platform, the mutex subsystem
  20055. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  20056. **
  20057. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  20058. ** a pointer to a static preexisting mutex. Six static mutexes are
  20059. ** used by the current version of SQLite. Future versions of SQLite
  20060. ** may add additional static mutexes. Static mutexes are for internal
  20061. ** use by SQLite only. Applications that use SQLite mutexes should
  20062. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  20063. ** SQLITE_MUTEX_RECURSIVE.
  20064. **
  20065. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  20066. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  20067. ** returns a different mutex on every call. But for the static
  20068. ** mutex types, the same mutex is returned on every call that has
  20069. ** the same type number.
  20070. */
  20071. static sqlite3_mutex *winMutexAlloc(int iType){
  20072. sqlite3_mutex *p;
  20073. switch( iType ){
  20074. case SQLITE_MUTEX_FAST:
  20075. case SQLITE_MUTEX_RECURSIVE: {
  20076. p = sqlite3MallocZero( sizeof(*p) );
  20077. if( p ){
  20078. p->id = iType;
  20079. #ifdef SQLITE_DEBUG
  20080. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  20081. p->trace = 1;
  20082. #endif
  20083. #endif
  20084. #if SQLITE_OS_WINRT
  20085. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  20086. #else
  20087. InitializeCriticalSection(&p->mutex);
  20088. #endif
  20089. }
  20090. break;
  20091. }
  20092. default: {
  20093. #ifdef SQLITE_ENABLE_API_ARMOR
  20094. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  20095. (void)SQLITE_MISUSE_BKPT;
  20096. return 0;
  20097. }
  20098. #endif
  20099. p = &winMutex_staticMutexes[iType-2];
  20100. p->id = iType;
  20101. #ifdef SQLITE_DEBUG
  20102. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  20103. p->trace = 1;
  20104. #endif
  20105. #endif
  20106. break;
  20107. }
  20108. }
  20109. return p;
  20110. }
  20111. /*
  20112. ** This routine deallocates a previously
  20113. ** allocated mutex. SQLite is careful to deallocate every
  20114. ** mutex that it allocates.
  20115. */
  20116. static void winMutexFree(sqlite3_mutex *p){
  20117. assert( p );
  20118. assert( p->nRef==0 && p->owner==0 );
  20119. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  20120. DeleteCriticalSection(&p->mutex);
  20121. sqlite3_free(p);
  20122. }else{
  20123. #ifdef SQLITE_ENABLE_API_ARMOR
  20124. (void)SQLITE_MISUSE_BKPT;
  20125. #endif
  20126. }
  20127. }
  20128. /*
  20129. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  20130. ** to enter a mutex. If another thread is already within the mutex,
  20131. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  20132. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  20133. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  20134. ** be entered multiple times by the same thread. In such cases the,
  20135. ** mutex must be exited an equal number of times before another thread
  20136. ** can enter. If the same thread tries to enter any other kind of mutex
  20137. ** more than once, the behavior is undefined.
  20138. */
  20139. static void winMutexEnter(sqlite3_mutex *p){
  20140. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20141. DWORD tid = GetCurrentThreadId();
  20142. #endif
  20143. #ifdef SQLITE_DEBUG
  20144. assert( p );
  20145. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20146. #else
  20147. assert( p );
  20148. #endif
  20149. assert( winMutex_isInit==1 );
  20150. EnterCriticalSection(&p->mutex);
  20151. #ifdef SQLITE_DEBUG
  20152. assert( p->nRef>0 || p->owner==0 );
  20153. p->owner = tid;
  20154. p->nRef++;
  20155. if( p->trace ){
  20156. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20157. tid, p, p->trace, p->nRef));
  20158. }
  20159. #endif
  20160. }
  20161. static int winMutexTry(sqlite3_mutex *p){
  20162. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20163. DWORD tid = GetCurrentThreadId();
  20164. #endif
  20165. int rc = SQLITE_BUSY;
  20166. assert( p );
  20167. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20168. /*
  20169. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  20170. ** is used it is merely an optimization. So it is OK for it to always
  20171. ** fail.
  20172. **
  20173. ** The TryEnterCriticalSection() interface is only available on WinNT.
  20174. ** And some windows compilers complain if you try to use it without
  20175. ** first doing some #defines that prevent SQLite from building on Win98.
  20176. ** For that reason, we will omit this optimization for now. See
  20177. ** ticket #2685.
  20178. */
  20179. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  20180. assert( winMutex_isInit==1 );
  20181. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  20182. if( winMutex_isNt<0 ){
  20183. winMutex_isNt = sqlite3_win32_is_nt();
  20184. }
  20185. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  20186. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  20187. #ifdef SQLITE_DEBUG
  20188. p->owner = tid;
  20189. p->nRef++;
  20190. #endif
  20191. rc = SQLITE_OK;
  20192. }
  20193. #else
  20194. UNUSED_PARAMETER(p);
  20195. #endif
  20196. #ifdef SQLITE_DEBUG
  20197. if( p->trace ){
  20198. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  20199. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  20200. }
  20201. #endif
  20202. return rc;
  20203. }
  20204. /*
  20205. ** The sqlite3_mutex_leave() routine exits a mutex that was
  20206. ** previously entered by the same thread. The behavior
  20207. ** is undefined if the mutex is not currently entered or
  20208. ** is not currently allocated. SQLite will never do either.
  20209. */
  20210. static void winMutexLeave(sqlite3_mutex *p){
  20211. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20212. DWORD tid = GetCurrentThreadId();
  20213. #endif
  20214. assert( p );
  20215. #ifdef SQLITE_DEBUG
  20216. assert( p->nRef>0 );
  20217. assert( p->owner==tid );
  20218. p->nRef--;
  20219. if( p->nRef==0 ) p->owner = 0;
  20220. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  20221. #endif
  20222. assert( winMutex_isInit==1 );
  20223. LeaveCriticalSection(&p->mutex);
  20224. #ifdef SQLITE_DEBUG
  20225. if( p->trace ){
  20226. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20227. tid, p, p->trace, p->nRef));
  20228. }
  20229. #endif
  20230. }
  20231. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  20232. static const sqlite3_mutex_methods sMutex = {
  20233. winMutexInit,
  20234. winMutexEnd,
  20235. winMutexAlloc,
  20236. winMutexFree,
  20237. winMutexEnter,
  20238. winMutexTry,
  20239. winMutexLeave,
  20240. #ifdef SQLITE_DEBUG
  20241. winMutexHeld,
  20242. winMutexNotheld
  20243. #else
  20244. 0,
  20245. 0
  20246. #endif
  20247. };
  20248. return &sMutex;
  20249. }
  20250. #endif /* SQLITE_MUTEX_W32 */
  20251. /************** End of mutex_w32.c *******************************************/
  20252. /************** Begin file malloc.c ******************************************/
  20253. /*
  20254. ** 2001 September 15
  20255. **
  20256. ** The author disclaims copyright to this source code. In place of
  20257. ** a legal notice, here is a blessing:
  20258. **
  20259. ** May you do good and not evil.
  20260. ** May you find forgiveness for yourself and forgive others.
  20261. ** May you share freely, never taking more than you give.
  20262. **
  20263. *************************************************************************
  20264. **
  20265. ** Memory allocation functions used throughout sqlite.
  20266. */
  20267. /* #include "sqliteInt.h" */
  20268. /* #include <stdarg.h> */
  20269. /*
  20270. ** Attempt to release up to n bytes of non-essential memory currently
  20271. ** held by SQLite. An example of non-essential memory is memory used to
  20272. ** cache database pages that are not currently in use.
  20273. */
  20274. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
  20275. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  20276. return sqlite3PcacheReleaseMemory(n);
  20277. #else
  20278. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  20279. ** is a no-op returning zero if SQLite is not compiled with
  20280. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  20281. UNUSED_PARAMETER(n);
  20282. return 0;
  20283. #endif
  20284. }
  20285. /*
  20286. ** An instance of the following object records the location of
  20287. ** each unused scratch buffer.
  20288. */
  20289. typedef struct ScratchFreeslot {
  20290. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  20291. } ScratchFreeslot;
  20292. /*
  20293. ** State information local to the memory allocation subsystem.
  20294. */
  20295. static SQLITE_WSD struct Mem0Global {
  20296. sqlite3_mutex *mutex; /* Mutex to serialize access */
  20297. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  20298. /*
  20299. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  20300. ** (so that a range test can be used to determine if an allocation
  20301. ** being freed came from pScratch) and a pointer to the list of
  20302. ** unused scratch allocations.
  20303. */
  20304. void *pScratchEnd;
  20305. ScratchFreeslot *pScratchFree;
  20306. u32 nScratchFree;
  20307. /*
  20308. ** True if heap is nearly "full" where "full" is defined by the
  20309. ** sqlite3_soft_heap_limit() setting.
  20310. */
  20311. int nearlyFull;
  20312. } mem0 = { 0, 0, 0, 0, 0, 0 };
  20313. #define mem0 GLOBAL(struct Mem0Global, mem0)
  20314. /*
  20315. ** Return the memory allocator mutex. sqlite3_status() needs it.
  20316. */
  20317. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  20318. return mem0.mutex;
  20319. }
  20320. #ifndef SQLITE_OMIT_DEPRECATED
  20321. /*
  20322. ** Deprecated external interface. It used to set an alarm callback
  20323. ** that was invoked when memory usage grew too large. Now it is a
  20324. ** no-op.
  20325. */
  20326. SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
  20327. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  20328. void *pArg,
  20329. sqlite3_int64 iThreshold
  20330. ){
  20331. (void)xCallback;
  20332. (void)pArg;
  20333. (void)iThreshold;
  20334. return SQLITE_OK;
  20335. }
  20336. #endif
  20337. /*
  20338. ** Set the soft heap-size limit for the library. Passing a zero or
  20339. ** negative value indicates no limit.
  20340. */
  20341. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
  20342. sqlite3_int64 priorLimit;
  20343. sqlite3_int64 excess;
  20344. sqlite3_int64 nUsed;
  20345. #ifndef SQLITE_OMIT_AUTOINIT
  20346. int rc = sqlite3_initialize();
  20347. if( rc ) return -1;
  20348. #endif
  20349. sqlite3_mutex_enter(mem0.mutex);
  20350. priorLimit = mem0.alarmThreshold;
  20351. if( n<0 ){
  20352. sqlite3_mutex_leave(mem0.mutex);
  20353. return priorLimit;
  20354. }
  20355. mem0.alarmThreshold = n;
  20356. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  20357. mem0.nearlyFull = (n>0 && n<=nUsed);
  20358. sqlite3_mutex_leave(mem0.mutex);
  20359. excess = sqlite3_memory_used() - n;
  20360. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  20361. return priorLimit;
  20362. }
  20363. SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
  20364. if( n<0 ) n = 0;
  20365. sqlite3_soft_heap_limit64(n);
  20366. }
  20367. /*
  20368. ** Initialize the memory allocation subsystem.
  20369. */
  20370. SQLITE_PRIVATE int sqlite3MallocInit(void){
  20371. int rc;
  20372. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  20373. sqlite3MemSetDefault();
  20374. }
  20375. memset(&mem0, 0, sizeof(mem0));
  20376. if( sqlite3GlobalConfig.bCoreMutex ){
  20377. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20378. }
  20379. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  20380. && sqlite3GlobalConfig.nScratch>0 ){
  20381. int i, n, sz;
  20382. ScratchFreeslot *pSlot;
  20383. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  20384. sqlite3GlobalConfig.szScratch = sz;
  20385. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  20386. n = sqlite3GlobalConfig.nScratch;
  20387. mem0.pScratchFree = pSlot;
  20388. mem0.nScratchFree = n;
  20389. for(i=0; i<n-1; i++){
  20390. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  20391. pSlot = pSlot->pNext;
  20392. }
  20393. pSlot->pNext = 0;
  20394. mem0.pScratchEnd = (void*)&pSlot[1];
  20395. }else{
  20396. mem0.pScratchEnd = 0;
  20397. sqlite3GlobalConfig.pScratch = 0;
  20398. sqlite3GlobalConfig.szScratch = 0;
  20399. sqlite3GlobalConfig.nScratch = 0;
  20400. }
  20401. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  20402. || sqlite3GlobalConfig.nPage<=0 ){
  20403. sqlite3GlobalConfig.pPage = 0;
  20404. sqlite3GlobalConfig.szPage = 0;
  20405. }
  20406. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  20407. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  20408. return rc;
  20409. }
  20410. /*
  20411. ** Return true if the heap is currently under memory pressure - in other
  20412. ** words if the amount of heap used is close to the limit set by
  20413. ** sqlite3_soft_heap_limit().
  20414. */
  20415. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  20416. return mem0.nearlyFull;
  20417. }
  20418. /*
  20419. ** Deinitialize the memory allocation subsystem.
  20420. */
  20421. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  20422. if( sqlite3GlobalConfig.m.xShutdown ){
  20423. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  20424. }
  20425. memset(&mem0, 0, sizeof(mem0));
  20426. }
  20427. /*
  20428. ** Return the amount of memory currently checked out.
  20429. */
  20430. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
  20431. sqlite3_int64 res, mx;
  20432. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  20433. return res;
  20434. }
  20435. /*
  20436. ** Return the maximum amount of memory that has ever been
  20437. ** checked out since either the beginning of this process
  20438. ** or since the most recent reset.
  20439. */
  20440. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
  20441. sqlite3_int64 res, mx;
  20442. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  20443. return mx;
  20444. }
  20445. /*
  20446. ** Trigger the alarm
  20447. */
  20448. static void sqlite3MallocAlarm(int nByte){
  20449. if( mem0.alarmThreshold<=0 ) return;
  20450. sqlite3_mutex_leave(mem0.mutex);
  20451. sqlite3_release_memory(nByte);
  20452. sqlite3_mutex_enter(mem0.mutex);
  20453. }
  20454. /*
  20455. ** Do a memory allocation with statistics and alarms. Assume the
  20456. ** lock is already held.
  20457. */
  20458. static int mallocWithAlarm(int n, void **pp){
  20459. int nFull;
  20460. void *p;
  20461. assert( sqlite3_mutex_held(mem0.mutex) );
  20462. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  20463. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  20464. if( mem0.alarmThreshold>0 ){
  20465. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  20466. if( nUsed >= mem0.alarmThreshold - nFull ){
  20467. mem0.nearlyFull = 1;
  20468. sqlite3MallocAlarm(nFull);
  20469. }else{
  20470. mem0.nearlyFull = 0;
  20471. }
  20472. }
  20473. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  20474. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  20475. if( p==0 && mem0.alarmThreshold>0 ){
  20476. sqlite3MallocAlarm(nFull);
  20477. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  20478. }
  20479. #endif
  20480. if( p ){
  20481. nFull = sqlite3MallocSize(p);
  20482. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  20483. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  20484. }
  20485. *pp = p;
  20486. return nFull;
  20487. }
  20488. /*
  20489. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  20490. ** assumes the memory subsystem has already been initialized.
  20491. */
  20492. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  20493. void *p;
  20494. if( n==0 || n>=0x7fffff00 ){
  20495. /* A memory allocation of a number of bytes which is near the maximum
  20496. ** signed integer value might cause an integer overflow inside of the
  20497. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  20498. ** 255 bytes of overhead. SQLite itself will never use anything near
  20499. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  20500. p = 0;
  20501. }else if( sqlite3GlobalConfig.bMemstat ){
  20502. sqlite3_mutex_enter(mem0.mutex);
  20503. mallocWithAlarm((int)n, &p);
  20504. sqlite3_mutex_leave(mem0.mutex);
  20505. }else{
  20506. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  20507. }
  20508. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  20509. return p;
  20510. }
  20511. /*
  20512. ** This version of the memory allocation is for use by the application.
  20513. ** First make sure the memory subsystem is initialized, then do the
  20514. ** allocation.
  20515. */
  20516. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
  20517. #ifndef SQLITE_OMIT_AUTOINIT
  20518. if( sqlite3_initialize() ) return 0;
  20519. #endif
  20520. return n<=0 ? 0 : sqlite3Malloc(n);
  20521. }
  20522. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
  20523. #ifndef SQLITE_OMIT_AUTOINIT
  20524. if( sqlite3_initialize() ) return 0;
  20525. #endif
  20526. return sqlite3Malloc(n);
  20527. }
  20528. /*
  20529. ** Each thread may only have a single outstanding allocation from
  20530. ** xScratchMalloc(). We verify this constraint in the single-threaded
  20531. ** case by setting scratchAllocOut to 1 when an allocation
  20532. ** is outstanding clearing it when the allocation is freed.
  20533. */
  20534. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20535. static int scratchAllocOut = 0;
  20536. #endif
  20537. /*
  20538. ** Allocate memory that is to be used and released right away.
  20539. ** This routine is similar to alloca() in that it is not intended
  20540. ** for situations where the memory might be held long-term. This
  20541. ** routine is intended to get memory to old large transient data
  20542. ** structures that would not normally fit on the stack of an
  20543. ** embedded processor.
  20544. */
  20545. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  20546. void *p;
  20547. assert( n>0 );
  20548. sqlite3_mutex_enter(mem0.mutex);
  20549. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  20550. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  20551. p = mem0.pScratchFree;
  20552. mem0.pScratchFree = mem0.pScratchFree->pNext;
  20553. mem0.nScratchFree--;
  20554. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  20555. sqlite3_mutex_leave(mem0.mutex);
  20556. }else{
  20557. sqlite3_mutex_leave(mem0.mutex);
  20558. p = sqlite3Malloc(n);
  20559. if( sqlite3GlobalConfig.bMemstat && p ){
  20560. sqlite3_mutex_enter(mem0.mutex);
  20561. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  20562. sqlite3_mutex_leave(mem0.mutex);
  20563. }
  20564. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  20565. }
  20566. assert( sqlite3_mutex_notheld(mem0.mutex) );
  20567. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20568. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  20569. ** buffers per thread.
  20570. **
  20571. ** This can only be checked in single-threaded mode.
  20572. */
  20573. assert( scratchAllocOut==0 );
  20574. if( p ) scratchAllocOut++;
  20575. #endif
  20576. return p;
  20577. }
  20578. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  20579. if( p ){
  20580. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20581. /* Verify that no more than two scratch allocation per thread
  20582. ** is outstanding at one time. (This is only checked in the
  20583. ** single-threaded case since checking in the multi-threaded case
  20584. ** would be much more complicated.) */
  20585. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  20586. scratchAllocOut--;
  20587. #endif
  20588. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  20589. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  20590. ScratchFreeslot *pSlot;
  20591. pSlot = (ScratchFreeslot*)p;
  20592. sqlite3_mutex_enter(mem0.mutex);
  20593. pSlot->pNext = mem0.pScratchFree;
  20594. mem0.pScratchFree = pSlot;
  20595. mem0.nScratchFree++;
  20596. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  20597. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  20598. sqlite3_mutex_leave(mem0.mutex);
  20599. }else{
  20600. /* Release memory back to the heap */
  20601. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  20602. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  20603. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20604. if( sqlite3GlobalConfig.bMemstat ){
  20605. int iSize = sqlite3MallocSize(p);
  20606. sqlite3_mutex_enter(mem0.mutex);
  20607. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  20608. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  20609. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  20610. sqlite3GlobalConfig.m.xFree(p);
  20611. sqlite3_mutex_leave(mem0.mutex);
  20612. }else{
  20613. sqlite3GlobalConfig.m.xFree(p);
  20614. }
  20615. }
  20616. }
  20617. }
  20618. /*
  20619. ** TRUE if p is a lookaside memory allocation from db
  20620. */
  20621. #ifndef SQLITE_OMIT_LOOKASIDE
  20622. static int isLookaside(sqlite3 *db, void *p){
  20623. return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  20624. }
  20625. #else
  20626. #define isLookaside(A,B) 0
  20627. #endif
  20628. /*
  20629. ** Return the size of a memory allocation previously obtained from
  20630. ** sqlite3Malloc() or sqlite3_malloc().
  20631. */
  20632. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  20633. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20634. return sqlite3GlobalConfig.m.xSize(p);
  20635. }
  20636. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  20637. if( db==0 || !isLookaside(db,p) ){
  20638. #if SQLITE_DEBUG
  20639. if( db==0 ){
  20640. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20641. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20642. }else{
  20643. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20644. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20645. }
  20646. #endif
  20647. return sqlite3GlobalConfig.m.xSize(p);
  20648. }else{
  20649. assert( sqlite3_mutex_held(db->mutex) );
  20650. return db->lookaside.sz;
  20651. }
  20652. }
  20653. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
  20654. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20655. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20656. return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
  20657. }
  20658. /*
  20659. ** Free memory previously obtained from sqlite3Malloc().
  20660. */
  20661. SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
  20662. if( p==0 ) return; /* IMP: R-49053-54554 */
  20663. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20664. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20665. if( sqlite3GlobalConfig.bMemstat ){
  20666. sqlite3_mutex_enter(mem0.mutex);
  20667. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  20668. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  20669. sqlite3GlobalConfig.m.xFree(p);
  20670. sqlite3_mutex_leave(mem0.mutex);
  20671. }else{
  20672. sqlite3GlobalConfig.m.xFree(p);
  20673. }
  20674. }
  20675. /*
  20676. ** Add the size of memory allocation "p" to the count in
  20677. ** *db->pnBytesFreed.
  20678. */
  20679. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  20680. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  20681. }
  20682. /*
  20683. ** Free memory that might be associated with a particular database
  20684. ** connection.
  20685. */
  20686. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  20687. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  20688. if( p==0 ) return;
  20689. if( db ){
  20690. if( db->pnBytesFreed ){
  20691. measureAllocationSize(db, p);
  20692. return;
  20693. }
  20694. if( isLookaside(db, p) ){
  20695. LookasideSlot *pBuf = (LookasideSlot*)p;
  20696. #if SQLITE_DEBUG
  20697. /* Trash all content in the buffer being freed */
  20698. memset(p, 0xaa, db->lookaside.sz);
  20699. #endif
  20700. pBuf->pNext = db->lookaside.pFree;
  20701. db->lookaside.pFree = pBuf;
  20702. db->lookaside.nOut--;
  20703. return;
  20704. }
  20705. }
  20706. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20707. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20708. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  20709. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20710. sqlite3_free(p);
  20711. }
  20712. /*
  20713. ** Change the size of an existing memory allocation
  20714. */
  20715. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  20716. int nOld, nNew, nDiff;
  20717. void *pNew;
  20718. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  20719. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  20720. if( pOld==0 ){
  20721. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  20722. }
  20723. if( nBytes==0 ){
  20724. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  20725. return 0;
  20726. }
  20727. if( nBytes>=0x7fffff00 ){
  20728. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  20729. return 0;
  20730. }
  20731. nOld = sqlite3MallocSize(pOld);
  20732. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  20733. ** argument to xRealloc is always a value returned by a prior call to
  20734. ** xRoundup. */
  20735. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  20736. if( nOld==nNew ){
  20737. pNew = pOld;
  20738. }else if( sqlite3GlobalConfig.bMemstat ){
  20739. sqlite3_mutex_enter(mem0.mutex);
  20740. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  20741. nDiff = nNew - nOld;
  20742. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  20743. mem0.alarmThreshold-nDiff ){
  20744. sqlite3MallocAlarm(nDiff);
  20745. }
  20746. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20747. if( pNew==0 && mem0.alarmThreshold>0 ){
  20748. sqlite3MallocAlarm((int)nBytes);
  20749. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20750. }
  20751. if( pNew ){
  20752. nNew = sqlite3MallocSize(pNew);
  20753. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  20754. }
  20755. sqlite3_mutex_leave(mem0.mutex);
  20756. }else{
  20757. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20758. }
  20759. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  20760. return pNew;
  20761. }
  20762. /*
  20763. ** The public interface to sqlite3Realloc. Make sure that the memory
  20764. ** subsystem is initialized prior to invoking sqliteRealloc.
  20765. */
  20766. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
  20767. #ifndef SQLITE_OMIT_AUTOINIT
  20768. if( sqlite3_initialize() ) return 0;
  20769. #endif
  20770. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  20771. return sqlite3Realloc(pOld, n);
  20772. }
  20773. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  20774. #ifndef SQLITE_OMIT_AUTOINIT
  20775. if( sqlite3_initialize() ) return 0;
  20776. #endif
  20777. return sqlite3Realloc(pOld, n);
  20778. }
  20779. /*
  20780. ** Allocate and zero memory.
  20781. */
  20782. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  20783. void *p = sqlite3Malloc(n);
  20784. if( p ){
  20785. memset(p, 0, (size_t)n);
  20786. }
  20787. return p;
  20788. }
  20789. /*
  20790. ** Allocate and zero memory. If the allocation fails, make
  20791. ** the mallocFailed flag in the connection pointer.
  20792. */
  20793. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  20794. void *p = sqlite3DbMallocRaw(db, n);
  20795. if( p ){
  20796. memset(p, 0, (size_t)n);
  20797. }
  20798. return p;
  20799. }
  20800. /*
  20801. ** Allocate and zero memory. If the allocation fails, make
  20802. ** the mallocFailed flag in the connection pointer.
  20803. **
  20804. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  20805. ** failure on the same database connection) then always return 0.
  20806. ** Hence for a particular database connection, once malloc starts
  20807. ** failing, it fails consistently until mallocFailed is reset.
  20808. ** This is an important assumption. There are many places in the
  20809. ** code that do things like this:
  20810. **
  20811. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  20812. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  20813. ** if( b ) a[10] = 9;
  20814. **
  20815. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  20816. ** that all prior mallocs (ex: "a") worked too.
  20817. */
  20818. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  20819. void *p;
  20820. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  20821. assert( db==0 || db->pnBytesFreed==0 );
  20822. #ifndef SQLITE_OMIT_LOOKASIDE
  20823. if( db ){
  20824. LookasideSlot *pBuf;
  20825. if( db->mallocFailed ){
  20826. return 0;
  20827. }
  20828. if( db->lookaside.bEnabled ){
  20829. if( n>db->lookaside.sz ){
  20830. db->lookaside.anStat[1]++;
  20831. }else if( (pBuf = db->lookaside.pFree)==0 ){
  20832. db->lookaside.anStat[2]++;
  20833. }else{
  20834. db->lookaside.pFree = pBuf->pNext;
  20835. db->lookaside.nOut++;
  20836. db->lookaside.anStat[0]++;
  20837. if( db->lookaside.nOut>db->lookaside.mxOut ){
  20838. db->lookaside.mxOut = db->lookaside.nOut;
  20839. }
  20840. return (void*)pBuf;
  20841. }
  20842. }
  20843. }
  20844. #else
  20845. if( db && db->mallocFailed ){
  20846. return 0;
  20847. }
  20848. #endif
  20849. p = sqlite3Malloc(n);
  20850. if( !p && db ){
  20851. db->mallocFailed = 1;
  20852. }
  20853. sqlite3MemdebugSetType(p,
  20854. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  20855. return p;
  20856. }
  20857. /*
  20858. ** Resize the block of memory pointed to by p to n bytes. If the
  20859. ** resize fails, set the mallocFailed flag in the connection object.
  20860. */
  20861. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  20862. void *pNew = 0;
  20863. assert( db!=0 );
  20864. assert( sqlite3_mutex_held(db->mutex) );
  20865. if( db->mallocFailed==0 ){
  20866. if( p==0 ){
  20867. return sqlite3DbMallocRaw(db, n);
  20868. }
  20869. if( isLookaside(db, p) ){
  20870. if( n<=db->lookaside.sz ){
  20871. return p;
  20872. }
  20873. pNew = sqlite3DbMallocRaw(db, n);
  20874. if( pNew ){
  20875. memcpy(pNew, p, db->lookaside.sz);
  20876. sqlite3DbFree(db, p);
  20877. }
  20878. }else{
  20879. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20880. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20881. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20882. pNew = sqlite3_realloc64(p, n);
  20883. if( !pNew ){
  20884. db->mallocFailed = 1;
  20885. }
  20886. sqlite3MemdebugSetType(pNew,
  20887. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  20888. }
  20889. }
  20890. return pNew;
  20891. }
  20892. /*
  20893. ** Attempt to reallocate p. If the reallocation fails, then free p
  20894. ** and set the mallocFailed flag in the database connection.
  20895. */
  20896. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  20897. void *pNew;
  20898. pNew = sqlite3DbRealloc(db, p, n);
  20899. if( !pNew ){
  20900. sqlite3DbFree(db, p);
  20901. }
  20902. return pNew;
  20903. }
  20904. /*
  20905. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  20906. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  20907. ** is because when memory debugging is turned on, these two functions are
  20908. ** called via macros that record the current file and line number in the
  20909. ** ThreadData structure.
  20910. */
  20911. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  20912. char *zNew;
  20913. size_t n;
  20914. if( z==0 ){
  20915. return 0;
  20916. }
  20917. n = sqlite3Strlen30(z) + 1;
  20918. assert( (n&0x7fffffff)==n );
  20919. zNew = sqlite3DbMallocRaw(db, (int)n);
  20920. if( zNew ){
  20921. memcpy(zNew, z, n);
  20922. }
  20923. return zNew;
  20924. }
  20925. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  20926. char *zNew;
  20927. if( z==0 ){
  20928. return 0;
  20929. }
  20930. assert( (n&0x7fffffff)==n );
  20931. zNew = sqlite3DbMallocRaw(db, n+1);
  20932. if( zNew ){
  20933. memcpy(zNew, z, (size_t)n);
  20934. zNew[n] = 0;
  20935. }
  20936. return zNew;
  20937. }
  20938. /*
  20939. ** Free any prior content in *pz and replace it with a copy of zNew.
  20940. */
  20941. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  20942. sqlite3DbFree(db, *pz);
  20943. *pz = sqlite3DbStrDup(db, zNew);
  20944. }
  20945. /*
  20946. ** Take actions at the end of an API call to indicate an OOM error
  20947. */
  20948. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  20949. db->mallocFailed = 0;
  20950. sqlite3Error(db, SQLITE_NOMEM);
  20951. return SQLITE_NOMEM;
  20952. }
  20953. /*
  20954. ** This function must be called before exiting any API function (i.e.
  20955. ** returning control to the user) that has called sqlite3_malloc or
  20956. ** sqlite3_realloc.
  20957. **
  20958. ** The returned value is normally a copy of the second argument to this
  20959. ** function. However, if a malloc() failure has occurred since the previous
  20960. ** invocation SQLITE_NOMEM is returned instead.
  20961. **
  20962. ** If an OOM as occurred, then the connection error-code (the value
  20963. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  20964. */
  20965. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  20966. /* If the db handle must hold the connection handle mutex here.
  20967. ** Otherwise the read (and possible write) of db->mallocFailed
  20968. ** is unsafe, as is the call to sqlite3Error().
  20969. */
  20970. assert( db!=0 );
  20971. assert( sqlite3_mutex_held(db->mutex) );
  20972. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  20973. return apiOomError(db);
  20974. }
  20975. return rc & db->errMask;
  20976. }
  20977. /************** End of malloc.c **********************************************/
  20978. /************** Begin file printf.c ******************************************/
  20979. /*
  20980. ** The "printf" code that follows dates from the 1980's. It is in
  20981. ** the public domain.
  20982. **
  20983. **************************************************************************
  20984. **
  20985. ** This file contains code for a set of "printf"-like routines. These
  20986. ** routines format strings much like the printf() from the standard C
  20987. ** library, though the implementation here has enhancements to support
  20988. ** SQLite.
  20989. */
  20990. /* #include "sqliteInt.h" */
  20991. /*
  20992. ** Conversion types fall into various categories as defined by the
  20993. ** following enumeration.
  20994. */
  20995. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  20996. #define etFLOAT 2 /* Floating point. %f */
  20997. #define etEXP 3 /* Exponentional notation. %e and %E */
  20998. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  20999. #define etSIZE 5 /* Return number of characters processed so far. %n */
  21000. #define etSTRING 6 /* Strings. %s */
  21001. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  21002. #define etPERCENT 8 /* Percent symbol. %% */
  21003. #define etCHARX 9 /* Characters. %c */
  21004. /* The rest are extensions, not normally found in printf() */
  21005. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  21006. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  21007. NULL pointers replaced by SQL NULL. %Q */
  21008. #define etTOKEN 12 /* a pointer to a Token structure */
  21009. #define etSRCLIST 13 /* a pointer to a SrcList */
  21010. #define etPOINTER 14 /* The %p conversion */
  21011. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  21012. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  21013. #define etINVALID 0 /* Any unrecognized conversion type */
  21014. /*
  21015. ** An "etByte" is an 8-bit unsigned value.
  21016. */
  21017. typedef unsigned char etByte;
  21018. /*
  21019. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  21020. ** by an instance of the following structure
  21021. */
  21022. typedef struct et_info { /* Information about each format field */
  21023. char fmttype; /* The format field code letter */
  21024. etByte base; /* The base for radix conversion */
  21025. etByte flags; /* One or more of FLAG_ constants below */
  21026. etByte type; /* Conversion paradigm */
  21027. etByte charset; /* Offset into aDigits[] of the digits string */
  21028. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  21029. } et_info;
  21030. /*
  21031. ** Allowed values for et_info.flags
  21032. */
  21033. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  21034. #define FLAG_INTERN 2 /* True if for internal use only */
  21035. #define FLAG_STRING 4 /* Allow infinity precision */
  21036. /*
  21037. ** The following table is searched linearly, so it is good to put the
  21038. ** most frequently used conversion types first.
  21039. */
  21040. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  21041. static const char aPrefix[] = "-x0\000X0";
  21042. static const et_info fmtinfo[] = {
  21043. { 'd', 10, 1, etRADIX, 0, 0 },
  21044. { 's', 0, 4, etSTRING, 0, 0 },
  21045. { 'g', 0, 1, etGENERIC, 30, 0 },
  21046. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  21047. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  21048. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  21049. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  21050. { 'c', 0, 0, etCHARX, 0, 0 },
  21051. { 'o', 8, 0, etRADIX, 0, 2 },
  21052. { 'u', 10, 0, etRADIX, 0, 0 },
  21053. { 'x', 16, 0, etRADIX, 16, 1 },
  21054. { 'X', 16, 0, etRADIX, 0, 4 },
  21055. #ifndef SQLITE_OMIT_FLOATING_POINT
  21056. { 'f', 0, 1, etFLOAT, 0, 0 },
  21057. { 'e', 0, 1, etEXP, 30, 0 },
  21058. { 'E', 0, 1, etEXP, 14, 0 },
  21059. { 'G', 0, 1, etGENERIC, 14, 0 },
  21060. #endif
  21061. { 'i', 10, 1, etRADIX, 0, 0 },
  21062. { 'n', 0, 0, etSIZE, 0, 0 },
  21063. { '%', 0, 0, etPERCENT, 0, 0 },
  21064. { 'p', 16, 0, etPOINTER, 0, 1 },
  21065. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  21066. ** use only */
  21067. { 'T', 0, 2, etTOKEN, 0, 0 },
  21068. { 'S', 0, 2, etSRCLIST, 0, 0 },
  21069. { 'r', 10, 3, etORDINAL, 0, 0 },
  21070. };
  21071. /*
  21072. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  21073. ** conversions will work.
  21074. */
  21075. #ifndef SQLITE_OMIT_FLOATING_POINT
  21076. /*
  21077. ** "*val" is a double such that 0.1 <= *val < 10.0
  21078. ** Return the ascii code for the leading digit of *val, then
  21079. ** multiply "*val" by 10.0 to renormalize.
  21080. **
  21081. ** Example:
  21082. ** input: *val = 3.14159
  21083. ** output: *val = 1.4159 function return = '3'
  21084. **
  21085. ** The counter *cnt is incremented each time. After counter exceeds
  21086. ** 16 (the number of significant digits in a 64-bit float) '0' is
  21087. ** always returned.
  21088. */
  21089. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  21090. int digit;
  21091. LONGDOUBLE_TYPE d;
  21092. if( (*cnt)<=0 ) return '0';
  21093. (*cnt)--;
  21094. digit = (int)*val;
  21095. d = digit;
  21096. digit += '0';
  21097. *val = (*val - d)*10.0;
  21098. return (char)digit;
  21099. }
  21100. #endif /* SQLITE_OMIT_FLOATING_POINT */
  21101. /*
  21102. ** Set the StrAccum object to an error mode.
  21103. */
  21104. static void setStrAccumError(StrAccum *p, u8 eError){
  21105. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  21106. p->accError = eError;
  21107. p->nAlloc = 0;
  21108. }
  21109. /*
  21110. ** Extra argument values from a PrintfArguments object
  21111. */
  21112. static sqlite3_int64 getIntArg(PrintfArguments *p){
  21113. if( p->nArg<=p->nUsed ) return 0;
  21114. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  21115. }
  21116. static double getDoubleArg(PrintfArguments *p){
  21117. if( p->nArg<=p->nUsed ) return 0.0;
  21118. return sqlite3_value_double(p->apArg[p->nUsed++]);
  21119. }
  21120. static char *getTextArg(PrintfArguments *p){
  21121. if( p->nArg<=p->nUsed ) return 0;
  21122. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  21123. }
  21124. /*
  21125. ** On machines with a small stack size, you can redefine the
  21126. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  21127. */
  21128. #ifndef SQLITE_PRINT_BUF_SIZE
  21129. # define SQLITE_PRINT_BUF_SIZE 70
  21130. #endif
  21131. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  21132. /*
  21133. ** Render a string given by "fmt" into the StrAccum object.
  21134. */
  21135. SQLITE_PRIVATE void sqlite3VXPrintf(
  21136. StrAccum *pAccum, /* Accumulate results here */
  21137. u32 bFlags, /* SQLITE_PRINTF_* flags */
  21138. const char *fmt, /* Format string */
  21139. va_list ap /* arguments */
  21140. ){
  21141. int c; /* Next character in the format string */
  21142. char *bufpt; /* Pointer to the conversion buffer */
  21143. int precision; /* Precision of the current field */
  21144. int length; /* Length of the field */
  21145. int idx; /* A general purpose loop counter */
  21146. int width; /* Width of the current field */
  21147. etByte flag_leftjustify; /* True if "-" flag is present */
  21148. etByte flag_plussign; /* True if "+" flag is present */
  21149. etByte flag_blanksign; /* True if " " flag is present */
  21150. etByte flag_alternateform; /* True if "#" flag is present */
  21151. etByte flag_altform2; /* True if "!" flag is present */
  21152. etByte flag_zeropad; /* True if field width constant starts with zero */
  21153. etByte flag_long; /* True if "l" flag is present */
  21154. etByte flag_longlong; /* True if the "ll" flag is present */
  21155. etByte done; /* Loop termination flag */
  21156. etByte xtype = 0; /* Conversion paradigm */
  21157. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  21158. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  21159. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  21160. sqlite_uint64 longvalue; /* Value for integer types */
  21161. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  21162. const et_info *infop; /* Pointer to the appropriate info structure */
  21163. char *zOut; /* Rendering buffer */
  21164. int nOut; /* Size of the rendering buffer */
  21165. char *zExtra = 0; /* Malloced memory used by some conversion */
  21166. #ifndef SQLITE_OMIT_FLOATING_POINT
  21167. int exp, e2; /* exponent of real numbers */
  21168. int nsd; /* Number of significant digits returned */
  21169. double rounder; /* Used for rounding floating point values */
  21170. etByte flag_dp; /* True if decimal point should be shown */
  21171. etByte flag_rtz; /* True if trailing zeros should be removed */
  21172. #endif
  21173. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  21174. char buf[etBUFSIZE]; /* Conversion buffer */
  21175. bufpt = 0;
  21176. if( bFlags ){
  21177. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  21178. pArgList = va_arg(ap, PrintfArguments*);
  21179. }
  21180. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  21181. }else{
  21182. bArgList = useIntern = 0;
  21183. }
  21184. for(; (c=(*fmt))!=0; ++fmt){
  21185. if( c!='%' ){
  21186. bufpt = (char *)fmt;
  21187. #if HAVE_STRCHRNUL
  21188. fmt = strchrnul(fmt, '%');
  21189. #else
  21190. do{ fmt++; }while( *fmt && *fmt != '%' );
  21191. #endif
  21192. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  21193. if( *fmt==0 ) break;
  21194. }
  21195. if( (c=(*++fmt))==0 ){
  21196. sqlite3StrAccumAppend(pAccum, "%", 1);
  21197. break;
  21198. }
  21199. /* Find out what flags are present */
  21200. flag_leftjustify = flag_plussign = flag_blanksign =
  21201. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  21202. done = 0;
  21203. do{
  21204. switch( c ){
  21205. case '-': flag_leftjustify = 1; break;
  21206. case '+': flag_plussign = 1; break;
  21207. case ' ': flag_blanksign = 1; break;
  21208. case '#': flag_alternateform = 1; break;
  21209. case '!': flag_altform2 = 1; break;
  21210. case '0': flag_zeropad = 1; break;
  21211. default: done = 1; break;
  21212. }
  21213. }while( !done && (c=(*++fmt))!=0 );
  21214. /* Get the field width */
  21215. if( c=='*' ){
  21216. if( bArgList ){
  21217. width = (int)getIntArg(pArgList);
  21218. }else{
  21219. width = va_arg(ap,int);
  21220. }
  21221. if( width<0 ){
  21222. flag_leftjustify = 1;
  21223. width = width >= -2147483647 ? -width : 0;
  21224. }
  21225. c = *++fmt;
  21226. }else{
  21227. unsigned wx = 0;
  21228. while( c>='0' && c<='9' ){
  21229. wx = wx*10 + c - '0';
  21230. c = *++fmt;
  21231. }
  21232. testcase( wx>0x7fffffff );
  21233. width = wx & 0x7fffffff;
  21234. }
  21235. /* Get the precision */
  21236. if( c=='.' ){
  21237. c = *++fmt;
  21238. if( c=='*' ){
  21239. if( bArgList ){
  21240. precision = (int)getIntArg(pArgList);
  21241. }else{
  21242. precision = va_arg(ap,int);
  21243. }
  21244. c = *++fmt;
  21245. if( precision<0 ){
  21246. precision = precision >= -2147483647 ? -precision : -1;
  21247. }
  21248. }else{
  21249. unsigned px = 0;
  21250. while( c>='0' && c<='9' ){
  21251. px = px*10 + c - '0';
  21252. c = *++fmt;
  21253. }
  21254. testcase( px>0x7fffffff );
  21255. precision = px & 0x7fffffff;
  21256. }
  21257. }else{
  21258. precision = -1;
  21259. }
  21260. /* Get the conversion type modifier */
  21261. if( c=='l' ){
  21262. flag_long = 1;
  21263. c = *++fmt;
  21264. if( c=='l' ){
  21265. flag_longlong = 1;
  21266. c = *++fmt;
  21267. }else{
  21268. flag_longlong = 0;
  21269. }
  21270. }else{
  21271. flag_long = flag_longlong = 0;
  21272. }
  21273. /* Fetch the info entry for the field */
  21274. infop = &fmtinfo[0];
  21275. xtype = etINVALID;
  21276. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  21277. if( c==fmtinfo[idx].fmttype ){
  21278. infop = &fmtinfo[idx];
  21279. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  21280. xtype = infop->type;
  21281. }else{
  21282. return;
  21283. }
  21284. break;
  21285. }
  21286. }
  21287. /*
  21288. ** At this point, variables are initialized as follows:
  21289. **
  21290. ** flag_alternateform TRUE if a '#' is present.
  21291. ** flag_altform2 TRUE if a '!' is present.
  21292. ** flag_plussign TRUE if a '+' is present.
  21293. ** flag_leftjustify TRUE if a '-' is present or if the
  21294. ** field width was negative.
  21295. ** flag_zeropad TRUE if the width began with 0.
  21296. ** flag_long TRUE if the letter 'l' (ell) prefixed
  21297. ** the conversion character.
  21298. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  21299. ** the conversion character.
  21300. ** flag_blanksign TRUE if a ' ' is present.
  21301. ** width The specified field width. This is
  21302. ** always non-negative. Zero is the default.
  21303. ** precision The specified precision. The default
  21304. ** is -1.
  21305. ** xtype The class of the conversion.
  21306. ** infop Pointer to the appropriate info struct.
  21307. */
  21308. switch( xtype ){
  21309. case etPOINTER:
  21310. flag_longlong = sizeof(char*)==sizeof(i64);
  21311. flag_long = sizeof(char*)==sizeof(long int);
  21312. /* Fall through into the next case */
  21313. case etORDINAL:
  21314. case etRADIX:
  21315. if( infop->flags & FLAG_SIGNED ){
  21316. i64 v;
  21317. if( bArgList ){
  21318. v = getIntArg(pArgList);
  21319. }else if( flag_longlong ){
  21320. v = va_arg(ap,i64);
  21321. }else if( flag_long ){
  21322. v = va_arg(ap,long int);
  21323. }else{
  21324. v = va_arg(ap,int);
  21325. }
  21326. if( v<0 ){
  21327. if( v==SMALLEST_INT64 ){
  21328. longvalue = ((u64)1)<<63;
  21329. }else{
  21330. longvalue = -v;
  21331. }
  21332. prefix = '-';
  21333. }else{
  21334. longvalue = v;
  21335. if( flag_plussign ) prefix = '+';
  21336. else if( flag_blanksign ) prefix = ' ';
  21337. else prefix = 0;
  21338. }
  21339. }else{
  21340. if( bArgList ){
  21341. longvalue = (u64)getIntArg(pArgList);
  21342. }else if( flag_longlong ){
  21343. longvalue = va_arg(ap,u64);
  21344. }else if( flag_long ){
  21345. longvalue = va_arg(ap,unsigned long int);
  21346. }else{
  21347. longvalue = va_arg(ap,unsigned int);
  21348. }
  21349. prefix = 0;
  21350. }
  21351. if( longvalue==0 ) flag_alternateform = 0;
  21352. if( flag_zeropad && precision<width-(prefix!=0) ){
  21353. precision = width-(prefix!=0);
  21354. }
  21355. if( precision<etBUFSIZE-10 ){
  21356. nOut = etBUFSIZE;
  21357. zOut = buf;
  21358. }else{
  21359. nOut = precision + 10;
  21360. zOut = zExtra = sqlite3Malloc( nOut );
  21361. if( zOut==0 ){
  21362. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21363. return;
  21364. }
  21365. }
  21366. bufpt = &zOut[nOut-1];
  21367. if( xtype==etORDINAL ){
  21368. static const char zOrd[] = "thstndrd";
  21369. int x = (int)(longvalue % 10);
  21370. if( x>=4 || (longvalue/10)%10==1 ){
  21371. x = 0;
  21372. }
  21373. *(--bufpt) = zOrd[x*2+1];
  21374. *(--bufpt) = zOrd[x*2];
  21375. }
  21376. {
  21377. const char *cset = &aDigits[infop->charset];
  21378. u8 base = infop->base;
  21379. do{ /* Convert to ascii */
  21380. *(--bufpt) = cset[longvalue%base];
  21381. longvalue = longvalue/base;
  21382. }while( longvalue>0 );
  21383. }
  21384. length = (int)(&zOut[nOut-1]-bufpt);
  21385. for(idx=precision-length; idx>0; idx--){
  21386. *(--bufpt) = '0'; /* Zero pad */
  21387. }
  21388. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  21389. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  21390. const char *pre;
  21391. char x;
  21392. pre = &aPrefix[infop->prefix];
  21393. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  21394. }
  21395. length = (int)(&zOut[nOut-1]-bufpt);
  21396. break;
  21397. case etFLOAT:
  21398. case etEXP:
  21399. case etGENERIC:
  21400. if( bArgList ){
  21401. realvalue = getDoubleArg(pArgList);
  21402. }else{
  21403. realvalue = va_arg(ap,double);
  21404. }
  21405. #ifdef SQLITE_OMIT_FLOATING_POINT
  21406. length = 0;
  21407. #else
  21408. if( precision<0 ) precision = 6; /* Set default precision */
  21409. if( realvalue<0.0 ){
  21410. realvalue = -realvalue;
  21411. prefix = '-';
  21412. }else{
  21413. if( flag_plussign ) prefix = '+';
  21414. else if( flag_blanksign ) prefix = ' ';
  21415. else prefix = 0;
  21416. }
  21417. if( xtype==etGENERIC && precision>0 ) precision--;
  21418. testcase( precision>0xfff );
  21419. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  21420. if( xtype==etFLOAT ) realvalue += rounder;
  21421. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  21422. exp = 0;
  21423. if( sqlite3IsNaN((double)realvalue) ){
  21424. bufpt = "NaN";
  21425. length = 3;
  21426. break;
  21427. }
  21428. if( realvalue>0.0 ){
  21429. LONGDOUBLE_TYPE scale = 1.0;
  21430. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  21431. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  21432. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  21433. realvalue /= scale;
  21434. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  21435. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  21436. if( exp>350 ){
  21437. bufpt = buf;
  21438. buf[0] = prefix;
  21439. memcpy(buf+(prefix!=0),"Inf",4);
  21440. length = 3+(prefix!=0);
  21441. break;
  21442. }
  21443. }
  21444. bufpt = buf;
  21445. /*
  21446. ** If the field type is etGENERIC, then convert to either etEXP
  21447. ** or etFLOAT, as appropriate.
  21448. */
  21449. if( xtype!=etFLOAT ){
  21450. realvalue += rounder;
  21451. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  21452. }
  21453. if( xtype==etGENERIC ){
  21454. flag_rtz = !flag_alternateform;
  21455. if( exp<-4 || exp>precision ){
  21456. xtype = etEXP;
  21457. }else{
  21458. precision = precision - exp;
  21459. xtype = etFLOAT;
  21460. }
  21461. }else{
  21462. flag_rtz = flag_altform2;
  21463. }
  21464. if( xtype==etEXP ){
  21465. e2 = 0;
  21466. }else{
  21467. e2 = exp;
  21468. }
  21469. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  21470. bufpt = zExtra
  21471. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  21472. if( bufpt==0 ){
  21473. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21474. return;
  21475. }
  21476. }
  21477. zOut = bufpt;
  21478. nsd = 16 + flag_altform2*10;
  21479. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  21480. /* The sign in front of the number */
  21481. if( prefix ){
  21482. *(bufpt++) = prefix;
  21483. }
  21484. /* Digits prior to the decimal point */
  21485. if( e2<0 ){
  21486. *(bufpt++) = '0';
  21487. }else{
  21488. for(; e2>=0; e2--){
  21489. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  21490. }
  21491. }
  21492. /* The decimal point */
  21493. if( flag_dp ){
  21494. *(bufpt++) = '.';
  21495. }
  21496. /* "0" digits after the decimal point but before the first
  21497. ** significant digit of the number */
  21498. for(e2++; e2<0; precision--, e2++){
  21499. assert( precision>0 );
  21500. *(bufpt++) = '0';
  21501. }
  21502. /* Significant digits after the decimal point */
  21503. while( (precision--)>0 ){
  21504. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  21505. }
  21506. /* Remove trailing zeros and the "." if no digits follow the "." */
  21507. if( flag_rtz && flag_dp ){
  21508. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  21509. assert( bufpt>zOut );
  21510. if( bufpt[-1]=='.' ){
  21511. if( flag_altform2 ){
  21512. *(bufpt++) = '0';
  21513. }else{
  21514. *(--bufpt) = 0;
  21515. }
  21516. }
  21517. }
  21518. /* Add the "eNNN" suffix */
  21519. if( xtype==etEXP ){
  21520. *(bufpt++) = aDigits[infop->charset];
  21521. if( exp<0 ){
  21522. *(bufpt++) = '-'; exp = -exp;
  21523. }else{
  21524. *(bufpt++) = '+';
  21525. }
  21526. if( exp>=100 ){
  21527. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  21528. exp %= 100;
  21529. }
  21530. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  21531. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  21532. }
  21533. *bufpt = 0;
  21534. /* The converted number is in buf[] and zero terminated. Output it.
  21535. ** Note that the number is in the usual order, not reversed as with
  21536. ** integer conversions. */
  21537. length = (int)(bufpt-zOut);
  21538. bufpt = zOut;
  21539. /* Special case: Add leading zeros if the flag_zeropad flag is
  21540. ** set and we are not left justified */
  21541. if( flag_zeropad && !flag_leftjustify && length < width){
  21542. int i;
  21543. int nPad = width - length;
  21544. for(i=width; i>=nPad; i--){
  21545. bufpt[i] = bufpt[i-nPad];
  21546. }
  21547. i = prefix!=0;
  21548. while( nPad-- ) bufpt[i++] = '0';
  21549. length = width;
  21550. }
  21551. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  21552. break;
  21553. case etSIZE:
  21554. if( !bArgList ){
  21555. *(va_arg(ap,int*)) = pAccum->nChar;
  21556. }
  21557. length = width = 0;
  21558. break;
  21559. case etPERCENT:
  21560. buf[0] = '%';
  21561. bufpt = buf;
  21562. length = 1;
  21563. break;
  21564. case etCHARX:
  21565. if( bArgList ){
  21566. bufpt = getTextArg(pArgList);
  21567. c = bufpt ? bufpt[0] : 0;
  21568. }else{
  21569. c = va_arg(ap,int);
  21570. }
  21571. if( precision>1 ){
  21572. width -= precision-1;
  21573. if( width>1 && !flag_leftjustify ){
  21574. sqlite3AppendChar(pAccum, width-1, ' ');
  21575. width = 0;
  21576. }
  21577. sqlite3AppendChar(pAccum, precision-1, c);
  21578. }
  21579. length = 1;
  21580. buf[0] = c;
  21581. bufpt = buf;
  21582. break;
  21583. case etSTRING:
  21584. case etDYNSTRING:
  21585. if( bArgList ){
  21586. bufpt = getTextArg(pArgList);
  21587. xtype = etSTRING;
  21588. }else{
  21589. bufpt = va_arg(ap,char*);
  21590. }
  21591. if( bufpt==0 ){
  21592. bufpt = "";
  21593. }else if( xtype==etDYNSTRING ){
  21594. zExtra = bufpt;
  21595. }
  21596. if( precision>=0 ){
  21597. for(length=0; length<precision && bufpt[length]; length++){}
  21598. }else{
  21599. length = sqlite3Strlen30(bufpt);
  21600. }
  21601. break;
  21602. case etSQLESCAPE: /* Escape ' characters */
  21603. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  21604. case etSQLESCAPE3: { /* Escape " characters */
  21605. int i, j, k, n, isnull;
  21606. int needQuote;
  21607. char ch;
  21608. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  21609. char *escarg;
  21610. if( bArgList ){
  21611. escarg = getTextArg(pArgList);
  21612. }else{
  21613. escarg = va_arg(ap,char*);
  21614. }
  21615. isnull = escarg==0;
  21616. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  21617. k = precision;
  21618. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  21619. if( ch==q ) n++;
  21620. }
  21621. needQuote = !isnull && xtype==etSQLESCAPE2;
  21622. n += i + 3;
  21623. if( n>etBUFSIZE ){
  21624. bufpt = zExtra = sqlite3Malloc( n );
  21625. if( bufpt==0 ){
  21626. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21627. return;
  21628. }
  21629. }else{
  21630. bufpt = buf;
  21631. }
  21632. j = 0;
  21633. if( needQuote ) bufpt[j++] = q;
  21634. k = i;
  21635. for(i=0; i<k; i++){
  21636. bufpt[j++] = ch = escarg[i];
  21637. if( ch==q ) bufpt[j++] = ch;
  21638. }
  21639. if( needQuote ) bufpt[j++] = q;
  21640. bufpt[j] = 0;
  21641. length = j;
  21642. /* The precision in %q and %Q means how many input characters to
  21643. ** consume, not the length of the output...
  21644. ** if( precision>=0 && precision<length ) length = precision; */
  21645. break;
  21646. }
  21647. case etTOKEN: {
  21648. Token *pToken = va_arg(ap, Token*);
  21649. assert( bArgList==0 );
  21650. if( pToken && pToken->n ){
  21651. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  21652. }
  21653. length = width = 0;
  21654. break;
  21655. }
  21656. case etSRCLIST: {
  21657. SrcList *pSrc = va_arg(ap, SrcList*);
  21658. int k = va_arg(ap, int);
  21659. struct SrcList_item *pItem = &pSrc->a[k];
  21660. assert( bArgList==0 );
  21661. assert( k>=0 && k<pSrc->nSrc );
  21662. if( pItem->zDatabase ){
  21663. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  21664. sqlite3StrAccumAppend(pAccum, ".", 1);
  21665. }
  21666. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  21667. length = width = 0;
  21668. break;
  21669. }
  21670. default: {
  21671. assert( xtype==etINVALID );
  21672. return;
  21673. }
  21674. }/* End switch over the format type */
  21675. /*
  21676. ** The text of the conversion is pointed to by "bufpt" and is
  21677. ** "length" characters long. The field width is "width". Do
  21678. ** the output.
  21679. */
  21680. width -= length;
  21681. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  21682. sqlite3StrAccumAppend(pAccum, bufpt, length);
  21683. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  21684. if( zExtra ){
  21685. sqlite3_free(zExtra);
  21686. zExtra = 0;
  21687. }
  21688. }/* End for loop over the format string */
  21689. } /* End of function */
  21690. /*
  21691. ** Enlarge the memory allocation on a StrAccum object so that it is
  21692. ** able to accept at least N more bytes of text.
  21693. **
  21694. ** Return the number of bytes of text that StrAccum is able to accept
  21695. ** after the attempted enlargement. The value returned might be zero.
  21696. */
  21697. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  21698. char *zNew;
  21699. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  21700. if( p->accError ){
  21701. testcase(p->accError==STRACCUM_TOOBIG);
  21702. testcase(p->accError==STRACCUM_NOMEM);
  21703. return 0;
  21704. }
  21705. if( p->mxAlloc==0 ){
  21706. N = p->nAlloc - p->nChar - 1;
  21707. setStrAccumError(p, STRACCUM_TOOBIG);
  21708. return N;
  21709. }else{
  21710. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  21711. i64 szNew = p->nChar;
  21712. szNew += N + 1;
  21713. if( szNew+p->nChar<=p->mxAlloc ){
  21714. /* Force exponential buffer size growth as long as it does not overflow,
  21715. ** to avoid having to call this routine too often */
  21716. szNew += p->nChar;
  21717. }
  21718. if( szNew > p->mxAlloc ){
  21719. sqlite3StrAccumReset(p);
  21720. setStrAccumError(p, STRACCUM_TOOBIG);
  21721. return 0;
  21722. }else{
  21723. p->nAlloc = (int)szNew;
  21724. }
  21725. if( p->db ){
  21726. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  21727. }else{
  21728. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  21729. }
  21730. if( zNew ){
  21731. assert( p->zText!=0 || p->nChar==0 );
  21732. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  21733. p->zText = zNew;
  21734. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  21735. }else{
  21736. sqlite3StrAccumReset(p);
  21737. setStrAccumError(p, STRACCUM_NOMEM);
  21738. return 0;
  21739. }
  21740. }
  21741. return N;
  21742. }
  21743. /*
  21744. ** Append N copies of character c to the given string buffer.
  21745. */
  21746. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  21747. testcase( p->nChar + (i64)N > 0x7fffffff );
  21748. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  21749. return;
  21750. }
  21751. while( (N--)>0 ) p->zText[p->nChar++] = c;
  21752. }
  21753. /*
  21754. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  21755. ** So enlarge if first, then do the append.
  21756. **
  21757. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  21758. ** work (enlarging the buffer) using tail recursion, so that the
  21759. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  21760. */
  21761. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  21762. N = sqlite3StrAccumEnlarge(p, N);
  21763. if( N>0 ){
  21764. memcpy(&p->zText[p->nChar], z, N);
  21765. p->nChar += N;
  21766. }
  21767. }
  21768. /*
  21769. ** Append N bytes of text from z to the StrAccum object. Increase the
  21770. ** size of the memory allocation for StrAccum if necessary.
  21771. */
  21772. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  21773. assert( z!=0 || N==0 );
  21774. assert( p->zText!=0 || p->nChar==0 || p->accError );
  21775. assert( N>=0 );
  21776. assert( p->accError==0 || p->nAlloc==0 );
  21777. if( p->nChar+N >= p->nAlloc ){
  21778. enlargeAndAppend(p,z,N);
  21779. }else{
  21780. assert( p->zText );
  21781. p->nChar += N;
  21782. memcpy(&p->zText[p->nChar-N], z, N);
  21783. }
  21784. }
  21785. /*
  21786. ** Append the complete text of zero-terminated string z[] to the p string.
  21787. */
  21788. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  21789. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  21790. }
  21791. /*
  21792. ** Finish off a string by making sure it is zero-terminated.
  21793. ** Return a pointer to the resulting string. Return a NULL
  21794. ** pointer if any kind of error was encountered.
  21795. */
  21796. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  21797. if( p->zText ){
  21798. p->zText[p->nChar] = 0;
  21799. if( p->mxAlloc>0 && p->zText==p->zBase ){
  21800. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  21801. if( p->zText ){
  21802. memcpy(p->zText, p->zBase, p->nChar+1);
  21803. }else{
  21804. setStrAccumError(p, STRACCUM_NOMEM);
  21805. }
  21806. }
  21807. }
  21808. return p->zText;
  21809. }
  21810. /*
  21811. ** Reset an StrAccum string. Reclaim all malloced memory.
  21812. */
  21813. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  21814. if( p->zText!=p->zBase ){
  21815. sqlite3DbFree(p->db, p->zText);
  21816. }
  21817. p->zText = 0;
  21818. }
  21819. /*
  21820. ** Initialize a string accumulator.
  21821. **
  21822. ** p: The accumulator to be initialized.
  21823. ** db: Pointer to a database connection. May be NULL. Lookaside
  21824. ** memory is used if not NULL. db->mallocFailed is set appropriately
  21825. ** when not NULL.
  21826. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  21827. ** is malloced.
  21828. ** n: Size of zBase in bytes. If total space requirements never exceed
  21829. ** n then no memory allocations ever occur.
  21830. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  21831. ** allocations will ever occur.
  21832. */
  21833. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  21834. p->zText = p->zBase = zBase;
  21835. p->db = db;
  21836. p->nChar = 0;
  21837. p->nAlloc = n;
  21838. p->mxAlloc = mx;
  21839. p->accError = 0;
  21840. }
  21841. /*
  21842. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21843. ** %-conversion extensions.
  21844. */
  21845. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  21846. char *z;
  21847. char zBase[SQLITE_PRINT_BUF_SIZE];
  21848. StrAccum acc;
  21849. assert( db!=0 );
  21850. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  21851. db->aLimit[SQLITE_LIMIT_LENGTH]);
  21852. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  21853. z = sqlite3StrAccumFinish(&acc);
  21854. if( acc.accError==STRACCUM_NOMEM ){
  21855. db->mallocFailed = 1;
  21856. }
  21857. return z;
  21858. }
  21859. /*
  21860. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21861. ** %-conversion extensions.
  21862. */
  21863. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  21864. va_list ap;
  21865. char *z;
  21866. va_start(ap, zFormat);
  21867. z = sqlite3VMPrintf(db, zFormat, ap);
  21868. va_end(ap);
  21869. return z;
  21870. }
  21871. /*
  21872. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  21873. ** %-conversion extensions.
  21874. */
  21875. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
  21876. char *z;
  21877. char zBase[SQLITE_PRINT_BUF_SIZE];
  21878. StrAccum acc;
  21879. #ifdef SQLITE_ENABLE_API_ARMOR
  21880. if( zFormat==0 ){
  21881. (void)SQLITE_MISUSE_BKPT;
  21882. return 0;
  21883. }
  21884. #endif
  21885. #ifndef SQLITE_OMIT_AUTOINIT
  21886. if( sqlite3_initialize() ) return 0;
  21887. #endif
  21888. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  21889. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21890. z = sqlite3StrAccumFinish(&acc);
  21891. return z;
  21892. }
  21893. /*
  21894. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  21895. ** %-conversion extensions.
  21896. */
  21897. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
  21898. va_list ap;
  21899. char *z;
  21900. #ifndef SQLITE_OMIT_AUTOINIT
  21901. if( sqlite3_initialize() ) return 0;
  21902. #endif
  21903. va_start(ap, zFormat);
  21904. z = sqlite3_vmprintf(zFormat, ap);
  21905. va_end(ap);
  21906. return z;
  21907. }
  21908. /*
  21909. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  21910. ** current locale settings. This is important for SQLite because we
  21911. ** are not able to use a "," as the decimal point in place of "." as
  21912. ** specified by some locales.
  21913. **
  21914. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  21915. ** from the snprintf() standard. Unfortunately, it is too late to change
  21916. ** this without breaking compatibility, so we just have to live with the
  21917. ** mistake.
  21918. **
  21919. ** sqlite3_vsnprintf() is the varargs version.
  21920. */
  21921. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  21922. StrAccum acc;
  21923. if( n<=0 ) return zBuf;
  21924. #ifdef SQLITE_ENABLE_API_ARMOR
  21925. if( zBuf==0 || zFormat==0 ) {
  21926. (void)SQLITE_MISUSE_BKPT;
  21927. if( zBuf ) zBuf[0] = 0;
  21928. return zBuf;
  21929. }
  21930. #endif
  21931. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  21932. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21933. return sqlite3StrAccumFinish(&acc);
  21934. }
  21935. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  21936. char *z;
  21937. va_list ap;
  21938. va_start(ap,zFormat);
  21939. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  21940. va_end(ap);
  21941. return z;
  21942. }
  21943. /*
  21944. ** This is the routine that actually formats the sqlite3_log() message.
  21945. ** We house it in a separate routine from sqlite3_log() to avoid using
  21946. ** stack space on small-stack systems when logging is disabled.
  21947. **
  21948. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  21949. ** allocate memory because it might be called while the memory allocator
  21950. ** mutex is held.
  21951. **
  21952. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  21953. ** certain format characters (%q) or for very large precisions or widths.
  21954. ** Care must be taken that any sqlite3_log() calls that occur while the
  21955. ** memory mutex is held do not use these mechanisms.
  21956. */
  21957. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  21958. StrAccum acc; /* String accumulator */
  21959. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  21960. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  21961. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21962. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  21963. sqlite3StrAccumFinish(&acc));
  21964. }
  21965. /*
  21966. ** Format and write a message to the log if logging is enabled.
  21967. */
  21968. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
  21969. va_list ap; /* Vararg list */
  21970. if( sqlite3GlobalConfig.xLog ){
  21971. va_start(ap, zFormat);
  21972. renderLogMsg(iErrCode, zFormat, ap);
  21973. va_end(ap);
  21974. }
  21975. }
  21976. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  21977. /*
  21978. ** A version of printf() that understands %lld. Used for debugging.
  21979. ** The printf() built into some versions of windows does not understand %lld
  21980. ** and segfaults if you give it a long long int.
  21981. */
  21982. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  21983. va_list ap;
  21984. StrAccum acc;
  21985. char zBuf[500];
  21986. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  21987. va_start(ap,zFormat);
  21988. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21989. va_end(ap);
  21990. sqlite3StrAccumFinish(&acc);
  21991. fprintf(stdout,"%s", zBuf);
  21992. fflush(stdout);
  21993. }
  21994. #endif
  21995. /*
  21996. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  21997. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  21998. */
  21999. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  22000. va_list ap;
  22001. va_start(ap,zFormat);
  22002. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  22003. va_end(ap);
  22004. }
  22005. /************** End of printf.c **********************************************/
  22006. /************** Begin file treeview.c ****************************************/
  22007. /*
  22008. ** 2015-06-08
  22009. **
  22010. ** The author disclaims copyright to this source code. In place of
  22011. ** a legal notice, here is a blessing:
  22012. **
  22013. ** May you do good and not evil.
  22014. ** May you find forgiveness for yourself and forgive others.
  22015. ** May you share freely, never taking more than you give.
  22016. **
  22017. *************************************************************************
  22018. **
  22019. ** This file contains C code to implement the TreeView debugging routines.
  22020. ** These routines print a parse tree to standard output for debugging and
  22021. ** analysis.
  22022. **
  22023. ** The interfaces in this file is only available when compiling
  22024. ** with SQLITE_DEBUG.
  22025. */
  22026. /* #include "sqliteInt.h" */
  22027. #ifdef SQLITE_DEBUG
  22028. /*
  22029. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  22030. ** is not the last item in the tree.
  22031. */
  22032. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  22033. if( p==0 ){
  22034. p = sqlite3_malloc64( sizeof(*p) );
  22035. if( p==0 ) return 0;
  22036. memset(p, 0, sizeof(*p));
  22037. }else{
  22038. p->iLevel++;
  22039. }
  22040. assert( moreToFollow==0 || moreToFollow==1 );
  22041. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  22042. return p;
  22043. }
  22044. /*
  22045. ** Finished with one layer of the tree
  22046. */
  22047. static void sqlite3TreeViewPop(TreeView *p){
  22048. if( p==0 ) return;
  22049. p->iLevel--;
  22050. if( p->iLevel<0 ) sqlite3_free(p);
  22051. }
  22052. /*
  22053. ** Generate a single line of output for the tree, with a prefix that contains
  22054. ** all the appropriate tree lines
  22055. */
  22056. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  22057. va_list ap;
  22058. int i;
  22059. StrAccum acc;
  22060. char zBuf[500];
  22061. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  22062. if( p ){
  22063. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  22064. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  22065. }
  22066. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  22067. }
  22068. va_start(ap, zFormat);
  22069. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22070. va_end(ap);
  22071. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  22072. sqlite3StrAccumFinish(&acc);
  22073. fprintf(stdout,"%s", zBuf);
  22074. fflush(stdout);
  22075. }
  22076. /*
  22077. ** Shorthand for starting a new tree item that consists of a single label
  22078. */
  22079. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  22080. p = sqlite3TreeViewPush(p, moreFollows);
  22081. sqlite3TreeViewLine(p, "%s", zLabel);
  22082. }
  22083. /*
  22084. ** Generate a human-readable description of a the Select object.
  22085. */
  22086. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  22087. int n = 0;
  22088. int cnt = 0;
  22089. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22090. do{
  22091. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x",
  22092. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  22093. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags
  22094. );
  22095. if( cnt++ ) sqlite3TreeViewPop(pView);
  22096. if( p->pPrior ){
  22097. n = 1000;
  22098. }else{
  22099. n = 0;
  22100. if( p->pSrc && p->pSrc->nSrc ) n++;
  22101. if( p->pWhere ) n++;
  22102. if( p->pGroupBy ) n++;
  22103. if( p->pHaving ) n++;
  22104. if( p->pOrderBy ) n++;
  22105. if( p->pLimit ) n++;
  22106. if( p->pOffset ) n++;
  22107. }
  22108. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  22109. if( p->pSrc && p->pSrc->nSrc ){
  22110. int i;
  22111. pView = sqlite3TreeViewPush(pView, (n--)>0);
  22112. sqlite3TreeViewLine(pView, "FROM");
  22113. for(i=0; i<p->pSrc->nSrc; i++){
  22114. struct SrcList_item *pItem = &p->pSrc->a[i];
  22115. StrAccum x;
  22116. char zLine[100];
  22117. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  22118. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  22119. if( pItem->zDatabase ){
  22120. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  22121. }else if( pItem->zName ){
  22122. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  22123. }
  22124. if( pItem->pTab ){
  22125. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  22126. }
  22127. if( pItem->zAlias ){
  22128. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  22129. }
  22130. if( pItem->fg.jointype & JT_LEFT ){
  22131. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  22132. }
  22133. sqlite3StrAccumFinish(&x);
  22134. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  22135. if( pItem->pSelect ){
  22136. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  22137. }
  22138. if( pItem->fg.isTabFunc ){
  22139. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  22140. }
  22141. sqlite3TreeViewPop(pView);
  22142. }
  22143. sqlite3TreeViewPop(pView);
  22144. }
  22145. if( p->pWhere ){
  22146. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  22147. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  22148. sqlite3TreeViewPop(pView);
  22149. }
  22150. if( p->pGroupBy ){
  22151. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  22152. }
  22153. if( p->pHaving ){
  22154. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  22155. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  22156. sqlite3TreeViewPop(pView);
  22157. }
  22158. if( p->pOrderBy ){
  22159. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  22160. }
  22161. if( p->pLimit ){
  22162. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  22163. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  22164. sqlite3TreeViewPop(pView);
  22165. }
  22166. if( p->pOffset ){
  22167. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  22168. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  22169. sqlite3TreeViewPop(pView);
  22170. }
  22171. if( p->pPrior ){
  22172. const char *zOp = "UNION";
  22173. switch( p->op ){
  22174. case TK_ALL: zOp = "UNION ALL"; break;
  22175. case TK_INTERSECT: zOp = "INTERSECT"; break;
  22176. case TK_EXCEPT: zOp = "EXCEPT"; break;
  22177. }
  22178. sqlite3TreeViewItem(pView, zOp, 1);
  22179. }
  22180. p = p->pPrior;
  22181. }while( p!=0 );
  22182. sqlite3TreeViewPop(pView);
  22183. }
  22184. /*
  22185. ** Generate a human-readable explanation of an expression tree.
  22186. */
  22187. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  22188. const char *zBinOp = 0; /* Binary operator */
  22189. const char *zUniOp = 0; /* Unary operator */
  22190. char zFlgs[30];
  22191. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22192. if( pExpr==0 ){
  22193. sqlite3TreeViewLine(pView, "nil");
  22194. sqlite3TreeViewPop(pView);
  22195. return;
  22196. }
  22197. if( pExpr->flags ){
  22198. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  22199. }else{
  22200. zFlgs[0] = 0;
  22201. }
  22202. switch( pExpr->op ){
  22203. case TK_AGG_COLUMN: {
  22204. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  22205. pExpr->iTable, pExpr->iColumn, zFlgs);
  22206. break;
  22207. }
  22208. case TK_COLUMN: {
  22209. if( pExpr->iTable<0 ){
  22210. /* This only happens when coding check constraints */
  22211. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  22212. }else{
  22213. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  22214. pExpr->iTable, pExpr->iColumn, zFlgs);
  22215. }
  22216. break;
  22217. }
  22218. case TK_INTEGER: {
  22219. if( pExpr->flags & EP_IntValue ){
  22220. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  22221. }else{
  22222. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  22223. }
  22224. break;
  22225. }
  22226. #ifndef SQLITE_OMIT_FLOATING_POINT
  22227. case TK_FLOAT: {
  22228. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  22229. break;
  22230. }
  22231. #endif
  22232. case TK_STRING: {
  22233. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  22234. break;
  22235. }
  22236. case TK_NULL: {
  22237. sqlite3TreeViewLine(pView,"NULL");
  22238. break;
  22239. }
  22240. #ifndef SQLITE_OMIT_BLOB_LITERAL
  22241. case TK_BLOB: {
  22242. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  22243. break;
  22244. }
  22245. #endif
  22246. case TK_VARIABLE: {
  22247. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  22248. pExpr->u.zToken, pExpr->iColumn);
  22249. break;
  22250. }
  22251. case TK_REGISTER: {
  22252. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  22253. break;
  22254. }
  22255. case TK_ID: {
  22256. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  22257. break;
  22258. }
  22259. #ifndef SQLITE_OMIT_CAST
  22260. case TK_CAST: {
  22261. /* Expressions of the form: CAST(pLeft AS token) */
  22262. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  22263. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22264. break;
  22265. }
  22266. #endif /* SQLITE_OMIT_CAST */
  22267. case TK_LT: zBinOp = "LT"; break;
  22268. case TK_LE: zBinOp = "LE"; break;
  22269. case TK_GT: zBinOp = "GT"; break;
  22270. case TK_GE: zBinOp = "GE"; break;
  22271. case TK_NE: zBinOp = "NE"; break;
  22272. case TK_EQ: zBinOp = "EQ"; break;
  22273. case TK_IS: zBinOp = "IS"; break;
  22274. case TK_ISNOT: zBinOp = "ISNOT"; break;
  22275. case TK_AND: zBinOp = "AND"; break;
  22276. case TK_OR: zBinOp = "OR"; break;
  22277. case TK_PLUS: zBinOp = "ADD"; break;
  22278. case TK_STAR: zBinOp = "MUL"; break;
  22279. case TK_MINUS: zBinOp = "SUB"; break;
  22280. case TK_REM: zBinOp = "REM"; break;
  22281. case TK_BITAND: zBinOp = "BITAND"; break;
  22282. case TK_BITOR: zBinOp = "BITOR"; break;
  22283. case TK_SLASH: zBinOp = "DIV"; break;
  22284. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  22285. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  22286. case TK_CONCAT: zBinOp = "CONCAT"; break;
  22287. case TK_DOT: zBinOp = "DOT"; break;
  22288. case TK_UMINUS: zUniOp = "UMINUS"; break;
  22289. case TK_UPLUS: zUniOp = "UPLUS"; break;
  22290. case TK_BITNOT: zUniOp = "BITNOT"; break;
  22291. case TK_NOT: zUniOp = "NOT"; break;
  22292. case TK_ISNULL: zUniOp = "ISNULL"; break;
  22293. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  22294. case TK_COLLATE: {
  22295. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  22296. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22297. break;
  22298. }
  22299. case TK_AGG_FUNCTION:
  22300. case TK_FUNCTION: {
  22301. ExprList *pFarg; /* List of function arguments */
  22302. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  22303. pFarg = 0;
  22304. }else{
  22305. pFarg = pExpr->x.pList;
  22306. }
  22307. if( pExpr->op==TK_AGG_FUNCTION ){
  22308. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  22309. pExpr->op2, pExpr->u.zToken);
  22310. }else{
  22311. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  22312. }
  22313. if( pFarg ){
  22314. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  22315. }
  22316. break;
  22317. }
  22318. #ifndef SQLITE_OMIT_SUBQUERY
  22319. case TK_EXISTS: {
  22320. sqlite3TreeViewLine(pView, "EXISTS-expr");
  22321. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22322. break;
  22323. }
  22324. case TK_SELECT: {
  22325. sqlite3TreeViewLine(pView, "SELECT-expr");
  22326. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22327. break;
  22328. }
  22329. case TK_IN: {
  22330. sqlite3TreeViewLine(pView, "IN");
  22331. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22332. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  22333. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22334. }else{
  22335. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  22336. }
  22337. break;
  22338. }
  22339. #endif /* SQLITE_OMIT_SUBQUERY */
  22340. /*
  22341. ** x BETWEEN y AND z
  22342. **
  22343. ** This is equivalent to
  22344. **
  22345. ** x>=y AND x<=z
  22346. **
  22347. ** X is stored in pExpr->pLeft.
  22348. ** Y is stored in pExpr->pList->a[0].pExpr.
  22349. ** Z is stored in pExpr->pList->a[1].pExpr.
  22350. */
  22351. case TK_BETWEEN: {
  22352. Expr *pX = pExpr->pLeft;
  22353. Expr *pY = pExpr->x.pList->a[0].pExpr;
  22354. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  22355. sqlite3TreeViewLine(pView, "BETWEEN");
  22356. sqlite3TreeViewExpr(pView, pX, 1);
  22357. sqlite3TreeViewExpr(pView, pY, 1);
  22358. sqlite3TreeViewExpr(pView, pZ, 0);
  22359. break;
  22360. }
  22361. case TK_TRIGGER: {
  22362. /* If the opcode is TK_TRIGGER, then the expression is a reference
  22363. ** to a column in the new.* or old.* pseudo-tables available to
  22364. ** trigger programs. In this case Expr.iTable is set to 1 for the
  22365. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  22366. ** is set to the column of the pseudo-table to read, or to -1 to
  22367. ** read the rowid field.
  22368. */
  22369. sqlite3TreeViewLine(pView, "%s(%d)",
  22370. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  22371. break;
  22372. }
  22373. case TK_CASE: {
  22374. sqlite3TreeViewLine(pView, "CASE");
  22375. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22376. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  22377. break;
  22378. }
  22379. #ifndef SQLITE_OMIT_TRIGGER
  22380. case TK_RAISE: {
  22381. const char *zType = "unk";
  22382. switch( pExpr->affinity ){
  22383. case OE_Rollback: zType = "rollback"; break;
  22384. case OE_Abort: zType = "abort"; break;
  22385. case OE_Fail: zType = "fail"; break;
  22386. case OE_Ignore: zType = "ignore"; break;
  22387. }
  22388. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  22389. break;
  22390. }
  22391. #endif
  22392. default: {
  22393. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  22394. break;
  22395. }
  22396. }
  22397. if( zBinOp ){
  22398. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  22399. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22400. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  22401. }else if( zUniOp ){
  22402. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  22403. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22404. }
  22405. sqlite3TreeViewPop(pView);
  22406. }
  22407. /*
  22408. ** Generate a human-readable explanation of an expression list.
  22409. */
  22410. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  22411. TreeView *pView,
  22412. const ExprList *pList,
  22413. u8 moreToFollow,
  22414. const char *zLabel
  22415. ){
  22416. int i;
  22417. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22418. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  22419. if( pList==0 ){
  22420. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  22421. }else{
  22422. sqlite3TreeViewLine(pView, "%s", zLabel);
  22423. for(i=0; i<pList->nExpr; i++){
  22424. int j = pList->a[i].u.x.iOrderByCol;
  22425. if( j ){
  22426. sqlite3TreeViewPush(pView, 0);
  22427. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  22428. }
  22429. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  22430. if( j ) sqlite3TreeViewPop(pView);
  22431. }
  22432. }
  22433. sqlite3TreeViewPop(pView);
  22434. }
  22435. #endif /* SQLITE_DEBUG */
  22436. /************** End of treeview.c ********************************************/
  22437. /************** Begin file random.c ******************************************/
  22438. /*
  22439. ** 2001 September 15
  22440. **
  22441. ** The author disclaims copyright to this source code. In place of
  22442. ** a legal notice, here is a blessing:
  22443. **
  22444. ** May you do good and not evil.
  22445. ** May you find forgiveness for yourself and forgive others.
  22446. ** May you share freely, never taking more than you give.
  22447. **
  22448. *************************************************************************
  22449. ** This file contains code to implement a pseudo-random number
  22450. ** generator (PRNG) for SQLite.
  22451. **
  22452. ** Random numbers are used by some of the database backends in order
  22453. ** to generate random integer keys for tables or random filenames.
  22454. */
  22455. /* #include "sqliteInt.h" */
  22456. /* All threads share a single random number generator.
  22457. ** This structure is the current state of the generator.
  22458. */
  22459. static SQLITE_WSD struct sqlite3PrngType {
  22460. unsigned char isInit; /* True if initialized */
  22461. unsigned char i, j; /* State variables */
  22462. unsigned char s[256]; /* State variables */
  22463. } sqlite3Prng;
  22464. /*
  22465. ** Return N random bytes.
  22466. */
  22467. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
  22468. unsigned char t;
  22469. unsigned char *zBuf = pBuf;
  22470. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  22471. ** state vector. If writable static data is unsupported on the target,
  22472. ** we have to locate the state vector at run-time. In the more common
  22473. ** case where writable static data is supported, wsdPrng can refer directly
  22474. ** to the "sqlite3Prng" state vector declared above.
  22475. */
  22476. #ifdef SQLITE_OMIT_WSD
  22477. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  22478. # define wsdPrng p[0]
  22479. #else
  22480. # define wsdPrng sqlite3Prng
  22481. #endif
  22482. #if SQLITE_THREADSAFE
  22483. sqlite3_mutex *mutex;
  22484. #endif
  22485. #ifndef SQLITE_OMIT_AUTOINIT
  22486. if( sqlite3_initialize() ) return;
  22487. #endif
  22488. #if SQLITE_THREADSAFE
  22489. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  22490. #endif
  22491. sqlite3_mutex_enter(mutex);
  22492. if( N<=0 || pBuf==0 ){
  22493. wsdPrng.isInit = 0;
  22494. sqlite3_mutex_leave(mutex);
  22495. return;
  22496. }
  22497. /* Initialize the state of the random number generator once,
  22498. ** the first time this routine is called. The seed value does
  22499. ** not need to contain a lot of randomness since we are not
  22500. ** trying to do secure encryption or anything like that...
  22501. **
  22502. ** Nothing in this file or anywhere else in SQLite does any kind of
  22503. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  22504. ** number generator) not as an encryption device.
  22505. */
  22506. if( !wsdPrng.isInit ){
  22507. int i;
  22508. char k[256];
  22509. wsdPrng.j = 0;
  22510. wsdPrng.i = 0;
  22511. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  22512. for(i=0; i<256; i++){
  22513. wsdPrng.s[i] = (u8)i;
  22514. }
  22515. for(i=0; i<256; i++){
  22516. wsdPrng.j += wsdPrng.s[i] + k[i];
  22517. t = wsdPrng.s[wsdPrng.j];
  22518. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  22519. wsdPrng.s[i] = t;
  22520. }
  22521. wsdPrng.isInit = 1;
  22522. }
  22523. assert( N>0 );
  22524. do{
  22525. wsdPrng.i++;
  22526. t = wsdPrng.s[wsdPrng.i];
  22527. wsdPrng.j += t;
  22528. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  22529. wsdPrng.s[wsdPrng.j] = t;
  22530. t += wsdPrng.s[wsdPrng.i];
  22531. *(zBuf++) = wsdPrng.s[t];
  22532. }while( --N );
  22533. sqlite3_mutex_leave(mutex);
  22534. }
  22535. #ifndef SQLITE_OMIT_BUILTIN_TEST
  22536. /*
  22537. ** For testing purposes, we sometimes want to preserve the state of
  22538. ** PRNG and restore the PRNG to its saved state at a later time, or
  22539. ** to reset the PRNG to its initial state. These routines accomplish
  22540. ** those tasks.
  22541. **
  22542. ** The sqlite3_test_control() interface calls these routines to
  22543. ** control the PRNG.
  22544. */
  22545. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  22546. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  22547. memcpy(
  22548. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  22549. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  22550. sizeof(sqlite3Prng)
  22551. );
  22552. }
  22553. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  22554. memcpy(
  22555. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  22556. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  22557. sizeof(sqlite3Prng)
  22558. );
  22559. }
  22560. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  22561. /************** End of random.c **********************************************/
  22562. /************** Begin file threads.c *****************************************/
  22563. /*
  22564. ** 2012 July 21
  22565. **
  22566. ** The author disclaims copyright to this source code. In place of
  22567. ** a legal notice, here is a blessing:
  22568. **
  22569. ** May you do good and not evil.
  22570. ** May you find forgiveness for yourself and forgive others.
  22571. ** May you share freely, never taking more than you give.
  22572. **
  22573. ******************************************************************************
  22574. **
  22575. ** This file presents a simple cross-platform threading interface for
  22576. ** use internally by SQLite.
  22577. **
  22578. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  22579. ** runs independently of its creator until it is joined using
  22580. ** sqlite3ThreadJoin(), at which point it terminates.
  22581. **
  22582. ** Threads do not have to be real. It could be that the work of the
  22583. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  22584. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  22585. ** single threaded systems. Nothing in SQLite requires multiple threads.
  22586. ** This interface exists so that applications that want to take advantage
  22587. ** of multiple cores can do so, while also allowing applications to stay
  22588. ** single-threaded if desired.
  22589. */
  22590. /* #include "sqliteInt.h" */
  22591. #if SQLITE_OS_WIN
  22592. /* # include "os_win.h" */
  22593. #endif
  22594. #if SQLITE_MAX_WORKER_THREADS>0
  22595. /********************************* Unix Pthreads ****************************/
  22596. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  22597. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  22598. /* #include <pthread.h> */
  22599. /* A running thread */
  22600. struct SQLiteThread {
  22601. pthread_t tid; /* Thread ID */
  22602. int done; /* Set to true when thread finishes */
  22603. void *pOut; /* Result returned by the thread */
  22604. void *(*xTask)(void*); /* The thread routine */
  22605. void *pIn; /* Argument to the thread */
  22606. };
  22607. /* Create a new thread */
  22608. SQLITE_PRIVATE int sqlite3ThreadCreate(
  22609. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  22610. void *(*xTask)(void*), /* Routine to run in a separate thread */
  22611. void *pIn /* Argument passed into xTask() */
  22612. ){
  22613. SQLiteThread *p;
  22614. int rc;
  22615. assert( ppThread!=0 );
  22616. assert( xTask!=0 );
  22617. /* This routine is never used in single-threaded mode */
  22618. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  22619. *ppThread = 0;
  22620. p = sqlite3Malloc(sizeof(*p));
  22621. if( p==0 ) return SQLITE_NOMEM;
  22622. memset(p, 0, sizeof(*p));
  22623. p->xTask = xTask;
  22624. p->pIn = pIn;
  22625. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  22626. ** function that returns SQLITE_ERROR when passed the argument 200, that
  22627. ** forces worker threads to run sequentially and deterministically
  22628. ** for testing purposes. */
  22629. if( sqlite3FaultSim(200) ){
  22630. rc = 1;
  22631. }else{
  22632. rc = pthread_create(&p->tid, 0, xTask, pIn);
  22633. }
  22634. if( rc ){
  22635. p->done = 1;
  22636. p->pOut = xTask(pIn);
  22637. }
  22638. *ppThread = p;
  22639. return SQLITE_OK;
  22640. }
  22641. /* Get the results of the thread */
  22642. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22643. int rc;
  22644. assert( ppOut!=0 );
  22645. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22646. if( p->done ){
  22647. *ppOut = p->pOut;
  22648. rc = SQLITE_OK;
  22649. }else{
  22650. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  22651. }
  22652. sqlite3_free(p);
  22653. return rc;
  22654. }
  22655. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  22656. /******************************** End Unix Pthreads *************************/
  22657. /********************************* Win32 Threads ****************************/
  22658. #if SQLITE_OS_WIN_THREADS
  22659. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  22660. #include <process.h>
  22661. /* A running thread */
  22662. struct SQLiteThread {
  22663. void *tid; /* The thread handle */
  22664. unsigned id; /* The thread identifier */
  22665. void *(*xTask)(void*); /* The routine to run as a thread */
  22666. void *pIn; /* Argument to xTask */
  22667. void *pResult; /* Result of xTask */
  22668. };
  22669. /* Thread procedure Win32 compatibility shim */
  22670. static unsigned __stdcall sqlite3ThreadProc(
  22671. void *pArg /* IN: Pointer to the SQLiteThread structure */
  22672. ){
  22673. SQLiteThread *p = (SQLiteThread *)pArg;
  22674. assert( p!=0 );
  22675. #if 0
  22676. /*
  22677. ** This assert appears to trigger spuriously on certain
  22678. ** versions of Windows, possibly due to _beginthreadex()
  22679. ** and/or CreateThread() not fully setting their thread
  22680. ** ID parameter before starting the thread.
  22681. */
  22682. assert( p->id==GetCurrentThreadId() );
  22683. #endif
  22684. assert( p->xTask!=0 );
  22685. p->pResult = p->xTask(p->pIn);
  22686. _endthreadex(0);
  22687. return 0; /* NOT REACHED */
  22688. }
  22689. /* Create a new thread */
  22690. SQLITE_PRIVATE int sqlite3ThreadCreate(
  22691. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  22692. void *(*xTask)(void*), /* Routine to run in a separate thread */
  22693. void *pIn /* Argument passed into xTask() */
  22694. ){
  22695. SQLiteThread *p;
  22696. assert( ppThread!=0 );
  22697. assert( xTask!=0 );
  22698. *ppThread = 0;
  22699. p = sqlite3Malloc(sizeof(*p));
  22700. if( p==0 ) return SQLITE_NOMEM;
  22701. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  22702. ** function that returns SQLITE_ERROR when passed the argument 200, that
  22703. ** forces worker threads to run sequentially and deterministically
  22704. ** (via the sqlite3FaultSim() term of the conditional) for testing
  22705. ** purposes. */
  22706. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  22707. memset(p, 0, sizeof(*p));
  22708. }else{
  22709. p->xTask = xTask;
  22710. p->pIn = pIn;
  22711. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  22712. if( p->tid==0 ){
  22713. memset(p, 0, sizeof(*p));
  22714. }
  22715. }
  22716. if( p->xTask==0 ){
  22717. p->id = GetCurrentThreadId();
  22718. p->pResult = xTask(pIn);
  22719. }
  22720. *ppThread = p;
  22721. return SQLITE_OK;
  22722. }
  22723. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  22724. /* Get the results of the thread */
  22725. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22726. DWORD rc;
  22727. BOOL bRc;
  22728. assert( ppOut!=0 );
  22729. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22730. if( p->xTask==0 ){
  22731. /* assert( p->id==GetCurrentThreadId() ); */
  22732. rc = WAIT_OBJECT_0;
  22733. assert( p->tid==0 );
  22734. }else{
  22735. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  22736. rc = sqlite3Win32Wait((HANDLE)p->tid);
  22737. assert( rc!=WAIT_IO_COMPLETION );
  22738. bRc = CloseHandle((HANDLE)p->tid);
  22739. assert( bRc );
  22740. }
  22741. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  22742. sqlite3_free(p);
  22743. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  22744. }
  22745. #endif /* SQLITE_OS_WIN_THREADS */
  22746. /******************************** End Win32 Threads *************************/
  22747. /********************************* Single-Threaded **************************/
  22748. #ifndef SQLITE_THREADS_IMPLEMENTED
  22749. /*
  22750. ** This implementation does not actually create a new thread. It does the
  22751. ** work of the thread in the main thread, when either the thread is created
  22752. ** or when it is joined
  22753. */
  22754. /* A running thread */
  22755. struct SQLiteThread {
  22756. void *(*xTask)(void*); /* The routine to run as a thread */
  22757. void *pIn; /* Argument to xTask */
  22758. void *pResult; /* Result of xTask */
  22759. };
  22760. /* Create a new thread */
  22761. SQLITE_PRIVATE int sqlite3ThreadCreate(
  22762. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  22763. void *(*xTask)(void*), /* Routine to run in a separate thread */
  22764. void *pIn /* Argument passed into xTask() */
  22765. ){
  22766. SQLiteThread *p;
  22767. assert( ppThread!=0 );
  22768. assert( xTask!=0 );
  22769. *ppThread = 0;
  22770. p = sqlite3Malloc(sizeof(*p));
  22771. if( p==0 ) return SQLITE_NOMEM;
  22772. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  22773. p->xTask = xTask;
  22774. p->pIn = pIn;
  22775. }else{
  22776. p->xTask = 0;
  22777. p->pResult = xTask(pIn);
  22778. }
  22779. *ppThread = p;
  22780. return SQLITE_OK;
  22781. }
  22782. /* Get the results of the thread */
  22783. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22784. assert( ppOut!=0 );
  22785. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22786. if( p->xTask ){
  22787. *ppOut = p->xTask(p->pIn);
  22788. }else{
  22789. *ppOut = p->pResult;
  22790. }
  22791. sqlite3_free(p);
  22792. #if defined(SQLITE_TEST)
  22793. {
  22794. void *pTstAlloc = sqlite3Malloc(10);
  22795. if (!pTstAlloc) return SQLITE_NOMEM;
  22796. sqlite3_free(pTstAlloc);
  22797. }
  22798. #endif
  22799. return SQLITE_OK;
  22800. }
  22801. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  22802. /****************************** End Single-Threaded *************************/
  22803. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  22804. /************** End of threads.c *********************************************/
  22805. /************** Begin file utf.c *********************************************/
  22806. /*
  22807. ** 2004 April 13
  22808. **
  22809. ** The author disclaims copyright to this source code. In place of
  22810. ** a legal notice, here is a blessing:
  22811. **
  22812. ** May you do good and not evil.
  22813. ** May you find forgiveness for yourself and forgive others.
  22814. ** May you share freely, never taking more than you give.
  22815. **
  22816. *************************************************************************
  22817. ** This file contains routines used to translate between UTF-8,
  22818. ** UTF-16, UTF-16BE, and UTF-16LE.
  22819. **
  22820. ** Notes on UTF-8:
  22821. **
  22822. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  22823. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  22824. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  22825. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  22826. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  22827. **
  22828. **
  22829. ** Notes on UTF-16: (with wwww+1==uuuuu)
  22830. **
  22831. ** Word-0 Word-1 Value
  22832. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  22833. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  22834. **
  22835. **
  22836. ** BOM or Byte Order Mark:
  22837. ** 0xff 0xfe little-endian utf-16 follows
  22838. ** 0xfe 0xff big-endian utf-16 follows
  22839. **
  22840. */
  22841. /* #include "sqliteInt.h" */
  22842. /* #include <assert.h> */
  22843. /* #include "vdbeInt.h" */
  22844. #ifndef SQLITE_AMALGAMATION
  22845. /*
  22846. ** The following constant value is used by the SQLITE_BIGENDIAN and
  22847. ** SQLITE_LITTLEENDIAN macros.
  22848. */
  22849. SQLITE_PRIVATE const int sqlite3one = 1;
  22850. #endif /* SQLITE_AMALGAMATION */
  22851. /*
  22852. ** This lookup table is used to help decode the first byte of
  22853. ** a multi-byte UTF8 character.
  22854. */
  22855. static const unsigned char sqlite3Utf8Trans1[] = {
  22856. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22857. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  22858. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  22859. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  22860. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22861. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  22862. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22863. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  22864. };
  22865. #define WRITE_UTF8(zOut, c) { \
  22866. if( c<0x00080 ){ \
  22867. *zOut++ = (u8)(c&0xFF); \
  22868. } \
  22869. else if( c<0x00800 ){ \
  22870. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  22871. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22872. } \
  22873. else if( c<0x10000 ){ \
  22874. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  22875. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  22876. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22877. }else{ \
  22878. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  22879. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  22880. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  22881. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22882. } \
  22883. }
  22884. #define WRITE_UTF16LE(zOut, c) { \
  22885. if( c<=0xFFFF ){ \
  22886. *zOut++ = (u8)(c&0x00FF); \
  22887. *zOut++ = (u8)((c>>8)&0x00FF); \
  22888. }else{ \
  22889. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  22890. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  22891. *zOut++ = (u8)(c&0x00FF); \
  22892. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  22893. } \
  22894. }
  22895. #define WRITE_UTF16BE(zOut, c) { \
  22896. if( c<=0xFFFF ){ \
  22897. *zOut++ = (u8)((c>>8)&0x00FF); \
  22898. *zOut++ = (u8)(c&0x00FF); \
  22899. }else{ \
  22900. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  22901. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  22902. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  22903. *zOut++ = (u8)(c&0x00FF); \
  22904. } \
  22905. }
  22906. #define READ_UTF16LE(zIn, TERM, c){ \
  22907. c = (*zIn++); \
  22908. c += ((*zIn++)<<8); \
  22909. if( c>=0xD800 && c<0xE000 && TERM ){ \
  22910. int c2 = (*zIn++); \
  22911. c2 += ((*zIn++)<<8); \
  22912. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  22913. } \
  22914. }
  22915. #define READ_UTF16BE(zIn, TERM, c){ \
  22916. c = ((*zIn++)<<8); \
  22917. c += (*zIn++); \
  22918. if( c>=0xD800 && c<0xE000 && TERM ){ \
  22919. int c2 = ((*zIn++)<<8); \
  22920. c2 += (*zIn++); \
  22921. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  22922. } \
  22923. }
  22924. /*
  22925. ** Translate a single UTF-8 character. Return the unicode value.
  22926. **
  22927. ** During translation, assume that the byte that zTerm points
  22928. ** is a 0x00.
  22929. **
  22930. ** Write a pointer to the next unread byte back into *pzNext.
  22931. **
  22932. ** Notes On Invalid UTF-8:
  22933. **
  22934. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  22935. ** be encoded as a multi-byte character. Any multi-byte character that
  22936. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  22937. **
  22938. ** * This routine never allows a UTF16 surrogate value to be encoded.
  22939. ** If a multi-byte character attempts to encode a value between
  22940. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  22941. **
  22942. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  22943. ** byte of a character are interpreted as single-byte characters
  22944. ** and rendered as themselves even though they are technically
  22945. ** invalid characters.
  22946. **
  22947. ** * This routine accepts over-length UTF8 encodings
  22948. ** for unicode values 0x80 and greater. It does not change over-length
  22949. ** encodings to 0xfffd as some systems recommend.
  22950. */
  22951. #define READ_UTF8(zIn, zTerm, c) \
  22952. c = *(zIn++); \
  22953. if( c>=0xc0 ){ \
  22954. c = sqlite3Utf8Trans1[c-0xc0]; \
  22955. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  22956. c = (c<<6) + (0x3f & *(zIn++)); \
  22957. } \
  22958. if( c<0x80 \
  22959. || (c&0xFFFFF800)==0xD800 \
  22960. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  22961. }
  22962. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  22963. const unsigned char **pz /* Pointer to string from which to read char */
  22964. ){
  22965. unsigned int c;
  22966. /* Same as READ_UTF8() above but without the zTerm parameter.
  22967. ** For this routine, we assume the UTF8 string is always zero-terminated.
  22968. */
  22969. c = *((*pz)++);
  22970. if( c>=0xc0 ){
  22971. c = sqlite3Utf8Trans1[c-0xc0];
  22972. while( (*(*pz) & 0xc0)==0x80 ){
  22973. c = (c<<6) + (0x3f & *((*pz)++));
  22974. }
  22975. if( c<0x80
  22976. || (c&0xFFFFF800)==0xD800
  22977. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  22978. }
  22979. return c;
  22980. }
  22981. /*
  22982. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  22983. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  22984. */
  22985. /* #define TRANSLATE_TRACE 1 */
  22986. #ifndef SQLITE_OMIT_UTF16
  22987. /*
  22988. ** This routine transforms the internal text encoding used by pMem to
  22989. ** desiredEnc. It is an error if the string is already of the desired
  22990. ** encoding, or if *pMem does not contain a string value.
  22991. */
  22992. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  22993. int len; /* Maximum length of output string in bytes */
  22994. unsigned char *zOut; /* Output buffer */
  22995. unsigned char *zIn; /* Input iterator */
  22996. unsigned char *zTerm; /* End of input */
  22997. unsigned char *z; /* Output iterator */
  22998. unsigned int c;
  22999. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  23000. assert( pMem->flags&MEM_Str );
  23001. assert( pMem->enc!=desiredEnc );
  23002. assert( pMem->enc!=0 );
  23003. assert( pMem->n>=0 );
  23004. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23005. {
  23006. char zBuf[100];
  23007. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23008. fprintf(stderr, "INPUT: %s\n", zBuf);
  23009. }
  23010. #endif
  23011. /* If the translation is between UTF-16 little and big endian, then
  23012. ** all that is required is to swap the byte order. This case is handled
  23013. ** differently from the others.
  23014. */
  23015. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  23016. u8 temp;
  23017. int rc;
  23018. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23019. if( rc!=SQLITE_OK ){
  23020. assert( rc==SQLITE_NOMEM );
  23021. return SQLITE_NOMEM;
  23022. }
  23023. zIn = (u8*)pMem->z;
  23024. zTerm = &zIn[pMem->n&~1];
  23025. while( zIn<zTerm ){
  23026. temp = *zIn;
  23027. *zIn = *(zIn+1);
  23028. zIn++;
  23029. *zIn++ = temp;
  23030. }
  23031. pMem->enc = desiredEnc;
  23032. goto translate_out;
  23033. }
  23034. /* Set len to the maximum number of bytes required in the output buffer. */
  23035. if( desiredEnc==SQLITE_UTF8 ){
  23036. /* When converting from UTF-16, the maximum growth results from
  23037. ** translating a 2-byte character to a 4-byte UTF-8 character.
  23038. ** A single byte is required for the output string
  23039. ** nul-terminator.
  23040. */
  23041. pMem->n &= ~1;
  23042. len = pMem->n * 2 + 1;
  23043. }else{
  23044. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  23045. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  23046. ** character. Two bytes are required in the output buffer for the
  23047. ** nul-terminator.
  23048. */
  23049. len = pMem->n * 2 + 2;
  23050. }
  23051. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  23052. ** byte past the end.
  23053. **
  23054. ** Variable zOut is set to point at the output buffer, space obtained
  23055. ** from sqlite3_malloc().
  23056. */
  23057. zIn = (u8*)pMem->z;
  23058. zTerm = &zIn[pMem->n];
  23059. zOut = sqlite3DbMallocRaw(pMem->db, len);
  23060. if( !zOut ){
  23061. return SQLITE_NOMEM;
  23062. }
  23063. z = zOut;
  23064. if( pMem->enc==SQLITE_UTF8 ){
  23065. if( desiredEnc==SQLITE_UTF16LE ){
  23066. /* UTF-8 -> UTF-16 Little-endian */
  23067. while( zIn<zTerm ){
  23068. READ_UTF8(zIn, zTerm, c);
  23069. WRITE_UTF16LE(z, c);
  23070. }
  23071. }else{
  23072. assert( desiredEnc==SQLITE_UTF16BE );
  23073. /* UTF-8 -> UTF-16 Big-endian */
  23074. while( zIn<zTerm ){
  23075. READ_UTF8(zIn, zTerm, c);
  23076. WRITE_UTF16BE(z, c);
  23077. }
  23078. }
  23079. pMem->n = (int)(z - zOut);
  23080. *z++ = 0;
  23081. }else{
  23082. assert( desiredEnc==SQLITE_UTF8 );
  23083. if( pMem->enc==SQLITE_UTF16LE ){
  23084. /* UTF-16 Little-endian -> UTF-8 */
  23085. while( zIn<zTerm ){
  23086. READ_UTF16LE(zIn, zIn<zTerm, c);
  23087. WRITE_UTF8(z, c);
  23088. }
  23089. }else{
  23090. /* UTF-16 Big-endian -> UTF-8 */
  23091. while( zIn<zTerm ){
  23092. READ_UTF16BE(zIn, zIn<zTerm, c);
  23093. WRITE_UTF8(z, c);
  23094. }
  23095. }
  23096. pMem->n = (int)(z - zOut);
  23097. }
  23098. *z = 0;
  23099. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  23100. c = pMem->flags;
  23101. sqlite3VdbeMemRelease(pMem);
  23102. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  23103. pMem->enc = desiredEnc;
  23104. pMem->z = (char*)zOut;
  23105. pMem->zMalloc = pMem->z;
  23106. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  23107. translate_out:
  23108. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23109. {
  23110. char zBuf[100];
  23111. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23112. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  23113. }
  23114. #endif
  23115. return SQLITE_OK;
  23116. }
  23117. /*
  23118. ** This routine checks for a byte-order mark at the beginning of the
  23119. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  23120. ** the encoding of the Mem adjusted. This routine does not do any
  23121. ** byte-swapping, it just sets Mem.enc appropriately.
  23122. **
  23123. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  23124. ** changed by this function.
  23125. */
  23126. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  23127. int rc = SQLITE_OK;
  23128. u8 bom = 0;
  23129. assert( pMem->n>=0 );
  23130. if( pMem->n>1 ){
  23131. u8 b1 = *(u8 *)pMem->z;
  23132. u8 b2 = *(((u8 *)pMem->z) + 1);
  23133. if( b1==0xFE && b2==0xFF ){
  23134. bom = SQLITE_UTF16BE;
  23135. }
  23136. if( b1==0xFF && b2==0xFE ){
  23137. bom = SQLITE_UTF16LE;
  23138. }
  23139. }
  23140. if( bom ){
  23141. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23142. if( rc==SQLITE_OK ){
  23143. pMem->n -= 2;
  23144. memmove(pMem->z, &pMem->z[2], pMem->n);
  23145. pMem->z[pMem->n] = '\0';
  23146. pMem->z[pMem->n+1] = '\0';
  23147. pMem->flags |= MEM_Term;
  23148. pMem->enc = bom;
  23149. }
  23150. }
  23151. return rc;
  23152. }
  23153. #endif /* SQLITE_OMIT_UTF16 */
  23154. /*
  23155. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  23156. ** return the number of unicode characters in pZ up to (but not including)
  23157. ** the first 0x00 byte. If nByte is not less than zero, return the
  23158. ** number of unicode characters in the first nByte of pZ (or up to
  23159. ** the first 0x00, whichever comes first).
  23160. */
  23161. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  23162. int r = 0;
  23163. const u8 *z = (const u8*)zIn;
  23164. const u8 *zTerm;
  23165. if( nByte>=0 ){
  23166. zTerm = &z[nByte];
  23167. }else{
  23168. zTerm = (const u8*)(-1);
  23169. }
  23170. assert( z<=zTerm );
  23171. while( *z!=0 && z<zTerm ){
  23172. SQLITE_SKIP_UTF8(z);
  23173. r++;
  23174. }
  23175. return r;
  23176. }
  23177. /* This test function is not currently used by the automated test-suite.
  23178. ** Hence it is only available in debug builds.
  23179. */
  23180. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23181. /*
  23182. ** Translate UTF-8 to UTF-8.
  23183. **
  23184. ** This has the effect of making sure that the string is well-formed
  23185. ** UTF-8. Miscoded characters are removed.
  23186. **
  23187. ** The translation is done in-place and aborted if the output
  23188. ** overruns the input.
  23189. */
  23190. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  23191. unsigned char *zOut = zIn;
  23192. unsigned char *zStart = zIn;
  23193. u32 c;
  23194. while( zIn[0] && zOut<=zIn ){
  23195. c = sqlite3Utf8Read((const u8**)&zIn);
  23196. if( c!=0xfffd ){
  23197. WRITE_UTF8(zOut, c);
  23198. }
  23199. }
  23200. *zOut = 0;
  23201. return (int)(zOut - zStart);
  23202. }
  23203. #endif
  23204. #ifndef SQLITE_OMIT_UTF16
  23205. /*
  23206. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  23207. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  23208. ** be freed by the calling function.
  23209. **
  23210. ** NULL is returned if there is an allocation error.
  23211. */
  23212. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  23213. Mem m;
  23214. memset(&m, 0, sizeof(m));
  23215. m.db = db;
  23216. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  23217. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  23218. if( db->mallocFailed ){
  23219. sqlite3VdbeMemRelease(&m);
  23220. m.z = 0;
  23221. }
  23222. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  23223. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  23224. assert( m.z || db->mallocFailed );
  23225. return m.z;
  23226. }
  23227. /*
  23228. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  23229. ** Return the number of bytes in the first nChar unicode characters
  23230. ** in pZ. nChar must be non-negative.
  23231. */
  23232. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  23233. int c;
  23234. unsigned char const *z = zIn;
  23235. int n = 0;
  23236. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  23237. while( n<nChar ){
  23238. READ_UTF16BE(z, 1, c);
  23239. n++;
  23240. }
  23241. }else{
  23242. while( n<nChar ){
  23243. READ_UTF16LE(z, 1, c);
  23244. n++;
  23245. }
  23246. }
  23247. return (int)(z-(unsigned char const *)zIn);
  23248. }
  23249. #if defined(SQLITE_TEST)
  23250. /*
  23251. ** This routine is called from the TCL test function "translate_selftest".
  23252. ** It checks that the primitives for serializing and deserializing
  23253. ** characters in each encoding are inverses of each other.
  23254. */
  23255. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  23256. unsigned int i, t;
  23257. unsigned char zBuf[20];
  23258. unsigned char *z;
  23259. int n;
  23260. unsigned int c;
  23261. for(i=0; i<0x00110000; i++){
  23262. z = zBuf;
  23263. WRITE_UTF8(z, i);
  23264. n = (int)(z-zBuf);
  23265. assert( n>0 && n<=4 );
  23266. z[0] = 0;
  23267. z = zBuf;
  23268. c = sqlite3Utf8Read((const u8**)&z);
  23269. t = i;
  23270. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  23271. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  23272. assert( c==t );
  23273. assert( (z-zBuf)==n );
  23274. }
  23275. for(i=0; i<0x00110000; i++){
  23276. if( i>=0xD800 && i<0xE000 ) continue;
  23277. z = zBuf;
  23278. WRITE_UTF16LE(z, i);
  23279. n = (int)(z-zBuf);
  23280. assert( n>0 && n<=4 );
  23281. z[0] = 0;
  23282. z = zBuf;
  23283. READ_UTF16LE(z, 1, c);
  23284. assert( c==i );
  23285. assert( (z-zBuf)==n );
  23286. }
  23287. for(i=0; i<0x00110000; i++){
  23288. if( i>=0xD800 && i<0xE000 ) continue;
  23289. z = zBuf;
  23290. WRITE_UTF16BE(z, i);
  23291. n = (int)(z-zBuf);
  23292. assert( n>0 && n<=4 );
  23293. z[0] = 0;
  23294. z = zBuf;
  23295. READ_UTF16BE(z, 1, c);
  23296. assert( c==i );
  23297. assert( (z-zBuf)==n );
  23298. }
  23299. }
  23300. #endif /* SQLITE_TEST */
  23301. #endif /* SQLITE_OMIT_UTF16 */
  23302. /************** End of utf.c *************************************************/
  23303. /************** Begin file util.c ********************************************/
  23304. /*
  23305. ** 2001 September 15
  23306. **
  23307. ** The author disclaims copyright to this source code. In place of
  23308. ** a legal notice, here is a blessing:
  23309. **
  23310. ** May you do good and not evil.
  23311. ** May you find forgiveness for yourself and forgive others.
  23312. ** May you share freely, never taking more than you give.
  23313. **
  23314. *************************************************************************
  23315. ** Utility functions used throughout sqlite.
  23316. **
  23317. ** This file contains functions for allocating memory, comparing
  23318. ** strings, and stuff like that.
  23319. **
  23320. */
  23321. /* #include "sqliteInt.h" */
  23322. /* #include <stdarg.h> */
  23323. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  23324. # include <math.h>
  23325. #endif
  23326. /*
  23327. ** Routine needed to support the testcase() macro.
  23328. */
  23329. #ifdef SQLITE_COVERAGE_TEST
  23330. SQLITE_PRIVATE void sqlite3Coverage(int x){
  23331. static unsigned dummy = 0;
  23332. dummy += (unsigned)x;
  23333. }
  23334. #endif
  23335. /*
  23336. ** Give a callback to the test harness that can be used to simulate faults
  23337. ** in places where it is difficult or expensive to do so purely by means
  23338. ** of inputs.
  23339. **
  23340. ** The intent of the integer argument is to let the fault simulator know
  23341. ** which of multiple sqlite3FaultSim() calls has been hit.
  23342. **
  23343. ** Return whatever integer value the test callback returns, or return
  23344. ** SQLITE_OK if no test callback is installed.
  23345. */
  23346. #ifndef SQLITE_OMIT_BUILTIN_TEST
  23347. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  23348. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  23349. return xCallback ? xCallback(iTest) : SQLITE_OK;
  23350. }
  23351. #endif
  23352. #ifndef SQLITE_OMIT_FLOATING_POINT
  23353. /*
  23354. ** Return true if the floating point value is Not a Number (NaN).
  23355. **
  23356. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  23357. ** Otherwise, we have our own implementation that works on most systems.
  23358. */
  23359. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  23360. int rc; /* The value return */
  23361. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  23362. /*
  23363. ** Systems that support the isnan() library function should probably
  23364. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  23365. ** found that many systems do not have a working isnan() function so
  23366. ** this implementation is provided as an alternative.
  23367. **
  23368. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  23369. ** On the other hand, the use of -ffast-math comes with the following
  23370. ** warning:
  23371. **
  23372. ** This option [-ffast-math] should never be turned on by any
  23373. ** -O option since it can result in incorrect output for programs
  23374. ** which depend on an exact implementation of IEEE or ISO
  23375. ** rules/specifications for math functions.
  23376. **
  23377. ** Under MSVC, this NaN test may fail if compiled with a floating-
  23378. ** point precision mode other than /fp:precise. From the MSDN
  23379. ** documentation:
  23380. **
  23381. ** The compiler [with /fp:precise] will properly handle comparisons
  23382. ** involving NaN. For example, x != x evaluates to true if x is NaN
  23383. ** ...
  23384. */
  23385. #ifdef __FAST_MATH__
  23386. # error SQLite will not work correctly with the -ffast-math option of GCC.
  23387. #endif
  23388. volatile double y = x;
  23389. volatile double z = y;
  23390. rc = (y!=z);
  23391. #else /* if HAVE_ISNAN */
  23392. rc = isnan(x);
  23393. #endif /* HAVE_ISNAN */
  23394. testcase( rc );
  23395. return rc;
  23396. }
  23397. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23398. /*
  23399. ** Compute a string length that is limited to what can be stored in
  23400. ** lower 30 bits of a 32-bit signed integer.
  23401. **
  23402. ** The value returned will never be negative. Nor will it ever be greater
  23403. ** than the actual length of the string. For very long strings (greater
  23404. ** than 1GiB) the value returned might be less than the true string length.
  23405. */
  23406. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  23407. if( z==0 ) return 0;
  23408. return 0x3fffffff & (int)strlen(z);
  23409. }
  23410. /*
  23411. ** Set the current error code to err_code and clear any prior error message.
  23412. */
  23413. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  23414. assert( db!=0 );
  23415. db->errCode = err_code;
  23416. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  23417. }
  23418. /*
  23419. ** Set the most recent error code and error string for the sqlite
  23420. ** handle "db". The error code is set to "err_code".
  23421. **
  23422. ** If it is not NULL, string zFormat specifies the format of the
  23423. ** error string in the style of the printf functions: The following
  23424. ** format characters are allowed:
  23425. **
  23426. ** %s Insert a string
  23427. ** %z A string that should be freed after use
  23428. ** %d Insert an integer
  23429. ** %T Insert a token
  23430. ** %S Insert the first element of a SrcList
  23431. **
  23432. ** zFormat and any string tokens that follow it are assumed to be
  23433. ** encoded in UTF-8.
  23434. **
  23435. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  23436. ** should be called with err_code set to SQLITE_OK and zFormat set
  23437. ** to NULL.
  23438. */
  23439. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  23440. assert( db!=0 );
  23441. db->errCode = err_code;
  23442. if( zFormat==0 ){
  23443. sqlite3Error(db, err_code);
  23444. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  23445. char *z;
  23446. va_list ap;
  23447. va_start(ap, zFormat);
  23448. z = sqlite3VMPrintf(db, zFormat, ap);
  23449. va_end(ap);
  23450. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  23451. }
  23452. }
  23453. /*
  23454. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  23455. ** The following formatting characters are allowed:
  23456. **
  23457. ** %s Insert a string
  23458. ** %z A string that should be freed after use
  23459. ** %d Insert an integer
  23460. ** %T Insert a token
  23461. ** %S Insert the first element of a SrcList
  23462. **
  23463. ** This function should be used to report any error that occurs while
  23464. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  23465. ** last thing the sqlite3_prepare() function does is copy the error
  23466. ** stored by this function into the database handle using sqlite3Error().
  23467. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  23468. ** during statement execution (sqlite3_step() etc.).
  23469. */
  23470. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  23471. char *zMsg;
  23472. va_list ap;
  23473. sqlite3 *db = pParse->db;
  23474. va_start(ap, zFormat);
  23475. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  23476. va_end(ap);
  23477. if( db->suppressErr ){
  23478. sqlite3DbFree(db, zMsg);
  23479. }else{
  23480. pParse->nErr++;
  23481. sqlite3DbFree(db, pParse->zErrMsg);
  23482. pParse->zErrMsg = zMsg;
  23483. pParse->rc = SQLITE_ERROR;
  23484. }
  23485. }
  23486. /*
  23487. ** Convert an SQL-style quoted string into a normal string by removing
  23488. ** the quote characters. The conversion is done in-place. If the
  23489. ** input does not begin with a quote character, then this routine
  23490. ** is a no-op.
  23491. **
  23492. ** The input string must be zero-terminated. A new zero-terminator
  23493. ** is added to the dequoted string.
  23494. **
  23495. ** The return value is -1 if no dequoting occurs or the length of the
  23496. ** dequoted string, exclusive of the zero terminator, if dequoting does
  23497. ** occur.
  23498. **
  23499. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  23500. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  23501. ** "a-b-c".
  23502. */
  23503. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  23504. char quote;
  23505. int i, j;
  23506. if( z==0 ) return -1;
  23507. quote = z[0];
  23508. switch( quote ){
  23509. case '\'': break;
  23510. case '"': break;
  23511. case '`': break; /* For MySQL compatibility */
  23512. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  23513. default: return -1;
  23514. }
  23515. for(i=1, j=0;; i++){
  23516. assert( z[i] );
  23517. if( z[i]==quote ){
  23518. if( z[i+1]==quote ){
  23519. z[j++] = quote;
  23520. i++;
  23521. }else{
  23522. break;
  23523. }
  23524. }else{
  23525. z[j++] = z[i];
  23526. }
  23527. }
  23528. z[j] = 0;
  23529. return j;
  23530. }
  23531. /* Convenient short-hand */
  23532. #define UpperToLower sqlite3UpperToLower
  23533. /*
  23534. ** Some systems have stricmp(). Others have strcasecmp(). Because
  23535. ** there is no consistency, we will define our own.
  23536. **
  23537. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  23538. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  23539. ** the contents of two buffers containing UTF-8 strings in a
  23540. ** case-independent fashion, using the same definition of "case
  23541. ** independence" that SQLite uses internally when comparing identifiers.
  23542. */
  23543. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
  23544. register unsigned char *a, *b;
  23545. if( zLeft==0 ){
  23546. return zRight ? -1 : 0;
  23547. }else if( zRight==0 ){
  23548. return 1;
  23549. }
  23550. a = (unsigned char *)zLeft;
  23551. b = (unsigned char *)zRight;
  23552. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  23553. return UpperToLower[*a] - UpperToLower[*b];
  23554. }
  23555. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  23556. register unsigned char *a, *b;
  23557. if( zLeft==0 ){
  23558. return zRight ? -1 : 0;
  23559. }else if( zRight==0 ){
  23560. return 1;
  23561. }
  23562. a = (unsigned char *)zLeft;
  23563. b = (unsigned char *)zRight;
  23564. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  23565. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  23566. }
  23567. /*
  23568. ** The string z[] is an text representation of a real number.
  23569. ** Convert this string to a double and write it into *pResult.
  23570. **
  23571. ** The string z[] is length bytes in length (bytes, not characters) and
  23572. ** uses the encoding enc. The string is not necessarily zero-terminated.
  23573. **
  23574. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  23575. ** if the string is empty or contains extraneous text. Valid numbers
  23576. ** are in one of these formats:
  23577. **
  23578. ** [+-]digits[E[+-]digits]
  23579. ** [+-]digits.[digits][E[+-]digits]
  23580. ** [+-].digits[E[+-]digits]
  23581. **
  23582. ** Leading and trailing whitespace is ignored for the purpose of determining
  23583. ** validity.
  23584. **
  23585. ** If some prefix of the input string is a valid number, this routine
  23586. ** returns FALSE but it still converts the prefix and writes the result
  23587. ** into *pResult.
  23588. */
  23589. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  23590. #ifndef SQLITE_OMIT_FLOATING_POINT
  23591. int incr;
  23592. const char *zEnd = z + length;
  23593. /* sign * significand * (10 ^ (esign * exponent)) */
  23594. int sign = 1; /* sign of significand */
  23595. i64 s = 0; /* significand */
  23596. int d = 0; /* adjust exponent for shifting decimal point */
  23597. int esign = 1; /* sign of exponent */
  23598. int e = 0; /* exponent */
  23599. int eValid = 1; /* True exponent is either not used or is well-formed */
  23600. double result;
  23601. int nDigits = 0;
  23602. int nonNum = 0;
  23603. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  23604. *pResult = 0.0; /* Default return value, in case of an error */
  23605. if( enc==SQLITE_UTF8 ){
  23606. incr = 1;
  23607. }else{
  23608. int i;
  23609. incr = 2;
  23610. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  23611. for(i=3-enc; i<length && z[i]==0; i+=2){}
  23612. nonNum = i<length;
  23613. zEnd = z+i+enc-3;
  23614. z += (enc&1);
  23615. }
  23616. /* skip leading spaces */
  23617. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  23618. if( z>=zEnd ) return 0;
  23619. /* get sign of significand */
  23620. if( *z=='-' ){
  23621. sign = -1;
  23622. z+=incr;
  23623. }else if( *z=='+' ){
  23624. z+=incr;
  23625. }
  23626. /* skip leading zeroes */
  23627. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  23628. /* copy max significant digits to significand */
  23629. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  23630. s = s*10 + (*z - '0');
  23631. z+=incr, nDigits++;
  23632. }
  23633. /* skip non-significant significand digits
  23634. ** (increase exponent by d to shift decimal left) */
  23635. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  23636. if( z>=zEnd ) goto do_atof_calc;
  23637. /* if decimal point is present */
  23638. if( *z=='.' ){
  23639. z+=incr;
  23640. /* copy digits from after decimal to significand
  23641. ** (decrease exponent by d to shift decimal right) */
  23642. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  23643. s = s*10 + (*z - '0');
  23644. z+=incr, nDigits++, d--;
  23645. }
  23646. /* skip non-significant digits */
  23647. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  23648. }
  23649. if( z>=zEnd ) goto do_atof_calc;
  23650. /* if exponent is present */
  23651. if( *z=='e' || *z=='E' ){
  23652. z+=incr;
  23653. eValid = 0;
  23654. if( z>=zEnd ) goto do_atof_calc;
  23655. /* get sign of exponent */
  23656. if( *z=='-' ){
  23657. esign = -1;
  23658. z+=incr;
  23659. }else if( *z=='+' ){
  23660. z+=incr;
  23661. }
  23662. /* copy digits to exponent */
  23663. while( z<zEnd && sqlite3Isdigit(*z) ){
  23664. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  23665. z+=incr;
  23666. eValid = 1;
  23667. }
  23668. }
  23669. /* skip trailing spaces */
  23670. if( nDigits && eValid ){
  23671. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  23672. }
  23673. do_atof_calc:
  23674. /* adjust exponent by d, and update sign */
  23675. e = (e*esign) + d;
  23676. if( e<0 ) {
  23677. esign = -1;
  23678. e *= -1;
  23679. } else {
  23680. esign = 1;
  23681. }
  23682. /* if 0 significand */
  23683. if( !s ) {
  23684. /* In the IEEE 754 standard, zero is signed.
  23685. ** Add the sign if we've seen at least one digit */
  23686. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  23687. } else {
  23688. /* attempt to reduce exponent */
  23689. if( esign>0 ){
  23690. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  23691. }else{
  23692. while( !(s%10) && e>0 ) e--,s/=10;
  23693. }
  23694. /* adjust the sign of significand */
  23695. s = sign<0 ? -s : s;
  23696. /* if exponent, scale significand as appropriate
  23697. ** and store in result. */
  23698. if( e ){
  23699. LONGDOUBLE_TYPE scale = 1.0;
  23700. /* attempt to handle extremely small/large numbers better */
  23701. if( e>307 && e<342 ){
  23702. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  23703. if( esign<0 ){
  23704. result = s / scale;
  23705. result /= 1.0e+308;
  23706. }else{
  23707. result = s * scale;
  23708. result *= 1.0e+308;
  23709. }
  23710. }else if( e>=342 ){
  23711. if( esign<0 ){
  23712. result = 0.0*s;
  23713. }else{
  23714. result = 1e308*1e308*s; /* Infinity */
  23715. }
  23716. }else{
  23717. /* 1.0e+22 is the largest power of 10 than can be
  23718. ** represented exactly. */
  23719. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  23720. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  23721. if( esign<0 ){
  23722. result = s / scale;
  23723. }else{
  23724. result = s * scale;
  23725. }
  23726. }
  23727. } else {
  23728. result = (double)s;
  23729. }
  23730. }
  23731. /* store the result */
  23732. *pResult = result;
  23733. /* return true if number and no extra non-whitespace chracters after */
  23734. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  23735. #else
  23736. return !sqlite3Atoi64(z, pResult, length, enc);
  23737. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23738. }
  23739. /*
  23740. ** Compare the 19-character string zNum against the text representation
  23741. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  23742. ** if zNum is less than, equal to, or greater than the string.
  23743. ** Note that zNum must contain exactly 19 characters.
  23744. **
  23745. ** Unlike memcmp() this routine is guaranteed to return the difference
  23746. ** in the values of the last digit if the only difference is in the
  23747. ** last digit. So, for example,
  23748. **
  23749. ** compare2pow63("9223372036854775800", 1)
  23750. **
  23751. ** will return -8.
  23752. */
  23753. static int compare2pow63(const char *zNum, int incr){
  23754. int c = 0;
  23755. int i;
  23756. /* 012345678901234567 */
  23757. const char *pow63 = "922337203685477580";
  23758. for(i=0; c==0 && i<18; i++){
  23759. c = (zNum[i*incr]-pow63[i])*10;
  23760. }
  23761. if( c==0 ){
  23762. c = zNum[18*incr] - '8';
  23763. testcase( c==(-1) );
  23764. testcase( c==0 );
  23765. testcase( c==(+1) );
  23766. }
  23767. return c;
  23768. }
  23769. /*
  23770. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  23771. ** routine does *not* accept hexadecimal notation.
  23772. **
  23773. ** If the zNum value is representable as a 64-bit twos-complement
  23774. ** integer, then write that value into *pNum and return 0.
  23775. **
  23776. ** If zNum is exactly 9223372036854775808, return 2. This special
  23777. ** case is broken out because while 9223372036854775808 cannot be a
  23778. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  23779. **
  23780. ** If zNum is too big for a 64-bit integer and is not
  23781. ** 9223372036854775808 or if zNum contains any non-numeric text,
  23782. ** then return 1.
  23783. **
  23784. ** length is the number of bytes in the string (bytes, not characters).
  23785. ** The string is not necessarily zero-terminated. The encoding is
  23786. ** given by enc.
  23787. */
  23788. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  23789. int incr;
  23790. u64 u = 0;
  23791. int neg = 0; /* assume positive */
  23792. int i;
  23793. int c = 0;
  23794. int nonNum = 0;
  23795. const char *zStart;
  23796. const char *zEnd = zNum + length;
  23797. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  23798. if( enc==SQLITE_UTF8 ){
  23799. incr = 1;
  23800. }else{
  23801. incr = 2;
  23802. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  23803. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  23804. nonNum = i<length;
  23805. zEnd = zNum+i+enc-3;
  23806. zNum += (enc&1);
  23807. }
  23808. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  23809. if( zNum<zEnd ){
  23810. if( *zNum=='-' ){
  23811. neg = 1;
  23812. zNum+=incr;
  23813. }else if( *zNum=='+' ){
  23814. zNum+=incr;
  23815. }
  23816. }
  23817. zStart = zNum;
  23818. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  23819. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  23820. u = u*10 + c - '0';
  23821. }
  23822. if( u>LARGEST_INT64 ){
  23823. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  23824. }else if( neg ){
  23825. *pNum = -(i64)u;
  23826. }else{
  23827. *pNum = (i64)u;
  23828. }
  23829. testcase( i==18 );
  23830. testcase( i==19 );
  23831. testcase( i==20 );
  23832. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  23833. /* zNum is empty or contains non-numeric text or is longer
  23834. ** than 19 digits (thus guaranteeing that it is too large) */
  23835. return 1;
  23836. }else if( i<19*incr ){
  23837. /* Less than 19 digits, so we know that it fits in 64 bits */
  23838. assert( u<=LARGEST_INT64 );
  23839. return 0;
  23840. }else{
  23841. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  23842. c = compare2pow63(zNum, incr);
  23843. if( c<0 ){
  23844. /* zNum is less than 9223372036854775808 so it fits */
  23845. assert( u<=LARGEST_INT64 );
  23846. return 0;
  23847. }else if( c>0 ){
  23848. /* zNum is greater than 9223372036854775808 so it overflows */
  23849. return 1;
  23850. }else{
  23851. /* zNum is exactly 9223372036854775808. Fits if negative. The
  23852. ** special case 2 overflow if positive */
  23853. assert( u-1==LARGEST_INT64 );
  23854. return neg ? 0 : 2;
  23855. }
  23856. }
  23857. }
  23858. /*
  23859. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  23860. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  23861. ** whereas sqlite3Atoi64() does not.
  23862. **
  23863. ** Returns:
  23864. **
  23865. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  23866. ** 1 Integer too large for a 64-bit signed integer or is malformed
  23867. ** 2 Special case of 9223372036854775808
  23868. */
  23869. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  23870. #ifndef SQLITE_OMIT_HEX_INTEGER
  23871. if( z[0]=='0'
  23872. && (z[1]=='x' || z[1]=='X')
  23873. && sqlite3Isxdigit(z[2])
  23874. ){
  23875. u64 u = 0;
  23876. int i, k;
  23877. for(i=2; z[i]=='0'; i++){}
  23878. for(k=i; sqlite3Isxdigit(z[k]); k++){
  23879. u = u*16 + sqlite3HexToInt(z[k]);
  23880. }
  23881. memcpy(pOut, &u, 8);
  23882. return (z[k]==0 && k-i<=16) ? 0 : 1;
  23883. }else
  23884. #endif /* SQLITE_OMIT_HEX_INTEGER */
  23885. {
  23886. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  23887. }
  23888. }
  23889. /*
  23890. ** If zNum represents an integer that will fit in 32-bits, then set
  23891. ** *pValue to that integer and return true. Otherwise return false.
  23892. **
  23893. ** This routine accepts both decimal and hexadecimal notation for integers.
  23894. **
  23895. ** Any non-numeric characters that following zNum are ignored.
  23896. ** This is different from sqlite3Atoi64() which requires the
  23897. ** input number to be zero-terminated.
  23898. */
  23899. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  23900. sqlite_int64 v = 0;
  23901. int i, c;
  23902. int neg = 0;
  23903. if( zNum[0]=='-' ){
  23904. neg = 1;
  23905. zNum++;
  23906. }else if( zNum[0]=='+' ){
  23907. zNum++;
  23908. }
  23909. #ifndef SQLITE_OMIT_HEX_INTEGER
  23910. else if( zNum[0]=='0'
  23911. && (zNum[1]=='x' || zNum[1]=='X')
  23912. && sqlite3Isxdigit(zNum[2])
  23913. ){
  23914. u32 u = 0;
  23915. zNum += 2;
  23916. while( zNum[0]=='0' ) zNum++;
  23917. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  23918. u = u*16 + sqlite3HexToInt(zNum[i]);
  23919. }
  23920. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  23921. memcpy(pValue, &u, 4);
  23922. return 1;
  23923. }else{
  23924. return 0;
  23925. }
  23926. }
  23927. #endif
  23928. while( zNum[0]=='0' ) zNum++;
  23929. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  23930. v = v*10 + c;
  23931. }
  23932. /* The longest decimal representation of a 32 bit integer is 10 digits:
  23933. **
  23934. ** 1234567890
  23935. ** 2^31 -> 2147483648
  23936. */
  23937. testcase( i==10 );
  23938. if( i>10 ){
  23939. return 0;
  23940. }
  23941. testcase( v-neg==2147483647 );
  23942. if( v-neg>2147483647 ){
  23943. return 0;
  23944. }
  23945. if( neg ){
  23946. v = -v;
  23947. }
  23948. *pValue = (int)v;
  23949. return 1;
  23950. }
  23951. /*
  23952. ** Return a 32-bit integer value extracted from a string. If the
  23953. ** string is not an integer, just return 0.
  23954. */
  23955. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  23956. int x = 0;
  23957. if( z ) sqlite3GetInt32(z, &x);
  23958. return x;
  23959. }
  23960. /*
  23961. ** The variable-length integer encoding is as follows:
  23962. **
  23963. ** KEY:
  23964. ** A = 0xxxxxxx 7 bits of data and one flag bit
  23965. ** B = 1xxxxxxx 7 bits of data and one flag bit
  23966. ** C = xxxxxxxx 8 bits of data
  23967. **
  23968. ** 7 bits - A
  23969. ** 14 bits - BA
  23970. ** 21 bits - BBA
  23971. ** 28 bits - BBBA
  23972. ** 35 bits - BBBBA
  23973. ** 42 bits - BBBBBA
  23974. ** 49 bits - BBBBBBA
  23975. ** 56 bits - BBBBBBBA
  23976. ** 64 bits - BBBBBBBBC
  23977. */
  23978. /*
  23979. ** Write a 64-bit variable-length integer to memory starting at p[0].
  23980. ** The length of data write will be between 1 and 9 bytes. The number
  23981. ** of bytes written is returned.
  23982. **
  23983. ** A variable-length integer consists of the lower 7 bits of each byte
  23984. ** for all bytes that have the 8th bit set and one byte with the 8th
  23985. ** bit clear. Except, if we get to the 9th byte, it stores the full
  23986. ** 8 bits and is the last byte.
  23987. */
  23988. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  23989. int i, j, n;
  23990. u8 buf[10];
  23991. if( v & (((u64)0xff000000)<<32) ){
  23992. p[8] = (u8)v;
  23993. v >>= 8;
  23994. for(i=7; i>=0; i--){
  23995. p[i] = (u8)((v & 0x7f) | 0x80);
  23996. v >>= 7;
  23997. }
  23998. return 9;
  23999. }
  24000. n = 0;
  24001. do{
  24002. buf[n++] = (u8)((v & 0x7f) | 0x80);
  24003. v >>= 7;
  24004. }while( v!=0 );
  24005. buf[0] &= 0x7f;
  24006. assert( n<=9 );
  24007. for(i=0, j=n-1; j>=0; j--, i++){
  24008. p[i] = buf[j];
  24009. }
  24010. return n;
  24011. }
  24012. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  24013. if( v<=0x7f ){
  24014. p[0] = v&0x7f;
  24015. return 1;
  24016. }
  24017. if( v<=0x3fff ){
  24018. p[0] = ((v>>7)&0x7f)|0x80;
  24019. p[1] = v&0x7f;
  24020. return 2;
  24021. }
  24022. return putVarint64(p,v);
  24023. }
  24024. /*
  24025. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  24026. ** are defined here rather than simply putting the constant expressions
  24027. ** inline in order to work around bugs in the RVT compiler.
  24028. **
  24029. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  24030. **
  24031. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  24032. */
  24033. #define SLOT_2_0 0x001fc07f
  24034. #define SLOT_4_2_0 0xf01fc07f
  24035. /*
  24036. ** Read a 64-bit variable-length integer from memory starting at p[0].
  24037. ** Return the number of bytes read. The value is stored in *v.
  24038. */
  24039. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  24040. u32 a,b,s;
  24041. a = *p;
  24042. /* a: p0 (unmasked) */
  24043. if (!(a&0x80))
  24044. {
  24045. *v = a;
  24046. return 1;
  24047. }
  24048. p++;
  24049. b = *p;
  24050. /* b: p1 (unmasked) */
  24051. if (!(b&0x80))
  24052. {
  24053. a &= 0x7f;
  24054. a = a<<7;
  24055. a |= b;
  24056. *v = a;
  24057. return 2;
  24058. }
  24059. /* Verify that constants are precomputed correctly */
  24060. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  24061. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  24062. p++;
  24063. a = a<<14;
  24064. a |= *p;
  24065. /* a: p0<<14 | p2 (unmasked) */
  24066. if (!(a&0x80))
  24067. {
  24068. a &= SLOT_2_0;
  24069. b &= 0x7f;
  24070. b = b<<7;
  24071. a |= b;
  24072. *v = a;
  24073. return 3;
  24074. }
  24075. /* CSE1 from below */
  24076. a &= SLOT_2_0;
  24077. p++;
  24078. b = b<<14;
  24079. b |= *p;
  24080. /* b: p1<<14 | p3 (unmasked) */
  24081. if (!(b&0x80))
  24082. {
  24083. b &= SLOT_2_0;
  24084. /* moved CSE1 up */
  24085. /* a &= (0x7f<<14)|(0x7f); */
  24086. a = a<<7;
  24087. a |= b;
  24088. *v = a;
  24089. return 4;
  24090. }
  24091. /* a: p0<<14 | p2 (masked) */
  24092. /* b: p1<<14 | p3 (unmasked) */
  24093. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24094. /* moved CSE1 up */
  24095. /* a &= (0x7f<<14)|(0x7f); */
  24096. b &= SLOT_2_0;
  24097. s = a;
  24098. /* s: p0<<14 | p2 (masked) */
  24099. p++;
  24100. a = a<<14;
  24101. a |= *p;
  24102. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  24103. if (!(a&0x80))
  24104. {
  24105. /* we can skip these cause they were (effectively) done above in calc'ing s */
  24106. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24107. /* b &= (0x7f<<14)|(0x7f); */
  24108. b = b<<7;
  24109. a |= b;
  24110. s = s>>18;
  24111. *v = ((u64)s)<<32 | a;
  24112. return 5;
  24113. }
  24114. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24115. s = s<<7;
  24116. s |= b;
  24117. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24118. p++;
  24119. b = b<<14;
  24120. b |= *p;
  24121. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  24122. if (!(b&0x80))
  24123. {
  24124. /* we can skip this cause it was (effectively) done above in calc'ing s */
  24125. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24126. a &= SLOT_2_0;
  24127. a = a<<7;
  24128. a |= b;
  24129. s = s>>18;
  24130. *v = ((u64)s)<<32 | a;
  24131. return 6;
  24132. }
  24133. p++;
  24134. a = a<<14;
  24135. a |= *p;
  24136. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  24137. if (!(a&0x80))
  24138. {
  24139. a &= SLOT_4_2_0;
  24140. b &= SLOT_2_0;
  24141. b = b<<7;
  24142. a |= b;
  24143. s = s>>11;
  24144. *v = ((u64)s)<<32 | a;
  24145. return 7;
  24146. }
  24147. /* CSE2 from below */
  24148. a &= SLOT_2_0;
  24149. p++;
  24150. b = b<<14;
  24151. b |= *p;
  24152. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  24153. if (!(b&0x80))
  24154. {
  24155. b &= SLOT_4_2_0;
  24156. /* moved CSE2 up */
  24157. /* a &= (0x7f<<14)|(0x7f); */
  24158. a = a<<7;
  24159. a |= b;
  24160. s = s>>4;
  24161. *v = ((u64)s)<<32 | a;
  24162. return 8;
  24163. }
  24164. p++;
  24165. a = a<<15;
  24166. a |= *p;
  24167. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  24168. /* moved CSE2 up */
  24169. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  24170. b &= SLOT_2_0;
  24171. b = b<<8;
  24172. a |= b;
  24173. s = s<<4;
  24174. b = p[-4];
  24175. b &= 0x7f;
  24176. b = b>>3;
  24177. s |= b;
  24178. *v = ((u64)s)<<32 | a;
  24179. return 9;
  24180. }
  24181. /*
  24182. ** Read a 32-bit variable-length integer from memory starting at p[0].
  24183. ** Return the number of bytes read. The value is stored in *v.
  24184. **
  24185. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  24186. ** integer, then set *v to 0xffffffff.
  24187. **
  24188. ** A MACRO version, getVarint32, is provided which inlines the
  24189. ** single-byte case. All code should use the MACRO version as
  24190. ** this function assumes the single-byte case has already been handled.
  24191. */
  24192. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  24193. u32 a,b;
  24194. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  24195. ** by the getVarin32() macro */
  24196. a = *p;
  24197. /* a: p0 (unmasked) */
  24198. #ifndef getVarint32
  24199. if (!(a&0x80))
  24200. {
  24201. /* Values between 0 and 127 */
  24202. *v = a;
  24203. return 1;
  24204. }
  24205. #endif
  24206. /* The 2-byte case */
  24207. p++;
  24208. b = *p;
  24209. /* b: p1 (unmasked) */
  24210. if (!(b&0x80))
  24211. {
  24212. /* Values between 128 and 16383 */
  24213. a &= 0x7f;
  24214. a = a<<7;
  24215. *v = a | b;
  24216. return 2;
  24217. }
  24218. /* The 3-byte case */
  24219. p++;
  24220. a = a<<14;
  24221. a |= *p;
  24222. /* a: p0<<14 | p2 (unmasked) */
  24223. if (!(a&0x80))
  24224. {
  24225. /* Values between 16384 and 2097151 */
  24226. a &= (0x7f<<14)|(0x7f);
  24227. b &= 0x7f;
  24228. b = b<<7;
  24229. *v = a | b;
  24230. return 3;
  24231. }
  24232. /* A 32-bit varint is used to store size information in btrees.
  24233. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  24234. ** A 3-byte varint is sufficient, for example, to record the size
  24235. ** of a 1048569-byte BLOB or string.
  24236. **
  24237. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  24238. ** rare larger cases can be handled by the slower 64-bit varint
  24239. ** routine.
  24240. */
  24241. #if 1
  24242. {
  24243. u64 v64;
  24244. u8 n;
  24245. p -= 2;
  24246. n = sqlite3GetVarint(p, &v64);
  24247. assert( n>3 && n<=9 );
  24248. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  24249. *v = 0xffffffff;
  24250. }else{
  24251. *v = (u32)v64;
  24252. }
  24253. return n;
  24254. }
  24255. #else
  24256. /* For following code (kept for historical record only) shows an
  24257. ** unrolling for the 3- and 4-byte varint cases. This code is
  24258. ** slightly faster, but it is also larger and much harder to test.
  24259. */
  24260. p++;
  24261. b = b<<14;
  24262. b |= *p;
  24263. /* b: p1<<14 | p3 (unmasked) */
  24264. if (!(b&0x80))
  24265. {
  24266. /* Values between 2097152 and 268435455 */
  24267. b &= (0x7f<<14)|(0x7f);
  24268. a &= (0x7f<<14)|(0x7f);
  24269. a = a<<7;
  24270. *v = a | b;
  24271. return 4;
  24272. }
  24273. p++;
  24274. a = a<<14;
  24275. a |= *p;
  24276. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  24277. if (!(a&0x80))
  24278. {
  24279. /* Values between 268435456 and 34359738367 */
  24280. a &= SLOT_4_2_0;
  24281. b &= SLOT_4_2_0;
  24282. b = b<<7;
  24283. *v = a | b;
  24284. return 5;
  24285. }
  24286. /* We can only reach this point when reading a corrupt database
  24287. ** file. In that case we are not in any hurry. Use the (relatively
  24288. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  24289. ** value. */
  24290. {
  24291. u64 v64;
  24292. u8 n;
  24293. p -= 4;
  24294. n = sqlite3GetVarint(p, &v64);
  24295. assert( n>5 && n<=9 );
  24296. *v = (u32)v64;
  24297. return n;
  24298. }
  24299. #endif
  24300. }
  24301. /*
  24302. ** Return the number of bytes that will be needed to store the given
  24303. ** 64-bit integer.
  24304. */
  24305. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  24306. int i;
  24307. for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
  24308. return i;
  24309. }
  24310. /*
  24311. ** Read or write a four-byte big-endian integer value.
  24312. */
  24313. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  24314. #if SQLITE_BYTEORDER==4321
  24315. u32 x;
  24316. memcpy(&x,p,4);
  24317. return x;
  24318. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  24319. && defined(__GNUC__) && GCC_VERSION>=4003000
  24320. u32 x;
  24321. memcpy(&x,p,4);
  24322. return __builtin_bswap32(x);
  24323. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  24324. && defined(_MSC_VER) && _MSC_VER>=1300
  24325. u32 x;
  24326. memcpy(&x,p,4);
  24327. return _byteswap_ulong(x);
  24328. #else
  24329. testcase( p[0]&0x80 );
  24330. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  24331. #endif
  24332. }
  24333. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  24334. #if SQLITE_BYTEORDER==4321
  24335. memcpy(p,&v,4);
  24336. #elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
  24337. u32 x = __builtin_bswap32(v);
  24338. memcpy(p,&x,4);
  24339. #elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
  24340. u32 x = _byteswap_ulong(v);
  24341. memcpy(p,&x,4);
  24342. #else
  24343. p[0] = (u8)(v>>24);
  24344. p[1] = (u8)(v>>16);
  24345. p[2] = (u8)(v>>8);
  24346. p[3] = (u8)v;
  24347. #endif
  24348. }
  24349. /*
  24350. ** Translate a single byte of Hex into an integer.
  24351. ** This routine only works if h really is a valid hexadecimal
  24352. ** character: 0..9a..fA..F
  24353. */
  24354. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  24355. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  24356. #ifdef SQLITE_ASCII
  24357. h += 9*(1&(h>>6));
  24358. #endif
  24359. #ifdef SQLITE_EBCDIC
  24360. h += 9*(1&~(h>>4));
  24361. #endif
  24362. return (u8)(h & 0xf);
  24363. }
  24364. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  24365. /*
  24366. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  24367. ** value. Return a pointer to its binary value. Space to hold the
  24368. ** binary value has been obtained from malloc and must be freed by
  24369. ** the calling routine.
  24370. */
  24371. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  24372. char *zBlob;
  24373. int i;
  24374. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  24375. n--;
  24376. if( zBlob ){
  24377. for(i=0; i<n; i+=2){
  24378. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  24379. }
  24380. zBlob[i/2] = 0;
  24381. }
  24382. return zBlob;
  24383. }
  24384. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  24385. /*
  24386. ** Log an error that is an API call on a connection pointer that should
  24387. ** not have been used. The "type" of connection pointer is given as the
  24388. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  24389. */
  24390. static void logBadConnection(const char *zType){
  24391. sqlite3_log(SQLITE_MISUSE,
  24392. "API call with %s database connection pointer",
  24393. zType
  24394. );
  24395. }
  24396. /*
  24397. ** Check to make sure we have a valid db pointer. This test is not
  24398. ** foolproof but it does provide some measure of protection against
  24399. ** misuse of the interface such as passing in db pointers that are
  24400. ** NULL or which have been previously closed. If this routine returns
  24401. ** 1 it means that the db pointer is valid and 0 if it should not be
  24402. ** dereferenced for any reason. The calling function should invoke
  24403. ** SQLITE_MISUSE immediately.
  24404. **
  24405. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  24406. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  24407. ** open properly and is not fit for general use but which can be
  24408. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  24409. */
  24410. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  24411. u32 magic;
  24412. if( db==0 ){
  24413. logBadConnection("NULL");
  24414. return 0;
  24415. }
  24416. magic = db->magic;
  24417. if( magic!=SQLITE_MAGIC_OPEN ){
  24418. if( sqlite3SafetyCheckSickOrOk(db) ){
  24419. testcase( sqlite3GlobalConfig.xLog!=0 );
  24420. logBadConnection("unopened");
  24421. }
  24422. return 0;
  24423. }else{
  24424. return 1;
  24425. }
  24426. }
  24427. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  24428. u32 magic;
  24429. magic = db->magic;
  24430. if( magic!=SQLITE_MAGIC_SICK &&
  24431. magic!=SQLITE_MAGIC_OPEN &&
  24432. magic!=SQLITE_MAGIC_BUSY ){
  24433. testcase( sqlite3GlobalConfig.xLog!=0 );
  24434. logBadConnection("invalid");
  24435. return 0;
  24436. }else{
  24437. return 1;
  24438. }
  24439. }
  24440. /*
  24441. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  24442. ** the other 64-bit signed integer at *pA and store the result in *pA.
  24443. ** Return 0 on success. Or if the operation would have resulted in an
  24444. ** overflow, leave *pA unchanged and return 1.
  24445. */
  24446. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  24447. i64 iA = *pA;
  24448. testcase( iA==0 ); testcase( iA==1 );
  24449. testcase( iB==-1 ); testcase( iB==0 );
  24450. if( iB>=0 ){
  24451. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  24452. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  24453. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  24454. }else{
  24455. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  24456. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  24457. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  24458. }
  24459. *pA += iB;
  24460. return 0;
  24461. }
  24462. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  24463. testcase( iB==SMALLEST_INT64+1 );
  24464. if( iB==SMALLEST_INT64 ){
  24465. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  24466. if( (*pA)>=0 ) return 1;
  24467. *pA -= iB;
  24468. return 0;
  24469. }else{
  24470. return sqlite3AddInt64(pA, -iB);
  24471. }
  24472. }
  24473. #define TWOPOWER32 (((i64)1)<<32)
  24474. #define TWOPOWER31 (((i64)1)<<31)
  24475. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  24476. i64 iA = *pA;
  24477. i64 iA1, iA0, iB1, iB0, r;
  24478. iA1 = iA/TWOPOWER32;
  24479. iA0 = iA % TWOPOWER32;
  24480. iB1 = iB/TWOPOWER32;
  24481. iB0 = iB % TWOPOWER32;
  24482. if( iA1==0 ){
  24483. if( iB1==0 ){
  24484. *pA *= iB;
  24485. return 0;
  24486. }
  24487. r = iA0*iB1;
  24488. }else if( iB1==0 ){
  24489. r = iA1*iB0;
  24490. }else{
  24491. /* If both iA1 and iB1 are non-zero, overflow will result */
  24492. return 1;
  24493. }
  24494. testcase( r==(-TWOPOWER31)-1 );
  24495. testcase( r==(-TWOPOWER31) );
  24496. testcase( r==TWOPOWER31 );
  24497. testcase( r==TWOPOWER31-1 );
  24498. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  24499. r *= TWOPOWER32;
  24500. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  24501. *pA = r;
  24502. return 0;
  24503. }
  24504. /*
  24505. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  24506. ** if the integer has a value of -2147483648, return +2147483647
  24507. */
  24508. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  24509. if( x>=0 ) return x;
  24510. if( x==(int)0x80000000 ) return 0x7fffffff;
  24511. return -x;
  24512. }
  24513. #ifdef SQLITE_ENABLE_8_3_NAMES
  24514. /*
  24515. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  24516. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  24517. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  24518. ** three characters, then shorten the suffix on z[] to be the last three
  24519. ** characters of the original suffix.
  24520. **
  24521. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  24522. ** do the suffix shortening regardless of URI parameter.
  24523. **
  24524. ** Examples:
  24525. **
  24526. ** test.db-journal => test.nal
  24527. ** test.db-wal => test.wal
  24528. ** test.db-shm => test.shm
  24529. ** test.db-mj7f3319fa => test.9fa
  24530. */
  24531. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  24532. #if SQLITE_ENABLE_8_3_NAMES<2
  24533. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  24534. #endif
  24535. {
  24536. int i, sz;
  24537. sz = sqlite3Strlen30(z);
  24538. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  24539. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  24540. }
  24541. }
  24542. #endif
  24543. /*
  24544. ** Find (an approximate) sum of two LogEst values. This computation is
  24545. ** not a simple "+" operator because LogEst is stored as a logarithmic
  24546. ** value.
  24547. **
  24548. */
  24549. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  24550. static const unsigned char x[] = {
  24551. 10, 10, /* 0,1 */
  24552. 9, 9, /* 2,3 */
  24553. 8, 8, /* 4,5 */
  24554. 7, 7, 7, /* 6,7,8 */
  24555. 6, 6, 6, /* 9,10,11 */
  24556. 5, 5, 5, /* 12-14 */
  24557. 4, 4, 4, 4, /* 15-18 */
  24558. 3, 3, 3, 3, 3, 3, /* 19-24 */
  24559. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  24560. };
  24561. if( a>=b ){
  24562. if( a>b+49 ) return a;
  24563. if( a>b+31 ) return a+1;
  24564. return a+x[a-b];
  24565. }else{
  24566. if( b>a+49 ) return b;
  24567. if( b>a+31 ) return b+1;
  24568. return b+x[b-a];
  24569. }
  24570. }
  24571. /*
  24572. ** Convert an integer into a LogEst. In other words, compute an
  24573. ** approximation for 10*log2(x).
  24574. */
  24575. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  24576. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  24577. LogEst y = 40;
  24578. if( x<8 ){
  24579. if( x<2 ) return 0;
  24580. while( x<8 ){ y -= 10; x <<= 1; }
  24581. }else{
  24582. while( x>255 ){ y += 40; x >>= 4; }
  24583. while( x>15 ){ y += 10; x >>= 1; }
  24584. }
  24585. return a[x&7] + y - 10;
  24586. }
  24587. #ifndef SQLITE_OMIT_VIRTUALTABLE
  24588. /*
  24589. ** Convert a double into a LogEst
  24590. ** In other words, compute an approximation for 10*log2(x).
  24591. */
  24592. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  24593. u64 a;
  24594. LogEst e;
  24595. assert( sizeof(x)==8 && sizeof(a)==8 );
  24596. if( x<=1 ) return 0;
  24597. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  24598. memcpy(&a, &x, 8);
  24599. e = (a>>52) - 1022;
  24600. return e*10;
  24601. }
  24602. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  24603. /*
  24604. ** Convert a LogEst into an integer.
  24605. */
  24606. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  24607. u64 n;
  24608. if( x<10 ) return 1;
  24609. n = x%10;
  24610. x /= 10;
  24611. if( n>=5 ) n -= 2;
  24612. else if( n>=1 ) n -= 1;
  24613. if( x>=3 ){
  24614. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  24615. }
  24616. return (n+8)>>(3-x);
  24617. }
  24618. /************** End of util.c ************************************************/
  24619. /************** Begin file hash.c ********************************************/
  24620. /*
  24621. ** 2001 September 22
  24622. **
  24623. ** The author disclaims copyright to this source code. In place of
  24624. ** a legal notice, here is a blessing:
  24625. **
  24626. ** May you do good and not evil.
  24627. ** May you find forgiveness for yourself and forgive others.
  24628. ** May you share freely, never taking more than you give.
  24629. **
  24630. *************************************************************************
  24631. ** This is the implementation of generic hash-tables
  24632. ** used in SQLite.
  24633. */
  24634. /* #include "sqliteInt.h" */
  24635. /* #include <assert.h> */
  24636. /* Turn bulk memory into a hash table object by initializing the
  24637. ** fields of the Hash structure.
  24638. **
  24639. ** "pNew" is a pointer to the hash table that is to be initialized.
  24640. */
  24641. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  24642. assert( pNew!=0 );
  24643. pNew->first = 0;
  24644. pNew->count = 0;
  24645. pNew->htsize = 0;
  24646. pNew->ht = 0;
  24647. }
  24648. /* Remove all entries from a hash table. Reclaim all memory.
  24649. ** Call this routine to delete a hash table or to reset a hash table
  24650. ** to the empty state.
  24651. */
  24652. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  24653. HashElem *elem; /* For looping over all elements of the table */
  24654. assert( pH!=0 );
  24655. elem = pH->first;
  24656. pH->first = 0;
  24657. sqlite3_free(pH->ht);
  24658. pH->ht = 0;
  24659. pH->htsize = 0;
  24660. while( elem ){
  24661. HashElem *next_elem = elem->next;
  24662. sqlite3_free(elem);
  24663. elem = next_elem;
  24664. }
  24665. pH->count = 0;
  24666. }
  24667. /*
  24668. ** The hashing function.
  24669. */
  24670. static unsigned int strHash(const char *z){
  24671. unsigned int h = 0;
  24672. unsigned char c;
  24673. while( (c = (unsigned char)*z++)!=0 ){
  24674. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  24675. }
  24676. return h;
  24677. }
  24678. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  24679. ** insert pNew into the pEntry hash bucket.
  24680. */
  24681. static void insertElement(
  24682. Hash *pH, /* The complete hash table */
  24683. struct _ht *pEntry, /* The entry into which pNew is inserted */
  24684. HashElem *pNew /* The element to be inserted */
  24685. ){
  24686. HashElem *pHead; /* First element already in pEntry */
  24687. if( pEntry ){
  24688. pHead = pEntry->count ? pEntry->chain : 0;
  24689. pEntry->count++;
  24690. pEntry->chain = pNew;
  24691. }else{
  24692. pHead = 0;
  24693. }
  24694. if( pHead ){
  24695. pNew->next = pHead;
  24696. pNew->prev = pHead->prev;
  24697. if( pHead->prev ){ pHead->prev->next = pNew; }
  24698. else { pH->first = pNew; }
  24699. pHead->prev = pNew;
  24700. }else{
  24701. pNew->next = pH->first;
  24702. if( pH->first ){ pH->first->prev = pNew; }
  24703. pNew->prev = 0;
  24704. pH->first = pNew;
  24705. }
  24706. }
  24707. /* Resize the hash table so that it cantains "new_size" buckets.
  24708. **
  24709. ** The hash table might fail to resize if sqlite3_malloc() fails or
  24710. ** if the new size is the same as the prior size.
  24711. ** Return TRUE if the resize occurs and false if not.
  24712. */
  24713. static int rehash(Hash *pH, unsigned int new_size){
  24714. struct _ht *new_ht; /* The new hash table */
  24715. HashElem *elem, *next_elem; /* For looping over existing elements */
  24716. #if SQLITE_MALLOC_SOFT_LIMIT>0
  24717. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  24718. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  24719. }
  24720. if( new_size==pH->htsize ) return 0;
  24721. #endif
  24722. /* The inability to allocates space for a larger hash table is
  24723. ** a performance hit but it is not a fatal error. So mark the
  24724. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  24725. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  24726. ** only zeroes the requested number of bytes whereas this module will
  24727. ** use the actual amount of space allocated for the hash table (which
  24728. ** may be larger than the requested amount).
  24729. */
  24730. sqlite3BeginBenignMalloc();
  24731. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  24732. sqlite3EndBenignMalloc();
  24733. if( new_ht==0 ) return 0;
  24734. sqlite3_free(pH->ht);
  24735. pH->ht = new_ht;
  24736. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  24737. memset(new_ht, 0, new_size*sizeof(struct _ht));
  24738. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  24739. unsigned int h = strHash(elem->pKey) % new_size;
  24740. next_elem = elem->next;
  24741. insertElement(pH, &new_ht[h], elem);
  24742. }
  24743. return 1;
  24744. }
  24745. /* This function (for internal use only) locates an element in an
  24746. ** hash table that matches the given key. The hash for this key is
  24747. ** also computed and returned in the *pH parameter.
  24748. */
  24749. static HashElem *findElementWithHash(
  24750. const Hash *pH, /* The pH to be searched */
  24751. const char *pKey, /* The key we are searching for */
  24752. unsigned int *pHash /* Write the hash value here */
  24753. ){
  24754. HashElem *elem; /* Used to loop thru the element list */
  24755. int count; /* Number of elements left to test */
  24756. unsigned int h; /* The computed hash */
  24757. if( pH->ht ){
  24758. struct _ht *pEntry;
  24759. h = strHash(pKey) % pH->htsize;
  24760. pEntry = &pH->ht[h];
  24761. elem = pEntry->chain;
  24762. count = pEntry->count;
  24763. }else{
  24764. h = 0;
  24765. elem = pH->first;
  24766. count = pH->count;
  24767. }
  24768. *pHash = h;
  24769. while( count-- ){
  24770. assert( elem!=0 );
  24771. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  24772. return elem;
  24773. }
  24774. elem = elem->next;
  24775. }
  24776. return 0;
  24777. }
  24778. /* Remove a single entry from the hash table given a pointer to that
  24779. ** element and a hash on the element's key.
  24780. */
  24781. static void removeElementGivenHash(
  24782. Hash *pH, /* The pH containing "elem" */
  24783. HashElem* elem, /* The element to be removed from the pH */
  24784. unsigned int h /* Hash value for the element */
  24785. ){
  24786. struct _ht *pEntry;
  24787. if( elem->prev ){
  24788. elem->prev->next = elem->next;
  24789. }else{
  24790. pH->first = elem->next;
  24791. }
  24792. if( elem->next ){
  24793. elem->next->prev = elem->prev;
  24794. }
  24795. if( pH->ht ){
  24796. pEntry = &pH->ht[h];
  24797. if( pEntry->chain==elem ){
  24798. pEntry->chain = elem->next;
  24799. }
  24800. pEntry->count--;
  24801. assert( pEntry->count>=0 );
  24802. }
  24803. sqlite3_free( elem );
  24804. pH->count--;
  24805. if( pH->count==0 ){
  24806. assert( pH->first==0 );
  24807. assert( pH->count==0 );
  24808. sqlite3HashClear(pH);
  24809. }
  24810. }
  24811. /* Attempt to locate an element of the hash table pH with a key
  24812. ** that matches pKey. Return the data for this element if it is
  24813. ** found, or NULL if there is no match.
  24814. */
  24815. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  24816. HashElem *elem; /* The element that matches key */
  24817. unsigned int h; /* A hash on key */
  24818. assert( pH!=0 );
  24819. assert( pKey!=0 );
  24820. elem = findElementWithHash(pH, pKey, &h);
  24821. return elem ? elem->data : 0;
  24822. }
  24823. /* Insert an element into the hash table pH. The key is pKey
  24824. ** and the data is "data".
  24825. **
  24826. ** If no element exists with a matching key, then a new
  24827. ** element is created and NULL is returned.
  24828. **
  24829. ** If another element already exists with the same key, then the
  24830. ** new data replaces the old data and the old data is returned.
  24831. ** The key is not copied in this instance. If a malloc fails, then
  24832. ** the new data is returned and the hash table is unchanged.
  24833. **
  24834. ** If the "data" parameter to this function is NULL, then the
  24835. ** element corresponding to "key" is removed from the hash table.
  24836. */
  24837. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  24838. unsigned int h; /* the hash of the key modulo hash table size */
  24839. HashElem *elem; /* Used to loop thru the element list */
  24840. HashElem *new_elem; /* New element added to the pH */
  24841. assert( pH!=0 );
  24842. assert( pKey!=0 );
  24843. elem = findElementWithHash(pH,pKey,&h);
  24844. if( elem ){
  24845. void *old_data = elem->data;
  24846. if( data==0 ){
  24847. removeElementGivenHash(pH,elem,h);
  24848. }else{
  24849. elem->data = data;
  24850. elem->pKey = pKey;
  24851. }
  24852. return old_data;
  24853. }
  24854. if( data==0 ) return 0;
  24855. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  24856. if( new_elem==0 ) return data;
  24857. new_elem->pKey = pKey;
  24858. new_elem->data = data;
  24859. pH->count++;
  24860. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  24861. if( rehash(pH, pH->count*2) ){
  24862. assert( pH->htsize>0 );
  24863. h = strHash(pKey) % pH->htsize;
  24864. }
  24865. }
  24866. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  24867. return 0;
  24868. }
  24869. /************** End of hash.c ************************************************/
  24870. /************** Begin file opcodes.c *****************************************/
  24871. /* Automatically generated. Do not edit */
  24872. /* See the mkopcodec.awk script for details. */
  24873. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  24874. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  24875. # define OpHelp(X) "\0" X
  24876. #else
  24877. # define OpHelp(X)
  24878. #endif
  24879. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  24880. static const char *const azName[] = { "?",
  24881. /* 1 */ "Savepoint" OpHelp(""),
  24882. /* 2 */ "AutoCommit" OpHelp(""),
  24883. /* 3 */ "Transaction" OpHelp(""),
  24884. /* 4 */ "SorterNext" OpHelp(""),
  24885. /* 5 */ "PrevIfOpen" OpHelp(""),
  24886. /* 6 */ "NextIfOpen" OpHelp(""),
  24887. /* 7 */ "Prev" OpHelp(""),
  24888. /* 8 */ "Next" OpHelp(""),
  24889. /* 9 */ "Checkpoint" OpHelp(""),
  24890. /* 10 */ "JournalMode" OpHelp(""),
  24891. /* 11 */ "Vacuum" OpHelp(""),
  24892. /* 12 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  24893. /* 13 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  24894. /* 14 */ "Goto" OpHelp(""),
  24895. /* 15 */ "Gosub" OpHelp(""),
  24896. /* 16 */ "Return" OpHelp(""),
  24897. /* 17 */ "InitCoroutine" OpHelp(""),
  24898. /* 18 */ "EndCoroutine" OpHelp(""),
  24899. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  24900. /* 20 */ "Yield" OpHelp(""),
  24901. /* 21 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  24902. /* 22 */ "Halt" OpHelp(""),
  24903. /* 23 */ "Integer" OpHelp("r[P2]=P1"),
  24904. /* 24 */ "Int64" OpHelp("r[P2]=P4"),
  24905. /* 25 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  24906. /* 26 */ "Null" OpHelp("r[P2..P3]=NULL"),
  24907. /* 27 */ "SoftNull" OpHelp("r[P1]=NULL"),
  24908. /* 28 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  24909. /* 29 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  24910. /* 30 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  24911. /* 31 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  24912. /* 32 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  24913. /* 33 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  24914. /* 34 */ "CollSeq" OpHelp(""),
  24915. /* 35 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  24916. /* 36 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  24917. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  24918. /* 38 */ "MustBeInt" OpHelp(""),
  24919. /* 39 */ "RealAffinity" OpHelp(""),
  24920. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  24921. /* 41 */ "Permutation" OpHelp(""),
  24922. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  24923. /* 43 */ "Jump" OpHelp(""),
  24924. /* 44 */ "Once" OpHelp(""),
  24925. /* 45 */ "If" OpHelp(""),
  24926. /* 46 */ "IfNot" OpHelp(""),
  24927. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  24928. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  24929. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  24930. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  24931. /* 51 */ "ReadCookie" OpHelp(""),
  24932. /* 52 */ "SetCookie" OpHelp(""),
  24933. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  24934. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  24935. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  24936. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  24937. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  24938. /* 58 */ "SorterOpen" OpHelp(""),
  24939. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  24940. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  24941. /* 61 */ "Close" OpHelp(""),
  24942. /* 62 */ "ColumnsUsed" OpHelp(""),
  24943. /* 63 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  24944. /* 64 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  24945. /* 65 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  24946. /* 66 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  24947. /* 67 */ "Seek" OpHelp("intkey=r[P2]"),
  24948. /* 68 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  24949. /* 69 */ "NotFound" OpHelp("key=r[P3@P4]"),
  24950. /* 70 */ "Found" OpHelp("key=r[P3@P4]"),
  24951. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  24952. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  24953. /* 73 */ "NotExists" OpHelp("intkey=r[P3]"),
  24954. /* 74 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  24955. /* 75 */ "NewRowid" OpHelp("r[P2]=rowid"),
  24956. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  24957. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  24958. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  24959. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  24960. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  24961. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  24962. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  24963. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  24964. /* 84 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  24965. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  24966. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  24967. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  24968. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  24969. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  24970. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  24971. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  24972. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  24973. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  24974. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  24975. /* 95 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  24976. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  24977. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  24978. /* 98 */ "Delete" OpHelp(""),
  24979. /* 99 */ "ResetCount" OpHelp(""),
  24980. /* 100 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  24981. /* 101 */ "SorterData" OpHelp("r[P2]=data"),
  24982. /* 102 */ "RowKey" OpHelp("r[P2]=key"),
  24983. /* 103 */ "RowData" OpHelp("r[P2]=data"),
  24984. /* 104 */ "Rowid" OpHelp("r[P2]=rowid"),
  24985. /* 105 */ "NullRow" OpHelp(""),
  24986. /* 106 */ "Last" OpHelp(""),
  24987. /* 107 */ "SorterSort" OpHelp(""),
  24988. /* 108 */ "Sort" OpHelp(""),
  24989. /* 109 */ "Rewind" OpHelp(""),
  24990. /* 110 */ "SorterInsert" OpHelp(""),
  24991. /* 111 */ "IdxInsert" OpHelp("key=r[P2]"),
  24992. /* 112 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  24993. /* 113 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  24994. /* 114 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  24995. /* 115 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  24996. /* 116 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  24997. /* 117 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  24998. /* 118 */ "Destroy" OpHelp(""),
  24999. /* 119 */ "Clear" OpHelp(""),
  25000. /* 120 */ "ResetSorter" OpHelp(""),
  25001. /* 121 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  25002. /* 122 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  25003. /* 123 */ "ParseSchema" OpHelp(""),
  25004. /* 124 */ "LoadAnalysis" OpHelp(""),
  25005. /* 125 */ "DropTable" OpHelp(""),
  25006. /* 126 */ "DropIndex" OpHelp(""),
  25007. /* 127 */ "DropTrigger" OpHelp(""),
  25008. /* 128 */ "IntegrityCk" OpHelp(""),
  25009. /* 129 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  25010. /* 130 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  25011. /* 131 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  25012. /* 132 */ "Program" OpHelp(""),
  25013. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  25014. /* 134 */ "Param" OpHelp(""),
  25015. /* 135 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  25016. /* 136 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  25017. /* 137 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  25018. /* 138 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  25019. /* 139 */ "SetIfNotPos" OpHelp("if r[P1]<=0 then r[P2]=P3"),
  25020. /* 140 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
  25021. /* 141 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  25022. /* 142 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
  25023. /* 143 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25024. /* 144 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25025. /* 145 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  25026. /* 146 */ "IncrVacuum" OpHelp(""),
  25027. /* 147 */ "Expire" OpHelp(""),
  25028. /* 148 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  25029. /* 149 */ "VBegin" OpHelp(""),
  25030. /* 150 */ "VCreate" OpHelp(""),
  25031. /* 151 */ "VDestroy" OpHelp(""),
  25032. /* 152 */ "VOpen" OpHelp(""),
  25033. /* 153 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  25034. /* 154 */ "VNext" OpHelp(""),
  25035. /* 155 */ "VRename" OpHelp(""),
  25036. /* 156 */ "Pagecount" OpHelp(""),
  25037. /* 157 */ "MaxPgcnt" OpHelp(""),
  25038. /* 158 */ "Init" OpHelp("Start at P2"),
  25039. /* 159 */ "Noop" OpHelp(""),
  25040. /* 160 */ "Explain" OpHelp(""),
  25041. };
  25042. return azName[i];
  25043. }
  25044. #endif
  25045. /************** End of opcodes.c *********************************************/
  25046. /************** Begin file os_unix.c *****************************************/
  25047. /*
  25048. ** 2004 May 22
  25049. **
  25050. ** The author disclaims copyright to this source code. In place of
  25051. ** a legal notice, here is a blessing:
  25052. **
  25053. ** May you do good and not evil.
  25054. ** May you find forgiveness for yourself and forgive others.
  25055. ** May you share freely, never taking more than you give.
  25056. **
  25057. ******************************************************************************
  25058. **
  25059. ** This file contains the VFS implementation for unix-like operating systems
  25060. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  25061. **
  25062. ** There are actually several different VFS implementations in this file.
  25063. ** The differences are in the way that file locking is done. The default
  25064. ** implementation uses Posix Advisory Locks. Alternative implementations
  25065. ** use flock(), dot-files, various proprietary locking schemas, or simply
  25066. ** skip locking all together.
  25067. **
  25068. ** This source file is organized into divisions where the logic for various
  25069. ** subfunctions is contained within the appropriate division. PLEASE
  25070. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  25071. ** in the correct division and should be clearly labeled.
  25072. **
  25073. ** The layout of divisions is as follows:
  25074. **
  25075. ** * General-purpose declarations and utility functions.
  25076. ** * Unique file ID logic used by VxWorks.
  25077. ** * Various locking primitive implementations (all except proxy locking):
  25078. ** + for Posix Advisory Locks
  25079. ** + for no-op locks
  25080. ** + for dot-file locks
  25081. ** + for flock() locking
  25082. ** + for named semaphore locks (VxWorks only)
  25083. ** + for AFP filesystem locks (MacOSX only)
  25084. ** * sqlite3_file methods not associated with locking.
  25085. ** * Definitions of sqlite3_io_methods objects for all locking
  25086. ** methods plus "finder" functions for each locking method.
  25087. ** * sqlite3_vfs method implementations.
  25088. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  25089. ** * Definitions of sqlite3_vfs objects for all locking methods
  25090. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  25091. */
  25092. /* #include "sqliteInt.h" */
  25093. #if SQLITE_OS_UNIX /* This file is used on unix only */
  25094. /*
  25095. ** There are various methods for file locking used for concurrency
  25096. ** control:
  25097. **
  25098. ** 1. POSIX locking (the default),
  25099. ** 2. No locking,
  25100. ** 3. Dot-file locking,
  25101. ** 4. flock() locking,
  25102. ** 5. AFP locking (OSX only),
  25103. ** 6. Named POSIX semaphores (VXWorks only),
  25104. ** 7. proxy locking. (OSX only)
  25105. **
  25106. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  25107. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  25108. ** selection of the appropriate locking style based on the filesystem
  25109. ** where the database is located.
  25110. */
  25111. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  25112. # if defined(__APPLE__)
  25113. # define SQLITE_ENABLE_LOCKING_STYLE 1
  25114. # else
  25115. # define SQLITE_ENABLE_LOCKING_STYLE 0
  25116. # endif
  25117. #endif
  25118. /*
  25119. ** standard include files.
  25120. */
  25121. #include <sys/types.h>
  25122. #include <sys/stat.h>
  25123. #include <fcntl.h>
  25124. #include <unistd.h>
  25125. /* #include <time.h> */
  25126. #include <sys/time.h>
  25127. #include <errno.h>
  25128. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  25129. # include <sys/mman.h>
  25130. #endif
  25131. #if SQLITE_ENABLE_LOCKING_STYLE
  25132. # include <sys/ioctl.h>
  25133. # include <sys/file.h>
  25134. # include <sys/param.h>
  25135. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  25136. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  25137. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  25138. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  25139. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  25140. # define HAVE_GETHOSTUUID 1
  25141. # else
  25142. # warning "gethostuuid() is disabled."
  25143. # endif
  25144. #endif
  25145. #if OS_VXWORKS
  25146. /* # include <sys/ioctl.h> */
  25147. # include <semaphore.h>
  25148. # include <limits.h>
  25149. #endif /* OS_VXWORKS */
  25150. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  25151. # include <sys/mount.h>
  25152. #endif
  25153. #ifdef HAVE_UTIME
  25154. # include <utime.h>
  25155. #endif
  25156. /*
  25157. ** Allowed values of unixFile.fsFlags
  25158. */
  25159. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  25160. /*
  25161. ** If we are to be thread-safe, include the pthreads header and define
  25162. ** the SQLITE_UNIX_THREADS macro.
  25163. */
  25164. #if SQLITE_THREADSAFE
  25165. /* # include <pthread.h> */
  25166. # define SQLITE_UNIX_THREADS 1
  25167. #endif
  25168. /*
  25169. ** Default permissions when creating a new file
  25170. */
  25171. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  25172. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  25173. #endif
  25174. /*
  25175. ** Default permissions when creating auto proxy dir
  25176. */
  25177. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  25178. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  25179. #endif
  25180. /*
  25181. ** Maximum supported path-length.
  25182. */
  25183. #define MAX_PATHNAME 512
  25184. /* Always cast the getpid() return type for compatibility with
  25185. ** kernel modules in VxWorks. */
  25186. #define osGetpid(X) (pid_t)getpid()
  25187. /*
  25188. ** Only set the lastErrno if the error code is a real error and not
  25189. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  25190. */
  25191. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  25192. /* Forward references */
  25193. typedef struct unixShm unixShm; /* Connection shared memory */
  25194. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  25195. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  25196. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  25197. /*
  25198. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  25199. ** cannot be closed immediately. In these cases, instances of the following
  25200. ** structure are used to store the file descriptor while waiting for an
  25201. ** opportunity to either close or reuse it.
  25202. */
  25203. struct UnixUnusedFd {
  25204. int fd; /* File descriptor to close */
  25205. int flags; /* Flags this file descriptor was opened with */
  25206. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  25207. };
  25208. /*
  25209. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  25210. ** VFS implementations.
  25211. */
  25212. typedef struct unixFile unixFile;
  25213. struct unixFile {
  25214. sqlite3_io_methods const *pMethod; /* Always the first entry */
  25215. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  25216. unixInodeInfo *pInode; /* Info about locks on this inode */
  25217. int h; /* The file descriptor */
  25218. unsigned char eFileLock; /* The type of lock held on this fd */
  25219. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  25220. int lastErrno; /* The unix errno from last I/O error */
  25221. void *lockingContext; /* Locking style specific state */
  25222. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  25223. const char *zPath; /* Name of the file */
  25224. unixShm *pShm; /* Shared memory segment information */
  25225. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  25226. #if SQLITE_MAX_MMAP_SIZE>0
  25227. int nFetchOut; /* Number of outstanding xFetch refs */
  25228. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  25229. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  25230. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  25231. void *pMapRegion; /* Memory mapped region */
  25232. #endif
  25233. #ifdef __QNXNTO__
  25234. int sectorSize; /* Device sector size */
  25235. int deviceCharacteristics; /* Precomputed device characteristics */
  25236. #endif
  25237. #if SQLITE_ENABLE_LOCKING_STYLE
  25238. int openFlags; /* The flags specified at open() */
  25239. #endif
  25240. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  25241. unsigned fsFlags; /* cached details from statfs() */
  25242. #endif
  25243. #if OS_VXWORKS
  25244. struct vxworksFileId *pId; /* Unique file ID */
  25245. #endif
  25246. #ifdef SQLITE_DEBUG
  25247. /* The next group of variables are used to track whether or not the
  25248. ** transaction counter in bytes 24-27 of database files are updated
  25249. ** whenever any part of the database changes. An assertion fault will
  25250. ** occur if a file is updated without also updating the transaction
  25251. ** counter. This test is made to avoid new problems similar to the
  25252. ** one described by ticket #3584.
  25253. */
  25254. unsigned char transCntrChng; /* True if the transaction counter changed */
  25255. unsigned char dbUpdate; /* True if any part of database file changed */
  25256. unsigned char inNormalWrite; /* True if in a normal write operation */
  25257. #endif
  25258. #ifdef SQLITE_TEST
  25259. /* In test mode, increase the size of this structure a bit so that
  25260. ** it is larger than the struct CrashFile defined in test6.c.
  25261. */
  25262. char aPadding[32];
  25263. #endif
  25264. };
  25265. /* This variable holds the process id (pid) from when the xRandomness()
  25266. ** method was called. If xOpen() is called from a different process id,
  25267. ** indicating that a fork() has occurred, the PRNG will be reset.
  25268. */
  25269. static pid_t randomnessPid = 0;
  25270. /*
  25271. ** Allowed values for the unixFile.ctrlFlags bitmask:
  25272. */
  25273. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  25274. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  25275. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  25276. #ifndef SQLITE_DISABLE_DIRSYNC
  25277. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  25278. #else
  25279. # define UNIXFILE_DIRSYNC 0x00
  25280. #endif
  25281. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  25282. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  25283. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  25284. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  25285. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
  25286. #define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
  25287. /*
  25288. ** Include code that is common to all os_*.c files
  25289. */
  25290. /************** Include os_common.h in the middle of os_unix.c ***************/
  25291. /************** Begin file os_common.h ***************************************/
  25292. /*
  25293. ** 2004 May 22
  25294. **
  25295. ** The author disclaims copyright to this source code. In place of
  25296. ** a legal notice, here is a blessing:
  25297. **
  25298. ** May you do good and not evil.
  25299. ** May you find forgiveness for yourself and forgive others.
  25300. ** May you share freely, never taking more than you give.
  25301. **
  25302. ******************************************************************************
  25303. **
  25304. ** This file contains macros and a little bit of code that is common to
  25305. ** all of the platform-specific files (os_*.c) and is #included into those
  25306. ** files.
  25307. **
  25308. ** This file should be #included by the os_*.c files only. It is not a
  25309. ** general purpose header file.
  25310. */
  25311. #ifndef _OS_COMMON_H_
  25312. #define _OS_COMMON_H_
  25313. /*
  25314. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  25315. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  25316. ** switch. The following code should catch this problem at compile-time.
  25317. */
  25318. #ifdef MEMORY_DEBUG
  25319. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  25320. #endif
  25321. /*
  25322. ** Macros for performance tracing. Normally turned off. Only works
  25323. ** on i486 hardware.
  25324. */
  25325. #ifdef SQLITE_PERFORMANCE_TRACE
  25326. /*
  25327. ** hwtime.h contains inline assembler code for implementing
  25328. ** high-performance timing routines.
  25329. */
  25330. /************** Include hwtime.h in the middle of os_common.h ****************/
  25331. /************** Begin file hwtime.h ******************************************/
  25332. /*
  25333. ** 2008 May 27
  25334. **
  25335. ** The author disclaims copyright to this source code. In place of
  25336. ** a legal notice, here is a blessing:
  25337. **
  25338. ** May you do good and not evil.
  25339. ** May you find forgiveness for yourself and forgive others.
  25340. ** May you share freely, never taking more than you give.
  25341. **
  25342. ******************************************************************************
  25343. **
  25344. ** This file contains inline asm code for retrieving "high-performance"
  25345. ** counters for x86 class CPUs.
  25346. */
  25347. #ifndef _HWTIME_H_
  25348. #define _HWTIME_H_
  25349. /*
  25350. ** The following routine only works on pentium-class (or newer) processors.
  25351. ** It uses the RDTSC opcode to read the cycle count value out of the
  25352. ** processor and returns that value. This can be used for high-res
  25353. ** profiling.
  25354. */
  25355. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  25356. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  25357. #if defined(__GNUC__)
  25358. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25359. unsigned int lo, hi;
  25360. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  25361. return (sqlite_uint64)hi << 32 | lo;
  25362. }
  25363. #elif defined(_MSC_VER)
  25364. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  25365. __asm {
  25366. rdtsc
  25367. ret ; return value at EDX:EAX
  25368. }
  25369. }
  25370. #endif
  25371. #elif (defined(__GNUC__) && defined(__x86_64__))
  25372. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25373. unsigned long val;
  25374. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  25375. return val;
  25376. }
  25377. #elif (defined(__GNUC__) && defined(__ppc__))
  25378. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25379. unsigned long long retval;
  25380. unsigned long junk;
  25381. __asm__ __volatile__ ("\n\
  25382. 1: mftbu %1\n\
  25383. mftb %L0\n\
  25384. mftbu %0\n\
  25385. cmpw %0,%1\n\
  25386. bne 1b"
  25387. : "=r" (retval), "=r" (junk));
  25388. return retval;
  25389. }
  25390. #else
  25391. #error Need implementation of sqlite3Hwtime() for your platform.
  25392. /*
  25393. ** To compile without implementing sqlite3Hwtime() for your platform,
  25394. ** you can remove the above #error and use the following
  25395. ** stub function. You will lose timing support for many
  25396. ** of the debugging and testing utilities, but it should at
  25397. ** least compile and run.
  25398. */
  25399. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  25400. #endif
  25401. #endif /* !defined(_HWTIME_H_) */
  25402. /************** End of hwtime.h **********************************************/
  25403. /************** Continuing where we left off in os_common.h ******************/
  25404. static sqlite_uint64 g_start;
  25405. static sqlite_uint64 g_elapsed;
  25406. #define TIMER_START g_start=sqlite3Hwtime()
  25407. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  25408. #define TIMER_ELAPSED g_elapsed
  25409. #else
  25410. #define TIMER_START
  25411. #define TIMER_END
  25412. #define TIMER_ELAPSED ((sqlite_uint64)0)
  25413. #endif
  25414. /*
  25415. ** If we compile with the SQLITE_TEST macro set, then the following block
  25416. ** of code will give us the ability to simulate a disk I/O error. This
  25417. ** is used for testing the I/O recovery logic.
  25418. */
  25419. #ifdef SQLITE_TEST
  25420. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  25421. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  25422. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  25423. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  25424. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  25425. SQLITE_API int sqlite3_diskfull_pending = 0;
  25426. SQLITE_API int sqlite3_diskfull = 0;
  25427. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  25428. #define SimulateIOError(CODE) \
  25429. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  25430. || sqlite3_io_error_pending-- == 1 ) \
  25431. { local_ioerr(); CODE; }
  25432. static void local_ioerr(){
  25433. IOTRACE(("IOERR\n"));
  25434. sqlite3_io_error_hit++;
  25435. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  25436. }
  25437. #define SimulateDiskfullError(CODE) \
  25438. if( sqlite3_diskfull_pending ){ \
  25439. if( sqlite3_diskfull_pending == 1 ){ \
  25440. local_ioerr(); \
  25441. sqlite3_diskfull = 1; \
  25442. sqlite3_io_error_hit = 1; \
  25443. CODE; \
  25444. }else{ \
  25445. sqlite3_diskfull_pending--; \
  25446. } \
  25447. }
  25448. #else
  25449. #define SimulateIOErrorBenign(X)
  25450. #define SimulateIOError(A)
  25451. #define SimulateDiskfullError(A)
  25452. #endif
  25453. /*
  25454. ** When testing, keep a count of the number of open files.
  25455. */
  25456. #ifdef SQLITE_TEST
  25457. SQLITE_API int sqlite3_open_file_count = 0;
  25458. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  25459. #else
  25460. #define OpenCounter(X)
  25461. #endif
  25462. #endif /* !defined(_OS_COMMON_H_) */
  25463. /************** End of os_common.h *******************************************/
  25464. /************** Continuing where we left off in os_unix.c ********************/
  25465. /*
  25466. ** Define various macros that are missing from some systems.
  25467. */
  25468. #ifndef O_LARGEFILE
  25469. # define O_LARGEFILE 0
  25470. #endif
  25471. #ifdef SQLITE_DISABLE_LFS
  25472. # undef O_LARGEFILE
  25473. # define O_LARGEFILE 0
  25474. #endif
  25475. #ifndef O_NOFOLLOW
  25476. # define O_NOFOLLOW 0
  25477. #endif
  25478. #ifndef O_BINARY
  25479. # define O_BINARY 0
  25480. #endif
  25481. /*
  25482. ** The threadid macro resolves to the thread-id or to 0. Used for
  25483. ** testing and debugging only.
  25484. */
  25485. #if SQLITE_THREADSAFE
  25486. #define threadid pthread_self()
  25487. #else
  25488. #define threadid 0
  25489. #endif
  25490. /*
  25491. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  25492. */
  25493. #if !defined(HAVE_MREMAP)
  25494. # if defined(__linux__) && defined(_GNU_SOURCE)
  25495. # define HAVE_MREMAP 1
  25496. # else
  25497. # define HAVE_MREMAP 0
  25498. # endif
  25499. #endif
  25500. /*
  25501. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  25502. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  25503. */
  25504. #ifdef __ANDROID__
  25505. # define lseek lseek64
  25506. #endif
  25507. /*
  25508. ** Different Unix systems declare open() in different ways. Same use
  25509. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  25510. ** The difference is important when using a pointer to the function.
  25511. **
  25512. ** The safest way to deal with the problem is to always use this wrapper
  25513. ** which always has the same well-defined interface.
  25514. */
  25515. static int posixOpen(const char *zFile, int flags, int mode){
  25516. return open(zFile, flags, mode);
  25517. }
  25518. /*
  25519. ** On some systems, calls to fchown() will trigger a message in a security
  25520. ** log if they come from non-root processes. So avoid calling fchown() if
  25521. ** we are not running as root.
  25522. */
  25523. static int posixFchown(int fd, uid_t uid, gid_t gid){
  25524. #if OS_VXWORKS
  25525. return 0;
  25526. #else
  25527. return geteuid() ? 0 : fchown(fd,uid,gid);
  25528. #endif
  25529. }
  25530. /* Forward reference */
  25531. static int openDirectory(const char*, int*);
  25532. static int unixGetpagesize(void);
  25533. /*
  25534. ** Many system calls are accessed through pointer-to-functions so that
  25535. ** they may be overridden at runtime to facilitate fault injection during
  25536. ** testing and sandboxing. The following array holds the names and pointers
  25537. ** to all overrideable system calls.
  25538. */
  25539. static struct unix_syscall {
  25540. const char *zName; /* Name of the system call */
  25541. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  25542. sqlite3_syscall_ptr pDefault; /* Default value */
  25543. } aSyscall[] = {
  25544. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  25545. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  25546. { "close", (sqlite3_syscall_ptr)close, 0 },
  25547. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  25548. { "access", (sqlite3_syscall_ptr)access, 0 },
  25549. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  25550. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  25551. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  25552. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  25553. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  25554. /*
  25555. ** The DJGPP compiler environment looks mostly like Unix, but it
  25556. ** lacks the fcntl() system call. So redefine fcntl() to be something
  25557. ** that always succeeds. This means that locking does not occur under
  25558. ** DJGPP. But it is DOS - what did you expect?
  25559. */
  25560. #ifdef __DJGPP__
  25561. { "fstat", 0, 0 },
  25562. #define osFstat(a,b,c) 0
  25563. #else
  25564. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  25565. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  25566. #endif
  25567. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  25568. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  25569. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  25570. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  25571. { "read", (sqlite3_syscall_ptr)read, 0 },
  25572. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  25573. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  25574. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  25575. #else
  25576. { "pread", (sqlite3_syscall_ptr)0, 0 },
  25577. #endif
  25578. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  25579. #if defined(USE_PREAD64)
  25580. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  25581. #else
  25582. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  25583. #endif
  25584. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  25585. { "write", (sqlite3_syscall_ptr)write, 0 },
  25586. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  25587. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  25588. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  25589. #else
  25590. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  25591. #endif
  25592. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  25593. aSyscall[12].pCurrent)
  25594. #if defined(USE_PREAD64)
  25595. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  25596. #else
  25597. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  25598. #endif
  25599. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  25600. aSyscall[13].pCurrent)
  25601. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  25602. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  25603. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25604. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  25605. #else
  25606. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  25607. #endif
  25608. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  25609. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  25610. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  25611. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  25612. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  25613. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  25614. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  25615. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  25616. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  25617. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  25618. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  25619. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  25620. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  25621. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  25622. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  25623. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  25624. #if HAVE_MREMAP
  25625. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  25626. #else
  25627. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  25628. #endif
  25629. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  25630. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  25631. #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
  25632. #endif
  25633. }; /* End of the overrideable system calls */
  25634. /*
  25635. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  25636. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  25637. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  25638. ** system call named zName.
  25639. */
  25640. static int unixSetSystemCall(
  25641. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  25642. const char *zName, /* Name of system call to override */
  25643. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  25644. ){
  25645. unsigned int i;
  25646. int rc = SQLITE_NOTFOUND;
  25647. UNUSED_PARAMETER(pNotUsed);
  25648. if( zName==0 ){
  25649. /* If no zName is given, restore all system calls to their default
  25650. ** settings and return NULL
  25651. */
  25652. rc = SQLITE_OK;
  25653. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25654. if( aSyscall[i].pDefault ){
  25655. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  25656. }
  25657. }
  25658. }else{
  25659. /* If zName is specified, operate on only the one system call
  25660. ** specified.
  25661. */
  25662. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25663. if( strcmp(zName, aSyscall[i].zName)==0 ){
  25664. if( aSyscall[i].pDefault==0 ){
  25665. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  25666. }
  25667. rc = SQLITE_OK;
  25668. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  25669. aSyscall[i].pCurrent = pNewFunc;
  25670. break;
  25671. }
  25672. }
  25673. }
  25674. return rc;
  25675. }
  25676. /*
  25677. ** Return the value of a system call. Return NULL if zName is not a
  25678. ** recognized system call name. NULL is also returned if the system call
  25679. ** is currently undefined.
  25680. */
  25681. static sqlite3_syscall_ptr unixGetSystemCall(
  25682. sqlite3_vfs *pNotUsed,
  25683. const char *zName
  25684. ){
  25685. unsigned int i;
  25686. UNUSED_PARAMETER(pNotUsed);
  25687. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25688. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  25689. }
  25690. return 0;
  25691. }
  25692. /*
  25693. ** Return the name of the first system call after zName. If zName==NULL
  25694. ** then return the name of the first system call. Return NULL if zName
  25695. ** is the last system call or if zName is not the name of a valid
  25696. ** system call.
  25697. */
  25698. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  25699. int i = -1;
  25700. UNUSED_PARAMETER(p);
  25701. if( zName ){
  25702. for(i=0; i<ArraySize(aSyscall)-1; i++){
  25703. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  25704. }
  25705. }
  25706. for(i++; i<ArraySize(aSyscall); i++){
  25707. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  25708. }
  25709. return 0;
  25710. }
  25711. /*
  25712. ** Do not accept any file descriptor less than this value, in order to avoid
  25713. ** opening database file using file descriptors that are commonly used for
  25714. ** standard input, output, and error.
  25715. */
  25716. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  25717. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  25718. #endif
  25719. /*
  25720. ** Invoke open(). Do so multiple times, until it either succeeds or
  25721. ** fails for some reason other than EINTR.
  25722. **
  25723. ** If the file creation mode "m" is 0 then set it to the default for
  25724. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  25725. ** 0644) as modified by the system umask. If m is not 0, then
  25726. ** make the file creation mode be exactly m ignoring the umask.
  25727. **
  25728. ** The m parameter will be non-zero only when creating -wal, -journal,
  25729. ** and -shm files. We want those files to have *exactly* the same
  25730. ** permissions as their original database, unadulterated by the umask.
  25731. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  25732. ** transaction crashes and leaves behind hot journals, then any
  25733. ** process that is able to write to the database will also be able to
  25734. ** recover the hot journals.
  25735. */
  25736. static int robust_open(const char *z, int f, mode_t m){
  25737. int fd;
  25738. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  25739. while(1){
  25740. #if defined(O_CLOEXEC)
  25741. fd = osOpen(z,f|O_CLOEXEC,m2);
  25742. #else
  25743. fd = osOpen(z,f,m2);
  25744. #endif
  25745. if( fd<0 ){
  25746. if( errno==EINTR ) continue;
  25747. break;
  25748. }
  25749. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  25750. osClose(fd);
  25751. sqlite3_log(SQLITE_WARNING,
  25752. "attempt to open \"%s\" as file descriptor %d", z, fd);
  25753. fd = -1;
  25754. if( osOpen("/dev/null", f, m)<0 ) break;
  25755. }
  25756. if( fd>=0 ){
  25757. if( m!=0 ){
  25758. struct stat statbuf;
  25759. if( osFstat(fd, &statbuf)==0
  25760. && statbuf.st_size==0
  25761. && (statbuf.st_mode&0777)!=m
  25762. ){
  25763. osFchmod(fd, m);
  25764. }
  25765. }
  25766. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  25767. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  25768. #endif
  25769. }
  25770. return fd;
  25771. }
  25772. /*
  25773. ** Helper functions to obtain and relinquish the global mutex. The
  25774. ** global mutex is used to protect the unixInodeInfo and
  25775. ** vxworksFileId objects used by this file, all of which may be
  25776. ** shared by multiple threads.
  25777. **
  25778. ** Function unixMutexHeld() is used to assert() that the global mutex
  25779. ** is held when required. This function is only used as part of assert()
  25780. ** statements. e.g.
  25781. **
  25782. ** unixEnterMutex()
  25783. ** assert( unixMutexHeld() );
  25784. ** unixEnterLeave()
  25785. */
  25786. static void unixEnterMutex(void){
  25787. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25788. }
  25789. static void unixLeaveMutex(void){
  25790. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25791. }
  25792. #ifdef SQLITE_DEBUG
  25793. static int unixMutexHeld(void) {
  25794. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25795. }
  25796. #endif
  25797. #ifdef SQLITE_HAVE_OS_TRACE
  25798. /*
  25799. ** Helper function for printing out trace information from debugging
  25800. ** binaries. This returns the string representation of the supplied
  25801. ** integer lock-type.
  25802. */
  25803. static const char *azFileLock(int eFileLock){
  25804. switch( eFileLock ){
  25805. case NO_LOCK: return "NONE";
  25806. case SHARED_LOCK: return "SHARED";
  25807. case RESERVED_LOCK: return "RESERVED";
  25808. case PENDING_LOCK: return "PENDING";
  25809. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  25810. }
  25811. return "ERROR";
  25812. }
  25813. #endif
  25814. #ifdef SQLITE_LOCK_TRACE
  25815. /*
  25816. ** Print out information about all locking operations.
  25817. **
  25818. ** This routine is used for troubleshooting locks on multithreaded
  25819. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  25820. ** command-line option on the compiler. This code is normally
  25821. ** turned off.
  25822. */
  25823. static int lockTrace(int fd, int op, struct flock *p){
  25824. char *zOpName, *zType;
  25825. int s;
  25826. int savedErrno;
  25827. if( op==F_GETLK ){
  25828. zOpName = "GETLK";
  25829. }else if( op==F_SETLK ){
  25830. zOpName = "SETLK";
  25831. }else{
  25832. s = osFcntl(fd, op, p);
  25833. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  25834. return s;
  25835. }
  25836. if( p->l_type==F_RDLCK ){
  25837. zType = "RDLCK";
  25838. }else if( p->l_type==F_WRLCK ){
  25839. zType = "WRLCK";
  25840. }else if( p->l_type==F_UNLCK ){
  25841. zType = "UNLCK";
  25842. }else{
  25843. assert( 0 );
  25844. }
  25845. assert( p->l_whence==SEEK_SET );
  25846. s = osFcntl(fd, op, p);
  25847. savedErrno = errno;
  25848. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  25849. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  25850. (int)p->l_pid, s);
  25851. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  25852. struct flock l2;
  25853. l2 = *p;
  25854. osFcntl(fd, F_GETLK, &l2);
  25855. if( l2.l_type==F_RDLCK ){
  25856. zType = "RDLCK";
  25857. }else if( l2.l_type==F_WRLCK ){
  25858. zType = "WRLCK";
  25859. }else if( l2.l_type==F_UNLCK ){
  25860. zType = "UNLCK";
  25861. }else{
  25862. assert( 0 );
  25863. }
  25864. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  25865. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  25866. }
  25867. errno = savedErrno;
  25868. return s;
  25869. }
  25870. #undef osFcntl
  25871. #define osFcntl lockTrace
  25872. #endif /* SQLITE_LOCK_TRACE */
  25873. /*
  25874. ** Retry ftruncate() calls that fail due to EINTR
  25875. **
  25876. ** All calls to ftruncate() within this file should be made through
  25877. ** this wrapper. On the Android platform, bypassing the logic below
  25878. ** could lead to a corrupt database.
  25879. */
  25880. static int robust_ftruncate(int h, sqlite3_int64 sz){
  25881. int rc;
  25882. #ifdef __ANDROID__
  25883. /* On Android, ftruncate() always uses 32-bit offsets, even if
  25884. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  25885. ** truncate a file to any size larger than 2GiB. Silently ignore any
  25886. ** such attempts. */
  25887. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  25888. rc = SQLITE_OK;
  25889. }else
  25890. #endif
  25891. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  25892. return rc;
  25893. }
  25894. /*
  25895. ** This routine translates a standard POSIX errno code into something
  25896. ** useful to the clients of the sqlite3 functions. Specifically, it is
  25897. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  25898. ** and a variety of "please close the file descriptor NOW" errors into
  25899. ** SQLITE_IOERR
  25900. **
  25901. ** Errors during initialization of locks, or file system support for locks,
  25902. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  25903. */
  25904. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  25905. switch (posixError) {
  25906. #if 0
  25907. /* At one point this code was not commented out. In theory, this branch
  25908. ** should never be hit, as this function should only be called after
  25909. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  25910. ** the value of errno as the first argument. Since a system call has failed,
  25911. ** errno should be non-zero.
  25912. **
  25913. ** Despite this, if errno really is zero, we still don't want to return
  25914. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  25915. ** propagated back to the caller. Commenting this branch out means errno==0
  25916. ** will be handled by the "default:" case below.
  25917. */
  25918. case 0:
  25919. return SQLITE_OK;
  25920. #endif
  25921. case EAGAIN:
  25922. case ETIMEDOUT:
  25923. case EBUSY:
  25924. case EINTR:
  25925. case ENOLCK:
  25926. /* random NFS retry error, unless during file system support
  25927. * introspection, in which it actually means what it says */
  25928. return SQLITE_BUSY;
  25929. case EACCES:
  25930. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  25931. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  25932. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  25933. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  25934. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  25935. return SQLITE_BUSY;
  25936. }
  25937. /* else fall through */
  25938. case EPERM:
  25939. return SQLITE_PERM;
  25940. #if EOPNOTSUPP!=ENOTSUP
  25941. case EOPNOTSUPP:
  25942. /* something went terribly awry, unless during file system support
  25943. * introspection, in which it actually means what it says */
  25944. #endif
  25945. #ifdef ENOTSUP
  25946. case ENOTSUP:
  25947. /* invalid fd, unless during file system support introspection, in which
  25948. * it actually means what it says */
  25949. #endif
  25950. case EIO:
  25951. case EBADF:
  25952. case EINVAL:
  25953. case ENOTCONN:
  25954. case ENODEV:
  25955. case ENXIO:
  25956. case ENOENT:
  25957. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  25958. case ESTALE:
  25959. #endif
  25960. case ENOSYS:
  25961. /* these should force the client to close the file and reconnect */
  25962. default:
  25963. return sqliteIOErr;
  25964. }
  25965. }
  25966. /******************************************************************************
  25967. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  25968. **
  25969. ** On most versions of unix, we can get a unique ID for a file by concatenating
  25970. ** the device number and the inode number. But this does not work on VxWorks.
  25971. ** On VxWorks, a unique file id must be based on the canonical filename.
  25972. **
  25973. ** A pointer to an instance of the following structure can be used as a
  25974. ** unique file ID in VxWorks. Each instance of this structure contains
  25975. ** a copy of the canonical filename. There is also a reference count.
  25976. ** The structure is reclaimed when the number of pointers to it drops to
  25977. ** zero.
  25978. **
  25979. ** There are never very many files open at one time and lookups are not
  25980. ** a performance-critical path, so it is sufficient to put these
  25981. ** structures on a linked list.
  25982. */
  25983. struct vxworksFileId {
  25984. struct vxworksFileId *pNext; /* Next in a list of them all */
  25985. int nRef; /* Number of references to this one */
  25986. int nName; /* Length of the zCanonicalName[] string */
  25987. char *zCanonicalName; /* Canonical filename */
  25988. };
  25989. #if OS_VXWORKS
  25990. /*
  25991. ** All unique filenames are held on a linked list headed by this
  25992. ** variable:
  25993. */
  25994. static struct vxworksFileId *vxworksFileList = 0;
  25995. /*
  25996. ** Simplify a filename into its canonical form
  25997. ** by making the following changes:
  25998. **
  25999. ** * removing any trailing and duplicate /
  26000. ** * convert /./ into just /
  26001. ** * convert /A/../ where A is any simple name into just /
  26002. **
  26003. ** Changes are made in-place. Return the new name length.
  26004. **
  26005. ** The original filename is in z[0..n-1]. Return the number of
  26006. ** characters in the simplified name.
  26007. */
  26008. static int vxworksSimplifyName(char *z, int n){
  26009. int i, j;
  26010. while( n>1 && z[n-1]=='/' ){ n--; }
  26011. for(i=j=0; i<n; i++){
  26012. if( z[i]=='/' ){
  26013. if( z[i+1]=='/' ) continue;
  26014. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  26015. i += 1;
  26016. continue;
  26017. }
  26018. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  26019. while( j>0 && z[j-1]!='/' ){ j--; }
  26020. if( j>0 ){ j--; }
  26021. i += 2;
  26022. continue;
  26023. }
  26024. }
  26025. z[j++] = z[i];
  26026. }
  26027. z[j] = 0;
  26028. return j;
  26029. }
  26030. /*
  26031. ** Find a unique file ID for the given absolute pathname. Return
  26032. ** a pointer to the vxworksFileId object. This pointer is the unique
  26033. ** file ID.
  26034. **
  26035. ** The nRef field of the vxworksFileId object is incremented before
  26036. ** the object is returned. A new vxworksFileId object is created
  26037. ** and added to the global list if necessary.
  26038. **
  26039. ** If a memory allocation error occurs, return NULL.
  26040. */
  26041. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  26042. struct vxworksFileId *pNew; /* search key and new file ID */
  26043. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  26044. int n; /* Length of zAbsoluteName string */
  26045. assert( zAbsoluteName[0]=='/' );
  26046. n = (int)strlen(zAbsoluteName);
  26047. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  26048. if( pNew==0 ) return 0;
  26049. pNew->zCanonicalName = (char*)&pNew[1];
  26050. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  26051. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  26052. /* Search for an existing entry that matching the canonical name.
  26053. ** If found, increment the reference count and return a pointer to
  26054. ** the existing file ID.
  26055. */
  26056. unixEnterMutex();
  26057. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  26058. if( pCandidate->nName==n
  26059. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  26060. ){
  26061. sqlite3_free(pNew);
  26062. pCandidate->nRef++;
  26063. unixLeaveMutex();
  26064. return pCandidate;
  26065. }
  26066. }
  26067. /* No match was found. We will make a new file ID */
  26068. pNew->nRef = 1;
  26069. pNew->nName = n;
  26070. pNew->pNext = vxworksFileList;
  26071. vxworksFileList = pNew;
  26072. unixLeaveMutex();
  26073. return pNew;
  26074. }
  26075. /*
  26076. ** Decrement the reference count on a vxworksFileId object. Free
  26077. ** the object when the reference count reaches zero.
  26078. */
  26079. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  26080. unixEnterMutex();
  26081. assert( pId->nRef>0 );
  26082. pId->nRef--;
  26083. if( pId->nRef==0 ){
  26084. struct vxworksFileId **pp;
  26085. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  26086. assert( *pp==pId );
  26087. *pp = pId->pNext;
  26088. sqlite3_free(pId);
  26089. }
  26090. unixLeaveMutex();
  26091. }
  26092. #endif /* OS_VXWORKS */
  26093. /*************** End of Unique File ID Utility Used By VxWorks ****************
  26094. ******************************************************************************/
  26095. /******************************************************************************
  26096. *************************** Posix Advisory Locking ****************************
  26097. **
  26098. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  26099. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  26100. ** sets or clears a lock, that operation overrides any prior locks set
  26101. ** by the same process. It does not explicitly say so, but this implies
  26102. ** that it overrides locks set by the same process using a different
  26103. ** file descriptor. Consider this test case:
  26104. **
  26105. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  26106. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  26107. **
  26108. ** Suppose ./file1 and ./file2 are really the same file (because
  26109. ** one is a hard or symbolic link to the other) then if you set
  26110. ** an exclusive lock on fd1, then try to get an exclusive lock
  26111. ** on fd2, it works. I would have expected the second lock to
  26112. ** fail since there was already a lock on the file due to fd1.
  26113. ** But not so. Since both locks came from the same process, the
  26114. ** second overrides the first, even though they were on different
  26115. ** file descriptors opened on different file names.
  26116. **
  26117. ** This means that we cannot use POSIX locks to synchronize file access
  26118. ** among competing threads of the same process. POSIX locks will work fine
  26119. ** to synchronize access for threads in separate processes, but not
  26120. ** threads within the same process.
  26121. **
  26122. ** To work around the problem, SQLite has to manage file locks internally
  26123. ** on its own. Whenever a new database is opened, we have to find the
  26124. ** specific inode of the database file (the inode is determined by the
  26125. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  26126. ** and check for locks already existing on that inode. When locks are
  26127. ** created or removed, we have to look at our own internal record of the
  26128. ** locks to see if another thread has previously set a lock on that same
  26129. ** inode.
  26130. **
  26131. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  26132. ** For VxWorks, we have to use the alternative unique ID system based on
  26133. ** canonical filename and implemented in the previous division.)
  26134. **
  26135. ** The sqlite3_file structure for POSIX is no longer just an integer file
  26136. ** descriptor. It is now a structure that holds the integer file
  26137. ** descriptor and a pointer to a structure that describes the internal
  26138. ** locks on the corresponding inode. There is one locking structure
  26139. ** per inode, so if the same inode is opened twice, both unixFile structures
  26140. ** point to the same locking structure. The locking structure keeps
  26141. ** a reference count (so we will know when to delete it) and a "cnt"
  26142. ** field that tells us its internal lock status. cnt==0 means the
  26143. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  26144. ** cnt>0 means there are cnt shared locks on the file.
  26145. **
  26146. ** Any attempt to lock or unlock a file first checks the locking
  26147. ** structure. The fcntl() system call is only invoked to set a
  26148. ** POSIX lock if the internal lock structure transitions between
  26149. ** a locked and an unlocked state.
  26150. **
  26151. ** But wait: there are yet more problems with POSIX advisory locks.
  26152. **
  26153. ** If you close a file descriptor that points to a file that has locks,
  26154. ** all locks on that file that are owned by the current process are
  26155. ** released. To work around this problem, each unixInodeInfo object
  26156. ** maintains a count of the number of pending locks on tha inode.
  26157. ** When an attempt is made to close an unixFile, if there are
  26158. ** other unixFile open on the same inode that are holding locks, the call
  26159. ** to close() the file descriptor is deferred until all of the locks clear.
  26160. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  26161. ** be closed and that list is walked (and cleared) when the last lock
  26162. ** clears.
  26163. **
  26164. ** Yet another problem: LinuxThreads do not play well with posix locks.
  26165. **
  26166. ** Many older versions of linux use the LinuxThreads library which is
  26167. ** not posix compliant. Under LinuxThreads, a lock created by thread
  26168. ** A cannot be modified or overridden by a different thread B.
  26169. ** Only thread A can modify the lock. Locking behavior is correct
  26170. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  26171. ** on linux - with NPTL a lock created by thread A can override locks
  26172. ** in thread B. But there is no way to know at compile-time which
  26173. ** threading library is being used. So there is no way to know at
  26174. ** compile-time whether or not thread A can override locks on thread B.
  26175. ** One has to do a run-time check to discover the behavior of the
  26176. ** current process.
  26177. **
  26178. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  26179. ** was dropped beginning with version 3.7.0. SQLite will still work with
  26180. ** LinuxThreads provided that (1) there is no more than one connection
  26181. ** per database file in the same process and (2) database connections
  26182. ** do not move across threads.
  26183. */
  26184. /*
  26185. ** An instance of the following structure serves as the key used
  26186. ** to locate a particular unixInodeInfo object.
  26187. */
  26188. struct unixFileId {
  26189. dev_t dev; /* Device number */
  26190. #if OS_VXWORKS
  26191. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  26192. #else
  26193. ino_t ino; /* Inode number */
  26194. #endif
  26195. };
  26196. /*
  26197. ** An instance of the following structure is allocated for each open
  26198. ** inode. Or, on LinuxThreads, there is one of these structures for
  26199. ** each inode opened by each thread.
  26200. **
  26201. ** A single inode can have multiple file descriptors, so each unixFile
  26202. ** structure contains a pointer to an instance of this object and this
  26203. ** object keeps a count of the number of unixFile pointing to it.
  26204. */
  26205. struct unixInodeInfo {
  26206. struct unixFileId fileId; /* The lookup key */
  26207. int nShared; /* Number of SHARED locks held */
  26208. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  26209. unsigned char bProcessLock; /* An exclusive process lock is held */
  26210. int nRef; /* Number of pointers to this structure */
  26211. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  26212. int nLock; /* Number of outstanding file locks */
  26213. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  26214. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  26215. unixInodeInfo *pPrev; /* .... doubly linked */
  26216. #if SQLITE_ENABLE_LOCKING_STYLE
  26217. unsigned long long sharedByte; /* for AFP simulated shared lock */
  26218. #endif
  26219. #if OS_VXWORKS
  26220. sem_t *pSem; /* Named POSIX semaphore */
  26221. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  26222. #endif
  26223. };
  26224. /*
  26225. ** A lists of all unixInodeInfo objects.
  26226. */
  26227. static unixInodeInfo *inodeList = 0;
  26228. /*
  26229. **
  26230. ** This function - unixLogError_x(), is only ever called via the macro
  26231. ** unixLogError().
  26232. **
  26233. ** It is invoked after an error occurs in an OS function and errno has been
  26234. ** set. It logs a message using sqlite3_log() containing the current value of
  26235. ** errno and, if possible, the human-readable equivalent from strerror() or
  26236. ** strerror_r().
  26237. **
  26238. ** The first argument passed to the macro should be the error code that
  26239. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  26240. ** The two subsequent arguments should be the name of the OS function that
  26241. ** failed (e.g. "unlink", "open") and the associated file-system path,
  26242. ** if any.
  26243. */
  26244. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  26245. static int unixLogErrorAtLine(
  26246. int errcode, /* SQLite error code */
  26247. const char *zFunc, /* Name of OS function that failed */
  26248. const char *zPath, /* File path associated with error */
  26249. int iLine /* Source line number where error occurred */
  26250. ){
  26251. char *zErr; /* Message from strerror() or equivalent */
  26252. int iErrno = errno; /* Saved syscall error number */
  26253. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  26254. ** the strerror() function to obtain the human-readable error message
  26255. ** equivalent to errno. Otherwise, use strerror_r().
  26256. */
  26257. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  26258. char aErr[80];
  26259. memset(aErr, 0, sizeof(aErr));
  26260. zErr = aErr;
  26261. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  26262. ** assume that the system provides the GNU version of strerror_r() that
  26263. ** returns a pointer to a buffer containing the error message. That pointer
  26264. ** may point to aErr[], or it may point to some static storage somewhere.
  26265. ** Otherwise, assume that the system provides the POSIX version of
  26266. ** strerror_r(), which always writes an error message into aErr[].
  26267. **
  26268. ** If the code incorrectly assumes that it is the POSIX version that is
  26269. ** available, the error message will often be an empty string. Not a
  26270. ** huge problem. Incorrectly concluding that the GNU version is available
  26271. ** could lead to a segfault though.
  26272. */
  26273. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  26274. zErr =
  26275. # endif
  26276. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  26277. #elif SQLITE_THREADSAFE
  26278. /* This is a threadsafe build, but strerror_r() is not available. */
  26279. zErr = "";
  26280. #else
  26281. /* Non-threadsafe build, use strerror(). */
  26282. zErr = strerror(iErrno);
  26283. #endif
  26284. if( zPath==0 ) zPath = "";
  26285. sqlite3_log(errcode,
  26286. "os_unix.c:%d: (%d) %s(%s) - %s",
  26287. iLine, iErrno, zFunc, zPath, zErr
  26288. );
  26289. return errcode;
  26290. }
  26291. /*
  26292. ** Close a file descriptor.
  26293. **
  26294. ** We assume that close() almost always works, since it is only in a
  26295. ** very sick application or on a very sick platform that it might fail.
  26296. ** If it does fail, simply leak the file descriptor, but do log the
  26297. ** error.
  26298. **
  26299. ** Note that it is not safe to retry close() after EINTR since the
  26300. ** file descriptor might have already been reused by another thread.
  26301. ** So we don't even try to recover from an EINTR. Just log the error
  26302. ** and move on.
  26303. */
  26304. static void robust_close(unixFile *pFile, int h, int lineno){
  26305. if( osClose(h) ){
  26306. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  26307. pFile ? pFile->zPath : 0, lineno);
  26308. }
  26309. }
  26310. /*
  26311. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  26312. ** a convenient place to set a breakpoint.
  26313. */
  26314. static void storeLastErrno(unixFile *pFile, int error){
  26315. pFile->lastErrno = error;
  26316. }
  26317. /*
  26318. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  26319. */
  26320. static void closePendingFds(unixFile *pFile){
  26321. unixInodeInfo *pInode = pFile->pInode;
  26322. UnixUnusedFd *p;
  26323. UnixUnusedFd *pNext;
  26324. for(p=pInode->pUnused; p; p=pNext){
  26325. pNext = p->pNext;
  26326. robust_close(pFile, p->fd, __LINE__);
  26327. sqlite3_free(p);
  26328. }
  26329. pInode->pUnused = 0;
  26330. }
  26331. /*
  26332. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  26333. **
  26334. ** The mutex entered using the unixEnterMutex() function must be held
  26335. ** when this function is called.
  26336. */
  26337. static void releaseInodeInfo(unixFile *pFile){
  26338. unixInodeInfo *pInode = pFile->pInode;
  26339. assert( unixMutexHeld() );
  26340. if( ALWAYS(pInode) ){
  26341. pInode->nRef--;
  26342. if( pInode->nRef==0 ){
  26343. assert( pInode->pShmNode==0 );
  26344. closePendingFds(pFile);
  26345. if( pInode->pPrev ){
  26346. assert( pInode->pPrev->pNext==pInode );
  26347. pInode->pPrev->pNext = pInode->pNext;
  26348. }else{
  26349. assert( inodeList==pInode );
  26350. inodeList = pInode->pNext;
  26351. }
  26352. if( pInode->pNext ){
  26353. assert( pInode->pNext->pPrev==pInode );
  26354. pInode->pNext->pPrev = pInode->pPrev;
  26355. }
  26356. sqlite3_free(pInode);
  26357. }
  26358. }
  26359. }
  26360. /*
  26361. ** Given a file descriptor, locate the unixInodeInfo object that
  26362. ** describes that file descriptor. Create a new one if necessary. The
  26363. ** return value might be uninitialized if an error occurs.
  26364. **
  26365. ** The mutex entered using the unixEnterMutex() function must be held
  26366. ** when this function is called.
  26367. **
  26368. ** Return an appropriate error code.
  26369. */
  26370. static int findInodeInfo(
  26371. unixFile *pFile, /* Unix file with file desc used in the key */
  26372. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  26373. ){
  26374. int rc; /* System call return code */
  26375. int fd; /* The file descriptor for pFile */
  26376. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  26377. struct stat statbuf; /* Low-level file information */
  26378. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  26379. assert( unixMutexHeld() );
  26380. /* Get low-level information about the file that we can used to
  26381. ** create a unique name for the file.
  26382. */
  26383. fd = pFile->h;
  26384. rc = osFstat(fd, &statbuf);
  26385. if( rc!=0 ){
  26386. storeLastErrno(pFile, errno);
  26387. #ifdef EOVERFLOW
  26388. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  26389. #endif
  26390. return SQLITE_IOERR;
  26391. }
  26392. #ifdef __APPLE__
  26393. /* On OS X on an msdos filesystem, the inode number is reported
  26394. ** incorrectly for zero-size files. See ticket #3260. To work
  26395. ** around this problem (we consider it a bug in OS X, not SQLite)
  26396. ** we always increase the file size to 1 by writing a single byte
  26397. ** prior to accessing the inode number. The one byte written is
  26398. ** an ASCII 'S' character which also happens to be the first byte
  26399. ** in the header of every SQLite database. In this way, if there
  26400. ** is a race condition such that another thread has already populated
  26401. ** the first page of the database, no damage is done.
  26402. */
  26403. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  26404. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  26405. if( rc!=1 ){
  26406. storeLastErrno(pFile, errno);
  26407. return SQLITE_IOERR;
  26408. }
  26409. rc = osFstat(fd, &statbuf);
  26410. if( rc!=0 ){
  26411. storeLastErrno(pFile, errno);
  26412. return SQLITE_IOERR;
  26413. }
  26414. }
  26415. #endif
  26416. memset(&fileId, 0, sizeof(fileId));
  26417. fileId.dev = statbuf.st_dev;
  26418. #if OS_VXWORKS
  26419. fileId.pId = pFile->pId;
  26420. #else
  26421. fileId.ino = statbuf.st_ino;
  26422. #endif
  26423. pInode = inodeList;
  26424. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  26425. pInode = pInode->pNext;
  26426. }
  26427. if( pInode==0 ){
  26428. pInode = sqlite3_malloc64( sizeof(*pInode) );
  26429. if( pInode==0 ){
  26430. return SQLITE_NOMEM;
  26431. }
  26432. memset(pInode, 0, sizeof(*pInode));
  26433. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  26434. pInode->nRef = 1;
  26435. pInode->pNext = inodeList;
  26436. pInode->pPrev = 0;
  26437. if( inodeList ) inodeList->pPrev = pInode;
  26438. inodeList = pInode;
  26439. }else{
  26440. pInode->nRef++;
  26441. }
  26442. *ppInode = pInode;
  26443. return SQLITE_OK;
  26444. }
  26445. /*
  26446. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  26447. */
  26448. static int fileHasMoved(unixFile *pFile){
  26449. #if OS_VXWORKS
  26450. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  26451. #else
  26452. struct stat buf;
  26453. return pFile->pInode!=0 &&
  26454. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  26455. #endif
  26456. }
  26457. /*
  26458. ** Check a unixFile that is a database. Verify the following:
  26459. **
  26460. ** (1) There is exactly one hard link on the file
  26461. ** (2) The file is not a symbolic link
  26462. ** (3) The file has not been renamed or unlinked
  26463. **
  26464. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  26465. */
  26466. static void verifyDbFile(unixFile *pFile){
  26467. struct stat buf;
  26468. int rc;
  26469. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  26470. /* One or more of the following warnings have already been issued. Do not
  26471. ** repeat them so as not to clutter the error log */
  26472. return;
  26473. }
  26474. rc = osFstat(pFile->h, &buf);
  26475. if( rc!=0 ){
  26476. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  26477. pFile->ctrlFlags |= UNIXFILE_WARNED;
  26478. return;
  26479. }
  26480. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  26481. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  26482. pFile->ctrlFlags |= UNIXFILE_WARNED;
  26483. return;
  26484. }
  26485. if( buf.st_nlink>1 ){
  26486. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  26487. pFile->ctrlFlags |= UNIXFILE_WARNED;
  26488. return;
  26489. }
  26490. if( fileHasMoved(pFile) ){
  26491. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  26492. pFile->ctrlFlags |= UNIXFILE_WARNED;
  26493. return;
  26494. }
  26495. }
  26496. /*
  26497. ** This routine checks if there is a RESERVED lock held on the specified
  26498. ** file by this or any other process. If such a lock is held, set *pResOut
  26499. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26500. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26501. */
  26502. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  26503. int rc = SQLITE_OK;
  26504. int reserved = 0;
  26505. unixFile *pFile = (unixFile*)id;
  26506. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26507. assert( pFile );
  26508. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  26509. /* Check if a thread in this process holds such a lock */
  26510. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  26511. reserved = 1;
  26512. }
  26513. /* Otherwise see if some other process holds it.
  26514. */
  26515. #ifndef __DJGPP__
  26516. if( !reserved && !pFile->pInode->bProcessLock ){
  26517. struct flock lock;
  26518. lock.l_whence = SEEK_SET;
  26519. lock.l_start = RESERVED_BYTE;
  26520. lock.l_len = 1;
  26521. lock.l_type = F_WRLCK;
  26522. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  26523. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  26524. storeLastErrno(pFile, errno);
  26525. } else if( lock.l_type!=F_UNLCK ){
  26526. reserved = 1;
  26527. }
  26528. }
  26529. #endif
  26530. unixLeaveMutex();
  26531. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  26532. *pResOut = reserved;
  26533. return rc;
  26534. }
  26535. /*
  26536. ** Attempt to set a system-lock on the file pFile. The lock is
  26537. ** described by pLock.
  26538. **
  26539. ** If the pFile was opened read/write from unix-excl, then the only lock
  26540. ** ever obtained is an exclusive lock, and it is obtained exactly once
  26541. ** the first time any lock is attempted. All subsequent system locking
  26542. ** operations become no-ops. Locking operations still happen internally,
  26543. ** in order to coordinate access between separate database connections
  26544. ** within this process, but all of that is handled in memory and the
  26545. ** operating system does not participate.
  26546. **
  26547. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  26548. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  26549. ** and is read-only.
  26550. **
  26551. ** Zero is returned if the call completes successfully, or -1 if a call
  26552. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  26553. */
  26554. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  26555. int rc;
  26556. unixInodeInfo *pInode = pFile->pInode;
  26557. assert( unixMutexHeld() );
  26558. assert( pInode!=0 );
  26559. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  26560. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  26561. ){
  26562. if( pInode->bProcessLock==0 ){
  26563. struct flock lock;
  26564. assert( pInode->nLock==0 );
  26565. lock.l_whence = SEEK_SET;
  26566. lock.l_start = SHARED_FIRST;
  26567. lock.l_len = SHARED_SIZE;
  26568. lock.l_type = F_WRLCK;
  26569. rc = osFcntl(pFile->h, F_SETLK, &lock);
  26570. if( rc<0 ) return rc;
  26571. pInode->bProcessLock = 1;
  26572. pInode->nLock++;
  26573. }else{
  26574. rc = 0;
  26575. }
  26576. }else{
  26577. rc = osFcntl(pFile->h, F_SETLK, pLock);
  26578. }
  26579. return rc;
  26580. }
  26581. /*
  26582. ** Lock the file with the lock specified by parameter eFileLock - one
  26583. ** of the following:
  26584. **
  26585. ** (1) SHARED_LOCK
  26586. ** (2) RESERVED_LOCK
  26587. ** (3) PENDING_LOCK
  26588. ** (4) EXCLUSIVE_LOCK
  26589. **
  26590. ** Sometimes when requesting one lock state, additional lock states
  26591. ** are inserted in between. The locking might fail on one of the later
  26592. ** transitions leaving the lock state different from what it started but
  26593. ** still short of its goal. The following chart shows the allowed
  26594. ** transitions and the inserted intermediate states:
  26595. **
  26596. ** UNLOCKED -> SHARED
  26597. ** SHARED -> RESERVED
  26598. ** SHARED -> (PENDING) -> EXCLUSIVE
  26599. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26600. ** PENDING -> EXCLUSIVE
  26601. **
  26602. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26603. ** routine to lower a locking level.
  26604. */
  26605. static int unixLock(sqlite3_file *id, int eFileLock){
  26606. /* The following describes the implementation of the various locks and
  26607. ** lock transitions in terms of the POSIX advisory shared and exclusive
  26608. ** lock primitives (called read-locks and write-locks below, to avoid
  26609. ** confusion with SQLite lock names). The algorithms are complicated
  26610. ** slightly in order to be compatible with windows systems simultaneously
  26611. ** accessing the same database file, in case that is ever required.
  26612. **
  26613. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  26614. ** byte', each single bytes at well known offsets, and the 'shared byte
  26615. ** range', a range of 510 bytes at a well known offset.
  26616. **
  26617. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  26618. ** byte'. If this is successful, a random byte from the 'shared byte
  26619. ** range' is read-locked and the lock on the 'pending byte' released.
  26620. **
  26621. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  26622. ** A RESERVED lock is implemented by grabbing a write-lock on the
  26623. ** 'reserved byte'.
  26624. **
  26625. ** A process may only obtain a PENDING lock after it has obtained a
  26626. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  26627. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  26628. ** obtained, but existing SHARED locks are allowed to persist. A process
  26629. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  26630. ** This property is used by the algorithm for rolling back a journal file
  26631. ** after a crash.
  26632. **
  26633. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  26634. ** implemented by obtaining a write-lock on the entire 'shared byte
  26635. ** range'. Since all other locks require a read-lock on one of the bytes
  26636. ** within this range, this ensures that no other locks are held on the
  26637. ** database.
  26638. **
  26639. ** The reason a single byte cannot be used instead of the 'shared byte
  26640. ** range' is that some versions of windows do not support read-locks. By
  26641. ** locking a random byte from a range, concurrent SHARED locks may exist
  26642. ** even if the locking primitive used is always a write-lock.
  26643. */
  26644. int rc = SQLITE_OK;
  26645. unixFile *pFile = (unixFile*)id;
  26646. unixInodeInfo *pInode;
  26647. struct flock lock;
  26648. int tErrno = 0;
  26649. assert( pFile );
  26650. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  26651. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  26652. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  26653. osGetpid(0)));
  26654. /* If there is already a lock of this type or more restrictive on the
  26655. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  26656. ** unixEnterMutex() hasn't been called yet.
  26657. */
  26658. if( pFile->eFileLock>=eFileLock ){
  26659. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  26660. azFileLock(eFileLock)));
  26661. return SQLITE_OK;
  26662. }
  26663. /* Make sure the locking sequence is correct.
  26664. ** (1) We never move from unlocked to anything higher than shared lock.
  26665. ** (2) SQLite never explicitly requests a pendig lock.
  26666. ** (3) A shared lock is always held when a reserve lock is requested.
  26667. */
  26668. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  26669. assert( eFileLock!=PENDING_LOCK );
  26670. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  26671. /* This mutex is needed because pFile->pInode is shared across threads
  26672. */
  26673. unixEnterMutex();
  26674. pInode = pFile->pInode;
  26675. /* If some thread using this PID has a lock via a different unixFile*
  26676. ** handle that precludes the requested lock, return BUSY.
  26677. */
  26678. if( (pFile->eFileLock!=pInode->eFileLock &&
  26679. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  26680. ){
  26681. rc = SQLITE_BUSY;
  26682. goto end_lock;
  26683. }
  26684. /* If a SHARED lock is requested, and some thread using this PID already
  26685. ** has a SHARED or RESERVED lock, then increment reference counts and
  26686. ** return SQLITE_OK.
  26687. */
  26688. if( eFileLock==SHARED_LOCK &&
  26689. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  26690. assert( eFileLock==SHARED_LOCK );
  26691. assert( pFile->eFileLock==0 );
  26692. assert( pInode->nShared>0 );
  26693. pFile->eFileLock = SHARED_LOCK;
  26694. pInode->nShared++;
  26695. pInode->nLock++;
  26696. goto end_lock;
  26697. }
  26698. /* A PENDING lock is needed before acquiring a SHARED lock and before
  26699. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  26700. ** be released.
  26701. */
  26702. lock.l_len = 1L;
  26703. lock.l_whence = SEEK_SET;
  26704. if( eFileLock==SHARED_LOCK
  26705. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  26706. ){
  26707. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  26708. lock.l_start = PENDING_BYTE;
  26709. if( unixFileLock(pFile, &lock) ){
  26710. tErrno = errno;
  26711. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26712. if( rc!=SQLITE_BUSY ){
  26713. storeLastErrno(pFile, tErrno);
  26714. }
  26715. goto end_lock;
  26716. }
  26717. }
  26718. /* If control gets to this point, then actually go ahead and make
  26719. ** operating system calls for the specified lock.
  26720. */
  26721. if( eFileLock==SHARED_LOCK ){
  26722. assert( pInode->nShared==0 );
  26723. assert( pInode->eFileLock==0 );
  26724. assert( rc==SQLITE_OK );
  26725. /* Now get the read-lock */
  26726. lock.l_start = SHARED_FIRST;
  26727. lock.l_len = SHARED_SIZE;
  26728. if( unixFileLock(pFile, &lock) ){
  26729. tErrno = errno;
  26730. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26731. }
  26732. /* Drop the temporary PENDING lock */
  26733. lock.l_start = PENDING_BYTE;
  26734. lock.l_len = 1L;
  26735. lock.l_type = F_UNLCK;
  26736. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  26737. /* This could happen with a network mount */
  26738. tErrno = errno;
  26739. rc = SQLITE_IOERR_UNLOCK;
  26740. }
  26741. if( rc ){
  26742. if( rc!=SQLITE_BUSY ){
  26743. storeLastErrno(pFile, tErrno);
  26744. }
  26745. goto end_lock;
  26746. }else{
  26747. pFile->eFileLock = SHARED_LOCK;
  26748. pInode->nLock++;
  26749. pInode->nShared = 1;
  26750. }
  26751. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  26752. /* We are trying for an exclusive lock but another thread in this
  26753. ** same process is still holding a shared lock. */
  26754. rc = SQLITE_BUSY;
  26755. }else{
  26756. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  26757. ** assumed that there is a SHARED or greater lock on the file
  26758. ** already.
  26759. */
  26760. assert( 0!=pFile->eFileLock );
  26761. lock.l_type = F_WRLCK;
  26762. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  26763. if( eFileLock==RESERVED_LOCK ){
  26764. lock.l_start = RESERVED_BYTE;
  26765. lock.l_len = 1L;
  26766. }else{
  26767. lock.l_start = SHARED_FIRST;
  26768. lock.l_len = SHARED_SIZE;
  26769. }
  26770. if( unixFileLock(pFile, &lock) ){
  26771. tErrno = errno;
  26772. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26773. if( rc!=SQLITE_BUSY ){
  26774. storeLastErrno(pFile, tErrno);
  26775. }
  26776. }
  26777. }
  26778. #ifdef SQLITE_DEBUG
  26779. /* Set up the transaction-counter change checking flags when
  26780. ** transitioning from a SHARED to a RESERVED lock. The change
  26781. ** from SHARED to RESERVED marks the beginning of a normal
  26782. ** write operation (not a hot journal rollback).
  26783. */
  26784. if( rc==SQLITE_OK
  26785. && pFile->eFileLock<=SHARED_LOCK
  26786. && eFileLock==RESERVED_LOCK
  26787. ){
  26788. pFile->transCntrChng = 0;
  26789. pFile->dbUpdate = 0;
  26790. pFile->inNormalWrite = 1;
  26791. }
  26792. #endif
  26793. if( rc==SQLITE_OK ){
  26794. pFile->eFileLock = eFileLock;
  26795. pInode->eFileLock = eFileLock;
  26796. }else if( eFileLock==EXCLUSIVE_LOCK ){
  26797. pFile->eFileLock = PENDING_LOCK;
  26798. pInode->eFileLock = PENDING_LOCK;
  26799. }
  26800. end_lock:
  26801. unixLeaveMutex();
  26802. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  26803. rc==SQLITE_OK ? "ok" : "failed"));
  26804. return rc;
  26805. }
  26806. /*
  26807. ** Add the file descriptor used by file handle pFile to the corresponding
  26808. ** pUnused list.
  26809. */
  26810. static void setPendingFd(unixFile *pFile){
  26811. unixInodeInfo *pInode = pFile->pInode;
  26812. UnixUnusedFd *p = pFile->pUnused;
  26813. p->pNext = pInode->pUnused;
  26814. pInode->pUnused = p;
  26815. pFile->h = -1;
  26816. pFile->pUnused = 0;
  26817. }
  26818. /*
  26819. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26820. ** must be either NO_LOCK or SHARED_LOCK.
  26821. **
  26822. ** If the locking level of the file descriptor is already at or below
  26823. ** the requested locking level, this routine is a no-op.
  26824. **
  26825. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  26826. ** the byte range is divided into 2 parts and the first part is unlocked then
  26827. ** set to a read lock, then the other part is simply unlocked. This works
  26828. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  26829. ** remove the write lock on a region when a read lock is set.
  26830. */
  26831. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  26832. unixFile *pFile = (unixFile*)id;
  26833. unixInodeInfo *pInode;
  26834. struct flock lock;
  26835. int rc = SQLITE_OK;
  26836. assert( pFile );
  26837. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  26838. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  26839. osGetpid(0)));
  26840. assert( eFileLock<=SHARED_LOCK );
  26841. if( pFile->eFileLock<=eFileLock ){
  26842. return SQLITE_OK;
  26843. }
  26844. unixEnterMutex();
  26845. pInode = pFile->pInode;
  26846. assert( pInode->nShared!=0 );
  26847. if( pFile->eFileLock>SHARED_LOCK ){
  26848. assert( pInode->eFileLock==pFile->eFileLock );
  26849. #ifdef SQLITE_DEBUG
  26850. /* When reducing a lock such that other processes can start
  26851. ** reading the database file again, make sure that the
  26852. ** transaction counter was updated if any part of the database
  26853. ** file changed. If the transaction counter is not updated,
  26854. ** other connections to the same file might not realize that
  26855. ** the file has changed and hence might not know to flush their
  26856. ** cache. The use of a stale cache can lead to database corruption.
  26857. */
  26858. pFile->inNormalWrite = 0;
  26859. #endif
  26860. /* downgrading to a shared lock on NFS involves clearing the write lock
  26861. ** before establishing the readlock - to avoid a race condition we downgrade
  26862. ** the lock in 2 blocks, so that part of the range will be covered by a
  26863. ** write lock until the rest is covered by a read lock:
  26864. ** 1: [WWWWW]
  26865. ** 2: [....W]
  26866. ** 3: [RRRRW]
  26867. ** 4: [RRRR.]
  26868. */
  26869. if( eFileLock==SHARED_LOCK ){
  26870. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  26871. (void)handleNFSUnlock;
  26872. assert( handleNFSUnlock==0 );
  26873. #endif
  26874. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26875. if( handleNFSUnlock ){
  26876. int tErrno; /* Error code from system call errors */
  26877. off_t divSize = SHARED_SIZE - 1;
  26878. lock.l_type = F_UNLCK;
  26879. lock.l_whence = SEEK_SET;
  26880. lock.l_start = SHARED_FIRST;
  26881. lock.l_len = divSize;
  26882. if( unixFileLock(pFile, &lock)==(-1) ){
  26883. tErrno = errno;
  26884. rc = SQLITE_IOERR_UNLOCK;
  26885. if( IS_LOCK_ERROR(rc) ){
  26886. storeLastErrno(pFile, tErrno);
  26887. }
  26888. goto end_unlock;
  26889. }
  26890. lock.l_type = F_RDLCK;
  26891. lock.l_whence = SEEK_SET;
  26892. lock.l_start = SHARED_FIRST;
  26893. lock.l_len = divSize;
  26894. if( unixFileLock(pFile, &lock)==(-1) ){
  26895. tErrno = errno;
  26896. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  26897. if( IS_LOCK_ERROR(rc) ){
  26898. storeLastErrno(pFile, tErrno);
  26899. }
  26900. goto end_unlock;
  26901. }
  26902. lock.l_type = F_UNLCK;
  26903. lock.l_whence = SEEK_SET;
  26904. lock.l_start = SHARED_FIRST+divSize;
  26905. lock.l_len = SHARED_SIZE-divSize;
  26906. if( unixFileLock(pFile, &lock)==(-1) ){
  26907. tErrno = errno;
  26908. rc = SQLITE_IOERR_UNLOCK;
  26909. if( IS_LOCK_ERROR(rc) ){
  26910. storeLastErrno(pFile, tErrno);
  26911. }
  26912. goto end_unlock;
  26913. }
  26914. }else
  26915. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26916. {
  26917. lock.l_type = F_RDLCK;
  26918. lock.l_whence = SEEK_SET;
  26919. lock.l_start = SHARED_FIRST;
  26920. lock.l_len = SHARED_SIZE;
  26921. if( unixFileLock(pFile, &lock) ){
  26922. /* In theory, the call to unixFileLock() cannot fail because another
  26923. ** process is holding an incompatible lock. If it does, this
  26924. ** indicates that the other process is not following the locking
  26925. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  26926. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  26927. ** an assert to fail). */
  26928. rc = SQLITE_IOERR_RDLOCK;
  26929. storeLastErrno(pFile, errno);
  26930. goto end_unlock;
  26931. }
  26932. }
  26933. }
  26934. lock.l_type = F_UNLCK;
  26935. lock.l_whence = SEEK_SET;
  26936. lock.l_start = PENDING_BYTE;
  26937. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  26938. if( unixFileLock(pFile, &lock)==0 ){
  26939. pInode->eFileLock = SHARED_LOCK;
  26940. }else{
  26941. rc = SQLITE_IOERR_UNLOCK;
  26942. storeLastErrno(pFile, errno);
  26943. goto end_unlock;
  26944. }
  26945. }
  26946. if( eFileLock==NO_LOCK ){
  26947. /* Decrement the shared lock counter. Release the lock using an
  26948. ** OS call only when all threads in this same process have released
  26949. ** the lock.
  26950. */
  26951. pInode->nShared--;
  26952. if( pInode->nShared==0 ){
  26953. lock.l_type = F_UNLCK;
  26954. lock.l_whence = SEEK_SET;
  26955. lock.l_start = lock.l_len = 0L;
  26956. if( unixFileLock(pFile, &lock)==0 ){
  26957. pInode->eFileLock = NO_LOCK;
  26958. }else{
  26959. rc = SQLITE_IOERR_UNLOCK;
  26960. storeLastErrno(pFile, errno);
  26961. pInode->eFileLock = NO_LOCK;
  26962. pFile->eFileLock = NO_LOCK;
  26963. }
  26964. }
  26965. /* Decrement the count of locks against this same file. When the
  26966. ** count reaches zero, close any other file descriptors whose close
  26967. ** was deferred because of outstanding locks.
  26968. */
  26969. pInode->nLock--;
  26970. assert( pInode->nLock>=0 );
  26971. if( pInode->nLock==0 ){
  26972. closePendingFds(pFile);
  26973. }
  26974. }
  26975. end_unlock:
  26976. unixLeaveMutex();
  26977. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  26978. return rc;
  26979. }
  26980. /*
  26981. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26982. ** must be either NO_LOCK or SHARED_LOCK.
  26983. **
  26984. ** If the locking level of the file descriptor is already at or below
  26985. ** the requested locking level, this routine is a no-op.
  26986. */
  26987. static int unixUnlock(sqlite3_file *id, int eFileLock){
  26988. #if SQLITE_MAX_MMAP_SIZE>0
  26989. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  26990. #endif
  26991. return posixUnlock(id, eFileLock, 0);
  26992. }
  26993. #if SQLITE_MAX_MMAP_SIZE>0
  26994. static int unixMapfile(unixFile *pFd, i64 nByte);
  26995. static void unixUnmapfile(unixFile *pFd);
  26996. #endif
  26997. /*
  26998. ** This function performs the parts of the "close file" operation
  26999. ** common to all locking schemes. It closes the directory and file
  27000. ** handles, if they are valid, and sets all fields of the unixFile
  27001. ** structure to 0.
  27002. **
  27003. ** It is *not* necessary to hold the mutex when this routine is called,
  27004. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  27005. ** vxworksReleaseFileId() routine.
  27006. */
  27007. static int closeUnixFile(sqlite3_file *id){
  27008. unixFile *pFile = (unixFile*)id;
  27009. #if SQLITE_MAX_MMAP_SIZE>0
  27010. unixUnmapfile(pFile);
  27011. #endif
  27012. if( pFile->h>=0 ){
  27013. robust_close(pFile, pFile->h, __LINE__);
  27014. pFile->h = -1;
  27015. }
  27016. #if OS_VXWORKS
  27017. if( pFile->pId ){
  27018. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27019. osUnlink(pFile->pId->zCanonicalName);
  27020. }
  27021. vxworksReleaseFileId(pFile->pId);
  27022. pFile->pId = 0;
  27023. }
  27024. #endif
  27025. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  27026. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27027. osUnlink(pFile->zPath);
  27028. sqlite3_free(*(char**)&pFile->zPath);
  27029. pFile->zPath = 0;
  27030. }
  27031. #endif
  27032. OSTRACE(("CLOSE %-3d\n", pFile->h));
  27033. OpenCounter(-1);
  27034. sqlite3_free(pFile->pUnused);
  27035. memset(pFile, 0, sizeof(unixFile));
  27036. return SQLITE_OK;
  27037. }
  27038. /*
  27039. ** Close a file.
  27040. */
  27041. static int unixClose(sqlite3_file *id){
  27042. int rc = SQLITE_OK;
  27043. unixFile *pFile = (unixFile *)id;
  27044. verifyDbFile(pFile);
  27045. unixUnlock(id, NO_LOCK);
  27046. unixEnterMutex();
  27047. /* unixFile.pInode is always valid here. Otherwise, a different close
  27048. ** routine (e.g. nolockClose()) would be called instead.
  27049. */
  27050. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  27051. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  27052. /* If there are outstanding locks, do not actually close the file just
  27053. ** yet because that would clear those locks. Instead, add the file
  27054. ** descriptor to pInode->pUnused list. It will be automatically closed
  27055. ** when the last lock is cleared.
  27056. */
  27057. setPendingFd(pFile);
  27058. }
  27059. releaseInodeInfo(pFile);
  27060. rc = closeUnixFile(id);
  27061. unixLeaveMutex();
  27062. return rc;
  27063. }
  27064. /************** End of the posix advisory lock implementation *****************
  27065. ******************************************************************************/
  27066. /******************************************************************************
  27067. ****************************** No-op Locking **********************************
  27068. **
  27069. ** Of the various locking implementations available, this is by far the
  27070. ** simplest: locking is ignored. No attempt is made to lock the database
  27071. ** file for reading or writing.
  27072. **
  27073. ** This locking mode is appropriate for use on read-only databases
  27074. ** (ex: databases that are burned into CD-ROM, for example.) It can
  27075. ** also be used if the application employs some external mechanism to
  27076. ** prevent simultaneous access of the same database by two or more
  27077. ** database connections. But there is a serious risk of database
  27078. ** corruption if this locking mode is used in situations where multiple
  27079. ** database connections are accessing the same database file at the same
  27080. ** time and one or more of those connections are writing.
  27081. */
  27082. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  27083. UNUSED_PARAMETER(NotUsed);
  27084. *pResOut = 0;
  27085. return SQLITE_OK;
  27086. }
  27087. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  27088. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27089. return SQLITE_OK;
  27090. }
  27091. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  27092. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27093. return SQLITE_OK;
  27094. }
  27095. /*
  27096. ** Close the file.
  27097. */
  27098. static int nolockClose(sqlite3_file *id) {
  27099. return closeUnixFile(id);
  27100. }
  27101. /******************* End of the no-op lock implementation *********************
  27102. ******************************************************************************/
  27103. /******************************************************************************
  27104. ************************* Begin dot-file Locking ******************************
  27105. **
  27106. ** The dotfile locking implementation uses the existence of separate lock
  27107. ** files (really a directory) to control access to the database. This works
  27108. ** on just about every filesystem imaginable. But there are serious downsides:
  27109. **
  27110. ** (1) There is zero concurrency. A single reader blocks all other
  27111. ** connections from reading or writing the database.
  27112. **
  27113. ** (2) An application crash or power loss can leave stale lock files
  27114. ** sitting around that need to be cleared manually.
  27115. **
  27116. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  27117. ** other locking strategy is available.
  27118. **
  27119. ** Dotfile locking works by creating a subdirectory in the same directory as
  27120. ** the database and with the same name but with a ".lock" extension added.
  27121. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  27122. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  27123. */
  27124. /*
  27125. ** The file suffix added to the data base filename in order to create the
  27126. ** lock directory.
  27127. */
  27128. #define DOTLOCK_SUFFIX ".lock"
  27129. /*
  27130. ** This routine checks if there is a RESERVED lock held on the specified
  27131. ** file by this or any other process. If such a lock is held, set *pResOut
  27132. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27133. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27134. **
  27135. ** In dotfile locking, either a lock exists or it does not. So in this
  27136. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  27137. ** is held on the file and false if the file is unlocked.
  27138. */
  27139. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27140. int rc = SQLITE_OK;
  27141. int reserved = 0;
  27142. unixFile *pFile = (unixFile*)id;
  27143. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27144. assert( pFile );
  27145. /* Check if a thread in this process holds such a lock */
  27146. if( pFile->eFileLock>SHARED_LOCK ){
  27147. /* Either this connection or some other connection in the same process
  27148. ** holds a lock on the file. No need to check further. */
  27149. reserved = 1;
  27150. }else{
  27151. /* The lock is held if and only if the lockfile exists */
  27152. const char *zLockFile = (const char*)pFile->lockingContext;
  27153. reserved = osAccess(zLockFile, 0)==0;
  27154. }
  27155. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  27156. *pResOut = reserved;
  27157. return rc;
  27158. }
  27159. /*
  27160. ** Lock the file with the lock specified by parameter eFileLock - one
  27161. ** of the following:
  27162. **
  27163. ** (1) SHARED_LOCK
  27164. ** (2) RESERVED_LOCK
  27165. ** (3) PENDING_LOCK
  27166. ** (4) EXCLUSIVE_LOCK
  27167. **
  27168. ** Sometimes when requesting one lock state, additional lock states
  27169. ** are inserted in between. The locking might fail on one of the later
  27170. ** transitions leaving the lock state different from what it started but
  27171. ** still short of its goal. The following chart shows the allowed
  27172. ** transitions and the inserted intermediate states:
  27173. **
  27174. ** UNLOCKED -> SHARED
  27175. ** SHARED -> RESERVED
  27176. ** SHARED -> (PENDING) -> EXCLUSIVE
  27177. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27178. ** PENDING -> EXCLUSIVE
  27179. **
  27180. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27181. ** routine to lower a locking level.
  27182. **
  27183. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  27184. ** But we track the other locking levels internally.
  27185. */
  27186. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  27187. unixFile *pFile = (unixFile*)id;
  27188. char *zLockFile = (char *)pFile->lockingContext;
  27189. int rc = SQLITE_OK;
  27190. /* If we have any lock, then the lock file already exists. All we have
  27191. ** to do is adjust our internal record of the lock level.
  27192. */
  27193. if( pFile->eFileLock > NO_LOCK ){
  27194. pFile->eFileLock = eFileLock;
  27195. /* Always update the timestamp on the old file */
  27196. #ifdef HAVE_UTIME
  27197. utime(zLockFile, NULL);
  27198. #else
  27199. utimes(zLockFile, NULL);
  27200. #endif
  27201. return SQLITE_OK;
  27202. }
  27203. /* grab an exclusive lock */
  27204. rc = osMkdir(zLockFile, 0777);
  27205. if( rc<0 ){
  27206. /* failed to open/create the lock directory */
  27207. int tErrno = errno;
  27208. if( EEXIST == tErrno ){
  27209. rc = SQLITE_BUSY;
  27210. } else {
  27211. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27212. if( IS_LOCK_ERROR(rc) ){
  27213. storeLastErrno(pFile, tErrno);
  27214. }
  27215. }
  27216. return rc;
  27217. }
  27218. /* got it, set the type and return ok */
  27219. pFile->eFileLock = eFileLock;
  27220. return rc;
  27221. }
  27222. /*
  27223. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27224. ** must be either NO_LOCK or SHARED_LOCK.
  27225. **
  27226. ** If the locking level of the file descriptor is already at or below
  27227. ** the requested locking level, this routine is a no-op.
  27228. **
  27229. ** When the locking level reaches NO_LOCK, delete the lock file.
  27230. */
  27231. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  27232. unixFile *pFile = (unixFile*)id;
  27233. char *zLockFile = (char *)pFile->lockingContext;
  27234. int rc;
  27235. assert( pFile );
  27236. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  27237. pFile->eFileLock, osGetpid(0)));
  27238. assert( eFileLock<=SHARED_LOCK );
  27239. /* no-op if possible */
  27240. if( pFile->eFileLock==eFileLock ){
  27241. return SQLITE_OK;
  27242. }
  27243. /* To downgrade to shared, simply update our internal notion of the
  27244. ** lock state. No need to mess with the file on disk.
  27245. */
  27246. if( eFileLock==SHARED_LOCK ){
  27247. pFile->eFileLock = SHARED_LOCK;
  27248. return SQLITE_OK;
  27249. }
  27250. /* To fully unlock the database, delete the lock file */
  27251. assert( eFileLock==NO_LOCK );
  27252. rc = osRmdir(zLockFile);
  27253. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  27254. if( rc<0 ){
  27255. int tErrno = errno;
  27256. rc = 0;
  27257. if( ENOENT != tErrno ){
  27258. rc = SQLITE_IOERR_UNLOCK;
  27259. }
  27260. if( IS_LOCK_ERROR(rc) ){
  27261. storeLastErrno(pFile, tErrno);
  27262. }
  27263. return rc;
  27264. }
  27265. pFile->eFileLock = NO_LOCK;
  27266. return SQLITE_OK;
  27267. }
  27268. /*
  27269. ** Close a file. Make sure the lock has been released before closing.
  27270. */
  27271. static int dotlockClose(sqlite3_file *id) {
  27272. int rc = SQLITE_OK;
  27273. if( id ){
  27274. unixFile *pFile = (unixFile*)id;
  27275. dotlockUnlock(id, NO_LOCK);
  27276. sqlite3_free(pFile->lockingContext);
  27277. rc = closeUnixFile(id);
  27278. }
  27279. return rc;
  27280. }
  27281. /****************** End of the dot-file lock implementation *******************
  27282. ******************************************************************************/
  27283. /******************************************************************************
  27284. ************************** Begin flock Locking ********************************
  27285. **
  27286. ** Use the flock() system call to do file locking.
  27287. **
  27288. ** flock() locking is like dot-file locking in that the various
  27289. ** fine-grain locking levels supported by SQLite are collapsed into
  27290. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  27291. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  27292. ** still works when you do this, but concurrency is reduced since
  27293. ** only a single process can be reading the database at a time.
  27294. **
  27295. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  27296. */
  27297. #if SQLITE_ENABLE_LOCKING_STYLE
  27298. /*
  27299. ** Retry flock() calls that fail with EINTR
  27300. */
  27301. #ifdef EINTR
  27302. static int robust_flock(int fd, int op){
  27303. int rc;
  27304. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  27305. return rc;
  27306. }
  27307. #else
  27308. # define robust_flock(a,b) flock(a,b)
  27309. #endif
  27310. /*
  27311. ** This routine checks if there is a RESERVED lock held on the specified
  27312. ** file by this or any other process. If such a lock is held, set *pResOut
  27313. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27314. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27315. */
  27316. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  27317. int rc = SQLITE_OK;
  27318. int reserved = 0;
  27319. unixFile *pFile = (unixFile*)id;
  27320. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27321. assert( pFile );
  27322. /* Check if a thread in this process holds such a lock */
  27323. if( pFile->eFileLock>SHARED_LOCK ){
  27324. reserved = 1;
  27325. }
  27326. /* Otherwise see if some other process holds it. */
  27327. if( !reserved ){
  27328. /* attempt to get the lock */
  27329. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  27330. if( !lrc ){
  27331. /* got the lock, unlock it */
  27332. lrc = robust_flock(pFile->h, LOCK_UN);
  27333. if ( lrc ) {
  27334. int tErrno = errno;
  27335. /* unlock failed with an error */
  27336. lrc = SQLITE_IOERR_UNLOCK;
  27337. if( IS_LOCK_ERROR(lrc) ){
  27338. storeLastErrno(pFile, tErrno);
  27339. rc = lrc;
  27340. }
  27341. }
  27342. } else {
  27343. int tErrno = errno;
  27344. reserved = 1;
  27345. /* someone else might have it reserved */
  27346. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27347. if( IS_LOCK_ERROR(lrc) ){
  27348. storeLastErrno(pFile, tErrno);
  27349. rc = lrc;
  27350. }
  27351. }
  27352. }
  27353. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  27354. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27355. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  27356. rc = SQLITE_OK;
  27357. reserved=1;
  27358. }
  27359. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27360. *pResOut = reserved;
  27361. return rc;
  27362. }
  27363. /*
  27364. ** Lock the file with the lock specified by parameter eFileLock - one
  27365. ** of the following:
  27366. **
  27367. ** (1) SHARED_LOCK
  27368. ** (2) RESERVED_LOCK
  27369. ** (3) PENDING_LOCK
  27370. ** (4) EXCLUSIVE_LOCK
  27371. **
  27372. ** Sometimes when requesting one lock state, additional lock states
  27373. ** are inserted in between. The locking might fail on one of the later
  27374. ** transitions leaving the lock state different from what it started but
  27375. ** still short of its goal. The following chart shows the allowed
  27376. ** transitions and the inserted intermediate states:
  27377. **
  27378. ** UNLOCKED -> SHARED
  27379. ** SHARED -> RESERVED
  27380. ** SHARED -> (PENDING) -> EXCLUSIVE
  27381. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27382. ** PENDING -> EXCLUSIVE
  27383. **
  27384. ** flock() only really support EXCLUSIVE locks. We track intermediate
  27385. ** lock states in the sqlite3_file structure, but all locks SHARED or
  27386. ** above are really EXCLUSIVE locks and exclude all other processes from
  27387. ** access the file.
  27388. **
  27389. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27390. ** routine to lower a locking level.
  27391. */
  27392. static int flockLock(sqlite3_file *id, int eFileLock) {
  27393. int rc = SQLITE_OK;
  27394. unixFile *pFile = (unixFile*)id;
  27395. assert( pFile );
  27396. /* if we already have a lock, it is exclusive.
  27397. ** Just adjust level and punt on outta here. */
  27398. if (pFile->eFileLock > NO_LOCK) {
  27399. pFile->eFileLock = eFileLock;
  27400. return SQLITE_OK;
  27401. }
  27402. /* grab an exclusive lock */
  27403. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  27404. int tErrno = errno;
  27405. /* didn't get, must be busy */
  27406. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27407. if( IS_LOCK_ERROR(rc) ){
  27408. storeLastErrno(pFile, tErrno);
  27409. }
  27410. } else {
  27411. /* got it, set the type and return ok */
  27412. pFile->eFileLock = eFileLock;
  27413. }
  27414. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  27415. rc==SQLITE_OK ? "ok" : "failed"));
  27416. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27417. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  27418. rc = SQLITE_BUSY;
  27419. }
  27420. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27421. return rc;
  27422. }
  27423. /*
  27424. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27425. ** must be either NO_LOCK or SHARED_LOCK.
  27426. **
  27427. ** If the locking level of the file descriptor is already at or below
  27428. ** the requested locking level, this routine is a no-op.
  27429. */
  27430. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  27431. unixFile *pFile = (unixFile*)id;
  27432. assert( pFile );
  27433. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  27434. pFile->eFileLock, osGetpid(0)));
  27435. assert( eFileLock<=SHARED_LOCK );
  27436. /* no-op if possible */
  27437. if( pFile->eFileLock==eFileLock ){
  27438. return SQLITE_OK;
  27439. }
  27440. /* shared can just be set because we always have an exclusive */
  27441. if (eFileLock==SHARED_LOCK) {
  27442. pFile->eFileLock = eFileLock;
  27443. return SQLITE_OK;
  27444. }
  27445. /* no, really, unlock. */
  27446. if( robust_flock(pFile->h, LOCK_UN) ){
  27447. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27448. return SQLITE_OK;
  27449. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27450. return SQLITE_IOERR_UNLOCK;
  27451. }else{
  27452. pFile->eFileLock = NO_LOCK;
  27453. return SQLITE_OK;
  27454. }
  27455. }
  27456. /*
  27457. ** Close a file.
  27458. */
  27459. static int flockClose(sqlite3_file *id) {
  27460. int rc = SQLITE_OK;
  27461. if( id ){
  27462. flockUnlock(id, NO_LOCK);
  27463. rc = closeUnixFile(id);
  27464. }
  27465. return rc;
  27466. }
  27467. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  27468. /******************* End of the flock lock implementation *********************
  27469. ******************************************************************************/
  27470. /******************************************************************************
  27471. ************************ Begin Named Semaphore Locking ************************
  27472. **
  27473. ** Named semaphore locking is only supported on VxWorks.
  27474. **
  27475. ** Semaphore locking is like dot-lock and flock in that it really only
  27476. ** supports EXCLUSIVE locking. Only a single process can read or write
  27477. ** the database file at a time. This reduces potential concurrency, but
  27478. ** makes the lock implementation much easier.
  27479. */
  27480. #if OS_VXWORKS
  27481. /*
  27482. ** This routine checks if there is a RESERVED lock held on the specified
  27483. ** file by this or any other process. If such a lock is held, set *pResOut
  27484. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27485. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27486. */
  27487. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27488. int rc = SQLITE_OK;
  27489. int reserved = 0;
  27490. unixFile *pFile = (unixFile*)id;
  27491. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27492. assert( pFile );
  27493. /* Check if a thread in this process holds such a lock */
  27494. if( pFile->eFileLock>SHARED_LOCK ){
  27495. reserved = 1;
  27496. }
  27497. /* Otherwise see if some other process holds it. */
  27498. if( !reserved ){
  27499. sem_t *pSem = pFile->pInode->pSem;
  27500. if( sem_trywait(pSem)==-1 ){
  27501. int tErrno = errno;
  27502. if( EAGAIN != tErrno ){
  27503. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  27504. storeLastErrno(pFile, tErrno);
  27505. } else {
  27506. /* someone else has the lock when we are in NO_LOCK */
  27507. reserved = (pFile->eFileLock < SHARED_LOCK);
  27508. }
  27509. }else{
  27510. /* we could have it if we want it */
  27511. sem_post(pSem);
  27512. }
  27513. }
  27514. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  27515. *pResOut = reserved;
  27516. return rc;
  27517. }
  27518. /*
  27519. ** Lock the file with the lock specified by parameter eFileLock - one
  27520. ** of the following:
  27521. **
  27522. ** (1) SHARED_LOCK
  27523. ** (2) RESERVED_LOCK
  27524. ** (3) PENDING_LOCK
  27525. ** (4) EXCLUSIVE_LOCK
  27526. **
  27527. ** Sometimes when requesting one lock state, additional lock states
  27528. ** are inserted in between. The locking might fail on one of the later
  27529. ** transitions leaving the lock state different from what it started but
  27530. ** still short of its goal. The following chart shows the allowed
  27531. ** transitions and the inserted intermediate states:
  27532. **
  27533. ** UNLOCKED -> SHARED
  27534. ** SHARED -> RESERVED
  27535. ** SHARED -> (PENDING) -> EXCLUSIVE
  27536. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27537. ** PENDING -> EXCLUSIVE
  27538. **
  27539. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  27540. ** lock states in the sqlite3_file structure, but all locks SHARED or
  27541. ** above are really EXCLUSIVE locks and exclude all other processes from
  27542. ** access the file.
  27543. **
  27544. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27545. ** routine to lower a locking level.
  27546. */
  27547. static int semXLock(sqlite3_file *id, int eFileLock) {
  27548. unixFile *pFile = (unixFile*)id;
  27549. sem_t *pSem = pFile->pInode->pSem;
  27550. int rc = SQLITE_OK;
  27551. /* if we already have a lock, it is exclusive.
  27552. ** Just adjust level and punt on outta here. */
  27553. if (pFile->eFileLock > NO_LOCK) {
  27554. pFile->eFileLock = eFileLock;
  27555. rc = SQLITE_OK;
  27556. goto sem_end_lock;
  27557. }
  27558. /* lock semaphore now but bail out when already locked. */
  27559. if( sem_trywait(pSem)==-1 ){
  27560. rc = SQLITE_BUSY;
  27561. goto sem_end_lock;
  27562. }
  27563. /* got it, set the type and return ok */
  27564. pFile->eFileLock = eFileLock;
  27565. sem_end_lock:
  27566. return rc;
  27567. }
  27568. /*
  27569. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27570. ** must be either NO_LOCK or SHARED_LOCK.
  27571. **
  27572. ** If the locking level of the file descriptor is already at or below
  27573. ** the requested locking level, this routine is a no-op.
  27574. */
  27575. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  27576. unixFile *pFile = (unixFile*)id;
  27577. sem_t *pSem = pFile->pInode->pSem;
  27578. assert( pFile );
  27579. assert( pSem );
  27580. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  27581. pFile->eFileLock, osGetpid(0)));
  27582. assert( eFileLock<=SHARED_LOCK );
  27583. /* no-op if possible */
  27584. if( pFile->eFileLock==eFileLock ){
  27585. return SQLITE_OK;
  27586. }
  27587. /* shared can just be set because we always have an exclusive */
  27588. if (eFileLock==SHARED_LOCK) {
  27589. pFile->eFileLock = eFileLock;
  27590. return SQLITE_OK;
  27591. }
  27592. /* no, really unlock. */
  27593. if ( sem_post(pSem)==-1 ) {
  27594. int rc, tErrno = errno;
  27595. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  27596. if( IS_LOCK_ERROR(rc) ){
  27597. storeLastErrno(pFile, tErrno);
  27598. }
  27599. return rc;
  27600. }
  27601. pFile->eFileLock = NO_LOCK;
  27602. return SQLITE_OK;
  27603. }
  27604. /*
  27605. ** Close a file.
  27606. */
  27607. static int semXClose(sqlite3_file *id) {
  27608. if( id ){
  27609. unixFile *pFile = (unixFile*)id;
  27610. semXUnlock(id, NO_LOCK);
  27611. assert( pFile );
  27612. unixEnterMutex();
  27613. releaseInodeInfo(pFile);
  27614. unixLeaveMutex();
  27615. closeUnixFile(id);
  27616. }
  27617. return SQLITE_OK;
  27618. }
  27619. #endif /* OS_VXWORKS */
  27620. /*
  27621. ** Named semaphore locking is only available on VxWorks.
  27622. **
  27623. *************** End of the named semaphore lock implementation ****************
  27624. ******************************************************************************/
  27625. /******************************************************************************
  27626. *************************** Begin AFP Locking *********************************
  27627. **
  27628. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  27629. ** on Apple Macintosh computers - both OS9 and OSX.
  27630. **
  27631. ** Third-party implementations of AFP are available. But this code here
  27632. ** only works on OSX.
  27633. */
  27634. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27635. /*
  27636. ** The afpLockingContext structure contains all afp lock specific state
  27637. */
  27638. typedef struct afpLockingContext afpLockingContext;
  27639. struct afpLockingContext {
  27640. int reserved;
  27641. const char *dbPath; /* Name of the open file */
  27642. };
  27643. struct ByteRangeLockPB2
  27644. {
  27645. unsigned long long offset; /* offset to first byte to lock */
  27646. unsigned long long length; /* nbr of bytes to lock */
  27647. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  27648. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  27649. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  27650. int fd; /* file desc to assoc this lock with */
  27651. };
  27652. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  27653. /*
  27654. ** This is a utility for setting or clearing a bit-range lock on an
  27655. ** AFP filesystem.
  27656. **
  27657. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  27658. */
  27659. static int afpSetLock(
  27660. const char *path, /* Name of the file to be locked or unlocked */
  27661. unixFile *pFile, /* Open file descriptor on path */
  27662. unsigned long long offset, /* First byte to be locked */
  27663. unsigned long long length, /* Number of bytes to lock */
  27664. int setLockFlag /* True to set lock. False to clear lock */
  27665. ){
  27666. struct ByteRangeLockPB2 pb;
  27667. int err;
  27668. pb.unLockFlag = setLockFlag ? 0 : 1;
  27669. pb.startEndFlag = 0;
  27670. pb.offset = offset;
  27671. pb.length = length;
  27672. pb.fd = pFile->h;
  27673. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  27674. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  27675. offset, length));
  27676. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  27677. if ( err==-1 ) {
  27678. int rc;
  27679. int tErrno = errno;
  27680. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  27681. path, tErrno, strerror(tErrno)));
  27682. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  27683. rc = SQLITE_BUSY;
  27684. #else
  27685. rc = sqliteErrorFromPosixError(tErrno,
  27686. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  27687. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  27688. if( IS_LOCK_ERROR(rc) ){
  27689. storeLastErrno(pFile, tErrno);
  27690. }
  27691. return rc;
  27692. } else {
  27693. return SQLITE_OK;
  27694. }
  27695. }
  27696. /*
  27697. ** This routine checks if there is a RESERVED lock held on the specified
  27698. ** file by this or any other process. If such a lock is held, set *pResOut
  27699. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27700. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27701. */
  27702. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  27703. int rc = SQLITE_OK;
  27704. int reserved = 0;
  27705. unixFile *pFile = (unixFile*)id;
  27706. afpLockingContext *context;
  27707. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27708. assert( pFile );
  27709. context = (afpLockingContext *) pFile->lockingContext;
  27710. if( context->reserved ){
  27711. *pResOut = 1;
  27712. return SQLITE_OK;
  27713. }
  27714. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  27715. /* Check if a thread in this process holds such a lock */
  27716. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  27717. reserved = 1;
  27718. }
  27719. /* Otherwise see if some other process holds it.
  27720. */
  27721. if( !reserved ){
  27722. /* lock the RESERVED byte */
  27723. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  27724. if( SQLITE_OK==lrc ){
  27725. /* if we succeeded in taking the reserved lock, unlock it to restore
  27726. ** the original state */
  27727. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  27728. } else {
  27729. /* if we failed to get the lock then someone else must have it */
  27730. reserved = 1;
  27731. }
  27732. if( IS_LOCK_ERROR(lrc) ){
  27733. rc=lrc;
  27734. }
  27735. }
  27736. unixLeaveMutex();
  27737. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  27738. *pResOut = reserved;
  27739. return rc;
  27740. }
  27741. /*
  27742. ** Lock the file with the lock specified by parameter eFileLock - one
  27743. ** of the following:
  27744. **
  27745. ** (1) SHARED_LOCK
  27746. ** (2) RESERVED_LOCK
  27747. ** (3) PENDING_LOCK
  27748. ** (4) EXCLUSIVE_LOCK
  27749. **
  27750. ** Sometimes when requesting one lock state, additional lock states
  27751. ** are inserted in between. The locking might fail on one of the later
  27752. ** transitions leaving the lock state different from what it started but
  27753. ** still short of its goal. The following chart shows the allowed
  27754. ** transitions and the inserted intermediate states:
  27755. **
  27756. ** UNLOCKED -> SHARED
  27757. ** SHARED -> RESERVED
  27758. ** SHARED -> (PENDING) -> EXCLUSIVE
  27759. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27760. ** PENDING -> EXCLUSIVE
  27761. **
  27762. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27763. ** routine to lower a locking level.
  27764. */
  27765. static int afpLock(sqlite3_file *id, int eFileLock){
  27766. int rc = SQLITE_OK;
  27767. unixFile *pFile = (unixFile*)id;
  27768. unixInodeInfo *pInode = pFile->pInode;
  27769. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  27770. assert( pFile );
  27771. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  27772. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  27773. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  27774. /* If there is already a lock of this type or more restrictive on the
  27775. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  27776. ** unixEnterMutex() hasn't been called yet.
  27777. */
  27778. if( pFile->eFileLock>=eFileLock ){
  27779. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  27780. azFileLock(eFileLock)));
  27781. return SQLITE_OK;
  27782. }
  27783. /* Make sure the locking sequence is correct
  27784. ** (1) We never move from unlocked to anything higher than shared lock.
  27785. ** (2) SQLite never explicitly requests a pendig lock.
  27786. ** (3) A shared lock is always held when a reserve lock is requested.
  27787. */
  27788. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  27789. assert( eFileLock!=PENDING_LOCK );
  27790. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  27791. /* This mutex is needed because pFile->pInode is shared across threads
  27792. */
  27793. unixEnterMutex();
  27794. pInode = pFile->pInode;
  27795. /* If some thread using this PID has a lock via a different unixFile*
  27796. ** handle that precludes the requested lock, return BUSY.
  27797. */
  27798. if( (pFile->eFileLock!=pInode->eFileLock &&
  27799. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  27800. ){
  27801. rc = SQLITE_BUSY;
  27802. goto afp_end_lock;
  27803. }
  27804. /* If a SHARED lock is requested, and some thread using this PID already
  27805. ** has a SHARED or RESERVED lock, then increment reference counts and
  27806. ** return SQLITE_OK.
  27807. */
  27808. if( eFileLock==SHARED_LOCK &&
  27809. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  27810. assert( eFileLock==SHARED_LOCK );
  27811. assert( pFile->eFileLock==0 );
  27812. assert( pInode->nShared>0 );
  27813. pFile->eFileLock = SHARED_LOCK;
  27814. pInode->nShared++;
  27815. pInode->nLock++;
  27816. goto afp_end_lock;
  27817. }
  27818. /* A PENDING lock is needed before acquiring a SHARED lock and before
  27819. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  27820. ** be released.
  27821. */
  27822. if( eFileLock==SHARED_LOCK
  27823. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  27824. ){
  27825. int failed;
  27826. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  27827. if (failed) {
  27828. rc = failed;
  27829. goto afp_end_lock;
  27830. }
  27831. }
  27832. /* If control gets to this point, then actually go ahead and make
  27833. ** operating system calls for the specified lock.
  27834. */
  27835. if( eFileLock==SHARED_LOCK ){
  27836. int lrc1, lrc2, lrc1Errno = 0;
  27837. long lk, mask;
  27838. assert( pInode->nShared==0 );
  27839. assert( pInode->eFileLock==0 );
  27840. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  27841. /* Now get the read-lock SHARED_LOCK */
  27842. /* note that the quality of the randomness doesn't matter that much */
  27843. lk = random();
  27844. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  27845. lrc1 = afpSetLock(context->dbPath, pFile,
  27846. SHARED_FIRST+pInode->sharedByte, 1, 1);
  27847. if( IS_LOCK_ERROR(lrc1) ){
  27848. lrc1Errno = pFile->lastErrno;
  27849. }
  27850. /* Drop the temporary PENDING lock */
  27851. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  27852. if( IS_LOCK_ERROR(lrc1) ) {
  27853. storeLastErrno(pFile, lrc1Errno);
  27854. rc = lrc1;
  27855. goto afp_end_lock;
  27856. } else if( IS_LOCK_ERROR(lrc2) ){
  27857. rc = lrc2;
  27858. goto afp_end_lock;
  27859. } else if( lrc1 != SQLITE_OK ) {
  27860. rc = lrc1;
  27861. } else {
  27862. pFile->eFileLock = SHARED_LOCK;
  27863. pInode->nLock++;
  27864. pInode->nShared = 1;
  27865. }
  27866. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  27867. /* We are trying for an exclusive lock but another thread in this
  27868. ** same process is still holding a shared lock. */
  27869. rc = SQLITE_BUSY;
  27870. }else{
  27871. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  27872. ** assumed that there is a SHARED or greater lock on the file
  27873. ** already.
  27874. */
  27875. int failed = 0;
  27876. assert( 0!=pFile->eFileLock );
  27877. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  27878. /* Acquire a RESERVED lock */
  27879. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  27880. if( !failed ){
  27881. context->reserved = 1;
  27882. }
  27883. }
  27884. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  27885. /* Acquire an EXCLUSIVE lock */
  27886. /* Remove the shared lock before trying the range. we'll need to
  27887. ** reestablish the shared lock if we can't get the afpUnlock
  27888. */
  27889. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  27890. pInode->sharedByte, 1, 0)) ){
  27891. int failed2 = SQLITE_OK;
  27892. /* now attemmpt to get the exclusive lock range */
  27893. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  27894. SHARED_SIZE, 1);
  27895. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  27896. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  27897. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  27898. ** a critical I/O error
  27899. */
  27900. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  27901. SQLITE_IOERR_LOCK;
  27902. goto afp_end_lock;
  27903. }
  27904. }else{
  27905. rc = failed;
  27906. }
  27907. }
  27908. if( failed ){
  27909. rc = failed;
  27910. }
  27911. }
  27912. if( rc==SQLITE_OK ){
  27913. pFile->eFileLock = eFileLock;
  27914. pInode->eFileLock = eFileLock;
  27915. }else if( eFileLock==EXCLUSIVE_LOCK ){
  27916. pFile->eFileLock = PENDING_LOCK;
  27917. pInode->eFileLock = PENDING_LOCK;
  27918. }
  27919. afp_end_lock:
  27920. unixLeaveMutex();
  27921. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  27922. rc==SQLITE_OK ? "ok" : "failed"));
  27923. return rc;
  27924. }
  27925. /*
  27926. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27927. ** must be either NO_LOCK or SHARED_LOCK.
  27928. **
  27929. ** If the locking level of the file descriptor is already at or below
  27930. ** the requested locking level, this routine is a no-op.
  27931. */
  27932. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  27933. int rc = SQLITE_OK;
  27934. unixFile *pFile = (unixFile*)id;
  27935. unixInodeInfo *pInode;
  27936. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  27937. int skipShared = 0;
  27938. #ifdef SQLITE_TEST
  27939. int h = pFile->h;
  27940. #endif
  27941. assert( pFile );
  27942. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  27943. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  27944. osGetpid(0)));
  27945. assert( eFileLock<=SHARED_LOCK );
  27946. if( pFile->eFileLock<=eFileLock ){
  27947. return SQLITE_OK;
  27948. }
  27949. unixEnterMutex();
  27950. pInode = pFile->pInode;
  27951. assert( pInode->nShared!=0 );
  27952. if( pFile->eFileLock>SHARED_LOCK ){
  27953. assert( pInode->eFileLock==pFile->eFileLock );
  27954. SimulateIOErrorBenign(1);
  27955. SimulateIOError( h=(-1) )
  27956. SimulateIOErrorBenign(0);
  27957. #ifdef SQLITE_DEBUG
  27958. /* When reducing a lock such that other processes can start
  27959. ** reading the database file again, make sure that the
  27960. ** transaction counter was updated if any part of the database
  27961. ** file changed. If the transaction counter is not updated,
  27962. ** other connections to the same file might not realize that
  27963. ** the file has changed and hence might not know to flush their
  27964. ** cache. The use of a stale cache can lead to database corruption.
  27965. */
  27966. assert( pFile->inNormalWrite==0
  27967. || pFile->dbUpdate==0
  27968. || pFile->transCntrChng==1 );
  27969. pFile->inNormalWrite = 0;
  27970. #endif
  27971. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  27972. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  27973. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  27974. /* only re-establish the shared lock if necessary */
  27975. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  27976. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  27977. } else {
  27978. skipShared = 1;
  27979. }
  27980. }
  27981. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  27982. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  27983. }
  27984. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  27985. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  27986. if( !rc ){
  27987. context->reserved = 0;
  27988. }
  27989. }
  27990. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  27991. pInode->eFileLock = SHARED_LOCK;
  27992. }
  27993. }
  27994. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  27995. /* Decrement the shared lock counter. Release the lock using an
  27996. ** OS call only when all threads in this same process have released
  27997. ** the lock.
  27998. */
  27999. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  28000. pInode->nShared--;
  28001. if( pInode->nShared==0 ){
  28002. SimulateIOErrorBenign(1);
  28003. SimulateIOError( h=(-1) )
  28004. SimulateIOErrorBenign(0);
  28005. if( !skipShared ){
  28006. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  28007. }
  28008. if( !rc ){
  28009. pInode->eFileLock = NO_LOCK;
  28010. pFile->eFileLock = NO_LOCK;
  28011. }
  28012. }
  28013. if( rc==SQLITE_OK ){
  28014. pInode->nLock--;
  28015. assert( pInode->nLock>=0 );
  28016. if( pInode->nLock==0 ){
  28017. closePendingFds(pFile);
  28018. }
  28019. }
  28020. }
  28021. unixLeaveMutex();
  28022. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  28023. return rc;
  28024. }
  28025. /*
  28026. ** Close a file & cleanup AFP specific locking context
  28027. */
  28028. static int afpClose(sqlite3_file *id) {
  28029. int rc = SQLITE_OK;
  28030. if( id ){
  28031. unixFile *pFile = (unixFile*)id;
  28032. afpUnlock(id, NO_LOCK);
  28033. unixEnterMutex();
  28034. if( pFile->pInode && pFile->pInode->nLock ){
  28035. /* If there are outstanding locks, do not actually close the file just
  28036. ** yet because that would clear those locks. Instead, add the file
  28037. ** descriptor to pInode->aPending. It will be automatically closed when
  28038. ** the last lock is cleared.
  28039. */
  28040. setPendingFd(pFile);
  28041. }
  28042. releaseInodeInfo(pFile);
  28043. sqlite3_free(pFile->lockingContext);
  28044. rc = closeUnixFile(id);
  28045. unixLeaveMutex();
  28046. }
  28047. return rc;
  28048. }
  28049. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28050. /*
  28051. ** The code above is the AFP lock implementation. The code is specific
  28052. ** to MacOSX and does not work on other unix platforms. No alternative
  28053. ** is available. If you don't compile for a mac, then the "unix-afp"
  28054. ** VFS is not available.
  28055. **
  28056. ********************* End of the AFP lock implementation **********************
  28057. ******************************************************************************/
  28058. /******************************************************************************
  28059. *************************** Begin NFS Locking ********************************/
  28060. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28061. /*
  28062. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28063. ** must be either NO_LOCK or SHARED_LOCK.
  28064. **
  28065. ** If the locking level of the file descriptor is already at or below
  28066. ** the requested locking level, this routine is a no-op.
  28067. */
  28068. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  28069. return posixUnlock(id, eFileLock, 1);
  28070. }
  28071. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28072. /*
  28073. ** The code above is the NFS lock implementation. The code is specific
  28074. ** to MacOSX and does not work on other unix platforms. No alternative
  28075. ** is available.
  28076. **
  28077. ********************* End of the NFS lock implementation **********************
  28078. ******************************************************************************/
  28079. /******************************************************************************
  28080. **************** Non-locking sqlite3_file methods *****************************
  28081. **
  28082. ** The next division contains implementations for all methods of the
  28083. ** sqlite3_file object other than the locking methods. The locking
  28084. ** methods were defined in divisions above (one locking method per
  28085. ** division). Those methods that are common to all locking modes
  28086. ** are gather together into this division.
  28087. */
  28088. /*
  28089. ** Seek to the offset passed as the second argument, then read cnt
  28090. ** bytes into pBuf. Return the number of bytes actually read.
  28091. **
  28092. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  28093. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  28094. ** one system to another. Since SQLite does not define USE_PREAD
  28095. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  28096. ** See tickets #2741 and #2681.
  28097. **
  28098. ** To avoid stomping the errno value on a failed read the lastErrno value
  28099. ** is set before returning.
  28100. */
  28101. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  28102. int got;
  28103. int prior = 0;
  28104. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  28105. i64 newOffset;
  28106. #endif
  28107. TIMER_START;
  28108. assert( cnt==(cnt&0x1ffff) );
  28109. assert( id->h>2 );
  28110. do{
  28111. #if defined(USE_PREAD)
  28112. got = osPread(id->h, pBuf, cnt, offset);
  28113. SimulateIOError( got = -1 );
  28114. #elif defined(USE_PREAD64)
  28115. got = osPread64(id->h, pBuf, cnt, offset);
  28116. SimulateIOError( got = -1 );
  28117. #else
  28118. newOffset = lseek(id->h, offset, SEEK_SET);
  28119. SimulateIOError( newOffset-- );
  28120. if( newOffset!=offset ){
  28121. if( newOffset == -1 ){
  28122. storeLastErrno((unixFile*)id, errno);
  28123. }else{
  28124. storeLastErrno((unixFile*)id, 0);
  28125. }
  28126. return -1;
  28127. }
  28128. got = osRead(id->h, pBuf, cnt);
  28129. #endif
  28130. if( got==cnt ) break;
  28131. if( got<0 ){
  28132. if( errno==EINTR ){ got = 1; continue; }
  28133. prior = 0;
  28134. storeLastErrno((unixFile*)id, errno);
  28135. break;
  28136. }else if( got>0 ){
  28137. cnt -= got;
  28138. offset += got;
  28139. prior += got;
  28140. pBuf = (void*)(got + (char*)pBuf);
  28141. }
  28142. }while( got>0 );
  28143. TIMER_END;
  28144. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  28145. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  28146. return got+prior;
  28147. }
  28148. /*
  28149. ** Read data from a file into a buffer. Return SQLITE_OK if all
  28150. ** bytes were read successfully and SQLITE_IOERR if anything goes
  28151. ** wrong.
  28152. */
  28153. static int unixRead(
  28154. sqlite3_file *id,
  28155. void *pBuf,
  28156. int amt,
  28157. sqlite3_int64 offset
  28158. ){
  28159. unixFile *pFile = (unixFile *)id;
  28160. int got;
  28161. assert( id );
  28162. assert( offset>=0 );
  28163. assert( amt>0 );
  28164. /* If this is a database file (not a journal, master-journal or temp
  28165. ** file), the bytes in the locking range should never be read or written. */
  28166. #if 0
  28167. assert( pFile->pUnused==0
  28168. || offset>=PENDING_BYTE+512
  28169. || offset+amt<=PENDING_BYTE
  28170. );
  28171. #endif
  28172. #if SQLITE_MAX_MMAP_SIZE>0
  28173. /* Deal with as much of this read request as possible by transfering
  28174. ** data from the memory mapping using memcpy(). */
  28175. if( offset<pFile->mmapSize ){
  28176. if( offset+amt <= pFile->mmapSize ){
  28177. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  28178. return SQLITE_OK;
  28179. }else{
  28180. int nCopy = pFile->mmapSize - offset;
  28181. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  28182. pBuf = &((u8 *)pBuf)[nCopy];
  28183. amt -= nCopy;
  28184. offset += nCopy;
  28185. }
  28186. }
  28187. #endif
  28188. got = seekAndRead(pFile, offset, pBuf, amt);
  28189. if( got==amt ){
  28190. return SQLITE_OK;
  28191. }else if( got<0 ){
  28192. /* lastErrno set by seekAndRead */
  28193. return SQLITE_IOERR_READ;
  28194. }else{
  28195. storeLastErrno(pFile, 0); /* not a system error */
  28196. /* Unread parts of the buffer must be zero-filled */
  28197. memset(&((char*)pBuf)[got], 0, amt-got);
  28198. return SQLITE_IOERR_SHORT_READ;
  28199. }
  28200. }
  28201. /*
  28202. ** Attempt to seek the file-descriptor passed as the first argument to
  28203. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  28204. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  28205. ** return the actual number of bytes written (which may be less than
  28206. ** nBuf).
  28207. */
  28208. static int seekAndWriteFd(
  28209. int fd, /* File descriptor to write to */
  28210. i64 iOff, /* File offset to begin writing at */
  28211. const void *pBuf, /* Copy data from this buffer to the file */
  28212. int nBuf, /* Size of buffer pBuf in bytes */
  28213. int *piErrno /* OUT: Error number if error occurs */
  28214. ){
  28215. int rc = 0; /* Value returned by system call */
  28216. assert( nBuf==(nBuf&0x1ffff) );
  28217. assert( fd>2 );
  28218. nBuf &= 0x1ffff;
  28219. TIMER_START;
  28220. #if defined(USE_PREAD)
  28221. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  28222. #elif defined(USE_PREAD64)
  28223. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  28224. #else
  28225. do{
  28226. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  28227. SimulateIOError( iSeek-- );
  28228. if( iSeek!=iOff ){
  28229. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  28230. return -1;
  28231. }
  28232. rc = osWrite(fd, pBuf, nBuf);
  28233. }while( rc<0 && errno==EINTR );
  28234. #endif
  28235. TIMER_END;
  28236. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  28237. if( rc<0 && piErrno ) *piErrno = errno;
  28238. return rc;
  28239. }
  28240. /*
  28241. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  28242. ** Return the number of bytes actually read. Update the offset.
  28243. **
  28244. ** To avoid stomping the errno value on a failed write the lastErrno value
  28245. ** is set before returning.
  28246. */
  28247. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  28248. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  28249. }
  28250. /*
  28251. ** Write data from a buffer into a file. Return SQLITE_OK on success
  28252. ** or some other error code on failure.
  28253. */
  28254. static int unixWrite(
  28255. sqlite3_file *id,
  28256. const void *pBuf,
  28257. int amt,
  28258. sqlite3_int64 offset
  28259. ){
  28260. unixFile *pFile = (unixFile*)id;
  28261. int wrote = 0;
  28262. assert( id );
  28263. assert( amt>0 );
  28264. /* If this is a database file (not a journal, master-journal or temp
  28265. ** file), the bytes in the locking range should never be read or written. */
  28266. #if 0
  28267. assert( pFile->pUnused==0
  28268. || offset>=PENDING_BYTE+512
  28269. || offset+amt<=PENDING_BYTE
  28270. );
  28271. #endif
  28272. #ifdef SQLITE_DEBUG
  28273. /* If we are doing a normal write to a database file (as opposed to
  28274. ** doing a hot-journal rollback or a write to some file other than a
  28275. ** normal database file) then record the fact that the database
  28276. ** has changed. If the transaction counter is modified, record that
  28277. ** fact too.
  28278. */
  28279. if( pFile->inNormalWrite ){
  28280. pFile->dbUpdate = 1; /* The database has been modified */
  28281. if( offset<=24 && offset+amt>=27 ){
  28282. int rc;
  28283. char oldCntr[4];
  28284. SimulateIOErrorBenign(1);
  28285. rc = seekAndRead(pFile, 24, oldCntr, 4);
  28286. SimulateIOErrorBenign(0);
  28287. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  28288. pFile->transCntrChng = 1; /* The transaction counter has changed */
  28289. }
  28290. }
  28291. }
  28292. #endif
  28293. #if SQLITE_MAX_MMAP_SIZE>0
  28294. /* Deal with as much of this write request as possible by transfering
  28295. ** data from the memory mapping using memcpy(). */
  28296. if( offset<pFile->mmapSize ){
  28297. if( offset+amt <= pFile->mmapSize ){
  28298. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  28299. return SQLITE_OK;
  28300. }else{
  28301. int nCopy = pFile->mmapSize - offset;
  28302. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  28303. pBuf = &((u8 *)pBuf)[nCopy];
  28304. amt -= nCopy;
  28305. offset += nCopy;
  28306. }
  28307. }
  28308. #endif
  28309. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  28310. amt -= wrote;
  28311. offset += wrote;
  28312. pBuf = &((char*)pBuf)[wrote];
  28313. }
  28314. SimulateIOError(( wrote=(-1), amt=1 ));
  28315. SimulateDiskfullError(( wrote=0, amt=1 ));
  28316. if( amt>wrote ){
  28317. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  28318. /* lastErrno set by seekAndWrite */
  28319. return SQLITE_IOERR_WRITE;
  28320. }else{
  28321. storeLastErrno(pFile, 0); /* not a system error */
  28322. return SQLITE_FULL;
  28323. }
  28324. }
  28325. return SQLITE_OK;
  28326. }
  28327. #ifdef SQLITE_TEST
  28328. /*
  28329. ** Count the number of fullsyncs and normal syncs. This is used to test
  28330. ** that syncs and fullsyncs are occurring at the right times.
  28331. */
  28332. SQLITE_API int sqlite3_sync_count = 0;
  28333. SQLITE_API int sqlite3_fullsync_count = 0;
  28334. #endif
  28335. /*
  28336. ** We do not trust systems to provide a working fdatasync(). Some do.
  28337. ** Others do no. To be safe, we will stick with the (slightly slower)
  28338. ** fsync(). If you know that your system does support fdatasync() correctly,
  28339. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  28340. */
  28341. #if !defined(fdatasync) && !HAVE_FDATASYNC
  28342. # define fdatasync fsync
  28343. #endif
  28344. /*
  28345. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  28346. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  28347. ** only available on Mac OS X. But that could change.
  28348. */
  28349. #ifdef F_FULLFSYNC
  28350. # define HAVE_FULLFSYNC 1
  28351. #else
  28352. # define HAVE_FULLFSYNC 0
  28353. #endif
  28354. /*
  28355. ** The fsync() system call does not work as advertised on many
  28356. ** unix systems. The following procedure is an attempt to make
  28357. ** it work better.
  28358. **
  28359. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  28360. ** for testing when we want to run through the test suite quickly.
  28361. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  28362. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  28363. ** or power failure will likely corrupt the database file.
  28364. **
  28365. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  28366. ** The idea behind dataOnly is that it should only write the file content
  28367. ** to disk, not the inode. We only set dataOnly if the file size is
  28368. ** unchanged since the file size is part of the inode. However,
  28369. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  28370. ** file size has changed. The only real difference between fdatasync()
  28371. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  28372. ** inode if the mtime or owner or other inode attributes have changed.
  28373. ** We only care about the file size, not the other file attributes, so
  28374. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  28375. ** So, we always use fdatasync() if it is available, regardless of
  28376. ** the value of the dataOnly flag.
  28377. */
  28378. static int full_fsync(int fd, int fullSync, int dataOnly){
  28379. int rc;
  28380. /* The following "ifdef/elif/else/" block has the same structure as
  28381. ** the one below. It is replicated here solely to avoid cluttering
  28382. ** up the real code with the UNUSED_PARAMETER() macros.
  28383. */
  28384. #ifdef SQLITE_NO_SYNC
  28385. UNUSED_PARAMETER(fd);
  28386. UNUSED_PARAMETER(fullSync);
  28387. UNUSED_PARAMETER(dataOnly);
  28388. #elif HAVE_FULLFSYNC
  28389. UNUSED_PARAMETER(dataOnly);
  28390. #else
  28391. UNUSED_PARAMETER(fullSync);
  28392. UNUSED_PARAMETER(dataOnly);
  28393. #endif
  28394. /* Record the number of times that we do a normal fsync() and
  28395. ** FULLSYNC. This is used during testing to verify that this procedure
  28396. ** gets called with the correct arguments.
  28397. */
  28398. #ifdef SQLITE_TEST
  28399. if( fullSync ) sqlite3_fullsync_count++;
  28400. sqlite3_sync_count++;
  28401. #endif
  28402. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  28403. ** no-op
  28404. */
  28405. #ifdef SQLITE_NO_SYNC
  28406. rc = SQLITE_OK;
  28407. #elif HAVE_FULLFSYNC
  28408. if( fullSync ){
  28409. rc = osFcntl(fd, F_FULLFSYNC, 0);
  28410. }else{
  28411. rc = 1;
  28412. }
  28413. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  28414. ** It shouldn't be possible for fullfsync to fail on the local
  28415. ** file system (on OSX), so failure indicates that FULLFSYNC
  28416. ** isn't supported for this file system. So, attempt an fsync
  28417. ** and (for now) ignore the overhead of a superfluous fcntl call.
  28418. ** It'd be better to detect fullfsync support once and avoid
  28419. ** the fcntl call every time sync is called.
  28420. */
  28421. if( rc ) rc = fsync(fd);
  28422. #elif defined(__APPLE__)
  28423. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  28424. ** so currently we default to the macro that redefines fdatasync to fsync
  28425. */
  28426. rc = fsync(fd);
  28427. #else
  28428. rc = fdatasync(fd);
  28429. #if OS_VXWORKS
  28430. if( rc==-1 && errno==ENOTSUP ){
  28431. rc = fsync(fd);
  28432. }
  28433. #endif /* OS_VXWORKS */
  28434. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  28435. if( OS_VXWORKS && rc!= -1 ){
  28436. rc = 0;
  28437. }
  28438. return rc;
  28439. }
  28440. /*
  28441. ** Open a file descriptor to the directory containing file zFilename.
  28442. ** If successful, *pFd is set to the opened file descriptor and
  28443. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  28444. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  28445. ** value.
  28446. **
  28447. ** The directory file descriptor is used for only one thing - to
  28448. ** fsync() a directory to make sure file creation and deletion events
  28449. ** are flushed to disk. Such fsyncs are not needed on newer
  28450. ** journaling filesystems, but are required on older filesystems.
  28451. **
  28452. ** This routine can be overridden using the xSetSysCall interface.
  28453. ** The ability to override this routine was added in support of the
  28454. ** chromium sandbox. Opening a directory is a security risk (we are
  28455. ** told) so making it overrideable allows the chromium sandbox to
  28456. ** replace this routine with a harmless no-op. To make this routine
  28457. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  28458. ** *pFd set to a negative number.
  28459. **
  28460. ** If SQLITE_OK is returned, the caller is responsible for closing
  28461. ** the file descriptor *pFd using close().
  28462. */
  28463. static int openDirectory(const char *zFilename, int *pFd){
  28464. int ii;
  28465. int fd = -1;
  28466. char zDirname[MAX_PATHNAME+1];
  28467. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  28468. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  28469. if( ii>0 ){
  28470. zDirname[ii] = '\0';
  28471. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  28472. if( fd>=0 ){
  28473. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  28474. }
  28475. }
  28476. *pFd = fd;
  28477. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  28478. }
  28479. /*
  28480. ** Make sure all writes to a particular file are committed to disk.
  28481. **
  28482. ** If dataOnly==0 then both the file itself and its metadata (file
  28483. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  28484. ** file data is synced.
  28485. **
  28486. ** Under Unix, also make sure that the directory entry for the file
  28487. ** has been created by fsync-ing the directory that contains the file.
  28488. ** If we do not do this and we encounter a power failure, the directory
  28489. ** entry for the journal might not exist after we reboot. The next
  28490. ** SQLite to access the file will not know that the journal exists (because
  28491. ** the directory entry for the journal was never created) and the transaction
  28492. ** will not roll back - possibly leading to database corruption.
  28493. */
  28494. static int unixSync(sqlite3_file *id, int flags){
  28495. int rc;
  28496. unixFile *pFile = (unixFile*)id;
  28497. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  28498. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  28499. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  28500. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  28501. || (flags&0x0F)==SQLITE_SYNC_FULL
  28502. );
  28503. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  28504. ** line is to test that doing so does not cause any problems.
  28505. */
  28506. SimulateDiskfullError( return SQLITE_FULL );
  28507. assert( pFile );
  28508. OSTRACE(("SYNC %-3d\n", pFile->h));
  28509. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  28510. SimulateIOError( rc=1 );
  28511. if( rc ){
  28512. storeLastErrno(pFile, errno);
  28513. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  28514. }
  28515. /* Also fsync the directory containing the file if the DIRSYNC flag
  28516. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  28517. ** are unable to fsync a directory, so ignore errors on the fsync.
  28518. */
  28519. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  28520. int dirfd;
  28521. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  28522. HAVE_FULLFSYNC, isFullsync));
  28523. rc = osOpenDirectory(pFile->zPath, &dirfd);
  28524. if( rc==SQLITE_OK && dirfd>=0 ){
  28525. full_fsync(dirfd, 0, 0);
  28526. robust_close(pFile, dirfd, __LINE__);
  28527. }else if( rc==SQLITE_CANTOPEN ){
  28528. rc = SQLITE_OK;
  28529. }
  28530. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  28531. }
  28532. return rc;
  28533. }
  28534. /*
  28535. ** Truncate an open file to a specified size
  28536. */
  28537. static int unixTruncate(sqlite3_file *id, i64 nByte){
  28538. unixFile *pFile = (unixFile *)id;
  28539. int rc;
  28540. assert( pFile );
  28541. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  28542. /* If the user has configured a chunk-size for this file, truncate the
  28543. ** file so that it consists of an integer number of chunks (i.e. the
  28544. ** actual file size after the operation may be larger than the requested
  28545. ** size).
  28546. */
  28547. if( pFile->szChunk>0 ){
  28548. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  28549. }
  28550. rc = robust_ftruncate(pFile->h, nByte);
  28551. if( rc ){
  28552. storeLastErrno(pFile, errno);
  28553. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  28554. }else{
  28555. #ifdef SQLITE_DEBUG
  28556. /* If we are doing a normal write to a database file (as opposed to
  28557. ** doing a hot-journal rollback or a write to some file other than a
  28558. ** normal database file) and we truncate the file to zero length,
  28559. ** that effectively updates the change counter. This might happen
  28560. ** when restoring a database using the backup API from a zero-length
  28561. ** source.
  28562. */
  28563. if( pFile->inNormalWrite && nByte==0 ){
  28564. pFile->transCntrChng = 1;
  28565. }
  28566. #endif
  28567. #if SQLITE_MAX_MMAP_SIZE>0
  28568. /* If the file was just truncated to a size smaller than the currently
  28569. ** mapped region, reduce the effective mapping size as well. SQLite will
  28570. ** use read() and write() to access data beyond this point from now on.
  28571. */
  28572. if( nByte<pFile->mmapSize ){
  28573. pFile->mmapSize = nByte;
  28574. }
  28575. #endif
  28576. return SQLITE_OK;
  28577. }
  28578. }
  28579. /*
  28580. ** Determine the current size of a file in bytes
  28581. */
  28582. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  28583. int rc;
  28584. struct stat buf;
  28585. assert( id );
  28586. rc = osFstat(((unixFile*)id)->h, &buf);
  28587. SimulateIOError( rc=1 );
  28588. if( rc!=0 ){
  28589. storeLastErrno((unixFile*)id, errno);
  28590. return SQLITE_IOERR_FSTAT;
  28591. }
  28592. *pSize = buf.st_size;
  28593. /* When opening a zero-size database, the findInodeInfo() procedure
  28594. ** writes a single byte into that file in order to work around a bug
  28595. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  28596. ** layers, we need to report this file size as zero even though it is
  28597. ** really 1. Ticket #3260.
  28598. */
  28599. if( *pSize==1 ) *pSize = 0;
  28600. return SQLITE_OK;
  28601. }
  28602. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28603. /*
  28604. ** Handler for proxy-locking file-control verbs. Defined below in the
  28605. ** proxying locking division.
  28606. */
  28607. static int proxyFileControl(sqlite3_file*,int,void*);
  28608. #endif
  28609. /*
  28610. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  28611. ** file-control operation. Enlarge the database to nBytes in size
  28612. ** (rounded up to the next chunk-size). If the database is already
  28613. ** nBytes or larger, this routine is a no-op.
  28614. */
  28615. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  28616. if( pFile->szChunk>0 ){
  28617. i64 nSize; /* Required file size */
  28618. struct stat buf; /* Used to hold return values of fstat() */
  28619. if( osFstat(pFile->h, &buf) ){
  28620. return SQLITE_IOERR_FSTAT;
  28621. }
  28622. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  28623. if( nSize>(i64)buf.st_size ){
  28624. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  28625. /* The code below is handling the return value of osFallocate()
  28626. ** correctly. posix_fallocate() is defined to "returns zero on success,
  28627. ** or an error number on failure". See the manpage for details. */
  28628. int err;
  28629. do{
  28630. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  28631. }while( err==EINTR );
  28632. if( err ) return SQLITE_IOERR_WRITE;
  28633. #else
  28634. /* If the OS does not have posix_fallocate(), fake it. Write a
  28635. ** single byte to the last byte in each block that falls entirely
  28636. ** within the extended region. Then, if required, a single byte
  28637. ** at offset (nSize-1), to set the size of the file correctly.
  28638. ** This is a similar technique to that used by glibc on systems
  28639. ** that do not have a real fallocate() call.
  28640. */
  28641. int nBlk = buf.st_blksize; /* File-system block size */
  28642. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  28643. i64 iWrite; /* Next offset to write to */
  28644. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  28645. assert( iWrite>=buf.st_size );
  28646. assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
  28647. assert( ((iWrite+1)%nBlk)==0 );
  28648. for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
  28649. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  28650. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  28651. }
  28652. if( nWrite==0 || (nSize%nBlk) ){
  28653. nWrite = seekAndWrite(pFile, nSize-1, "", 1);
  28654. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  28655. }
  28656. #endif
  28657. }
  28658. }
  28659. #if SQLITE_MAX_MMAP_SIZE>0
  28660. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  28661. int rc;
  28662. if( pFile->szChunk<=0 ){
  28663. if( robust_ftruncate(pFile->h, nByte) ){
  28664. storeLastErrno(pFile, errno);
  28665. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  28666. }
  28667. }
  28668. rc = unixMapfile(pFile, nByte);
  28669. return rc;
  28670. }
  28671. #endif
  28672. return SQLITE_OK;
  28673. }
  28674. /*
  28675. ** If *pArg is initially negative then this is a query. Set *pArg to
  28676. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  28677. **
  28678. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  28679. */
  28680. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  28681. if( *pArg<0 ){
  28682. *pArg = (pFile->ctrlFlags & mask)!=0;
  28683. }else if( (*pArg)==0 ){
  28684. pFile->ctrlFlags &= ~mask;
  28685. }else{
  28686. pFile->ctrlFlags |= mask;
  28687. }
  28688. }
  28689. /* Forward declaration */
  28690. static int unixGetTempname(int nBuf, char *zBuf);
  28691. /*
  28692. ** Information and control of an open file handle.
  28693. */
  28694. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  28695. unixFile *pFile = (unixFile*)id;
  28696. switch( op ){
  28697. case SQLITE_FCNTL_WAL_BLOCK: {
  28698. /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
  28699. return SQLITE_OK;
  28700. }
  28701. case SQLITE_FCNTL_LOCKSTATE: {
  28702. *(int*)pArg = pFile->eFileLock;
  28703. return SQLITE_OK;
  28704. }
  28705. case SQLITE_FCNTL_LAST_ERRNO: {
  28706. *(int*)pArg = pFile->lastErrno;
  28707. return SQLITE_OK;
  28708. }
  28709. case SQLITE_FCNTL_CHUNK_SIZE: {
  28710. pFile->szChunk = *(int *)pArg;
  28711. return SQLITE_OK;
  28712. }
  28713. case SQLITE_FCNTL_SIZE_HINT: {
  28714. int rc;
  28715. SimulateIOErrorBenign(1);
  28716. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  28717. SimulateIOErrorBenign(0);
  28718. return rc;
  28719. }
  28720. case SQLITE_FCNTL_PERSIST_WAL: {
  28721. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  28722. return SQLITE_OK;
  28723. }
  28724. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  28725. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  28726. return SQLITE_OK;
  28727. }
  28728. case SQLITE_FCNTL_VFSNAME: {
  28729. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  28730. return SQLITE_OK;
  28731. }
  28732. case SQLITE_FCNTL_TEMPFILENAME: {
  28733. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  28734. if( zTFile ){
  28735. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  28736. *(char**)pArg = zTFile;
  28737. }
  28738. return SQLITE_OK;
  28739. }
  28740. case SQLITE_FCNTL_HAS_MOVED: {
  28741. *(int*)pArg = fileHasMoved(pFile);
  28742. return SQLITE_OK;
  28743. }
  28744. #if SQLITE_MAX_MMAP_SIZE>0
  28745. case SQLITE_FCNTL_MMAP_SIZE: {
  28746. i64 newLimit = *(i64*)pArg;
  28747. int rc = SQLITE_OK;
  28748. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  28749. newLimit = sqlite3GlobalConfig.mxMmap;
  28750. }
  28751. *(i64*)pArg = pFile->mmapSizeMax;
  28752. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  28753. pFile->mmapSizeMax = newLimit;
  28754. if( pFile->mmapSize>0 ){
  28755. unixUnmapfile(pFile);
  28756. rc = unixMapfile(pFile, -1);
  28757. }
  28758. }
  28759. return rc;
  28760. }
  28761. #endif
  28762. #ifdef SQLITE_DEBUG
  28763. /* The pager calls this method to signal that it has done
  28764. ** a rollback and that the database is therefore unchanged and
  28765. ** it hence it is OK for the transaction change counter to be
  28766. ** unchanged.
  28767. */
  28768. case SQLITE_FCNTL_DB_UNCHANGED: {
  28769. ((unixFile*)id)->dbUpdate = 0;
  28770. return SQLITE_OK;
  28771. }
  28772. #endif
  28773. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28774. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  28775. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  28776. return proxyFileControl(id,op,pArg);
  28777. }
  28778. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  28779. }
  28780. return SQLITE_NOTFOUND;
  28781. }
  28782. /*
  28783. ** Return the sector size in bytes of the underlying block device for
  28784. ** the specified file. This is almost always 512 bytes, but may be
  28785. ** larger for some devices.
  28786. **
  28787. ** SQLite code assumes this function cannot fail. It also assumes that
  28788. ** if two files are created in the same file-system directory (i.e.
  28789. ** a database and its journal file) that the sector size will be the
  28790. ** same for both.
  28791. */
  28792. #ifndef __QNXNTO__
  28793. static int unixSectorSize(sqlite3_file *NotUsed){
  28794. UNUSED_PARAMETER(NotUsed);
  28795. return SQLITE_DEFAULT_SECTOR_SIZE;
  28796. }
  28797. #endif
  28798. /*
  28799. ** The following version of unixSectorSize() is optimized for QNX.
  28800. */
  28801. #ifdef __QNXNTO__
  28802. #include <sys/dcmd_blk.h>
  28803. #include <sys/statvfs.h>
  28804. static int unixSectorSize(sqlite3_file *id){
  28805. unixFile *pFile = (unixFile*)id;
  28806. if( pFile->sectorSize == 0 ){
  28807. struct statvfs fsInfo;
  28808. /* Set defaults for non-supported filesystems */
  28809. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  28810. pFile->deviceCharacteristics = 0;
  28811. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  28812. return pFile->sectorSize;
  28813. }
  28814. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  28815. pFile->sectorSize = fsInfo.f_bsize;
  28816. pFile->deviceCharacteristics =
  28817. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  28818. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28819. ** the write succeeds */
  28820. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28821. ** so it is ordered */
  28822. 0;
  28823. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  28824. pFile->sectorSize = fsInfo.f_bsize;
  28825. pFile->deviceCharacteristics =
  28826. /* etfs cluster size writes are atomic */
  28827. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  28828. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28829. ** the write succeeds */
  28830. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28831. ** so it is ordered */
  28832. 0;
  28833. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  28834. pFile->sectorSize = fsInfo.f_bsize;
  28835. pFile->deviceCharacteristics =
  28836. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  28837. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28838. ** the write succeeds */
  28839. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28840. ** so it is ordered */
  28841. 0;
  28842. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  28843. pFile->sectorSize = fsInfo.f_bsize;
  28844. pFile->deviceCharacteristics =
  28845. /* full bitset of atomics from max sector size and smaller */
  28846. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  28847. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28848. ** so it is ordered */
  28849. 0;
  28850. }else if( strstr(fsInfo.f_basetype, "dos") ){
  28851. pFile->sectorSize = fsInfo.f_bsize;
  28852. pFile->deviceCharacteristics =
  28853. /* full bitset of atomics from max sector size and smaller */
  28854. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  28855. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28856. ** so it is ordered */
  28857. 0;
  28858. }else{
  28859. pFile->deviceCharacteristics =
  28860. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  28861. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28862. ** the write succeeds */
  28863. 0;
  28864. }
  28865. }
  28866. /* Last chance verification. If the sector size isn't a multiple of 512
  28867. ** then it isn't valid.*/
  28868. if( pFile->sectorSize % 512 != 0 ){
  28869. pFile->deviceCharacteristics = 0;
  28870. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  28871. }
  28872. return pFile->sectorSize;
  28873. }
  28874. #endif /* __QNXNTO__ */
  28875. /*
  28876. ** Return the device characteristics for the file.
  28877. **
  28878. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  28879. ** However, that choice is controversial since technically the underlying
  28880. ** file system does not always provide powersafe overwrites. (In other
  28881. ** words, after a power-loss event, parts of the file that were never
  28882. ** written might end up being altered.) However, non-PSOW behavior is very,
  28883. ** very rare. And asserting PSOW makes a large reduction in the amount
  28884. ** of required I/O for journaling, since a lot of padding is eliminated.
  28885. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  28886. ** available to turn it off and URI query parameter available to turn it off.
  28887. */
  28888. static int unixDeviceCharacteristics(sqlite3_file *id){
  28889. unixFile *p = (unixFile*)id;
  28890. int rc = 0;
  28891. #ifdef __QNXNTO__
  28892. if( p->sectorSize==0 ) unixSectorSize(id);
  28893. rc = p->deviceCharacteristics;
  28894. #endif
  28895. if( p->ctrlFlags & UNIXFILE_PSOW ){
  28896. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  28897. }
  28898. return rc;
  28899. }
  28900. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28901. /*
  28902. ** Return the system page size.
  28903. **
  28904. ** This function should not be called directly by other code in this file.
  28905. ** Instead, it should be called via macro osGetpagesize().
  28906. */
  28907. static int unixGetpagesize(void){
  28908. #if OS_VXWORKS
  28909. return 1024;
  28910. #elif defined(_BSD_SOURCE)
  28911. return getpagesize();
  28912. #else
  28913. return (int)sysconf(_SC_PAGESIZE);
  28914. #endif
  28915. }
  28916. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  28917. #ifndef SQLITE_OMIT_WAL
  28918. /*
  28919. ** Object used to represent an shared memory buffer.
  28920. **
  28921. ** When multiple threads all reference the same wal-index, each thread
  28922. ** has its own unixShm object, but they all point to a single instance
  28923. ** of this unixShmNode object. In other words, each wal-index is opened
  28924. ** only once per process.
  28925. **
  28926. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  28927. ** We could coalesce this object into unixInodeInfo, but that would mean
  28928. ** every open file that does not use shared memory (in other words, most
  28929. ** open files) would have to carry around this extra information. So
  28930. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  28931. ** and the unixShmNode object is created only when needed.
  28932. **
  28933. ** unixMutexHeld() must be true when creating or destroying
  28934. ** this object or while reading or writing the following fields:
  28935. **
  28936. ** nRef
  28937. **
  28938. ** The following fields are read-only after the object is created:
  28939. **
  28940. ** fid
  28941. ** zFilename
  28942. **
  28943. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  28944. ** unixMutexHeld() is true when reading or writing any other field
  28945. ** in this structure.
  28946. */
  28947. struct unixShmNode {
  28948. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  28949. sqlite3_mutex *mutex; /* Mutex to access this object */
  28950. char *zFilename; /* Name of the mmapped file */
  28951. int h; /* Open file descriptor */
  28952. int szRegion; /* Size of shared-memory regions */
  28953. u16 nRegion; /* Size of array apRegion */
  28954. u8 isReadonly; /* True if read-only */
  28955. char **apRegion; /* Array of mapped shared-memory regions */
  28956. int nRef; /* Number of unixShm objects pointing to this */
  28957. unixShm *pFirst; /* All unixShm objects pointing to this */
  28958. #ifdef SQLITE_DEBUG
  28959. u8 exclMask; /* Mask of exclusive locks held */
  28960. u8 sharedMask; /* Mask of shared locks held */
  28961. u8 nextShmId; /* Next available unixShm.id value */
  28962. #endif
  28963. };
  28964. /*
  28965. ** Structure used internally by this VFS to record the state of an
  28966. ** open shared memory connection.
  28967. **
  28968. ** The following fields are initialized when this object is created and
  28969. ** are read-only thereafter:
  28970. **
  28971. ** unixShm.pFile
  28972. ** unixShm.id
  28973. **
  28974. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  28975. ** while accessing any read/write fields.
  28976. */
  28977. struct unixShm {
  28978. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  28979. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  28980. u8 hasMutex; /* True if holding the unixShmNode mutex */
  28981. u8 id; /* Id of this connection within its unixShmNode */
  28982. u16 sharedMask; /* Mask of shared locks held */
  28983. u16 exclMask; /* Mask of exclusive locks held */
  28984. };
  28985. /*
  28986. ** Constants used for locking
  28987. */
  28988. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  28989. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  28990. /*
  28991. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  28992. **
  28993. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  28994. ** otherwise.
  28995. */
  28996. static int unixShmSystemLock(
  28997. unixFile *pFile, /* Open connection to the WAL file */
  28998. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  28999. int ofst, /* First byte of the locking range */
  29000. int n /* Number of bytes to lock */
  29001. ){
  29002. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  29003. struct flock f; /* The posix advisory locking structure */
  29004. int rc = SQLITE_OK; /* Result code form fcntl() */
  29005. /* Access to the unixShmNode object is serialized by the caller */
  29006. pShmNode = pFile->pInode->pShmNode;
  29007. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  29008. /* Shared locks never span more than one byte */
  29009. assert( n==1 || lockType!=F_RDLCK );
  29010. /* Locks are within range */
  29011. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  29012. if( pShmNode->h>=0 ){
  29013. int lkType;
  29014. /* Initialize the locking parameters */
  29015. memset(&f, 0, sizeof(f));
  29016. f.l_type = lockType;
  29017. f.l_whence = SEEK_SET;
  29018. f.l_start = ofst;
  29019. f.l_len = n;
  29020. lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
  29021. rc = osFcntl(pShmNode->h, lkType, &f);
  29022. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  29023. pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
  29024. }
  29025. /* Update the global lock state and do debug tracing */
  29026. #ifdef SQLITE_DEBUG
  29027. { u16 mask;
  29028. OSTRACE(("SHM-LOCK "));
  29029. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  29030. if( rc==SQLITE_OK ){
  29031. if( lockType==F_UNLCK ){
  29032. OSTRACE(("unlock %d ok", ofst));
  29033. pShmNode->exclMask &= ~mask;
  29034. pShmNode->sharedMask &= ~mask;
  29035. }else if( lockType==F_RDLCK ){
  29036. OSTRACE(("read-lock %d ok", ofst));
  29037. pShmNode->exclMask &= ~mask;
  29038. pShmNode->sharedMask |= mask;
  29039. }else{
  29040. assert( lockType==F_WRLCK );
  29041. OSTRACE(("write-lock %d ok", ofst));
  29042. pShmNode->exclMask |= mask;
  29043. pShmNode->sharedMask &= ~mask;
  29044. }
  29045. }else{
  29046. if( lockType==F_UNLCK ){
  29047. OSTRACE(("unlock %d failed", ofst));
  29048. }else if( lockType==F_RDLCK ){
  29049. OSTRACE(("read-lock failed"));
  29050. }else{
  29051. assert( lockType==F_WRLCK );
  29052. OSTRACE(("write-lock %d failed", ofst));
  29053. }
  29054. }
  29055. OSTRACE((" - afterwards %03x,%03x\n",
  29056. pShmNode->sharedMask, pShmNode->exclMask));
  29057. }
  29058. #endif
  29059. return rc;
  29060. }
  29061. /*
  29062. ** Return the minimum number of 32KB shm regions that should be mapped at
  29063. ** a time, assuming that each mapping must be an integer multiple of the
  29064. ** current system page-size.
  29065. **
  29066. ** Usually, this is 1. The exception seems to be systems that are configured
  29067. ** to use 64KB pages - in this case each mapping must cover at least two
  29068. ** shm regions.
  29069. */
  29070. static int unixShmRegionPerMap(void){
  29071. int shmsz = 32*1024; /* SHM region size */
  29072. int pgsz = osGetpagesize(); /* System page size */
  29073. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  29074. if( pgsz<shmsz ) return 1;
  29075. return pgsz/shmsz;
  29076. }
  29077. /*
  29078. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  29079. **
  29080. ** This is not a VFS shared-memory method; it is a utility function called
  29081. ** by VFS shared-memory methods.
  29082. */
  29083. static void unixShmPurge(unixFile *pFd){
  29084. unixShmNode *p = pFd->pInode->pShmNode;
  29085. assert( unixMutexHeld() );
  29086. if( p && p->nRef==0 ){
  29087. int nShmPerMap = unixShmRegionPerMap();
  29088. int i;
  29089. assert( p->pInode==pFd->pInode );
  29090. sqlite3_mutex_free(p->mutex);
  29091. for(i=0; i<p->nRegion; i+=nShmPerMap){
  29092. if( p->h>=0 ){
  29093. osMunmap(p->apRegion[i], p->szRegion);
  29094. }else{
  29095. sqlite3_free(p->apRegion[i]);
  29096. }
  29097. }
  29098. sqlite3_free(p->apRegion);
  29099. if( p->h>=0 ){
  29100. robust_close(pFd, p->h, __LINE__);
  29101. p->h = -1;
  29102. }
  29103. p->pInode->pShmNode = 0;
  29104. sqlite3_free(p);
  29105. }
  29106. }
  29107. /*
  29108. ** Open a shared-memory area associated with open database file pDbFd.
  29109. ** This particular implementation uses mmapped files.
  29110. **
  29111. ** The file used to implement shared-memory is in the same directory
  29112. ** as the open database file and has the same name as the open database
  29113. ** file with the "-shm" suffix added. For example, if the database file
  29114. ** is "/home/user1/config.db" then the file that is created and mmapped
  29115. ** for shared memory will be called "/home/user1/config.db-shm".
  29116. **
  29117. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  29118. ** some other tmpfs mount. But if a file in a different directory
  29119. ** from the database file is used, then differing access permissions
  29120. ** or a chroot() might cause two different processes on the same
  29121. ** database to end up using different files for shared memory -
  29122. ** meaning that their memory would not really be shared - resulting
  29123. ** in database corruption. Nevertheless, this tmpfs file usage
  29124. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  29125. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  29126. ** option results in an incompatible build of SQLite; builds of SQLite
  29127. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  29128. ** same database file at the same time, database corruption will likely
  29129. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  29130. ** "unsupported" and may go away in a future SQLite release.
  29131. **
  29132. ** When opening a new shared-memory file, if no other instances of that
  29133. ** file are currently open, in this process or in other processes, then
  29134. ** the file must be truncated to zero length or have its header cleared.
  29135. **
  29136. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  29137. ** that means that an exclusive lock is held on the database file and
  29138. ** that no other processes are able to read or write the database. In
  29139. ** that case, we do not really need shared memory. No shared memory
  29140. ** file is created. The shared memory will be simulated with heap memory.
  29141. */
  29142. static int unixOpenSharedMemory(unixFile *pDbFd){
  29143. struct unixShm *p = 0; /* The connection to be opened */
  29144. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  29145. int rc; /* Result code */
  29146. unixInodeInfo *pInode; /* The inode of fd */
  29147. char *zShmFilename; /* Name of the file used for SHM */
  29148. int nShmFilename; /* Size of the SHM filename in bytes */
  29149. /* Allocate space for the new unixShm object. */
  29150. p = sqlite3_malloc64( sizeof(*p) );
  29151. if( p==0 ) return SQLITE_NOMEM;
  29152. memset(p, 0, sizeof(*p));
  29153. assert( pDbFd->pShm==0 );
  29154. /* Check to see if a unixShmNode object already exists. Reuse an existing
  29155. ** one if present. Create a new one if necessary.
  29156. */
  29157. unixEnterMutex();
  29158. pInode = pDbFd->pInode;
  29159. pShmNode = pInode->pShmNode;
  29160. if( pShmNode==0 ){
  29161. struct stat sStat; /* fstat() info for database file */
  29162. #ifndef SQLITE_SHM_DIRECTORY
  29163. const char *zBasePath = pDbFd->zPath;
  29164. #endif
  29165. /* Call fstat() to figure out the permissions on the database file. If
  29166. ** a new *-shm file is created, an attempt will be made to create it
  29167. ** with the same permissions.
  29168. */
  29169. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  29170. rc = SQLITE_IOERR_FSTAT;
  29171. goto shm_open_err;
  29172. }
  29173. #ifdef SQLITE_SHM_DIRECTORY
  29174. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  29175. #else
  29176. nShmFilename = 6 + (int)strlen(zBasePath);
  29177. #endif
  29178. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  29179. if( pShmNode==0 ){
  29180. rc = SQLITE_NOMEM;
  29181. goto shm_open_err;
  29182. }
  29183. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  29184. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  29185. #ifdef SQLITE_SHM_DIRECTORY
  29186. sqlite3_snprintf(nShmFilename, zShmFilename,
  29187. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  29188. (u32)sStat.st_ino, (u32)sStat.st_dev);
  29189. #else
  29190. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  29191. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  29192. #endif
  29193. pShmNode->h = -1;
  29194. pDbFd->pInode->pShmNode = pShmNode;
  29195. pShmNode->pInode = pDbFd->pInode;
  29196. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  29197. if( pShmNode->mutex==0 ){
  29198. rc = SQLITE_NOMEM;
  29199. goto shm_open_err;
  29200. }
  29201. if( pInode->bProcessLock==0 ){
  29202. int openFlags = O_RDWR | O_CREAT;
  29203. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  29204. openFlags = O_RDONLY;
  29205. pShmNode->isReadonly = 1;
  29206. }
  29207. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  29208. if( pShmNode->h<0 ){
  29209. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  29210. goto shm_open_err;
  29211. }
  29212. /* If this process is running as root, make sure that the SHM file
  29213. ** is owned by the same user that owns the original database. Otherwise,
  29214. ** the original owner will not be able to connect.
  29215. */
  29216. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  29217. /* Check to see if another process is holding the dead-man switch.
  29218. ** If not, truncate the file to zero length.
  29219. */
  29220. rc = SQLITE_OK;
  29221. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  29222. if( robust_ftruncate(pShmNode->h, 0) ){
  29223. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  29224. }
  29225. }
  29226. if( rc==SQLITE_OK ){
  29227. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  29228. }
  29229. if( rc ) goto shm_open_err;
  29230. }
  29231. }
  29232. /* Make the new connection a child of the unixShmNode */
  29233. p->pShmNode = pShmNode;
  29234. #ifdef SQLITE_DEBUG
  29235. p->id = pShmNode->nextShmId++;
  29236. #endif
  29237. pShmNode->nRef++;
  29238. pDbFd->pShm = p;
  29239. unixLeaveMutex();
  29240. /* The reference count on pShmNode has already been incremented under
  29241. ** the cover of the unixEnterMutex() mutex and the pointer from the
  29242. ** new (struct unixShm) object to the pShmNode has been set. All that is
  29243. ** left to do is to link the new object into the linked list starting
  29244. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  29245. ** mutex.
  29246. */
  29247. sqlite3_mutex_enter(pShmNode->mutex);
  29248. p->pNext = pShmNode->pFirst;
  29249. pShmNode->pFirst = p;
  29250. sqlite3_mutex_leave(pShmNode->mutex);
  29251. return SQLITE_OK;
  29252. /* Jump here on any error */
  29253. shm_open_err:
  29254. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  29255. sqlite3_free(p);
  29256. unixLeaveMutex();
  29257. return rc;
  29258. }
  29259. /*
  29260. ** This function is called to obtain a pointer to region iRegion of the
  29261. ** shared-memory associated with the database file fd. Shared-memory regions
  29262. ** are numbered starting from zero. Each shared-memory region is szRegion
  29263. ** bytes in size.
  29264. **
  29265. ** If an error occurs, an error code is returned and *pp is set to NULL.
  29266. **
  29267. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  29268. ** region has not been allocated (by any client, including one running in a
  29269. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  29270. ** bExtend is non-zero and the requested shared-memory region has not yet
  29271. ** been allocated, it is allocated by this function.
  29272. **
  29273. ** If the shared-memory region has already been allocated or is allocated by
  29274. ** this call as described above, then it is mapped into this processes
  29275. ** address space (if it is not already), *pp is set to point to the mapped
  29276. ** memory and SQLITE_OK returned.
  29277. */
  29278. static int unixShmMap(
  29279. sqlite3_file *fd, /* Handle open on database file */
  29280. int iRegion, /* Region to retrieve */
  29281. int szRegion, /* Size of regions */
  29282. int bExtend, /* True to extend file if necessary */
  29283. void volatile **pp /* OUT: Mapped memory */
  29284. ){
  29285. unixFile *pDbFd = (unixFile*)fd;
  29286. unixShm *p;
  29287. unixShmNode *pShmNode;
  29288. int rc = SQLITE_OK;
  29289. int nShmPerMap = unixShmRegionPerMap();
  29290. int nReqRegion;
  29291. /* If the shared-memory file has not yet been opened, open it now. */
  29292. if( pDbFd->pShm==0 ){
  29293. rc = unixOpenSharedMemory(pDbFd);
  29294. if( rc!=SQLITE_OK ) return rc;
  29295. }
  29296. p = pDbFd->pShm;
  29297. pShmNode = p->pShmNode;
  29298. sqlite3_mutex_enter(pShmNode->mutex);
  29299. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  29300. assert( pShmNode->pInode==pDbFd->pInode );
  29301. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  29302. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  29303. /* Minimum number of regions required to be mapped. */
  29304. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  29305. if( pShmNode->nRegion<nReqRegion ){
  29306. char **apNew; /* New apRegion[] array */
  29307. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  29308. struct stat sStat; /* Used by fstat() */
  29309. pShmNode->szRegion = szRegion;
  29310. if( pShmNode->h>=0 ){
  29311. /* The requested region is not mapped into this processes address space.
  29312. ** Check to see if it has been allocated (i.e. if the wal-index file is
  29313. ** large enough to contain the requested region).
  29314. */
  29315. if( osFstat(pShmNode->h, &sStat) ){
  29316. rc = SQLITE_IOERR_SHMSIZE;
  29317. goto shmpage_out;
  29318. }
  29319. if( sStat.st_size<nByte ){
  29320. /* The requested memory region does not exist. If bExtend is set to
  29321. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  29322. */
  29323. if( !bExtend ){
  29324. goto shmpage_out;
  29325. }
  29326. /* Alternatively, if bExtend is true, extend the file. Do this by
  29327. ** writing a single byte to the end of each (OS) page being
  29328. ** allocated or extended. Technically, we need only write to the
  29329. ** last page in order to extend the file. But writing to all new
  29330. ** pages forces the OS to allocate them immediately, which reduces
  29331. ** the chances of SIGBUS while accessing the mapped region later on.
  29332. */
  29333. else{
  29334. static const int pgsz = 4096;
  29335. int iPg;
  29336. /* Write to the last byte of each newly allocated or extended page */
  29337. assert( (nByte % pgsz)==0 );
  29338. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  29339. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  29340. const char *zFile = pShmNode->zFilename;
  29341. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  29342. goto shmpage_out;
  29343. }
  29344. }
  29345. }
  29346. }
  29347. }
  29348. /* Map the requested memory region into this processes address space. */
  29349. apNew = (char **)sqlite3_realloc(
  29350. pShmNode->apRegion, nReqRegion*sizeof(char *)
  29351. );
  29352. if( !apNew ){
  29353. rc = SQLITE_IOERR_NOMEM;
  29354. goto shmpage_out;
  29355. }
  29356. pShmNode->apRegion = apNew;
  29357. while( pShmNode->nRegion<nReqRegion ){
  29358. int nMap = szRegion*nShmPerMap;
  29359. int i;
  29360. void *pMem;
  29361. if( pShmNode->h>=0 ){
  29362. pMem = osMmap(0, nMap,
  29363. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  29364. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  29365. );
  29366. if( pMem==MAP_FAILED ){
  29367. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  29368. goto shmpage_out;
  29369. }
  29370. }else{
  29371. pMem = sqlite3_malloc64(szRegion);
  29372. if( pMem==0 ){
  29373. rc = SQLITE_NOMEM;
  29374. goto shmpage_out;
  29375. }
  29376. memset(pMem, 0, szRegion);
  29377. }
  29378. for(i=0; i<nShmPerMap; i++){
  29379. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  29380. }
  29381. pShmNode->nRegion += nShmPerMap;
  29382. }
  29383. }
  29384. shmpage_out:
  29385. if( pShmNode->nRegion>iRegion ){
  29386. *pp = pShmNode->apRegion[iRegion];
  29387. }else{
  29388. *pp = 0;
  29389. }
  29390. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  29391. sqlite3_mutex_leave(pShmNode->mutex);
  29392. return rc;
  29393. }
  29394. /*
  29395. ** Change the lock state for a shared-memory segment.
  29396. **
  29397. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  29398. ** different here than in posix. In xShmLock(), one can go from unlocked
  29399. ** to shared and back or from unlocked to exclusive and back. But one may
  29400. ** not go from shared to exclusive or from exclusive to shared.
  29401. */
  29402. static int unixShmLock(
  29403. sqlite3_file *fd, /* Database file holding the shared memory */
  29404. int ofst, /* First lock to acquire or release */
  29405. int n, /* Number of locks to acquire or release */
  29406. int flags /* What to do with the lock */
  29407. ){
  29408. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  29409. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  29410. unixShm *pX; /* For looping over all siblings */
  29411. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  29412. int rc = SQLITE_OK; /* Result code */
  29413. u16 mask; /* Mask of locks to take or release */
  29414. assert( pShmNode==pDbFd->pInode->pShmNode );
  29415. assert( pShmNode->pInode==pDbFd->pInode );
  29416. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  29417. assert( n>=1 );
  29418. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  29419. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  29420. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  29421. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  29422. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  29423. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  29424. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  29425. mask = (1<<(ofst+n)) - (1<<ofst);
  29426. assert( n>1 || mask==(1<<ofst) );
  29427. sqlite3_mutex_enter(pShmNode->mutex);
  29428. if( flags & SQLITE_SHM_UNLOCK ){
  29429. u16 allMask = 0; /* Mask of locks held by siblings */
  29430. /* See if any siblings hold this same lock */
  29431. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29432. if( pX==p ) continue;
  29433. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  29434. allMask |= pX->sharedMask;
  29435. }
  29436. /* Unlock the system-level locks */
  29437. if( (mask & allMask)==0 ){
  29438. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  29439. }else{
  29440. rc = SQLITE_OK;
  29441. }
  29442. /* Undo the local locks */
  29443. if( rc==SQLITE_OK ){
  29444. p->exclMask &= ~mask;
  29445. p->sharedMask &= ~mask;
  29446. }
  29447. }else if( flags & SQLITE_SHM_SHARED ){
  29448. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  29449. /* Find out which shared locks are already held by sibling connections.
  29450. ** If any sibling already holds an exclusive lock, go ahead and return
  29451. ** SQLITE_BUSY.
  29452. */
  29453. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29454. if( (pX->exclMask & mask)!=0 ){
  29455. rc = SQLITE_BUSY;
  29456. break;
  29457. }
  29458. allShared |= pX->sharedMask;
  29459. }
  29460. /* Get shared locks at the system level, if necessary */
  29461. if( rc==SQLITE_OK ){
  29462. if( (allShared & mask)==0 ){
  29463. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  29464. }else{
  29465. rc = SQLITE_OK;
  29466. }
  29467. }
  29468. /* Get the local shared locks */
  29469. if( rc==SQLITE_OK ){
  29470. p->sharedMask |= mask;
  29471. }
  29472. }else{
  29473. /* Make sure no sibling connections hold locks that will block this
  29474. ** lock. If any do, return SQLITE_BUSY right away.
  29475. */
  29476. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29477. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  29478. rc = SQLITE_BUSY;
  29479. break;
  29480. }
  29481. }
  29482. /* Get the exclusive locks at the system level. Then if successful
  29483. ** also mark the local connection as being locked.
  29484. */
  29485. if( rc==SQLITE_OK ){
  29486. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  29487. if( rc==SQLITE_OK ){
  29488. assert( (p->sharedMask & mask)==0 );
  29489. p->exclMask |= mask;
  29490. }
  29491. }
  29492. }
  29493. sqlite3_mutex_leave(pShmNode->mutex);
  29494. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  29495. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  29496. return rc;
  29497. }
  29498. /*
  29499. ** Implement a memory barrier or memory fence on shared memory.
  29500. **
  29501. ** All loads and stores begun before the barrier must complete before
  29502. ** any load or store begun after the barrier.
  29503. */
  29504. static void unixShmBarrier(
  29505. sqlite3_file *fd /* Database file holding the shared memory */
  29506. ){
  29507. UNUSED_PARAMETER(fd);
  29508. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  29509. unixEnterMutex(); /* Also mutex, for redundancy */
  29510. unixLeaveMutex();
  29511. }
  29512. /*
  29513. ** Close a connection to shared-memory. Delete the underlying
  29514. ** storage if deleteFlag is true.
  29515. **
  29516. ** If there is no shared memory associated with the connection then this
  29517. ** routine is a harmless no-op.
  29518. */
  29519. static int unixShmUnmap(
  29520. sqlite3_file *fd, /* The underlying database file */
  29521. int deleteFlag /* Delete shared-memory if true */
  29522. ){
  29523. unixShm *p; /* The connection to be closed */
  29524. unixShmNode *pShmNode; /* The underlying shared-memory file */
  29525. unixShm **pp; /* For looping over sibling connections */
  29526. unixFile *pDbFd; /* The underlying database file */
  29527. pDbFd = (unixFile*)fd;
  29528. p = pDbFd->pShm;
  29529. if( p==0 ) return SQLITE_OK;
  29530. pShmNode = p->pShmNode;
  29531. assert( pShmNode==pDbFd->pInode->pShmNode );
  29532. assert( pShmNode->pInode==pDbFd->pInode );
  29533. /* Remove connection p from the set of connections associated
  29534. ** with pShmNode */
  29535. sqlite3_mutex_enter(pShmNode->mutex);
  29536. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  29537. *pp = p->pNext;
  29538. /* Free the connection p */
  29539. sqlite3_free(p);
  29540. pDbFd->pShm = 0;
  29541. sqlite3_mutex_leave(pShmNode->mutex);
  29542. /* If pShmNode->nRef has reached 0, then close the underlying
  29543. ** shared-memory file, too */
  29544. unixEnterMutex();
  29545. assert( pShmNode->nRef>0 );
  29546. pShmNode->nRef--;
  29547. if( pShmNode->nRef==0 ){
  29548. if( deleteFlag && pShmNode->h>=0 ){
  29549. osUnlink(pShmNode->zFilename);
  29550. }
  29551. unixShmPurge(pDbFd);
  29552. }
  29553. unixLeaveMutex();
  29554. return SQLITE_OK;
  29555. }
  29556. #else
  29557. # define unixShmMap 0
  29558. # define unixShmLock 0
  29559. # define unixShmBarrier 0
  29560. # define unixShmUnmap 0
  29561. #endif /* #ifndef SQLITE_OMIT_WAL */
  29562. #if SQLITE_MAX_MMAP_SIZE>0
  29563. /*
  29564. ** If it is currently memory mapped, unmap file pFd.
  29565. */
  29566. static void unixUnmapfile(unixFile *pFd){
  29567. assert( pFd->nFetchOut==0 );
  29568. if( pFd->pMapRegion ){
  29569. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  29570. pFd->pMapRegion = 0;
  29571. pFd->mmapSize = 0;
  29572. pFd->mmapSizeActual = 0;
  29573. }
  29574. }
  29575. /*
  29576. ** Attempt to set the size of the memory mapping maintained by file
  29577. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  29578. **
  29579. ** If successful, this function sets the following variables:
  29580. **
  29581. ** unixFile.pMapRegion
  29582. ** unixFile.mmapSize
  29583. ** unixFile.mmapSizeActual
  29584. **
  29585. ** If unsuccessful, an error message is logged via sqlite3_log() and
  29586. ** the three variables above are zeroed. In this case SQLite should
  29587. ** continue accessing the database using the xRead() and xWrite()
  29588. ** methods.
  29589. */
  29590. static void unixRemapfile(
  29591. unixFile *pFd, /* File descriptor object */
  29592. i64 nNew /* Required mapping size */
  29593. ){
  29594. const char *zErr = "mmap";
  29595. int h = pFd->h; /* File descriptor open on db file */
  29596. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  29597. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  29598. u8 *pNew = 0; /* Location of new mapping */
  29599. int flags = PROT_READ; /* Flags to pass to mmap() */
  29600. assert( pFd->nFetchOut==0 );
  29601. assert( nNew>pFd->mmapSize );
  29602. assert( nNew<=pFd->mmapSizeMax );
  29603. assert( nNew>0 );
  29604. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  29605. assert( MAP_FAILED!=0 );
  29606. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  29607. if( pOrig ){
  29608. #if HAVE_MREMAP
  29609. i64 nReuse = pFd->mmapSize;
  29610. #else
  29611. const int szSyspage = osGetpagesize();
  29612. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  29613. #endif
  29614. u8 *pReq = &pOrig[nReuse];
  29615. /* Unmap any pages of the existing mapping that cannot be reused. */
  29616. if( nReuse!=nOrig ){
  29617. osMunmap(pReq, nOrig-nReuse);
  29618. }
  29619. #if HAVE_MREMAP
  29620. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  29621. zErr = "mremap";
  29622. #else
  29623. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  29624. if( pNew!=MAP_FAILED ){
  29625. if( pNew!=pReq ){
  29626. osMunmap(pNew, nNew - nReuse);
  29627. pNew = 0;
  29628. }else{
  29629. pNew = pOrig;
  29630. }
  29631. }
  29632. #endif
  29633. /* The attempt to extend the existing mapping failed. Free it. */
  29634. if( pNew==MAP_FAILED || pNew==0 ){
  29635. osMunmap(pOrig, nReuse);
  29636. }
  29637. }
  29638. /* If pNew is still NULL, try to create an entirely new mapping. */
  29639. if( pNew==0 ){
  29640. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  29641. }
  29642. if( pNew==MAP_FAILED ){
  29643. pNew = 0;
  29644. nNew = 0;
  29645. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  29646. /* If the mmap() above failed, assume that all subsequent mmap() calls
  29647. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  29648. ** in this case. */
  29649. pFd->mmapSizeMax = 0;
  29650. }
  29651. pFd->pMapRegion = (void *)pNew;
  29652. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  29653. }
  29654. /*
  29655. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  29656. ** is already mapped, the existing mapping is replaced by the new). Or, if
  29657. ** there already exists a mapping for this file, and there are still
  29658. ** outstanding xFetch() references to it, this function is a no-op.
  29659. **
  29660. ** If parameter nByte is non-negative, then it is the requested size of
  29661. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  29662. ** requested size is the size of the file on disk. The actual size of the
  29663. ** created mapping is either the requested size or the value configured
  29664. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  29665. **
  29666. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  29667. ** recreated as a result of outstanding references) or an SQLite error
  29668. ** code otherwise.
  29669. */
  29670. static int unixMapfile(unixFile *pFd, i64 nByte){
  29671. i64 nMap = nByte;
  29672. int rc;
  29673. assert( nMap>=0 || pFd->nFetchOut==0 );
  29674. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  29675. if( nMap<0 ){
  29676. struct stat statbuf; /* Low-level file information */
  29677. rc = osFstat(pFd->h, &statbuf);
  29678. if( rc!=SQLITE_OK ){
  29679. return SQLITE_IOERR_FSTAT;
  29680. }
  29681. nMap = statbuf.st_size;
  29682. }
  29683. if( nMap>pFd->mmapSizeMax ){
  29684. nMap = pFd->mmapSizeMax;
  29685. }
  29686. if( nMap!=pFd->mmapSize ){
  29687. if( nMap>0 ){
  29688. unixRemapfile(pFd, nMap);
  29689. }else{
  29690. unixUnmapfile(pFd);
  29691. }
  29692. }
  29693. return SQLITE_OK;
  29694. }
  29695. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  29696. /*
  29697. ** If possible, return a pointer to a mapping of file fd starting at offset
  29698. ** iOff. The mapping must be valid for at least nAmt bytes.
  29699. **
  29700. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  29701. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  29702. ** Finally, if an error does occur, return an SQLite error code. The final
  29703. ** value of *pp is undefined in this case.
  29704. **
  29705. ** If this function does return a pointer, the caller must eventually
  29706. ** release the reference by calling unixUnfetch().
  29707. */
  29708. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  29709. #if SQLITE_MAX_MMAP_SIZE>0
  29710. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  29711. #endif
  29712. *pp = 0;
  29713. #if SQLITE_MAX_MMAP_SIZE>0
  29714. if( pFd->mmapSizeMax>0 ){
  29715. if( pFd->pMapRegion==0 ){
  29716. int rc = unixMapfile(pFd, -1);
  29717. if( rc!=SQLITE_OK ) return rc;
  29718. }
  29719. if( pFd->mmapSize >= iOff+nAmt ){
  29720. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  29721. pFd->nFetchOut++;
  29722. }
  29723. }
  29724. #endif
  29725. return SQLITE_OK;
  29726. }
  29727. /*
  29728. ** If the third argument is non-NULL, then this function releases a
  29729. ** reference obtained by an earlier call to unixFetch(). The second
  29730. ** argument passed to this function must be the same as the corresponding
  29731. ** argument that was passed to the unixFetch() invocation.
  29732. **
  29733. ** Or, if the third argument is NULL, then this function is being called
  29734. ** to inform the VFS layer that, according to POSIX, any existing mapping
  29735. ** may now be invalid and should be unmapped.
  29736. */
  29737. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  29738. #if SQLITE_MAX_MMAP_SIZE>0
  29739. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  29740. UNUSED_PARAMETER(iOff);
  29741. /* If p==0 (unmap the entire file) then there must be no outstanding
  29742. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  29743. ** then there must be at least one outstanding. */
  29744. assert( (p==0)==(pFd->nFetchOut==0) );
  29745. /* If p!=0, it must match the iOff value. */
  29746. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  29747. if( p ){
  29748. pFd->nFetchOut--;
  29749. }else{
  29750. unixUnmapfile(pFd);
  29751. }
  29752. assert( pFd->nFetchOut>=0 );
  29753. #else
  29754. UNUSED_PARAMETER(fd);
  29755. UNUSED_PARAMETER(p);
  29756. UNUSED_PARAMETER(iOff);
  29757. #endif
  29758. return SQLITE_OK;
  29759. }
  29760. /*
  29761. ** Here ends the implementation of all sqlite3_file methods.
  29762. **
  29763. ********************** End sqlite3_file Methods *******************************
  29764. ******************************************************************************/
  29765. /*
  29766. ** This division contains definitions of sqlite3_io_methods objects that
  29767. ** implement various file locking strategies. It also contains definitions
  29768. ** of "finder" functions. A finder-function is used to locate the appropriate
  29769. ** sqlite3_io_methods object for a particular database file. The pAppData
  29770. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  29771. ** the correct finder-function for that VFS.
  29772. **
  29773. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  29774. ** object. The only interesting finder-function is autolockIoFinder, which
  29775. ** looks at the filesystem type and tries to guess the best locking
  29776. ** strategy from that.
  29777. **
  29778. ** For finder-function F, two objects are created:
  29779. **
  29780. ** (1) The real finder-function named "FImpt()".
  29781. **
  29782. ** (2) A constant pointer to this function named just "F".
  29783. **
  29784. **
  29785. ** A pointer to the F pointer is used as the pAppData value for VFS
  29786. ** objects. We have to do this instead of letting pAppData point
  29787. ** directly at the finder-function since C90 rules prevent a void*
  29788. ** from be cast into a function pointer.
  29789. **
  29790. **
  29791. ** Each instance of this macro generates two objects:
  29792. **
  29793. ** * A constant sqlite3_io_methods object call METHOD that has locking
  29794. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  29795. **
  29796. ** * An I/O method finder function called FINDER that returns a pointer
  29797. ** to the METHOD object in the previous bullet.
  29798. */
  29799. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  29800. static const sqlite3_io_methods METHOD = { \
  29801. VERSION, /* iVersion */ \
  29802. CLOSE, /* xClose */ \
  29803. unixRead, /* xRead */ \
  29804. unixWrite, /* xWrite */ \
  29805. unixTruncate, /* xTruncate */ \
  29806. unixSync, /* xSync */ \
  29807. unixFileSize, /* xFileSize */ \
  29808. LOCK, /* xLock */ \
  29809. UNLOCK, /* xUnlock */ \
  29810. CKLOCK, /* xCheckReservedLock */ \
  29811. unixFileControl, /* xFileControl */ \
  29812. unixSectorSize, /* xSectorSize */ \
  29813. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  29814. SHMMAP, /* xShmMap */ \
  29815. unixShmLock, /* xShmLock */ \
  29816. unixShmBarrier, /* xShmBarrier */ \
  29817. unixShmUnmap, /* xShmUnmap */ \
  29818. unixFetch, /* xFetch */ \
  29819. unixUnfetch, /* xUnfetch */ \
  29820. }; \
  29821. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  29822. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  29823. return &METHOD; \
  29824. } \
  29825. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  29826. = FINDER##Impl;
  29827. /*
  29828. ** Here are all of the sqlite3_io_methods objects for each of the
  29829. ** locking strategies. Functions that return pointers to these methods
  29830. ** are also created.
  29831. */
  29832. IOMETHODS(
  29833. posixIoFinder, /* Finder function name */
  29834. posixIoMethods, /* sqlite3_io_methods object name */
  29835. 3, /* shared memory and mmap are enabled */
  29836. unixClose, /* xClose method */
  29837. unixLock, /* xLock method */
  29838. unixUnlock, /* xUnlock method */
  29839. unixCheckReservedLock, /* xCheckReservedLock method */
  29840. unixShmMap /* xShmMap method */
  29841. )
  29842. IOMETHODS(
  29843. nolockIoFinder, /* Finder function name */
  29844. nolockIoMethods, /* sqlite3_io_methods object name */
  29845. 3, /* shared memory is disabled */
  29846. nolockClose, /* xClose method */
  29847. nolockLock, /* xLock method */
  29848. nolockUnlock, /* xUnlock method */
  29849. nolockCheckReservedLock, /* xCheckReservedLock method */
  29850. 0 /* xShmMap method */
  29851. )
  29852. IOMETHODS(
  29853. dotlockIoFinder, /* Finder function name */
  29854. dotlockIoMethods, /* sqlite3_io_methods object name */
  29855. 1, /* shared memory is disabled */
  29856. dotlockClose, /* xClose method */
  29857. dotlockLock, /* xLock method */
  29858. dotlockUnlock, /* xUnlock method */
  29859. dotlockCheckReservedLock, /* xCheckReservedLock method */
  29860. 0 /* xShmMap method */
  29861. )
  29862. #if SQLITE_ENABLE_LOCKING_STYLE
  29863. IOMETHODS(
  29864. flockIoFinder, /* Finder function name */
  29865. flockIoMethods, /* sqlite3_io_methods object name */
  29866. 1, /* shared memory is disabled */
  29867. flockClose, /* xClose method */
  29868. flockLock, /* xLock method */
  29869. flockUnlock, /* xUnlock method */
  29870. flockCheckReservedLock, /* xCheckReservedLock method */
  29871. 0 /* xShmMap method */
  29872. )
  29873. #endif
  29874. #if OS_VXWORKS
  29875. IOMETHODS(
  29876. semIoFinder, /* Finder function name */
  29877. semIoMethods, /* sqlite3_io_methods object name */
  29878. 1, /* shared memory is disabled */
  29879. semXClose, /* xClose method */
  29880. semXLock, /* xLock method */
  29881. semXUnlock, /* xUnlock method */
  29882. semXCheckReservedLock, /* xCheckReservedLock method */
  29883. 0 /* xShmMap method */
  29884. )
  29885. #endif
  29886. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29887. IOMETHODS(
  29888. afpIoFinder, /* Finder function name */
  29889. afpIoMethods, /* sqlite3_io_methods object name */
  29890. 1, /* shared memory is disabled */
  29891. afpClose, /* xClose method */
  29892. afpLock, /* xLock method */
  29893. afpUnlock, /* xUnlock method */
  29894. afpCheckReservedLock, /* xCheckReservedLock method */
  29895. 0 /* xShmMap method */
  29896. )
  29897. #endif
  29898. /*
  29899. ** The proxy locking method is a "super-method" in the sense that it
  29900. ** opens secondary file descriptors for the conch and lock files and
  29901. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  29902. ** secondary files. For this reason, the division that implements
  29903. ** proxy locking is located much further down in the file. But we need
  29904. ** to go ahead and define the sqlite3_io_methods and finder function
  29905. ** for proxy locking here. So we forward declare the I/O methods.
  29906. */
  29907. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29908. static int proxyClose(sqlite3_file*);
  29909. static int proxyLock(sqlite3_file*, int);
  29910. static int proxyUnlock(sqlite3_file*, int);
  29911. static int proxyCheckReservedLock(sqlite3_file*, int*);
  29912. IOMETHODS(
  29913. proxyIoFinder, /* Finder function name */
  29914. proxyIoMethods, /* sqlite3_io_methods object name */
  29915. 1, /* shared memory is disabled */
  29916. proxyClose, /* xClose method */
  29917. proxyLock, /* xLock method */
  29918. proxyUnlock, /* xUnlock method */
  29919. proxyCheckReservedLock, /* xCheckReservedLock method */
  29920. 0 /* xShmMap method */
  29921. )
  29922. #endif
  29923. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  29924. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29925. IOMETHODS(
  29926. nfsIoFinder, /* Finder function name */
  29927. nfsIoMethods, /* sqlite3_io_methods object name */
  29928. 1, /* shared memory is disabled */
  29929. unixClose, /* xClose method */
  29930. unixLock, /* xLock method */
  29931. nfsUnlock, /* xUnlock method */
  29932. unixCheckReservedLock, /* xCheckReservedLock method */
  29933. 0 /* xShmMap method */
  29934. )
  29935. #endif
  29936. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29937. /*
  29938. ** This "finder" function attempts to determine the best locking strategy
  29939. ** for the database file "filePath". It then returns the sqlite3_io_methods
  29940. ** object that implements that strategy.
  29941. **
  29942. ** This is for MacOSX only.
  29943. */
  29944. static const sqlite3_io_methods *autolockIoFinderImpl(
  29945. const char *filePath, /* name of the database file */
  29946. unixFile *pNew /* open file object for the database file */
  29947. ){
  29948. static const struct Mapping {
  29949. const char *zFilesystem; /* Filesystem type name */
  29950. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  29951. } aMap[] = {
  29952. { "hfs", &posixIoMethods },
  29953. { "ufs", &posixIoMethods },
  29954. { "afpfs", &afpIoMethods },
  29955. { "smbfs", &afpIoMethods },
  29956. { "webdav", &nolockIoMethods },
  29957. { 0, 0 }
  29958. };
  29959. int i;
  29960. struct statfs fsInfo;
  29961. struct flock lockInfo;
  29962. if( !filePath ){
  29963. /* If filePath==NULL that means we are dealing with a transient file
  29964. ** that does not need to be locked. */
  29965. return &nolockIoMethods;
  29966. }
  29967. if( statfs(filePath, &fsInfo) != -1 ){
  29968. if( fsInfo.f_flags & MNT_RDONLY ){
  29969. return &nolockIoMethods;
  29970. }
  29971. for(i=0; aMap[i].zFilesystem; i++){
  29972. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  29973. return aMap[i].pMethods;
  29974. }
  29975. }
  29976. }
  29977. /* Default case. Handles, amongst others, "nfs".
  29978. ** Test byte-range lock using fcntl(). If the call succeeds,
  29979. ** assume that the file-system supports POSIX style locks.
  29980. */
  29981. lockInfo.l_len = 1;
  29982. lockInfo.l_start = 0;
  29983. lockInfo.l_whence = SEEK_SET;
  29984. lockInfo.l_type = F_RDLCK;
  29985. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  29986. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  29987. return &nfsIoMethods;
  29988. } else {
  29989. return &posixIoMethods;
  29990. }
  29991. }else{
  29992. return &dotlockIoMethods;
  29993. }
  29994. }
  29995. static const sqlite3_io_methods
  29996. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  29997. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  29998. #if OS_VXWORKS
  29999. /*
  30000. ** This "finder" function for VxWorks checks to see if posix advisory
  30001. ** locking works. If it does, then that is what is used. If it does not
  30002. ** work, then fallback to named semaphore locking.
  30003. */
  30004. static const sqlite3_io_methods *vxworksIoFinderImpl(
  30005. const char *filePath, /* name of the database file */
  30006. unixFile *pNew /* the open file object */
  30007. ){
  30008. struct flock lockInfo;
  30009. if( !filePath ){
  30010. /* If filePath==NULL that means we are dealing with a transient file
  30011. ** that does not need to be locked. */
  30012. return &nolockIoMethods;
  30013. }
  30014. /* Test if fcntl() is supported and use POSIX style locks.
  30015. ** Otherwise fall back to the named semaphore method.
  30016. */
  30017. lockInfo.l_len = 1;
  30018. lockInfo.l_start = 0;
  30019. lockInfo.l_whence = SEEK_SET;
  30020. lockInfo.l_type = F_RDLCK;
  30021. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  30022. return &posixIoMethods;
  30023. }else{
  30024. return &semIoMethods;
  30025. }
  30026. }
  30027. static const sqlite3_io_methods
  30028. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  30029. #endif /* OS_VXWORKS */
  30030. /*
  30031. ** An abstract type for a pointer to an IO method finder function:
  30032. */
  30033. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  30034. /****************************************************************************
  30035. **************************** sqlite3_vfs methods ****************************
  30036. **
  30037. ** This division contains the implementation of methods on the
  30038. ** sqlite3_vfs object.
  30039. */
  30040. /*
  30041. ** Initialize the contents of the unixFile structure pointed to by pId.
  30042. */
  30043. static int fillInUnixFile(
  30044. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  30045. int h, /* Open file descriptor of file being opened */
  30046. sqlite3_file *pId, /* Write to the unixFile structure here */
  30047. const char *zFilename, /* Name of the file being opened */
  30048. int ctrlFlags /* Zero or more UNIXFILE_* values */
  30049. ){
  30050. const sqlite3_io_methods *pLockingStyle;
  30051. unixFile *pNew = (unixFile *)pId;
  30052. int rc = SQLITE_OK;
  30053. assert( pNew->pInode==NULL );
  30054. /* Usually the path zFilename should not be a relative pathname. The
  30055. ** exception is when opening the proxy "conch" file in builds that
  30056. ** include the special Apple locking styles.
  30057. */
  30058. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30059. assert( zFilename==0 || zFilename[0]=='/'
  30060. || pVfs->pAppData==(void*)&autolockIoFinder );
  30061. #else
  30062. assert( zFilename==0 || zFilename[0]=='/' );
  30063. #endif
  30064. /* No locking occurs in temporary files */
  30065. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  30066. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  30067. pNew->h = h;
  30068. pNew->pVfs = pVfs;
  30069. pNew->zPath = zFilename;
  30070. pNew->ctrlFlags = (u8)ctrlFlags;
  30071. #if SQLITE_MAX_MMAP_SIZE>0
  30072. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  30073. #endif
  30074. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  30075. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  30076. pNew->ctrlFlags |= UNIXFILE_PSOW;
  30077. }
  30078. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  30079. pNew->ctrlFlags |= UNIXFILE_EXCL;
  30080. }
  30081. #if OS_VXWORKS
  30082. pNew->pId = vxworksFindFileId(zFilename);
  30083. if( pNew->pId==0 ){
  30084. ctrlFlags |= UNIXFILE_NOLOCK;
  30085. rc = SQLITE_NOMEM;
  30086. }
  30087. #endif
  30088. if( ctrlFlags & UNIXFILE_NOLOCK ){
  30089. pLockingStyle = &nolockIoMethods;
  30090. }else{
  30091. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  30092. #if SQLITE_ENABLE_LOCKING_STYLE
  30093. /* Cache zFilename in the locking context (AFP and dotlock override) for
  30094. ** proxyLock activation is possible (remote proxy is based on db name)
  30095. ** zFilename remains valid until file is closed, to support */
  30096. pNew->lockingContext = (void*)zFilename;
  30097. #endif
  30098. }
  30099. if( pLockingStyle == &posixIoMethods
  30100. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30101. || pLockingStyle == &nfsIoMethods
  30102. #endif
  30103. ){
  30104. unixEnterMutex();
  30105. rc = findInodeInfo(pNew, &pNew->pInode);
  30106. if( rc!=SQLITE_OK ){
  30107. /* If an error occurred in findInodeInfo(), close the file descriptor
  30108. ** immediately, before releasing the mutex. findInodeInfo() may fail
  30109. ** in two scenarios:
  30110. **
  30111. ** (a) A call to fstat() failed.
  30112. ** (b) A malloc failed.
  30113. **
  30114. ** Scenario (b) may only occur if the process is holding no other
  30115. ** file descriptors open on the same file. If there were other file
  30116. ** descriptors on this file, then no malloc would be required by
  30117. ** findInodeInfo(). If this is the case, it is quite safe to close
  30118. ** handle h - as it is guaranteed that no posix locks will be released
  30119. ** by doing so.
  30120. **
  30121. ** If scenario (a) caused the error then things are not so safe. The
  30122. ** implicit assumption here is that if fstat() fails, things are in
  30123. ** such bad shape that dropping a lock or two doesn't matter much.
  30124. */
  30125. robust_close(pNew, h, __LINE__);
  30126. h = -1;
  30127. }
  30128. unixLeaveMutex();
  30129. }
  30130. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30131. else if( pLockingStyle == &afpIoMethods ){
  30132. /* AFP locking uses the file path so it needs to be included in
  30133. ** the afpLockingContext.
  30134. */
  30135. afpLockingContext *pCtx;
  30136. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  30137. if( pCtx==0 ){
  30138. rc = SQLITE_NOMEM;
  30139. }else{
  30140. /* NB: zFilename exists and remains valid until the file is closed
  30141. ** according to requirement F11141. So we do not need to make a
  30142. ** copy of the filename. */
  30143. pCtx->dbPath = zFilename;
  30144. pCtx->reserved = 0;
  30145. srandomdev();
  30146. unixEnterMutex();
  30147. rc = findInodeInfo(pNew, &pNew->pInode);
  30148. if( rc!=SQLITE_OK ){
  30149. sqlite3_free(pNew->lockingContext);
  30150. robust_close(pNew, h, __LINE__);
  30151. h = -1;
  30152. }
  30153. unixLeaveMutex();
  30154. }
  30155. }
  30156. #endif
  30157. else if( pLockingStyle == &dotlockIoMethods ){
  30158. /* Dotfile locking uses the file path so it needs to be included in
  30159. ** the dotlockLockingContext
  30160. */
  30161. char *zLockFile;
  30162. int nFilename;
  30163. assert( zFilename!=0 );
  30164. nFilename = (int)strlen(zFilename) + 6;
  30165. zLockFile = (char *)sqlite3_malloc64(nFilename);
  30166. if( zLockFile==0 ){
  30167. rc = SQLITE_NOMEM;
  30168. }else{
  30169. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  30170. }
  30171. pNew->lockingContext = zLockFile;
  30172. }
  30173. #if OS_VXWORKS
  30174. else if( pLockingStyle == &semIoMethods ){
  30175. /* Named semaphore locking uses the file path so it needs to be
  30176. ** included in the semLockingContext
  30177. */
  30178. unixEnterMutex();
  30179. rc = findInodeInfo(pNew, &pNew->pInode);
  30180. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  30181. char *zSemName = pNew->pInode->aSemName;
  30182. int n;
  30183. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  30184. pNew->pId->zCanonicalName);
  30185. for( n=1; zSemName[n]; n++ )
  30186. if( zSemName[n]=='/' ) zSemName[n] = '_';
  30187. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  30188. if( pNew->pInode->pSem == SEM_FAILED ){
  30189. rc = SQLITE_NOMEM;
  30190. pNew->pInode->aSemName[0] = '\0';
  30191. }
  30192. }
  30193. unixLeaveMutex();
  30194. }
  30195. #endif
  30196. storeLastErrno(pNew, 0);
  30197. #if OS_VXWORKS
  30198. if( rc!=SQLITE_OK ){
  30199. if( h>=0 ) robust_close(pNew, h, __LINE__);
  30200. h = -1;
  30201. osUnlink(zFilename);
  30202. pNew->ctrlFlags |= UNIXFILE_DELETE;
  30203. }
  30204. #endif
  30205. if( rc!=SQLITE_OK ){
  30206. if( h>=0 ) robust_close(pNew, h, __LINE__);
  30207. }else{
  30208. pNew->pMethod = pLockingStyle;
  30209. OpenCounter(+1);
  30210. verifyDbFile(pNew);
  30211. }
  30212. return rc;
  30213. }
  30214. /*
  30215. ** Return the name of a directory in which to put temporary files.
  30216. ** If no suitable temporary file directory can be found, return NULL.
  30217. */
  30218. static const char *unixTempFileDir(void){
  30219. static const char *azDirs[] = {
  30220. 0,
  30221. 0,
  30222. 0,
  30223. "/var/tmp",
  30224. "/usr/tmp",
  30225. "/tmp",
  30226. 0 /* List terminator */
  30227. };
  30228. unsigned int i;
  30229. struct stat buf;
  30230. const char *zDir = 0;
  30231. azDirs[0] = sqlite3_temp_directory;
  30232. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  30233. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  30234. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  30235. if( zDir==0 ) continue;
  30236. if( osStat(zDir, &buf) ) continue;
  30237. if( !S_ISDIR(buf.st_mode) ) continue;
  30238. if( osAccess(zDir, 07) ) continue;
  30239. break;
  30240. }
  30241. return zDir;
  30242. }
  30243. /*
  30244. ** Create a temporary file name in zBuf. zBuf must be allocated
  30245. ** by the calling process and must be big enough to hold at least
  30246. ** pVfs->mxPathname bytes.
  30247. */
  30248. static int unixGetTempname(int nBuf, char *zBuf){
  30249. static const unsigned char zChars[] =
  30250. "abcdefghijklmnopqrstuvwxyz"
  30251. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  30252. "0123456789";
  30253. unsigned int i, j;
  30254. const char *zDir;
  30255. /* It's odd to simulate an io-error here, but really this is just
  30256. ** using the io-error infrastructure to test that SQLite handles this
  30257. ** function failing.
  30258. */
  30259. SimulateIOError( return SQLITE_IOERR );
  30260. zDir = unixTempFileDir();
  30261. if( zDir==0 ) zDir = ".";
  30262. /* Check that the output buffer is large enough for the temporary file
  30263. ** name. If it is not, return SQLITE_ERROR.
  30264. */
  30265. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  30266. return SQLITE_ERROR;
  30267. }
  30268. do{
  30269. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  30270. j = (int)strlen(zBuf);
  30271. sqlite3_randomness(15, &zBuf[j]);
  30272. for(i=0; i<15; i++, j++){
  30273. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  30274. }
  30275. zBuf[j] = 0;
  30276. zBuf[j+1] = 0;
  30277. }while( osAccess(zBuf,0)==0 );
  30278. return SQLITE_OK;
  30279. }
  30280. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30281. /*
  30282. ** Routine to transform a unixFile into a proxy-locking unixFile.
  30283. ** Implementation in the proxy-lock division, but used by unixOpen()
  30284. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  30285. */
  30286. static int proxyTransformUnixFile(unixFile*, const char*);
  30287. #endif
  30288. /*
  30289. ** Search for an unused file descriptor that was opened on the database
  30290. ** file (not a journal or master-journal file) identified by pathname
  30291. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  30292. ** argument to this function.
  30293. **
  30294. ** Such a file descriptor may exist if a database connection was closed
  30295. ** but the associated file descriptor could not be closed because some
  30296. ** other file descriptor open on the same file is holding a file-lock.
  30297. ** Refer to comments in the unixClose() function and the lengthy comment
  30298. ** describing "Posix Advisory Locking" at the start of this file for
  30299. ** further details. Also, ticket #4018.
  30300. **
  30301. ** If a suitable file descriptor is found, then it is returned. If no
  30302. ** such file descriptor is located, -1 is returned.
  30303. */
  30304. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  30305. UnixUnusedFd *pUnused = 0;
  30306. /* Do not search for an unused file descriptor on vxworks. Not because
  30307. ** vxworks would not benefit from the change (it might, we're not sure),
  30308. ** but because no way to test it is currently available. It is better
  30309. ** not to risk breaking vxworks support for the sake of such an obscure
  30310. ** feature. */
  30311. #if !OS_VXWORKS
  30312. struct stat sStat; /* Results of stat() call */
  30313. /* A stat() call may fail for various reasons. If this happens, it is
  30314. ** almost certain that an open() call on the same path will also fail.
  30315. ** For this reason, if an error occurs in the stat() call here, it is
  30316. ** ignored and -1 is returned. The caller will try to open a new file
  30317. ** descriptor on the same path, fail, and return an error to SQLite.
  30318. **
  30319. ** Even if a subsequent open() call does succeed, the consequences of
  30320. ** not searching for a reusable file descriptor are not dire. */
  30321. if( 0==osStat(zPath, &sStat) ){
  30322. unixInodeInfo *pInode;
  30323. unixEnterMutex();
  30324. pInode = inodeList;
  30325. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  30326. || pInode->fileId.ino!=sStat.st_ino) ){
  30327. pInode = pInode->pNext;
  30328. }
  30329. if( pInode ){
  30330. UnixUnusedFd **pp;
  30331. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  30332. pUnused = *pp;
  30333. if( pUnused ){
  30334. *pp = pUnused->pNext;
  30335. }
  30336. }
  30337. unixLeaveMutex();
  30338. }
  30339. #endif /* if !OS_VXWORKS */
  30340. return pUnused;
  30341. }
  30342. /*
  30343. ** This function is called by unixOpen() to determine the unix permissions
  30344. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  30345. ** and a value suitable for passing as the third argument to open(2) is
  30346. ** written to *pMode. If an IO error occurs, an SQLite error code is
  30347. ** returned and the value of *pMode is not modified.
  30348. **
  30349. ** In most cases, this routine sets *pMode to 0, which will become
  30350. ** an indication to robust_open() to create the file using
  30351. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  30352. ** But if the file being opened is a WAL or regular journal file, then
  30353. ** this function queries the file-system for the permissions on the
  30354. ** corresponding database file and sets *pMode to this value. Whenever
  30355. ** possible, WAL and journal files are created using the same permissions
  30356. ** as the associated database file.
  30357. **
  30358. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  30359. ** original filename is unavailable. But 8_3_NAMES is only used for
  30360. ** FAT filesystems and permissions do not matter there, so just use
  30361. ** the default permissions.
  30362. */
  30363. static int findCreateFileMode(
  30364. const char *zPath, /* Path of file (possibly) being created */
  30365. int flags, /* Flags passed as 4th argument to xOpen() */
  30366. mode_t *pMode, /* OUT: Permissions to open file with */
  30367. uid_t *pUid, /* OUT: uid to set on the file */
  30368. gid_t *pGid /* OUT: gid to set on the file */
  30369. ){
  30370. int rc = SQLITE_OK; /* Return Code */
  30371. *pMode = 0;
  30372. *pUid = 0;
  30373. *pGid = 0;
  30374. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  30375. char zDb[MAX_PATHNAME+1]; /* Database file path */
  30376. int nDb; /* Number of valid bytes in zDb */
  30377. struct stat sStat; /* Output of stat() on database file */
  30378. /* zPath is a path to a WAL or journal file. The following block derives
  30379. ** the path to the associated database file from zPath. This block handles
  30380. ** the following naming conventions:
  30381. **
  30382. ** "<path to db>-journal"
  30383. ** "<path to db>-wal"
  30384. ** "<path to db>-journalNN"
  30385. ** "<path to db>-walNN"
  30386. **
  30387. ** where NN is a decimal number. The NN naming schemes are
  30388. ** used by the test_multiplex.c module.
  30389. */
  30390. nDb = sqlite3Strlen30(zPath) - 1;
  30391. #ifdef SQLITE_ENABLE_8_3_NAMES
  30392. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  30393. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  30394. #else
  30395. while( zPath[nDb]!='-' ){
  30396. assert( nDb>0 );
  30397. assert( zPath[nDb]!='\n' );
  30398. nDb--;
  30399. }
  30400. #endif
  30401. memcpy(zDb, zPath, nDb);
  30402. zDb[nDb] = '\0';
  30403. if( 0==osStat(zDb, &sStat) ){
  30404. *pMode = sStat.st_mode & 0777;
  30405. *pUid = sStat.st_uid;
  30406. *pGid = sStat.st_gid;
  30407. }else{
  30408. rc = SQLITE_IOERR_FSTAT;
  30409. }
  30410. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  30411. *pMode = 0600;
  30412. }
  30413. return rc;
  30414. }
  30415. /*
  30416. ** Open the file zPath.
  30417. **
  30418. ** Previously, the SQLite OS layer used three functions in place of this
  30419. ** one:
  30420. **
  30421. ** sqlite3OsOpenReadWrite();
  30422. ** sqlite3OsOpenReadOnly();
  30423. ** sqlite3OsOpenExclusive();
  30424. **
  30425. ** These calls correspond to the following combinations of flags:
  30426. **
  30427. ** ReadWrite() -> (READWRITE | CREATE)
  30428. ** ReadOnly() -> (READONLY)
  30429. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  30430. **
  30431. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  30432. ** true, the file was configured to be automatically deleted when the
  30433. ** file handle closed. To achieve the same effect using this new
  30434. ** interface, add the DELETEONCLOSE flag to those specified above for
  30435. ** OpenExclusive().
  30436. */
  30437. static int unixOpen(
  30438. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  30439. const char *zPath, /* Pathname of file to be opened */
  30440. sqlite3_file *pFile, /* The file descriptor to be filled in */
  30441. int flags, /* Input flags to control the opening */
  30442. int *pOutFlags /* Output flags returned to SQLite core */
  30443. ){
  30444. unixFile *p = (unixFile *)pFile;
  30445. int fd = -1; /* File descriptor returned by open() */
  30446. int openFlags = 0; /* Flags to pass to open() */
  30447. int eType = flags&0xFFFFFF00; /* Type of file to open */
  30448. int noLock; /* True to omit locking primitives */
  30449. int rc = SQLITE_OK; /* Function Return Code */
  30450. int ctrlFlags = 0; /* UNIXFILE_* flags */
  30451. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  30452. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  30453. int isCreate = (flags & SQLITE_OPEN_CREATE);
  30454. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  30455. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  30456. #if SQLITE_ENABLE_LOCKING_STYLE
  30457. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  30458. #endif
  30459. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30460. struct statfs fsInfo;
  30461. #endif
  30462. /* If creating a master or main-file journal, this function will open
  30463. ** a file-descriptor on the directory too. The first time unixSync()
  30464. ** is called the directory file descriptor will be fsync()ed and close()d.
  30465. */
  30466. int syncDir = (isCreate && (
  30467. eType==SQLITE_OPEN_MASTER_JOURNAL
  30468. || eType==SQLITE_OPEN_MAIN_JOURNAL
  30469. || eType==SQLITE_OPEN_WAL
  30470. ));
  30471. /* If argument zPath is a NULL pointer, this function is required to open
  30472. ** a temporary file. Use this buffer to store the file name in.
  30473. */
  30474. char zTmpname[MAX_PATHNAME+2];
  30475. const char *zName = zPath;
  30476. /* Check the following statements are true:
  30477. **
  30478. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  30479. ** (b) if CREATE is set, then READWRITE must also be set, and
  30480. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  30481. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  30482. */
  30483. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  30484. assert(isCreate==0 || isReadWrite);
  30485. assert(isExclusive==0 || isCreate);
  30486. assert(isDelete==0 || isCreate);
  30487. /* The main DB, main journal, WAL file and master journal are never
  30488. ** automatically deleted. Nor are they ever temporary files. */
  30489. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  30490. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  30491. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  30492. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  30493. /* Assert that the upper layer has set one of the "file-type" flags. */
  30494. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  30495. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  30496. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  30497. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  30498. );
  30499. /* Detect a pid change and reset the PRNG. There is a race condition
  30500. ** here such that two or more threads all trying to open databases at
  30501. ** the same instant might all reset the PRNG. But multiple resets
  30502. ** are harmless.
  30503. */
  30504. if( randomnessPid!=osGetpid(0) ){
  30505. randomnessPid = osGetpid(0);
  30506. sqlite3_randomness(0,0);
  30507. }
  30508. memset(p, 0, sizeof(unixFile));
  30509. if( eType==SQLITE_OPEN_MAIN_DB ){
  30510. UnixUnusedFd *pUnused;
  30511. pUnused = findReusableFd(zName, flags);
  30512. if( pUnused ){
  30513. fd = pUnused->fd;
  30514. }else{
  30515. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  30516. if( !pUnused ){
  30517. return SQLITE_NOMEM;
  30518. }
  30519. }
  30520. p->pUnused = pUnused;
  30521. /* Database filenames are double-zero terminated if they are not
  30522. ** URIs with parameters. Hence, they can always be passed into
  30523. ** sqlite3_uri_parameter(). */
  30524. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  30525. }else if( !zName ){
  30526. /* If zName is NULL, the upper layer is requesting a temp file. */
  30527. assert(isDelete && !syncDir);
  30528. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  30529. if( rc!=SQLITE_OK ){
  30530. return rc;
  30531. }
  30532. zName = zTmpname;
  30533. /* Generated temporary filenames are always double-zero terminated
  30534. ** for use by sqlite3_uri_parameter(). */
  30535. assert( zName[strlen(zName)+1]==0 );
  30536. }
  30537. /* Determine the value of the flags parameter passed to POSIX function
  30538. ** open(). These must be calculated even if open() is not called, as
  30539. ** they may be stored as part of the file handle and used by the
  30540. ** 'conch file' locking functions later on. */
  30541. if( isReadonly ) openFlags |= O_RDONLY;
  30542. if( isReadWrite ) openFlags |= O_RDWR;
  30543. if( isCreate ) openFlags |= O_CREAT;
  30544. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  30545. openFlags |= (O_LARGEFILE|O_BINARY);
  30546. if( fd<0 ){
  30547. mode_t openMode; /* Permissions to create file with */
  30548. uid_t uid; /* Userid for the file */
  30549. gid_t gid; /* Groupid for the file */
  30550. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  30551. if( rc!=SQLITE_OK ){
  30552. assert( !p->pUnused );
  30553. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  30554. return rc;
  30555. }
  30556. fd = robust_open(zName, openFlags, openMode);
  30557. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  30558. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  30559. /* Failed to open the file for read/write access. Try read-only. */
  30560. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  30561. openFlags &= ~(O_RDWR|O_CREAT);
  30562. flags |= SQLITE_OPEN_READONLY;
  30563. openFlags |= O_RDONLY;
  30564. isReadonly = 1;
  30565. fd = robust_open(zName, openFlags, openMode);
  30566. }
  30567. if( fd<0 ){
  30568. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  30569. goto open_finished;
  30570. }
  30571. /* If this process is running as root and if creating a new rollback
  30572. ** journal or WAL file, set the ownership of the journal or WAL to be
  30573. ** the same as the original database.
  30574. */
  30575. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  30576. osFchown(fd, uid, gid);
  30577. }
  30578. }
  30579. assert( fd>=0 );
  30580. if( pOutFlags ){
  30581. *pOutFlags = flags;
  30582. }
  30583. if( p->pUnused ){
  30584. p->pUnused->fd = fd;
  30585. p->pUnused->flags = flags;
  30586. }
  30587. if( isDelete ){
  30588. #if OS_VXWORKS
  30589. zPath = zName;
  30590. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  30591. zPath = sqlite3_mprintf("%s", zName);
  30592. if( zPath==0 ){
  30593. robust_close(p, fd, __LINE__);
  30594. return SQLITE_NOMEM;
  30595. }
  30596. #else
  30597. osUnlink(zName);
  30598. #endif
  30599. }
  30600. #if SQLITE_ENABLE_LOCKING_STYLE
  30601. else{
  30602. p->openFlags = openFlags;
  30603. }
  30604. #endif
  30605. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  30606. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30607. if( fstatfs(fd, &fsInfo) == -1 ){
  30608. storeLastErrno(p, errno);
  30609. robust_close(p, fd, __LINE__);
  30610. return SQLITE_IOERR_ACCESS;
  30611. }
  30612. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  30613. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  30614. }
  30615. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  30616. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  30617. }
  30618. #endif
  30619. /* Set up appropriate ctrlFlags */
  30620. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  30621. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  30622. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  30623. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  30624. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  30625. #if SQLITE_ENABLE_LOCKING_STYLE
  30626. #if SQLITE_PREFER_PROXY_LOCKING
  30627. isAutoProxy = 1;
  30628. #endif
  30629. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  30630. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  30631. int useProxy = 0;
  30632. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  30633. ** never use proxy, NULL means use proxy for non-local files only. */
  30634. if( envforce!=NULL ){
  30635. useProxy = atoi(envforce)>0;
  30636. }else{
  30637. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  30638. }
  30639. if( useProxy ){
  30640. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30641. if( rc==SQLITE_OK ){
  30642. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  30643. if( rc!=SQLITE_OK ){
  30644. /* Use unixClose to clean up the resources added in fillInUnixFile
  30645. ** and clear all the structure's references. Specifically,
  30646. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  30647. */
  30648. unixClose(pFile);
  30649. return rc;
  30650. }
  30651. }
  30652. goto open_finished;
  30653. }
  30654. }
  30655. #endif
  30656. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30657. open_finished:
  30658. if( rc!=SQLITE_OK ){
  30659. sqlite3_free(p->pUnused);
  30660. }
  30661. return rc;
  30662. }
  30663. /*
  30664. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  30665. ** the directory after deleting the file.
  30666. */
  30667. static int unixDelete(
  30668. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  30669. const char *zPath, /* Name of file to be deleted */
  30670. int dirSync /* If true, fsync() directory after deleting file */
  30671. ){
  30672. int rc = SQLITE_OK;
  30673. UNUSED_PARAMETER(NotUsed);
  30674. SimulateIOError(return SQLITE_IOERR_DELETE);
  30675. if( osUnlink(zPath)==(-1) ){
  30676. if( errno==ENOENT
  30677. #if OS_VXWORKS
  30678. || osAccess(zPath,0)!=0
  30679. #endif
  30680. ){
  30681. rc = SQLITE_IOERR_DELETE_NOENT;
  30682. }else{
  30683. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  30684. }
  30685. return rc;
  30686. }
  30687. #ifndef SQLITE_DISABLE_DIRSYNC
  30688. if( (dirSync & 1)!=0 ){
  30689. int fd;
  30690. rc = osOpenDirectory(zPath, &fd);
  30691. if( rc==SQLITE_OK ){
  30692. #if OS_VXWORKS
  30693. if( fsync(fd)==-1 )
  30694. #else
  30695. if( fsync(fd) )
  30696. #endif
  30697. {
  30698. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  30699. }
  30700. robust_close(0, fd, __LINE__);
  30701. }else if( rc==SQLITE_CANTOPEN ){
  30702. rc = SQLITE_OK;
  30703. }
  30704. }
  30705. #endif
  30706. return rc;
  30707. }
  30708. /*
  30709. ** Test the existence of or access permissions of file zPath. The
  30710. ** test performed depends on the value of flags:
  30711. **
  30712. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  30713. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  30714. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  30715. **
  30716. ** Otherwise return 0.
  30717. */
  30718. static int unixAccess(
  30719. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  30720. const char *zPath, /* Path of the file to examine */
  30721. int flags, /* What do we want to learn about the zPath file? */
  30722. int *pResOut /* Write result boolean here */
  30723. ){
  30724. int amode = 0;
  30725. UNUSED_PARAMETER(NotUsed);
  30726. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  30727. switch( flags ){
  30728. case SQLITE_ACCESS_EXISTS:
  30729. amode = F_OK;
  30730. break;
  30731. case SQLITE_ACCESS_READWRITE:
  30732. amode = W_OK|R_OK;
  30733. break;
  30734. case SQLITE_ACCESS_READ:
  30735. amode = R_OK;
  30736. break;
  30737. default:
  30738. assert(!"Invalid flags argument");
  30739. }
  30740. *pResOut = (osAccess(zPath, amode)==0);
  30741. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  30742. struct stat buf;
  30743. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  30744. *pResOut = 0;
  30745. }
  30746. }
  30747. return SQLITE_OK;
  30748. }
  30749. /*
  30750. ** Turn a relative pathname into a full pathname. The relative path
  30751. ** is stored as a nul-terminated string in the buffer pointed to by
  30752. ** zPath.
  30753. **
  30754. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  30755. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  30756. ** this buffer before returning.
  30757. */
  30758. static int unixFullPathname(
  30759. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  30760. const char *zPath, /* Possibly relative input path */
  30761. int nOut, /* Size of output buffer in bytes */
  30762. char *zOut /* Output buffer */
  30763. ){
  30764. /* It's odd to simulate an io-error here, but really this is just
  30765. ** using the io-error infrastructure to test that SQLite handles this
  30766. ** function failing. This function could fail if, for example, the
  30767. ** current working directory has been unlinked.
  30768. */
  30769. SimulateIOError( return SQLITE_ERROR );
  30770. assert( pVfs->mxPathname==MAX_PATHNAME );
  30771. UNUSED_PARAMETER(pVfs);
  30772. zOut[nOut-1] = '\0';
  30773. if( zPath[0]=='/' ){
  30774. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  30775. }else{
  30776. int nCwd;
  30777. if( osGetcwd(zOut, nOut-1)==0 ){
  30778. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  30779. }
  30780. nCwd = (int)strlen(zOut);
  30781. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  30782. }
  30783. return SQLITE_OK;
  30784. }
  30785. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  30786. /*
  30787. ** Interfaces for opening a shared library, finding entry points
  30788. ** within the shared library, and closing the shared library.
  30789. */
  30790. #include <dlfcn.h>
  30791. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  30792. UNUSED_PARAMETER(NotUsed);
  30793. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  30794. }
  30795. /*
  30796. ** SQLite calls this function immediately after a call to unixDlSym() or
  30797. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  30798. ** message is available, it is written to zBufOut. If no error message
  30799. ** is available, zBufOut is left unmodified and SQLite uses a default
  30800. ** error message.
  30801. */
  30802. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  30803. const char *zErr;
  30804. UNUSED_PARAMETER(NotUsed);
  30805. unixEnterMutex();
  30806. zErr = dlerror();
  30807. if( zErr ){
  30808. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  30809. }
  30810. unixLeaveMutex();
  30811. }
  30812. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  30813. /*
  30814. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  30815. ** cast into a pointer to a function. And yet the library dlsym() routine
  30816. ** returns a void* which is really a pointer to a function. So how do we
  30817. ** use dlsym() with -pedantic-errors?
  30818. **
  30819. ** Variable x below is defined to be a pointer to a function taking
  30820. ** parameters void* and const char* and returning a pointer to a function.
  30821. ** We initialize x by assigning it a pointer to the dlsym() function.
  30822. ** (That assignment requires a cast.) Then we call the function that
  30823. ** x points to.
  30824. **
  30825. ** This work-around is unlikely to work correctly on any system where
  30826. ** you really cannot cast a function pointer into void*. But then, on the
  30827. ** other hand, dlsym() will not work on such a system either, so we have
  30828. ** not really lost anything.
  30829. */
  30830. void (*(*x)(void*,const char*))(void);
  30831. UNUSED_PARAMETER(NotUsed);
  30832. x = (void(*(*)(void*,const char*))(void))dlsym;
  30833. return (*x)(p, zSym);
  30834. }
  30835. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  30836. UNUSED_PARAMETER(NotUsed);
  30837. dlclose(pHandle);
  30838. }
  30839. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  30840. #define unixDlOpen 0
  30841. #define unixDlError 0
  30842. #define unixDlSym 0
  30843. #define unixDlClose 0
  30844. #endif
  30845. /*
  30846. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  30847. */
  30848. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  30849. UNUSED_PARAMETER(NotUsed);
  30850. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  30851. /* We have to initialize zBuf to prevent valgrind from reporting
  30852. ** errors. The reports issued by valgrind are incorrect - we would
  30853. ** prefer that the randomness be increased by making use of the
  30854. ** uninitialized space in zBuf - but valgrind errors tend to worry
  30855. ** some users. Rather than argue, it seems easier just to initialize
  30856. ** the whole array and silence valgrind, even if that means less randomness
  30857. ** in the random seed.
  30858. **
  30859. ** When testing, initializing zBuf[] to zero is all we do. That means
  30860. ** that we always use the same random number sequence. This makes the
  30861. ** tests repeatable.
  30862. */
  30863. memset(zBuf, 0, nBuf);
  30864. randomnessPid = osGetpid(0);
  30865. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  30866. {
  30867. int fd, got;
  30868. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  30869. if( fd<0 ){
  30870. time_t t;
  30871. time(&t);
  30872. memcpy(zBuf, &t, sizeof(t));
  30873. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  30874. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  30875. nBuf = sizeof(t) + sizeof(randomnessPid);
  30876. }else{
  30877. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  30878. robust_close(0, fd, __LINE__);
  30879. }
  30880. }
  30881. #endif
  30882. return nBuf;
  30883. }
  30884. /*
  30885. ** Sleep for a little while. Return the amount of time slept.
  30886. ** The argument is the number of microseconds we want to sleep.
  30887. ** The return value is the number of microseconds of sleep actually
  30888. ** requested from the underlying operating system, a number which
  30889. ** might be greater than or equal to the argument, but not less
  30890. ** than the argument.
  30891. */
  30892. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  30893. #if OS_VXWORKS
  30894. struct timespec sp;
  30895. sp.tv_sec = microseconds / 1000000;
  30896. sp.tv_nsec = (microseconds % 1000000) * 1000;
  30897. nanosleep(&sp, NULL);
  30898. UNUSED_PARAMETER(NotUsed);
  30899. return microseconds;
  30900. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  30901. usleep(microseconds);
  30902. UNUSED_PARAMETER(NotUsed);
  30903. return microseconds;
  30904. #else
  30905. int seconds = (microseconds+999999)/1000000;
  30906. sleep(seconds);
  30907. UNUSED_PARAMETER(NotUsed);
  30908. return seconds*1000000;
  30909. #endif
  30910. }
  30911. /*
  30912. ** The following variable, if set to a non-zero value, is interpreted as
  30913. ** the number of seconds since 1970 and is used to set the result of
  30914. ** sqlite3OsCurrentTime() during testing.
  30915. */
  30916. #ifdef SQLITE_TEST
  30917. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  30918. #endif
  30919. /*
  30920. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  30921. ** the current time and date as a Julian Day number times 86_400_000. In
  30922. ** other words, write into *piNow the number of milliseconds since the Julian
  30923. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  30924. ** proleptic Gregorian calendar.
  30925. **
  30926. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  30927. ** cannot be found.
  30928. */
  30929. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  30930. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  30931. int rc = SQLITE_OK;
  30932. #if defined(NO_GETTOD)
  30933. time_t t;
  30934. time(&t);
  30935. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  30936. #elif OS_VXWORKS
  30937. struct timespec sNow;
  30938. clock_gettime(CLOCK_REALTIME, &sNow);
  30939. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  30940. #else
  30941. struct timeval sNow;
  30942. if( gettimeofday(&sNow, 0)==0 ){
  30943. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  30944. }else{
  30945. rc = SQLITE_ERROR;
  30946. }
  30947. #endif
  30948. #ifdef SQLITE_TEST
  30949. if( sqlite3_current_time ){
  30950. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  30951. }
  30952. #endif
  30953. UNUSED_PARAMETER(NotUsed);
  30954. return rc;
  30955. }
  30956. /*
  30957. ** Find the current time (in Universal Coordinated Time). Write the
  30958. ** current time and date as a Julian Day number into *prNow and
  30959. ** return 0. Return 1 if the time and date cannot be found.
  30960. */
  30961. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  30962. sqlite3_int64 i = 0;
  30963. int rc;
  30964. UNUSED_PARAMETER(NotUsed);
  30965. rc = unixCurrentTimeInt64(0, &i);
  30966. *prNow = i/86400000.0;
  30967. return rc;
  30968. }
  30969. /*
  30970. ** We added the xGetLastError() method with the intention of providing
  30971. ** better low-level error messages when operating-system problems come up
  30972. ** during SQLite operation. But so far, none of that has been implemented
  30973. ** in the core. So this routine is never called. For now, it is merely
  30974. ** a place-holder.
  30975. */
  30976. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  30977. UNUSED_PARAMETER(NotUsed);
  30978. UNUSED_PARAMETER(NotUsed2);
  30979. UNUSED_PARAMETER(NotUsed3);
  30980. return 0;
  30981. }
  30982. /*
  30983. ************************ End of sqlite3_vfs methods ***************************
  30984. ******************************************************************************/
  30985. /******************************************************************************
  30986. ************************** Begin Proxy Locking ********************************
  30987. **
  30988. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  30989. ** other locking methods on secondary lock files. Proxy locking is a
  30990. ** meta-layer over top of the primitive locking implemented above. For
  30991. ** this reason, the division that implements of proxy locking is deferred
  30992. ** until late in the file (here) after all of the other I/O methods have
  30993. ** been defined - so that the primitive locking methods are available
  30994. ** as services to help with the implementation of proxy locking.
  30995. **
  30996. ****
  30997. **
  30998. ** The default locking schemes in SQLite use byte-range locks on the
  30999. ** database file to coordinate safe, concurrent access by multiple readers
  31000. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  31001. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  31002. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  31003. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  31004. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  31005. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  31006. ** address in the shared range is taken for a SHARED lock, the entire
  31007. ** shared range is taken for an EXCLUSIVE lock):
  31008. **
  31009. ** PENDING_BYTE 0x40000000
  31010. ** RESERVED_BYTE 0x40000001
  31011. ** SHARED_RANGE 0x40000002 -> 0x40000200
  31012. **
  31013. ** This works well on the local file system, but shows a nearly 100x
  31014. ** slowdown in read performance on AFP because the AFP client disables
  31015. ** the read cache when byte-range locks are present. Enabling the read
  31016. ** cache exposes a cache coherency problem that is present on all OS X
  31017. ** supported network file systems. NFS and AFP both observe the
  31018. ** close-to-open semantics for ensuring cache coherency
  31019. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  31020. ** address the requirements for concurrent database access by multiple
  31021. ** readers and writers
  31022. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  31023. **
  31024. ** To address the performance and cache coherency issues, proxy file locking
  31025. ** changes the way database access is controlled by limiting access to a
  31026. ** single host at a time and moving file locks off of the database file
  31027. ** and onto a proxy file on the local file system.
  31028. **
  31029. **
  31030. ** Using proxy locks
  31031. ** -----------------
  31032. **
  31033. ** C APIs
  31034. **
  31035. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  31036. ** <proxy_path> | ":auto:");
  31037. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  31038. ** &<proxy_path>);
  31039. **
  31040. **
  31041. ** SQL pragmas
  31042. **
  31043. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  31044. ** PRAGMA [database.]lock_proxy_file
  31045. **
  31046. ** Specifying ":auto:" means that if there is a conch file with a matching
  31047. ** host ID in it, the proxy path in the conch file will be used, otherwise
  31048. ** a proxy path based on the user's temp dir
  31049. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  31050. ** actual proxy file name is generated from the name and path of the
  31051. ** database file. For example:
  31052. **
  31053. ** For database path "/Users/me/foo.db"
  31054. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  31055. **
  31056. ** Once a lock proxy is configured for a database connection, it can not
  31057. ** be removed, however it may be switched to a different proxy path via
  31058. ** the above APIs (assuming the conch file is not being held by another
  31059. ** connection or process).
  31060. **
  31061. **
  31062. ** How proxy locking works
  31063. ** -----------------------
  31064. **
  31065. ** Proxy file locking relies primarily on two new supporting files:
  31066. **
  31067. ** * conch file to limit access to the database file to a single host
  31068. ** at a time
  31069. **
  31070. ** * proxy file to act as a proxy for the advisory locks normally
  31071. ** taken on the database
  31072. **
  31073. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  31074. ** by taking an sqlite-style shared lock on the conch file, reading the
  31075. ** contents and comparing the host's unique host ID (see below) and lock
  31076. ** proxy path against the values stored in the conch. The conch file is
  31077. ** stored in the same directory as the database file and the file name
  31078. ** is patterned after the database file name as ".<databasename>-conch".
  31079. ** If the conch file does not exist, or its contents do not match the
  31080. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  31081. ** lock and the conch file contents is updated with the host ID and proxy
  31082. ** path and the lock is downgraded to a shared lock again. If the conch
  31083. ** is held by another process (with a shared lock), the exclusive lock
  31084. ** will fail and SQLITE_BUSY is returned.
  31085. **
  31086. ** The proxy file - a single-byte file used for all advisory file locks
  31087. ** normally taken on the database file. This allows for safe sharing
  31088. ** of the database file for multiple readers and writers on the same
  31089. ** host (the conch ensures that they all use the same local lock file).
  31090. **
  31091. ** Requesting the lock proxy does not immediately take the conch, it is
  31092. ** only taken when the first request to lock database file is made.
  31093. ** This matches the semantics of the traditional locking behavior, where
  31094. ** opening a connection to a database file does not take a lock on it.
  31095. ** The shared lock and an open file descriptor are maintained until
  31096. ** the connection to the database is closed.
  31097. **
  31098. ** The proxy file and the lock file are never deleted so they only need
  31099. ** to be created the first time they are used.
  31100. **
  31101. ** Configuration options
  31102. ** ---------------------
  31103. **
  31104. ** SQLITE_PREFER_PROXY_LOCKING
  31105. **
  31106. ** Database files accessed on non-local file systems are
  31107. ** automatically configured for proxy locking, lock files are
  31108. ** named automatically using the same logic as
  31109. ** PRAGMA lock_proxy_file=":auto:"
  31110. **
  31111. ** SQLITE_PROXY_DEBUG
  31112. **
  31113. ** Enables the logging of error messages during host id file
  31114. ** retrieval and creation
  31115. **
  31116. ** LOCKPROXYDIR
  31117. **
  31118. ** Overrides the default directory used for lock proxy files that
  31119. ** are named automatically via the ":auto:" setting
  31120. **
  31121. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  31122. **
  31123. ** Permissions to use when creating a directory for storing the
  31124. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  31125. **
  31126. **
  31127. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  31128. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  31129. ** force proxy locking to be used for every database file opened, and 0
  31130. ** will force automatic proxy locking to be disabled for all database
  31131. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  31132. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  31133. */
  31134. /*
  31135. ** Proxy locking is only available on MacOSX
  31136. */
  31137. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31138. /*
  31139. ** The proxyLockingContext has the path and file structures for the remote
  31140. ** and local proxy files in it
  31141. */
  31142. typedef struct proxyLockingContext proxyLockingContext;
  31143. struct proxyLockingContext {
  31144. unixFile *conchFile; /* Open conch file */
  31145. char *conchFilePath; /* Name of the conch file */
  31146. unixFile *lockProxy; /* Open proxy lock file */
  31147. char *lockProxyPath; /* Name of the proxy lock file */
  31148. char *dbPath; /* Name of the open file */
  31149. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  31150. int nFails; /* Number of conch taking failures */
  31151. void *oldLockingContext; /* Original lockingcontext to restore on close */
  31152. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  31153. };
  31154. /*
  31155. ** The proxy lock file path for the database at dbPath is written into lPath,
  31156. ** which must point to valid, writable memory large enough for a maxLen length
  31157. ** file path.
  31158. */
  31159. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  31160. int len;
  31161. int dbLen;
  31162. int i;
  31163. #ifdef LOCKPROXYDIR
  31164. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  31165. #else
  31166. # ifdef _CS_DARWIN_USER_TEMP_DIR
  31167. {
  31168. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  31169. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  31170. lPath, errno, osGetpid(0)));
  31171. return SQLITE_IOERR_LOCK;
  31172. }
  31173. len = strlcat(lPath, "sqliteplocks", maxLen);
  31174. }
  31175. # else
  31176. len = strlcpy(lPath, "/tmp/", maxLen);
  31177. # endif
  31178. #endif
  31179. if( lPath[len-1]!='/' ){
  31180. len = strlcat(lPath, "/", maxLen);
  31181. }
  31182. /* transform the db path to a unique cache name */
  31183. dbLen = (int)strlen(dbPath);
  31184. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  31185. char c = dbPath[i];
  31186. lPath[i+len] = (c=='/')?'_':c;
  31187. }
  31188. lPath[i+len]='\0';
  31189. strlcat(lPath, ":auto:", maxLen);
  31190. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  31191. return SQLITE_OK;
  31192. }
  31193. /*
  31194. ** Creates the lock file and any missing directories in lockPath
  31195. */
  31196. static int proxyCreateLockPath(const char *lockPath){
  31197. int i, len;
  31198. char buf[MAXPATHLEN];
  31199. int start = 0;
  31200. assert(lockPath!=NULL);
  31201. /* try to create all the intermediate directories */
  31202. len = (int)strlen(lockPath);
  31203. buf[0] = lockPath[0];
  31204. for( i=1; i<len; i++ ){
  31205. if( lockPath[i] == '/' && (i - start > 0) ){
  31206. /* only mkdir if leaf dir != "." or "/" or ".." */
  31207. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  31208. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  31209. buf[i]='\0';
  31210. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  31211. int err=errno;
  31212. if( err!=EEXIST ) {
  31213. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  31214. "'%s' proxy lock path=%s pid=%d\n",
  31215. buf, strerror(err), lockPath, osGetpid(0)));
  31216. return err;
  31217. }
  31218. }
  31219. }
  31220. start=i+1;
  31221. }
  31222. buf[i] = lockPath[i];
  31223. }
  31224. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
  31225. return 0;
  31226. }
  31227. /*
  31228. ** Create a new VFS file descriptor (stored in memory obtained from
  31229. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  31230. **
  31231. ** The caller is responsible not only for closing the file descriptor
  31232. ** but also for freeing the memory associated with the file descriptor.
  31233. */
  31234. static int proxyCreateUnixFile(
  31235. const char *path, /* path for the new unixFile */
  31236. unixFile **ppFile, /* unixFile created and returned by ref */
  31237. int islockfile /* if non zero missing dirs will be created */
  31238. ) {
  31239. int fd = -1;
  31240. unixFile *pNew;
  31241. int rc = SQLITE_OK;
  31242. int openFlags = O_RDWR | O_CREAT;
  31243. sqlite3_vfs dummyVfs;
  31244. int terrno = 0;
  31245. UnixUnusedFd *pUnused = NULL;
  31246. /* 1. first try to open/create the file
  31247. ** 2. if that fails, and this is a lock file (not-conch), try creating
  31248. ** the parent directories and then try again.
  31249. ** 3. if that fails, try to open the file read-only
  31250. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  31251. */
  31252. pUnused = findReusableFd(path, openFlags);
  31253. if( pUnused ){
  31254. fd = pUnused->fd;
  31255. }else{
  31256. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  31257. if( !pUnused ){
  31258. return SQLITE_NOMEM;
  31259. }
  31260. }
  31261. if( fd<0 ){
  31262. fd = robust_open(path, openFlags, 0);
  31263. terrno = errno;
  31264. if( fd<0 && errno==ENOENT && islockfile ){
  31265. if( proxyCreateLockPath(path) == SQLITE_OK ){
  31266. fd = robust_open(path, openFlags, 0);
  31267. }
  31268. }
  31269. }
  31270. if( fd<0 ){
  31271. openFlags = O_RDONLY;
  31272. fd = robust_open(path, openFlags, 0);
  31273. terrno = errno;
  31274. }
  31275. if( fd<0 ){
  31276. if( islockfile ){
  31277. return SQLITE_BUSY;
  31278. }
  31279. switch (terrno) {
  31280. case EACCES:
  31281. return SQLITE_PERM;
  31282. case EIO:
  31283. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  31284. default:
  31285. return SQLITE_CANTOPEN_BKPT;
  31286. }
  31287. }
  31288. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  31289. if( pNew==NULL ){
  31290. rc = SQLITE_NOMEM;
  31291. goto end_create_proxy;
  31292. }
  31293. memset(pNew, 0, sizeof(unixFile));
  31294. pNew->openFlags = openFlags;
  31295. memset(&dummyVfs, 0, sizeof(dummyVfs));
  31296. dummyVfs.pAppData = (void*)&autolockIoFinder;
  31297. dummyVfs.zName = "dummy";
  31298. pUnused->fd = fd;
  31299. pUnused->flags = openFlags;
  31300. pNew->pUnused = pUnused;
  31301. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  31302. if( rc==SQLITE_OK ){
  31303. *ppFile = pNew;
  31304. return SQLITE_OK;
  31305. }
  31306. end_create_proxy:
  31307. robust_close(pNew, fd, __LINE__);
  31308. sqlite3_free(pNew);
  31309. sqlite3_free(pUnused);
  31310. return rc;
  31311. }
  31312. #ifdef SQLITE_TEST
  31313. /* simulate multiple hosts by creating unique hostid file paths */
  31314. SQLITE_API int sqlite3_hostid_num = 0;
  31315. #endif
  31316. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  31317. #ifdef HAVE_GETHOSTUUID
  31318. /* Not always defined in the headers as it ought to be */
  31319. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  31320. #endif
  31321. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  31322. ** bytes of writable memory.
  31323. */
  31324. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  31325. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  31326. memset(pHostID, 0, PROXY_HOSTIDLEN);
  31327. #ifdef HAVE_GETHOSTUUID
  31328. {
  31329. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  31330. if( gethostuuid(pHostID, &timeout) ){
  31331. int err = errno;
  31332. if( pError ){
  31333. *pError = err;
  31334. }
  31335. return SQLITE_IOERR;
  31336. }
  31337. }
  31338. #else
  31339. UNUSED_PARAMETER(pError);
  31340. #endif
  31341. #ifdef SQLITE_TEST
  31342. /* simulate multiple hosts by creating unique hostid file paths */
  31343. if( sqlite3_hostid_num != 0){
  31344. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  31345. }
  31346. #endif
  31347. return SQLITE_OK;
  31348. }
  31349. /* The conch file contains the header, host id and lock file path
  31350. */
  31351. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  31352. #define PROXY_HEADERLEN 1 /* conch file header length */
  31353. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  31354. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  31355. /*
  31356. ** Takes an open conch file, copies the contents to a new path and then moves
  31357. ** it back. The newly created file's file descriptor is assigned to the
  31358. ** conch file structure and finally the original conch file descriptor is
  31359. ** closed. Returns zero if successful.
  31360. */
  31361. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  31362. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31363. unixFile *conchFile = pCtx->conchFile;
  31364. char tPath[MAXPATHLEN];
  31365. char buf[PROXY_MAXCONCHLEN];
  31366. char *cPath = pCtx->conchFilePath;
  31367. size_t readLen = 0;
  31368. size_t pathLen = 0;
  31369. char errmsg[64] = "";
  31370. int fd = -1;
  31371. int rc = -1;
  31372. UNUSED_PARAMETER(myHostID);
  31373. /* create a new path by replace the trailing '-conch' with '-break' */
  31374. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  31375. if( pathLen>MAXPATHLEN || pathLen<6 ||
  31376. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  31377. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  31378. goto end_breaklock;
  31379. }
  31380. /* read the conch content */
  31381. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  31382. if( readLen<PROXY_PATHINDEX ){
  31383. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  31384. goto end_breaklock;
  31385. }
  31386. /* write it out to the temporary break file */
  31387. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  31388. if( fd<0 ){
  31389. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  31390. goto end_breaklock;
  31391. }
  31392. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  31393. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  31394. goto end_breaklock;
  31395. }
  31396. if( rename(tPath, cPath) ){
  31397. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  31398. goto end_breaklock;
  31399. }
  31400. rc = 0;
  31401. fprintf(stderr, "broke stale lock on %s\n", cPath);
  31402. robust_close(pFile, conchFile->h, __LINE__);
  31403. conchFile->h = fd;
  31404. conchFile->openFlags = O_RDWR | O_CREAT;
  31405. end_breaklock:
  31406. if( rc ){
  31407. if( fd>=0 ){
  31408. osUnlink(tPath);
  31409. robust_close(pFile, fd, __LINE__);
  31410. }
  31411. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  31412. }
  31413. return rc;
  31414. }
  31415. /* Take the requested lock on the conch file and break a stale lock if the
  31416. ** host id matches.
  31417. */
  31418. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  31419. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31420. unixFile *conchFile = pCtx->conchFile;
  31421. int rc = SQLITE_OK;
  31422. int nTries = 0;
  31423. struct timespec conchModTime;
  31424. memset(&conchModTime, 0, sizeof(conchModTime));
  31425. do {
  31426. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  31427. nTries ++;
  31428. if( rc==SQLITE_BUSY ){
  31429. /* If the lock failed (busy):
  31430. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  31431. * 2nd try: fail if the mod time changed or host id is different, wait
  31432. * 10 sec and try again
  31433. * 3rd try: break the lock unless the mod time has changed.
  31434. */
  31435. struct stat buf;
  31436. if( osFstat(conchFile->h, &buf) ){
  31437. storeLastErrno(pFile, errno);
  31438. return SQLITE_IOERR_LOCK;
  31439. }
  31440. if( nTries==1 ){
  31441. conchModTime = buf.st_mtimespec;
  31442. usleep(500000); /* wait 0.5 sec and try the lock again*/
  31443. continue;
  31444. }
  31445. assert( nTries>1 );
  31446. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  31447. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  31448. return SQLITE_BUSY;
  31449. }
  31450. if( nTries==2 ){
  31451. char tBuf[PROXY_MAXCONCHLEN];
  31452. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  31453. if( len<0 ){
  31454. storeLastErrno(pFile, errno);
  31455. return SQLITE_IOERR_LOCK;
  31456. }
  31457. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  31458. /* don't break the lock if the host id doesn't match */
  31459. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  31460. return SQLITE_BUSY;
  31461. }
  31462. }else{
  31463. /* don't break the lock on short read or a version mismatch */
  31464. return SQLITE_BUSY;
  31465. }
  31466. usleep(10000000); /* wait 10 sec and try the lock again */
  31467. continue;
  31468. }
  31469. assert( nTries==3 );
  31470. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  31471. rc = SQLITE_OK;
  31472. if( lockType==EXCLUSIVE_LOCK ){
  31473. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  31474. }
  31475. if( !rc ){
  31476. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  31477. }
  31478. }
  31479. }
  31480. } while( rc==SQLITE_BUSY && nTries<3 );
  31481. return rc;
  31482. }
  31483. /* Takes the conch by taking a shared lock and read the contents conch, if
  31484. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  31485. ** lockPath means that the lockPath in the conch file will be used if the
  31486. ** host IDs match, or a new lock path will be generated automatically
  31487. ** and written to the conch file.
  31488. */
  31489. static int proxyTakeConch(unixFile *pFile){
  31490. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31491. if( pCtx->conchHeld!=0 ){
  31492. return SQLITE_OK;
  31493. }else{
  31494. unixFile *conchFile = pCtx->conchFile;
  31495. uuid_t myHostID;
  31496. int pError = 0;
  31497. char readBuf[PROXY_MAXCONCHLEN];
  31498. char lockPath[MAXPATHLEN];
  31499. char *tempLockPath = NULL;
  31500. int rc = SQLITE_OK;
  31501. int createConch = 0;
  31502. int hostIdMatch = 0;
  31503. int readLen = 0;
  31504. int tryOldLockPath = 0;
  31505. int forceNewLockPath = 0;
  31506. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  31507. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  31508. osGetpid(0)));
  31509. rc = proxyGetHostID(myHostID, &pError);
  31510. if( (rc&0xff)==SQLITE_IOERR ){
  31511. storeLastErrno(pFile, pError);
  31512. goto end_takeconch;
  31513. }
  31514. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  31515. if( rc!=SQLITE_OK ){
  31516. goto end_takeconch;
  31517. }
  31518. /* read the existing conch file */
  31519. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  31520. if( readLen<0 ){
  31521. /* I/O error: lastErrno set by seekAndRead */
  31522. storeLastErrno(pFile, conchFile->lastErrno);
  31523. rc = SQLITE_IOERR_READ;
  31524. goto end_takeconch;
  31525. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  31526. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  31527. /* a short read or version format mismatch means we need to create a new
  31528. ** conch file.
  31529. */
  31530. createConch = 1;
  31531. }
  31532. /* if the host id matches and the lock path already exists in the conch
  31533. ** we'll try to use the path there, if we can't open that path, we'll
  31534. ** retry with a new auto-generated path
  31535. */
  31536. do { /* in case we need to try again for an :auto: named lock file */
  31537. if( !createConch && !forceNewLockPath ){
  31538. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  31539. PROXY_HOSTIDLEN);
  31540. /* if the conch has data compare the contents */
  31541. if( !pCtx->lockProxyPath ){
  31542. /* for auto-named local lock file, just check the host ID and we'll
  31543. ** use the local lock file path that's already in there
  31544. */
  31545. if( hostIdMatch ){
  31546. size_t pathLen = (readLen - PROXY_PATHINDEX);
  31547. if( pathLen>=MAXPATHLEN ){
  31548. pathLen=MAXPATHLEN-1;
  31549. }
  31550. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  31551. lockPath[pathLen] = 0;
  31552. tempLockPath = lockPath;
  31553. tryOldLockPath = 1;
  31554. /* create a copy of the lock path if the conch is taken */
  31555. goto end_takeconch;
  31556. }
  31557. }else if( hostIdMatch
  31558. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  31559. readLen-PROXY_PATHINDEX)
  31560. ){
  31561. /* conch host and lock path match */
  31562. goto end_takeconch;
  31563. }
  31564. }
  31565. /* if the conch isn't writable and doesn't match, we can't take it */
  31566. if( (conchFile->openFlags&O_RDWR) == 0 ){
  31567. rc = SQLITE_BUSY;
  31568. goto end_takeconch;
  31569. }
  31570. /* either the conch didn't match or we need to create a new one */
  31571. if( !pCtx->lockProxyPath ){
  31572. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  31573. tempLockPath = lockPath;
  31574. /* create a copy of the lock path _only_ if the conch is taken */
  31575. }
  31576. /* update conch with host and path (this will fail if other process
  31577. ** has a shared lock already), if the host id matches, use the big
  31578. ** stick.
  31579. */
  31580. futimes(conchFile->h, NULL);
  31581. if( hostIdMatch && !createConch ){
  31582. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  31583. /* We are trying for an exclusive lock but another thread in this
  31584. ** same process is still holding a shared lock. */
  31585. rc = SQLITE_BUSY;
  31586. } else {
  31587. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  31588. }
  31589. }else{
  31590. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  31591. }
  31592. if( rc==SQLITE_OK ){
  31593. char writeBuffer[PROXY_MAXCONCHLEN];
  31594. int writeSize = 0;
  31595. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  31596. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  31597. if( pCtx->lockProxyPath!=NULL ){
  31598. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  31599. MAXPATHLEN);
  31600. }else{
  31601. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  31602. }
  31603. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  31604. robust_ftruncate(conchFile->h, writeSize);
  31605. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  31606. fsync(conchFile->h);
  31607. /* If we created a new conch file (not just updated the contents of a
  31608. ** valid conch file), try to match the permissions of the database
  31609. */
  31610. if( rc==SQLITE_OK && createConch ){
  31611. struct stat buf;
  31612. int err = osFstat(pFile->h, &buf);
  31613. if( err==0 ){
  31614. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  31615. S_IROTH|S_IWOTH);
  31616. /* try to match the database file R/W permissions, ignore failure */
  31617. #ifndef SQLITE_PROXY_DEBUG
  31618. osFchmod(conchFile->h, cmode);
  31619. #else
  31620. do{
  31621. rc = osFchmod(conchFile->h, cmode);
  31622. }while( rc==(-1) && errno==EINTR );
  31623. if( rc!=0 ){
  31624. int code = errno;
  31625. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  31626. cmode, code, strerror(code));
  31627. } else {
  31628. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  31629. }
  31630. }else{
  31631. int code = errno;
  31632. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  31633. err, code, strerror(code));
  31634. #endif
  31635. }
  31636. }
  31637. }
  31638. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  31639. end_takeconch:
  31640. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  31641. if( rc==SQLITE_OK && pFile->openFlags ){
  31642. int fd;
  31643. if( pFile->h>=0 ){
  31644. robust_close(pFile, pFile->h, __LINE__);
  31645. }
  31646. pFile->h = -1;
  31647. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  31648. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  31649. if( fd>=0 ){
  31650. pFile->h = fd;
  31651. }else{
  31652. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  31653. during locking */
  31654. }
  31655. }
  31656. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  31657. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  31658. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  31659. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  31660. /* we couldn't create the proxy lock file with the old lock file path
  31661. ** so try again via auto-naming
  31662. */
  31663. forceNewLockPath = 1;
  31664. tryOldLockPath = 0;
  31665. continue; /* go back to the do {} while start point, try again */
  31666. }
  31667. }
  31668. if( rc==SQLITE_OK ){
  31669. /* Need to make a copy of path if we extracted the value
  31670. ** from the conch file or the path was allocated on the stack
  31671. */
  31672. if( tempLockPath ){
  31673. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  31674. if( !pCtx->lockProxyPath ){
  31675. rc = SQLITE_NOMEM;
  31676. }
  31677. }
  31678. }
  31679. if( rc==SQLITE_OK ){
  31680. pCtx->conchHeld = 1;
  31681. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  31682. afpLockingContext *afpCtx;
  31683. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  31684. afpCtx->dbPath = pCtx->lockProxyPath;
  31685. }
  31686. } else {
  31687. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  31688. }
  31689. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  31690. rc==SQLITE_OK?"ok":"failed"));
  31691. return rc;
  31692. } while (1); /* in case we need to retry the :auto: lock file -
  31693. ** we should never get here except via the 'continue' call. */
  31694. }
  31695. }
  31696. /*
  31697. ** If pFile holds a lock on a conch file, then release that lock.
  31698. */
  31699. static int proxyReleaseConch(unixFile *pFile){
  31700. int rc = SQLITE_OK; /* Subroutine return code */
  31701. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  31702. unixFile *conchFile; /* Name of the conch file */
  31703. pCtx = (proxyLockingContext *)pFile->lockingContext;
  31704. conchFile = pCtx->conchFile;
  31705. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  31706. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  31707. osGetpid(0)));
  31708. if( pCtx->conchHeld>0 ){
  31709. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  31710. }
  31711. pCtx->conchHeld = 0;
  31712. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  31713. (rc==SQLITE_OK ? "ok" : "failed")));
  31714. return rc;
  31715. }
  31716. /*
  31717. ** Given the name of a database file, compute the name of its conch file.
  31718. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  31719. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  31720. ** or SQLITE_NOMEM if unable to obtain memory.
  31721. **
  31722. ** The caller is responsible for ensuring that the allocated memory
  31723. ** space is eventually freed.
  31724. **
  31725. ** *pConchPath is set to NULL if a memory allocation error occurs.
  31726. */
  31727. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  31728. int i; /* Loop counter */
  31729. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  31730. char *conchPath; /* buffer in which to construct conch name */
  31731. /* Allocate space for the conch filename and initialize the name to
  31732. ** the name of the original database file. */
  31733. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  31734. if( conchPath==0 ){
  31735. return SQLITE_NOMEM;
  31736. }
  31737. memcpy(conchPath, dbPath, len+1);
  31738. /* now insert a "." before the last / character */
  31739. for( i=(len-1); i>=0; i-- ){
  31740. if( conchPath[i]=='/' ){
  31741. i++;
  31742. break;
  31743. }
  31744. }
  31745. conchPath[i]='.';
  31746. while ( i<len ){
  31747. conchPath[i+1]=dbPath[i];
  31748. i++;
  31749. }
  31750. /* append the "-conch" suffix to the file */
  31751. memcpy(&conchPath[i+1], "-conch", 7);
  31752. assert( (int)strlen(conchPath) == len+7 );
  31753. return SQLITE_OK;
  31754. }
  31755. /* Takes a fully configured proxy locking-style unix file and switches
  31756. ** the local lock file path
  31757. */
  31758. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  31759. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  31760. char *oldPath = pCtx->lockProxyPath;
  31761. int rc = SQLITE_OK;
  31762. if( pFile->eFileLock!=NO_LOCK ){
  31763. return SQLITE_BUSY;
  31764. }
  31765. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  31766. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  31767. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  31768. return SQLITE_OK;
  31769. }else{
  31770. unixFile *lockProxy = pCtx->lockProxy;
  31771. pCtx->lockProxy=NULL;
  31772. pCtx->conchHeld = 0;
  31773. if( lockProxy!=NULL ){
  31774. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  31775. if( rc ) return rc;
  31776. sqlite3_free(lockProxy);
  31777. }
  31778. sqlite3_free(oldPath);
  31779. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  31780. }
  31781. return rc;
  31782. }
  31783. /*
  31784. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  31785. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  31786. **
  31787. ** This routine find the filename associated with pFile and writes it
  31788. ** int dbPath.
  31789. */
  31790. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  31791. #if defined(__APPLE__)
  31792. if( pFile->pMethod == &afpIoMethods ){
  31793. /* afp style keeps a reference to the db path in the filePath field
  31794. ** of the struct */
  31795. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  31796. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  31797. MAXPATHLEN);
  31798. } else
  31799. #endif
  31800. if( pFile->pMethod == &dotlockIoMethods ){
  31801. /* dot lock style uses the locking context to store the dot lock
  31802. ** file path */
  31803. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  31804. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  31805. }else{
  31806. /* all other styles use the locking context to store the db file path */
  31807. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  31808. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  31809. }
  31810. return SQLITE_OK;
  31811. }
  31812. /*
  31813. ** Takes an already filled in unix file and alters it so all file locking
  31814. ** will be performed on the local proxy lock file. The following fields
  31815. ** are preserved in the locking context so that they can be restored and
  31816. ** the unix structure properly cleaned up at close time:
  31817. ** ->lockingContext
  31818. ** ->pMethod
  31819. */
  31820. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  31821. proxyLockingContext *pCtx;
  31822. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  31823. char *lockPath=NULL;
  31824. int rc = SQLITE_OK;
  31825. if( pFile->eFileLock!=NO_LOCK ){
  31826. return SQLITE_BUSY;
  31827. }
  31828. proxyGetDbPathForUnixFile(pFile, dbPath);
  31829. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  31830. lockPath=NULL;
  31831. }else{
  31832. lockPath=(char *)path;
  31833. }
  31834. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  31835. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  31836. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  31837. if( pCtx==0 ){
  31838. return SQLITE_NOMEM;
  31839. }
  31840. memset(pCtx, 0, sizeof(*pCtx));
  31841. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  31842. if( rc==SQLITE_OK ){
  31843. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  31844. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  31845. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  31846. ** (c) the file system is read-only, then enable no-locking access.
  31847. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  31848. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  31849. */
  31850. struct statfs fsInfo;
  31851. struct stat conchInfo;
  31852. int goLockless = 0;
  31853. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  31854. int err = errno;
  31855. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  31856. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  31857. }
  31858. }
  31859. if( goLockless ){
  31860. pCtx->conchHeld = -1; /* read only FS/ lockless */
  31861. rc = SQLITE_OK;
  31862. }
  31863. }
  31864. }
  31865. if( rc==SQLITE_OK && lockPath ){
  31866. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  31867. }
  31868. if( rc==SQLITE_OK ){
  31869. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  31870. if( pCtx->dbPath==NULL ){
  31871. rc = SQLITE_NOMEM;
  31872. }
  31873. }
  31874. if( rc==SQLITE_OK ){
  31875. /* all memory is allocated, proxys are created and assigned,
  31876. ** switch the locking context and pMethod then return.
  31877. */
  31878. pCtx->oldLockingContext = pFile->lockingContext;
  31879. pFile->lockingContext = pCtx;
  31880. pCtx->pOldMethod = pFile->pMethod;
  31881. pFile->pMethod = &proxyIoMethods;
  31882. }else{
  31883. if( pCtx->conchFile ){
  31884. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  31885. sqlite3_free(pCtx->conchFile);
  31886. }
  31887. sqlite3DbFree(0, pCtx->lockProxyPath);
  31888. sqlite3_free(pCtx->conchFilePath);
  31889. sqlite3_free(pCtx);
  31890. }
  31891. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  31892. (rc==SQLITE_OK ? "ok" : "failed")));
  31893. return rc;
  31894. }
  31895. /*
  31896. ** This routine handles sqlite3_file_control() calls that are specific
  31897. ** to proxy locking.
  31898. */
  31899. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  31900. switch( op ){
  31901. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  31902. unixFile *pFile = (unixFile*)id;
  31903. if( pFile->pMethod == &proxyIoMethods ){
  31904. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  31905. proxyTakeConch(pFile);
  31906. if( pCtx->lockProxyPath ){
  31907. *(const char **)pArg = pCtx->lockProxyPath;
  31908. }else{
  31909. *(const char **)pArg = ":auto: (not held)";
  31910. }
  31911. } else {
  31912. *(const char **)pArg = NULL;
  31913. }
  31914. return SQLITE_OK;
  31915. }
  31916. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  31917. unixFile *pFile = (unixFile*)id;
  31918. int rc = SQLITE_OK;
  31919. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  31920. if( pArg==NULL || (const char *)pArg==0 ){
  31921. if( isProxyStyle ){
  31922. /* turn off proxy locking - not supported. If support is added for
  31923. ** switching proxy locking mode off then it will need to fail if
  31924. ** the journal mode is WAL mode.
  31925. */
  31926. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  31927. }else{
  31928. /* turn off proxy locking - already off - NOOP */
  31929. rc = SQLITE_OK;
  31930. }
  31931. }else{
  31932. const char *proxyPath = (const char *)pArg;
  31933. if( isProxyStyle ){
  31934. proxyLockingContext *pCtx =
  31935. (proxyLockingContext*)pFile->lockingContext;
  31936. if( !strcmp(pArg, ":auto:")
  31937. || (pCtx->lockProxyPath &&
  31938. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  31939. ){
  31940. rc = SQLITE_OK;
  31941. }else{
  31942. rc = switchLockProxyPath(pFile, proxyPath);
  31943. }
  31944. }else{
  31945. /* turn on proxy file locking */
  31946. rc = proxyTransformUnixFile(pFile, proxyPath);
  31947. }
  31948. }
  31949. return rc;
  31950. }
  31951. default: {
  31952. assert( 0 ); /* The call assures that only valid opcodes are sent */
  31953. }
  31954. }
  31955. /*NOTREACHED*/
  31956. return SQLITE_ERROR;
  31957. }
  31958. /*
  31959. ** Within this division (the proxying locking implementation) the procedures
  31960. ** above this point are all utilities. The lock-related methods of the
  31961. ** proxy-locking sqlite3_io_method object follow.
  31962. */
  31963. /*
  31964. ** This routine checks if there is a RESERVED lock held on the specified
  31965. ** file by this or any other process. If such a lock is held, set *pResOut
  31966. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31967. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31968. */
  31969. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  31970. unixFile *pFile = (unixFile*)id;
  31971. int rc = proxyTakeConch(pFile);
  31972. if( rc==SQLITE_OK ){
  31973. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31974. if( pCtx->conchHeld>0 ){
  31975. unixFile *proxy = pCtx->lockProxy;
  31976. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  31977. }else{ /* conchHeld < 0 is lockless */
  31978. pResOut=0;
  31979. }
  31980. }
  31981. return rc;
  31982. }
  31983. /*
  31984. ** Lock the file with the lock specified by parameter eFileLock - one
  31985. ** of the following:
  31986. **
  31987. ** (1) SHARED_LOCK
  31988. ** (2) RESERVED_LOCK
  31989. ** (3) PENDING_LOCK
  31990. ** (4) EXCLUSIVE_LOCK
  31991. **
  31992. ** Sometimes when requesting one lock state, additional lock states
  31993. ** are inserted in between. The locking might fail on one of the later
  31994. ** transitions leaving the lock state different from what it started but
  31995. ** still short of its goal. The following chart shows the allowed
  31996. ** transitions and the inserted intermediate states:
  31997. **
  31998. ** UNLOCKED -> SHARED
  31999. ** SHARED -> RESERVED
  32000. ** SHARED -> (PENDING) -> EXCLUSIVE
  32001. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32002. ** PENDING -> EXCLUSIVE
  32003. **
  32004. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32005. ** routine to lower a locking level.
  32006. */
  32007. static int proxyLock(sqlite3_file *id, int eFileLock) {
  32008. unixFile *pFile = (unixFile*)id;
  32009. int rc = proxyTakeConch(pFile);
  32010. if( rc==SQLITE_OK ){
  32011. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32012. if( pCtx->conchHeld>0 ){
  32013. unixFile *proxy = pCtx->lockProxy;
  32014. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  32015. pFile->eFileLock = proxy->eFileLock;
  32016. }else{
  32017. /* conchHeld < 0 is lockless */
  32018. }
  32019. }
  32020. return rc;
  32021. }
  32022. /*
  32023. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32024. ** must be either NO_LOCK or SHARED_LOCK.
  32025. **
  32026. ** If the locking level of the file descriptor is already at or below
  32027. ** the requested locking level, this routine is a no-op.
  32028. */
  32029. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  32030. unixFile *pFile = (unixFile*)id;
  32031. int rc = proxyTakeConch(pFile);
  32032. if( rc==SQLITE_OK ){
  32033. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32034. if( pCtx->conchHeld>0 ){
  32035. unixFile *proxy = pCtx->lockProxy;
  32036. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  32037. pFile->eFileLock = proxy->eFileLock;
  32038. }else{
  32039. /* conchHeld < 0 is lockless */
  32040. }
  32041. }
  32042. return rc;
  32043. }
  32044. /*
  32045. ** Close a file that uses proxy locks.
  32046. */
  32047. static int proxyClose(sqlite3_file *id) {
  32048. if( id ){
  32049. unixFile *pFile = (unixFile*)id;
  32050. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32051. unixFile *lockProxy = pCtx->lockProxy;
  32052. unixFile *conchFile = pCtx->conchFile;
  32053. int rc = SQLITE_OK;
  32054. if( lockProxy ){
  32055. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  32056. if( rc ) return rc;
  32057. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  32058. if( rc ) return rc;
  32059. sqlite3_free(lockProxy);
  32060. pCtx->lockProxy = 0;
  32061. }
  32062. if( conchFile ){
  32063. if( pCtx->conchHeld ){
  32064. rc = proxyReleaseConch(pFile);
  32065. if( rc ) return rc;
  32066. }
  32067. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  32068. if( rc ) return rc;
  32069. sqlite3_free(conchFile);
  32070. }
  32071. sqlite3DbFree(0, pCtx->lockProxyPath);
  32072. sqlite3_free(pCtx->conchFilePath);
  32073. sqlite3DbFree(0, pCtx->dbPath);
  32074. /* restore the original locking context and pMethod then close it */
  32075. pFile->lockingContext = pCtx->oldLockingContext;
  32076. pFile->pMethod = pCtx->pOldMethod;
  32077. sqlite3_free(pCtx);
  32078. return pFile->pMethod->xClose(id);
  32079. }
  32080. return SQLITE_OK;
  32081. }
  32082. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32083. /*
  32084. ** The proxy locking style is intended for use with AFP filesystems.
  32085. ** And since AFP is only supported on MacOSX, the proxy locking is also
  32086. ** restricted to MacOSX.
  32087. **
  32088. **
  32089. ******************* End of the proxy lock implementation **********************
  32090. ******************************************************************************/
  32091. /*
  32092. ** Initialize the operating system interface.
  32093. **
  32094. ** This routine registers all VFS implementations for unix-like operating
  32095. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  32096. ** should be the only routines in this file that are visible from other
  32097. ** files.
  32098. **
  32099. ** This routine is called once during SQLite initialization and by a
  32100. ** single thread. The memory allocation and mutex subsystems have not
  32101. ** necessarily been initialized when this routine is called, and so they
  32102. ** should not be used.
  32103. */
  32104. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  32105. /*
  32106. ** The following macro defines an initializer for an sqlite3_vfs object.
  32107. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  32108. ** to the "finder" function. (pAppData is a pointer to a pointer because
  32109. ** silly C90 rules prohibit a void* from being cast to a function pointer
  32110. ** and so we have to go through the intermediate pointer to avoid problems
  32111. ** when compiling with -pedantic-errors on GCC.)
  32112. **
  32113. ** The FINDER parameter to this macro is the name of the pointer to the
  32114. ** finder-function. The finder-function returns a pointer to the
  32115. ** sqlite_io_methods object that implements the desired locking
  32116. ** behaviors. See the division above that contains the IOMETHODS
  32117. ** macro for addition information on finder-functions.
  32118. **
  32119. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  32120. ** object. But the "autolockIoFinder" available on MacOSX does a little
  32121. ** more than that; it looks at the filesystem type that hosts the
  32122. ** database file and tries to choose an locking method appropriate for
  32123. ** that filesystem time.
  32124. */
  32125. #define UNIXVFS(VFSNAME, FINDER) { \
  32126. 3, /* iVersion */ \
  32127. sizeof(unixFile), /* szOsFile */ \
  32128. MAX_PATHNAME, /* mxPathname */ \
  32129. 0, /* pNext */ \
  32130. VFSNAME, /* zName */ \
  32131. (void*)&FINDER, /* pAppData */ \
  32132. unixOpen, /* xOpen */ \
  32133. unixDelete, /* xDelete */ \
  32134. unixAccess, /* xAccess */ \
  32135. unixFullPathname, /* xFullPathname */ \
  32136. unixDlOpen, /* xDlOpen */ \
  32137. unixDlError, /* xDlError */ \
  32138. unixDlSym, /* xDlSym */ \
  32139. unixDlClose, /* xDlClose */ \
  32140. unixRandomness, /* xRandomness */ \
  32141. unixSleep, /* xSleep */ \
  32142. unixCurrentTime, /* xCurrentTime */ \
  32143. unixGetLastError, /* xGetLastError */ \
  32144. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  32145. unixSetSystemCall, /* xSetSystemCall */ \
  32146. unixGetSystemCall, /* xGetSystemCall */ \
  32147. unixNextSystemCall, /* xNextSystemCall */ \
  32148. }
  32149. /*
  32150. ** All default VFSes for unix are contained in the following array.
  32151. **
  32152. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  32153. ** by the SQLite core when the VFS is registered. So the following
  32154. ** array cannot be const.
  32155. */
  32156. static sqlite3_vfs aVfs[] = {
  32157. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32158. UNIXVFS("unix", autolockIoFinder ),
  32159. #elif OS_VXWORKS
  32160. UNIXVFS("unix", vxworksIoFinder ),
  32161. #else
  32162. UNIXVFS("unix", posixIoFinder ),
  32163. #endif
  32164. UNIXVFS("unix-none", nolockIoFinder ),
  32165. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  32166. UNIXVFS("unix-excl", posixIoFinder ),
  32167. #if OS_VXWORKS
  32168. UNIXVFS("unix-namedsem", semIoFinder ),
  32169. #endif
  32170. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  32171. UNIXVFS("unix-posix", posixIoFinder ),
  32172. #endif
  32173. #if SQLITE_ENABLE_LOCKING_STYLE
  32174. UNIXVFS("unix-flock", flockIoFinder ),
  32175. #endif
  32176. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32177. UNIXVFS("unix-afp", afpIoFinder ),
  32178. UNIXVFS("unix-nfs", nfsIoFinder ),
  32179. UNIXVFS("unix-proxy", proxyIoFinder ),
  32180. #endif
  32181. };
  32182. unsigned int i; /* Loop counter */
  32183. /* Double-check that the aSyscall[] array has been constructed
  32184. ** correctly. See ticket [bb3a86e890c8e96ab] */
  32185. assert( ArraySize(aSyscall)==25 );
  32186. /* Register all VFSes defined in the aVfs[] array */
  32187. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  32188. sqlite3_vfs_register(&aVfs[i], i==0);
  32189. }
  32190. return SQLITE_OK;
  32191. }
  32192. /*
  32193. ** Shutdown the operating system interface.
  32194. **
  32195. ** Some operating systems might need to do some cleanup in this routine,
  32196. ** to release dynamically allocated objects. But not on unix.
  32197. ** This routine is a no-op for unix.
  32198. */
  32199. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  32200. return SQLITE_OK;
  32201. }
  32202. #endif /* SQLITE_OS_UNIX */
  32203. /************** End of os_unix.c *********************************************/
  32204. /************** Begin file os_win.c ******************************************/
  32205. /*
  32206. ** 2004 May 22
  32207. **
  32208. ** The author disclaims copyright to this source code. In place of
  32209. ** a legal notice, here is a blessing:
  32210. **
  32211. ** May you do good and not evil.
  32212. ** May you find forgiveness for yourself and forgive others.
  32213. ** May you share freely, never taking more than you give.
  32214. **
  32215. ******************************************************************************
  32216. **
  32217. ** This file contains code that is specific to Windows.
  32218. */
  32219. /* #include "sqliteInt.h" */
  32220. #if SQLITE_OS_WIN /* This file is used for Windows only */
  32221. /*
  32222. ** Include code that is common to all os_*.c files
  32223. */
  32224. /************** Include os_common.h in the middle of os_win.c ****************/
  32225. /************** Begin file os_common.h ***************************************/
  32226. /*
  32227. ** 2004 May 22
  32228. **
  32229. ** The author disclaims copyright to this source code. In place of
  32230. ** a legal notice, here is a blessing:
  32231. **
  32232. ** May you do good and not evil.
  32233. ** May you find forgiveness for yourself and forgive others.
  32234. ** May you share freely, never taking more than you give.
  32235. **
  32236. ******************************************************************************
  32237. **
  32238. ** This file contains macros and a little bit of code that is common to
  32239. ** all of the platform-specific files (os_*.c) and is #included into those
  32240. ** files.
  32241. **
  32242. ** This file should be #included by the os_*.c files only. It is not a
  32243. ** general purpose header file.
  32244. */
  32245. #ifndef _OS_COMMON_H_
  32246. #define _OS_COMMON_H_
  32247. /*
  32248. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  32249. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  32250. ** switch. The following code should catch this problem at compile-time.
  32251. */
  32252. #ifdef MEMORY_DEBUG
  32253. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  32254. #endif
  32255. /*
  32256. ** Macros for performance tracing. Normally turned off. Only works
  32257. ** on i486 hardware.
  32258. */
  32259. #ifdef SQLITE_PERFORMANCE_TRACE
  32260. /*
  32261. ** hwtime.h contains inline assembler code for implementing
  32262. ** high-performance timing routines.
  32263. */
  32264. /************** Include hwtime.h in the middle of os_common.h ****************/
  32265. /************** Begin file hwtime.h ******************************************/
  32266. /*
  32267. ** 2008 May 27
  32268. **
  32269. ** The author disclaims copyright to this source code. In place of
  32270. ** a legal notice, here is a blessing:
  32271. **
  32272. ** May you do good and not evil.
  32273. ** May you find forgiveness for yourself and forgive others.
  32274. ** May you share freely, never taking more than you give.
  32275. **
  32276. ******************************************************************************
  32277. **
  32278. ** This file contains inline asm code for retrieving "high-performance"
  32279. ** counters for x86 class CPUs.
  32280. */
  32281. #ifndef _HWTIME_H_
  32282. #define _HWTIME_H_
  32283. /*
  32284. ** The following routine only works on pentium-class (or newer) processors.
  32285. ** It uses the RDTSC opcode to read the cycle count value out of the
  32286. ** processor and returns that value. This can be used for high-res
  32287. ** profiling.
  32288. */
  32289. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  32290. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  32291. #if defined(__GNUC__)
  32292. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32293. unsigned int lo, hi;
  32294. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  32295. return (sqlite_uint64)hi << 32 | lo;
  32296. }
  32297. #elif defined(_MSC_VER)
  32298. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  32299. __asm {
  32300. rdtsc
  32301. ret ; return value at EDX:EAX
  32302. }
  32303. }
  32304. #endif
  32305. #elif (defined(__GNUC__) && defined(__x86_64__))
  32306. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32307. unsigned long val;
  32308. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  32309. return val;
  32310. }
  32311. #elif (defined(__GNUC__) && defined(__ppc__))
  32312. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32313. unsigned long long retval;
  32314. unsigned long junk;
  32315. __asm__ __volatile__ ("\n\
  32316. 1: mftbu %1\n\
  32317. mftb %L0\n\
  32318. mftbu %0\n\
  32319. cmpw %0,%1\n\
  32320. bne 1b"
  32321. : "=r" (retval), "=r" (junk));
  32322. return retval;
  32323. }
  32324. #else
  32325. #error Need implementation of sqlite3Hwtime() for your platform.
  32326. /*
  32327. ** To compile without implementing sqlite3Hwtime() for your platform,
  32328. ** you can remove the above #error and use the following
  32329. ** stub function. You will lose timing support for many
  32330. ** of the debugging and testing utilities, but it should at
  32331. ** least compile and run.
  32332. */
  32333. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  32334. #endif
  32335. #endif /* !defined(_HWTIME_H_) */
  32336. /************** End of hwtime.h **********************************************/
  32337. /************** Continuing where we left off in os_common.h ******************/
  32338. static sqlite_uint64 g_start;
  32339. static sqlite_uint64 g_elapsed;
  32340. #define TIMER_START g_start=sqlite3Hwtime()
  32341. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  32342. #define TIMER_ELAPSED g_elapsed
  32343. #else
  32344. #define TIMER_START
  32345. #define TIMER_END
  32346. #define TIMER_ELAPSED ((sqlite_uint64)0)
  32347. #endif
  32348. /*
  32349. ** If we compile with the SQLITE_TEST macro set, then the following block
  32350. ** of code will give us the ability to simulate a disk I/O error. This
  32351. ** is used for testing the I/O recovery logic.
  32352. */
  32353. #ifdef SQLITE_TEST
  32354. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  32355. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  32356. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  32357. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  32358. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  32359. SQLITE_API int sqlite3_diskfull_pending = 0;
  32360. SQLITE_API int sqlite3_diskfull = 0;
  32361. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  32362. #define SimulateIOError(CODE) \
  32363. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  32364. || sqlite3_io_error_pending-- == 1 ) \
  32365. { local_ioerr(); CODE; }
  32366. static void local_ioerr(){
  32367. IOTRACE(("IOERR\n"));
  32368. sqlite3_io_error_hit++;
  32369. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  32370. }
  32371. #define SimulateDiskfullError(CODE) \
  32372. if( sqlite3_diskfull_pending ){ \
  32373. if( sqlite3_diskfull_pending == 1 ){ \
  32374. local_ioerr(); \
  32375. sqlite3_diskfull = 1; \
  32376. sqlite3_io_error_hit = 1; \
  32377. CODE; \
  32378. }else{ \
  32379. sqlite3_diskfull_pending--; \
  32380. } \
  32381. }
  32382. #else
  32383. #define SimulateIOErrorBenign(X)
  32384. #define SimulateIOError(A)
  32385. #define SimulateDiskfullError(A)
  32386. #endif
  32387. /*
  32388. ** When testing, keep a count of the number of open files.
  32389. */
  32390. #ifdef SQLITE_TEST
  32391. SQLITE_API int sqlite3_open_file_count = 0;
  32392. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  32393. #else
  32394. #define OpenCounter(X)
  32395. #endif
  32396. #endif /* !defined(_OS_COMMON_H_) */
  32397. /************** End of os_common.h *******************************************/
  32398. /************** Continuing where we left off in os_win.c *********************/
  32399. /*
  32400. ** Include the header file for the Windows VFS.
  32401. */
  32402. /* #include "os_win.h" */
  32403. /*
  32404. ** Compiling and using WAL mode requires several APIs that are only
  32405. ** available in Windows platforms based on the NT kernel.
  32406. */
  32407. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  32408. # error "WAL mode requires support from the Windows NT kernel, compile\
  32409. with SQLITE_OMIT_WAL."
  32410. #endif
  32411. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  32412. # error "Memory mapped files require support from the Windows NT kernel,\
  32413. compile with SQLITE_MAX_MMAP_SIZE=0."
  32414. #endif
  32415. /*
  32416. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  32417. ** based on the sub-platform)?
  32418. */
  32419. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  32420. # define SQLITE_WIN32_HAS_ANSI
  32421. #endif
  32422. /*
  32423. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  32424. ** based on the sub-platform)?
  32425. */
  32426. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  32427. !defined(SQLITE_WIN32_NO_WIDE)
  32428. # define SQLITE_WIN32_HAS_WIDE
  32429. #endif
  32430. /*
  32431. ** Make sure at least one set of Win32 APIs is available.
  32432. */
  32433. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  32434. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  32435. must be defined."
  32436. #endif
  32437. /*
  32438. ** Define the required Windows SDK version constants if they are not
  32439. ** already available.
  32440. */
  32441. #ifndef NTDDI_WIN8
  32442. # define NTDDI_WIN8 0x06020000
  32443. #endif
  32444. #ifndef NTDDI_WINBLUE
  32445. # define NTDDI_WINBLUE 0x06030000
  32446. #endif
  32447. /*
  32448. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  32449. ** target system. GetVersionEx was first deprecated in Win8.1.
  32450. */
  32451. #ifndef SQLITE_WIN32_GETVERSIONEX
  32452. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  32453. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  32454. # else
  32455. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  32456. # endif
  32457. #endif
  32458. /*
  32459. ** This constant should already be defined (in the "WinDef.h" SDK file).
  32460. */
  32461. #ifndef MAX_PATH
  32462. # define MAX_PATH (260)
  32463. #endif
  32464. /*
  32465. ** Maximum pathname length (in chars) for Win32. This should normally be
  32466. ** MAX_PATH.
  32467. */
  32468. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  32469. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  32470. #endif
  32471. /*
  32472. ** This constant should already be defined (in the "WinNT.h" SDK file).
  32473. */
  32474. #ifndef UNICODE_STRING_MAX_CHARS
  32475. # define UNICODE_STRING_MAX_CHARS (32767)
  32476. #endif
  32477. /*
  32478. ** Maximum pathname length (in chars) for WinNT. This should normally be
  32479. ** UNICODE_STRING_MAX_CHARS.
  32480. */
  32481. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  32482. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  32483. #endif
  32484. /*
  32485. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  32486. ** characters, so we allocate 4 bytes per character assuming worst-case of
  32487. ** 4-bytes-per-character for UTF8.
  32488. */
  32489. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  32490. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  32491. #endif
  32492. /*
  32493. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  32494. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  32495. */
  32496. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  32497. # define SQLITE_WINNT_MAX_PATH_BYTES \
  32498. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  32499. #endif
  32500. /*
  32501. ** Maximum error message length (in chars) for WinRT.
  32502. */
  32503. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  32504. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  32505. #endif
  32506. /*
  32507. ** Returns non-zero if the character should be treated as a directory
  32508. ** separator.
  32509. */
  32510. #ifndef winIsDirSep
  32511. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  32512. #endif
  32513. /*
  32514. ** This macro is used when a local variable is set to a value that is
  32515. ** [sometimes] not used by the code (e.g. via conditional compilation).
  32516. */
  32517. #ifndef UNUSED_VARIABLE_VALUE
  32518. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  32519. #endif
  32520. /*
  32521. ** Returns the character that should be used as the directory separator.
  32522. */
  32523. #ifndef winGetDirSep
  32524. # define winGetDirSep() '\\'
  32525. #endif
  32526. /*
  32527. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  32528. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  32529. ** CE SDK; however, they are not present in the header file)?
  32530. */
  32531. #if SQLITE_WIN32_FILEMAPPING_API && \
  32532. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32533. /*
  32534. ** Two of the file mapping APIs are different under WinRT. Figure out which
  32535. ** set we need.
  32536. */
  32537. #if SQLITE_OS_WINRT
  32538. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  32539. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  32540. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  32541. #else
  32542. #if defined(SQLITE_WIN32_HAS_ANSI)
  32543. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  32544. DWORD, DWORD, DWORD, LPCSTR);
  32545. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  32546. #if defined(SQLITE_WIN32_HAS_WIDE)
  32547. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  32548. DWORD, DWORD, DWORD, LPCWSTR);
  32549. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  32550. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  32551. #endif /* SQLITE_OS_WINRT */
  32552. /*
  32553. ** These file mapping APIs are common to both Win32 and WinRT.
  32554. */
  32555. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  32556. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  32557. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  32558. /*
  32559. ** Some Microsoft compilers lack this definition.
  32560. */
  32561. #ifndef INVALID_FILE_ATTRIBUTES
  32562. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  32563. #endif
  32564. #ifndef FILE_FLAG_MASK
  32565. # define FILE_FLAG_MASK (0xFF3C0000)
  32566. #endif
  32567. #ifndef FILE_ATTRIBUTE_MASK
  32568. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  32569. #endif
  32570. #ifndef SQLITE_OMIT_WAL
  32571. /* Forward references to structures used for WAL */
  32572. typedef struct winShm winShm; /* A connection to shared-memory */
  32573. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  32574. #endif
  32575. /*
  32576. ** WinCE lacks native support for file locking so we have to fake it
  32577. ** with some code of our own.
  32578. */
  32579. #if SQLITE_OS_WINCE
  32580. typedef struct winceLock {
  32581. int nReaders; /* Number of reader locks obtained */
  32582. BOOL bPending; /* Indicates a pending lock has been obtained */
  32583. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  32584. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  32585. } winceLock;
  32586. #endif
  32587. /*
  32588. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  32589. ** portability layer.
  32590. */
  32591. typedef struct winFile winFile;
  32592. struct winFile {
  32593. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  32594. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  32595. HANDLE h; /* Handle for accessing the file */
  32596. u8 locktype; /* Type of lock currently held on this file */
  32597. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  32598. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  32599. DWORD lastErrno; /* The Windows errno from the last I/O error */
  32600. #ifndef SQLITE_OMIT_WAL
  32601. winShm *pShm; /* Instance of shared memory on this file */
  32602. #endif
  32603. const char *zPath; /* Full pathname of this file */
  32604. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  32605. #if SQLITE_OS_WINCE
  32606. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  32607. HANDLE hMutex; /* Mutex used to control access to shared lock */
  32608. HANDLE hShared; /* Shared memory segment used for locking */
  32609. winceLock local; /* Locks obtained by this instance of winFile */
  32610. winceLock *shared; /* Global shared lock memory for the file */
  32611. #endif
  32612. #if SQLITE_MAX_MMAP_SIZE>0
  32613. int nFetchOut; /* Number of outstanding xFetch references */
  32614. HANDLE hMap; /* Handle for accessing memory mapping */
  32615. void *pMapRegion; /* Area memory mapped */
  32616. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  32617. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  32618. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  32619. #endif
  32620. };
  32621. /*
  32622. ** Allowed values for winFile.ctrlFlags
  32623. */
  32624. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  32625. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  32626. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  32627. /*
  32628. * The size of the buffer used by sqlite3_win32_write_debug().
  32629. */
  32630. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  32631. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  32632. #endif
  32633. /*
  32634. * The value used with sqlite3_win32_set_directory() to specify that
  32635. * the data directory should be changed.
  32636. */
  32637. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  32638. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  32639. #endif
  32640. /*
  32641. * The value used with sqlite3_win32_set_directory() to specify that
  32642. * the temporary directory should be changed.
  32643. */
  32644. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  32645. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  32646. #endif
  32647. /*
  32648. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  32649. * various Win32 API heap functions instead of our own.
  32650. */
  32651. #ifdef SQLITE_WIN32_MALLOC
  32652. /*
  32653. * If this is non-zero, an isolated heap will be created by the native Win32
  32654. * allocator subsystem; otherwise, the default process heap will be used. This
  32655. * setting has no effect when compiling for WinRT. By default, this is enabled
  32656. * and an isolated heap will be created to store all allocated data.
  32657. *
  32658. ******************************************************************************
  32659. * WARNING: It is important to note that when this setting is non-zero and the
  32660. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  32661. * function), all data that was allocated using the isolated heap will
  32662. * be freed immediately and any attempt to access any of that freed
  32663. * data will almost certainly result in an immediate access violation.
  32664. ******************************************************************************
  32665. */
  32666. #ifndef SQLITE_WIN32_HEAP_CREATE
  32667. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  32668. #endif
  32669. /*
  32670. * The initial size of the Win32-specific heap. This value may be zero.
  32671. */
  32672. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  32673. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  32674. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  32675. #endif
  32676. /*
  32677. * The maximum size of the Win32-specific heap. This value may be zero.
  32678. */
  32679. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  32680. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  32681. #endif
  32682. /*
  32683. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  32684. * zero for the default behavior.
  32685. */
  32686. #ifndef SQLITE_WIN32_HEAP_FLAGS
  32687. # define SQLITE_WIN32_HEAP_FLAGS (0)
  32688. #endif
  32689. /*
  32690. ** The winMemData structure stores information required by the Win32-specific
  32691. ** sqlite3_mem_methods implementation.
  32692. */
  32693. typedef struct winMemData winMemData;
  32694. struct winMemData {
  32695. #ifndef NDEBUG
  32696. u32 magic1; /* Magic number to detect structure corruption. */
  32697. #endif
  32698. HANDLE hHeap; /* The handle to our heap. */
  32699. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  32700. #ifndef NDEBUG
  32701. u32 magic2; /* Magic number to detect structure corruption. */
  32702. #endif
  32703. };
  32704. #ifndef NDEBUG
  32705. #define WINMEM_MAGIC1 0x42b2830b
  32706. #define WINMEM_MAGIC2 0xbd4d7cf4
  32707. #endif
  32708. static struct winMemData win_mem_data = {
  32709. #ifndef NDEBUG
  32710. WINMEM_MAGIC1,
  32711. #endif
  32712. NULL, FALSE
  32713. #ifndef NDEBUG
  32714. ,WINMEM_MAGIC2
  32715. #endif
  32716. };
  32717. #ifndef NDEBUG
  32718. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  32719. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  32720. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  32721. #else
  32722. #define winMemAssertMagic()
  32723. #endif
  32724. #define winMemGetDataPtr() &win_mem_data
  32725. #define winMemGetHeap() win_mem_data.hHeap
  32726. #define winMemGetOwned() win_mem_data.bOwned
  32727. static void *winMemMalloc(int nBytes);
  32728. static void winMemFree(void *pPrior);
  32729. static void *winMemRealloc(void *pPrior, int nBytes);
  32730. static int winMemSize(void *p);
  32731. static int winMemRoundup(int n);
  32732. static int winMemInit(void *pAppData);
  32733. static void winMemShutdown(void *pAppData);
  32734. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  32735. #endif /* SQLITE_WIN32_MALLOC */
  32736. /*
  32737. ** The following variable is (normally) set once and never changes
  32738. ** thereafter. It records whether the operating system is Win9x
  32739. ** or WinNT.
  32740. **
  32741. ** 0: Operating system unknown.
  32742. ** 1: Operating system is Win9x.
  32743. ** 2: Operating system is WinNT.
  32744. **
  32745. ** In order to facilitate testing on a WinNT system, the test fixture
  32746. ** can manually set this value to 1 to emulate Win98 behavior.
  32747. */
  32748. #ifdef SQLITE_TEST
  32749. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  32750. #else
  32751. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  32752. #endif
  32753. #ifndef SYSCALL
  32754. # define SYSCALL sqlite3_syscall_ptr
  32755. #endif
  32756. /*
  32757. ** This function is not available on Windows CE or WinRT.
  32758. */
  32759. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  32760. # define osAreFileApisANSI() 1
  32761. #endif
  32762. /*
  32763. ** Many system calls are accessed through pointer-to-functions so that
  32764. ** they may be overridden at runtime to facilitate fault injection during
  32765. ** testing and sandboxing. The following array holds the names and pointers
  32766. ** to all overrideable system calls.
  32767. */
  32768. static struct win_syscall {
  32769. const char *zName; /* Name of the system call */
  32770. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  32771. sqlite3_syscall_ptr pDefault; /* Default value */
  32772. } aSyscall[] = {
  32773. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32774. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  32775. #else
  32776. { "AreFileApisANSI", (SYSCALL)0, 0 },
  32777. #endif
  32778. #ifndef osAreFileApisANSI
  32779. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  32780. #endif
  32781. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  32782. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  32783. #else
  32784. { "CharLowerW", (SYSCALL)0, 0 },
  32785. #endif
  32786. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  32787. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  32788. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  32789. #else
  32790. { "CharUpperW", (SYSCALL)0, 0 },
  32791. #endif
  32792. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  32793. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  32794. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  32795. #if defined(SQLITE_WIN32_HAS_ANSI)
  32796. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  32797. #else
  32798. { "CreateFileA", (SYSCALL)0, 0 },
  32799. #endif
  32800. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  32801. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  32802. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32803. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  32804. #else
  32805. { "CreateFileW", (SYSCALL)0, 0 },
  32806. #endif
  32807. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  32808. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  32809. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  32810. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  32811. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  32812. #else
  32813. { "CreateFileMappingA", (SYSCALL)0, 0 },
  32814. #endif
  32815. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  32816. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  32817. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  32818. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  32819. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  32820. #else
  32821. { "CreateFileMappingW", (SYSCALL)0, 0 },
  32822. #endif
  32823. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  32824. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  32825. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32826. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  32827. #else
  32828. { "CreateMutexW", (SYSCALL)0, 0 },
  32829. #endif
  32830. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  32831. LPCWSTR))aSyscall[8].pCurrent)
  32832. #if defined(SQLITE_WIN32_HAS_ANSI)
  32833. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  32834. #else
  32835. { "DeleteFileA", (SYSCALL)0, 0 },
  32836. #endif
  32837. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  32838. #if defined(SQLITE_WIN32_HAS_WIDE)
  32839. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  32840. #else
  32841. { "DeleteFileW", (SYSCALL)0, 0 },
  32842. #endif
  32843. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  32844. #if SQLITE_OS_WINCE
  32845. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  32846. #else
  32847. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  32848. #endif
  32849. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  32850. LPFILETIME))aSyscall[11].pCurrent)
  32851. #if SQLITE_OS_WINCE
  32852. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  32853. #else
  32854. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  32855. #endif
  32856. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  32857. LPSYSTEMTIME))aSyscall[12].pCurrent)
  32858. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  32859. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  32860. #if defined(SQLITE_WIN32_HAS_ANSI)
  32861. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  32862. #else
  32863. { "FormatMessageA", (SYSCALL)0, 0 },
  32864. #endif
  32865. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  32866. DWORD,va_list*))aSyscall[14].pCurrent)
  32867. #if defined(SQLITE_WIN32_HAS_WIDE)
  32868. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  32869. #else
  32870. { "FormatMessageW", (SYSCALL)0, 0 },
  32871. #endif
  32872. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  32873. DWORD,va_list*))aSyscall[15].pCurrent)
  32874. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32875. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  32876. #else
  32877. { "FreeLibrary", (SYSCALL)0, 0 },
  32878. #endif
  32879. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  32880. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  32881. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  32882. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  32883. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  32884. #else
  32885. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  32886. #endif
  32887. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  32888. LPDWORD))aSyscall[18].pCurrent)
  32889. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32890. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  32891. #else
  32892. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  32893. #endif
  32894. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  32895. LPDWORD))aSyscall[19].pCurrent)
  32896. #if defined(SQLITE_WIN32_HAS_ANSI)
  32897. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  32898. #else
  32899. { "GetFileAttributesA", (SYSCALL)0, 0 },
  32900. #endif
  32901. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  32902. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32903. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  32904. #else
  32905. { "GetFileAttributesW", (SYSCALL)0, 0 },
  32906. #endif
  32907. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  32908. #if defined(SQLITE_WIN32_HAS_WIDE)
  32909. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  32910. #else
  32911. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  32912. #endif
  32913. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  32914. LPVOID))aSyscall[22].pCurrent)
  32915. #if !SQLITE_OS_WINRT
  32916. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  32917. #else
  32918. { "GetFileSize", (SYSCALL)0, 0 },
  32919. #endif
  32920. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  32921. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  32922. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  32923. #else
  32924. { "GetFullPathNameA", (SYSCALL)0, 0 },
  32925. #endif
  32926. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  32927. LPSTR*))aSyscall[24].pCurrent)
  32928. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32929. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  32930. #else
  32931. { "GetFullPathNameW", (SYSCALL)0, 0 },
  32932. #endif
  32933. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  32934. LPWSTR*))aSyscall[25].pCurrent)
  32935. { "GetLastError", (SYSCALL)GetLastError, 0 },
  32936. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  32937. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32938. #if SQLITE_OS_WINCE
  32939. /* The GetProcAddressA() routine is only available on Windows CE. */
  32940. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  32941. #else
  32942. /* All other Windows platforms expect GetProcAddress() to take
  32943. ** an ANSI string regardless of the _UNICODE setting */
  32944. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  32945. #endif
  32946. #else
  32947. { "GetProcAddressA", (SYSCALL)0, 0 },
  32948. #endif
  32949. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  32950. LPCSTR))aSyscall[27].pCurrent)
  32951. #if !SQLITE_OS_WINRT
  32952. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  32953. #else
  32954. { "GetSystemInfo", (SYSCALL)0, 0 },
  32955. #endif
  32956. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  32957. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  32958. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  32959. #if !SQLITE_OS_WINCE
  32960. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  32961. #else
  32962. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  32963. #endif
  32964. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  32965. LPFILETIME))aSyscall[30].pCurrent)
  32966. #if defined(SQLITE_WIN32_HAS_ANSI)
  32967. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  32968. #else
  32969. { "GetTempPathA", (SYSCALL)0, 0 },
  32970. #endif
  32971. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  32972. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32973. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  32974. #else
  32975. { "GetTempPathW", (SYSCALL)0, 0 },
  32976. #endif
  32977. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  32978. #if !SQLITE_OS_WINRT
  32979. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  32980. #else
  32981. { "GetTickCount", (SYSCALL)0, 0 },
  32982. #endif
  32983. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  32984. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  32985. SQLITE_WIN32_GETVERSIONEX
  32986. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  32987. #else
  32988. { "GetVersionExA", (SYSCALL)0, 0 },
  32989. #endif
  32990. #define osGetVersionExA ((BOOL(WINAPI*)( \
  32991. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  32992. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  32993. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  32994. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  32995. #else
  32996. { "GetVersionExW", (SYSCALL)0, 0 },
  32997. #endif
  32998. #define osGetVersionExW ((BOOL(WINAPI*)( \
  32999. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  33000. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  33001. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  33002. SIZE_T))aSyscall[36].pCurrent)
  33003. #if !SQLITE_OS_WINRT
  33004. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  33005. #else
  33006. { "HeapCreate", (SYSCALL)0, 0 },
  33007. #endif
  33008. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  33009. SIZE_T))aSyscall[37].pCurrent)
  33010. #if !SQLITE_OS_WINRT
  33011. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  33012. #else
  33013. { "HeapDestroy", (SYSCALL)0, 0 },
  33014. #endif
  33015. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  33016. { "HeapFree", (SYSCALL)HeapFree, 0 },
  33017. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  33018. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  33019. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  33020. SIZE_T))aSyscall[40].pCurrent)
  33021. { "HeapSize", (SYSCALL)HeapSize, 0 },
  33022. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  33023. LPCVOID))aSyscall[41].pCurrent)
  33024. #if !SQLITE_OS_WINRT
  33025. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  33026. #else
  33027. { "HeapValidate", (SYSCALL)0, 0 },
  33028. #endif
  33029. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  33030. LPCVOID))aSyscall[42].pCurrent)
  33031. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33032. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  33033. #else
  33034. { "HeapCompact", (SYSCALL)0, 0 },
  33035. #endif
  33036. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  33037. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33038. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  33039. #else
  33040. { "LoadLibraryA", (SYSCALL)0, 0 },
  33041. #endif
  33042. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  33043. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33044. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33045. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  33046. #else
  33047. { "LoadLibraryW", (SYSCALL)0, 0 },
  33048. #endif
  33049. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  33050. #if !SQLITE_OS_WINRT
  33051. { "LocalFree", (SYSCALL)LocalFree, 0 },
  33052. #else
  33053. { "LocalFree", (SYSCALL)0, 0 },
  33054. #endif
  33055. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  33056. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33057. { "LockFile", (SYSCALL)LockFile, 0 },
  33058. #else
  33059. { "LockFile", (SYSCALL)0, 0 },
  33060. #endif
  33061. #ifndef osLockFile
  33062. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33063. DWORD))aSyscall[47].pCurrent)
  33064. #endif
  33065. #if !SQLITE_OS_WINCE
  33066. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  33067. #else
  33068. { "LockFileEx", (SYSCALL)0, 0 },
  33069. #endif
  33070. #ifndef osLockFileEx
  33071. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  33072. LPOVERLAPPED))aSyscall[48].pCurrent)
  33073. #endif
  33074. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  33075. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33076. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  33077. #else
  33078. { "MapViewOfFile", (SYSCALL)0, 0 },
  33079. #endif
  33080. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33081. SIZE_T))aSyscall[49].pCurrent)
  33082. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  33083. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  33084. int))aSyscall[50].pCurrent)
  33085. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  33086. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  33087. LARGE_INTEGER*))aSyscall[51].pCurrent)
  33088. { "ReadFile", (SYSCALL)ReadFile, 0 },
  33089. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  33090. LPOVERLAPPED))aSyscall[52].pCurrent)
  33091. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  33092. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  33093. #if !SQLITE_OS_WINRT
  33094. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  33095. #else
  33096. { "SetFilePointer", (SYSCALL)0, 0 },
  33097. #endif
  33098. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  33099. DWORD))aSyscall[54].pCurrent)
  33100. #if !SQLITE_OS_WINRT
  33101. { "Sleep", (SYSCALL)Sleep, 0 },
  33102. #else
  33103. { "Sleep", (SYSCALL)0, 0 },
  33104. #endif
  33105. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  33106. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  33107. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  33108. LPFILETIME))aSyscall[56].pCurrent)
  33109. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33110. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  33111. #else
  33112. { "UnlockFile", (SYSCALL)0, 0 },
  33113. #endif
  33114. #ifndef osUnlockFile
  33115. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33116. DWORD))aSyscall[57].pCurrent)
  33117. #endif
  33118. #if !SQLITE_OS_WINCE
  33119. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  33120. #else
  33121. { "UnlockFileEx", (SYSCALL)0, 0 },
  33122. #endif
  33123. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33124. LPOVERLAPPED))aSyscall[58].pCurrent)
  33125. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  33126. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  33127. #else
  33128. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  33129. #endif
  33130. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  33131. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  33132. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  33133. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  33134. { "WriteFile", (SYSCALL)WriteFile, 0 },
  33135. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  33136. LPOVERLAPPED))aSyscall[61].pCurrent)
  33137. #if SQLITE_OS_WINRT
  33138. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  33139. #else
  33140. { "CreateEventExW", (SYSCALL)0, 0 },
  33141. #endif
  33142. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  33143. DWORD,DWORD))aSyscall[62].pCurrent)
  33144. #if !SQLITE_OS_WINRT
  33145. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  33146. #else
  33147. { "WaitForSingleObject", (SYSCALL)0, 0 },
  33148. #endif
  33149. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  33150. DWORD))aSyscall[63].pCurrent)
  33151. #if !SQLITE_OS_WINCE
  33152. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  33153. #else
  33154. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  33155. #endif
  33156. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  33157. BOOL))aSyscall[64].pCurrent)
  33158. #if SQLITE_OS_WINRT
  33159. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  33160. #else
  33161. { "SetFilePointerEx", (SYSCALL)0, 0 },
  33162. #endif
  33163. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  33164. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  33165. #if SQLITE_OS_WINRT
  33166. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  33167. #else
  33168. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  33169. #endif
  33170. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  33171. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  33172. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  33173. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  33174. #else
  33175. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  33176. #endif
  33177. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  33178. SIZE_T))aSyscall[67].pCurrent)
  33179. #if SQLITE_OS_WINRT
  33180. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  33181. #else
  33182. { "CreateFile2", (SYSCALL)0, 0 },
  33183. #endif
  33184. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  33185. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  33186. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33187. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  33188. #else
  33189. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  33190. #endif
  33191. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  33192. DWORD))aSyscall[69].pCurrent)
  33193. #if SQLITE_OS_WINRT
  33194. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  33195. #else
  33196. { "GetTickCount64", (SYSCALL)0, 0 },
  33197. #endif
  33198. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  33199. #if SQLITE_OS_WINRT
  33200. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  33201. #else
  33202. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  33203. #endif
  33204. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  33205. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  33206. #if defined(SQLITE_WIN32_HAS_ANSI)
  33207. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  33208. #else
  33209. { "OutputDebugStringA", (SYSCALL)0, 0 },
  33210. #endif
  33211. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  33212. #if defined(SQLITE_WIN32_HAS_WIDE)
  33213. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  33214. #else
  33215. { "OutputDebugStringW", (SYSCALL)0, 0 },
  33216. #endif
  33217. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  33218. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  33219. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  33220. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  33221. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  33222. #else
  33223. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  33224. #endif
  33225. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  33226. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  33227. /*
  33228. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  33229. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  33230. ** So do not try to make this is into a redefinable interface.
  33231. */
  33232. #if defined(InterlockedCompareExchange)
  33233. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  33234. #define osInterlockedCompareExchange InterlockedCompareExchange
  33235. #else
  33236. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  33237. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  33238. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  33239. #endif /* defined(InterlockedCompareExchange) */
  33240. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  33241. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  33242. #else
  33243. { "UuidCreate", (SYSCALL)0, 0 },
  33244. #endif
  33245. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  33246. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  33247. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  33248. #else
  33249. { "UuidCreateSequential", (SYSCALL)0, 0 },
  33250. #endif
  33251. #define osUuidCreateSequential \
  33252. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  33253. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  33254. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  33255. #else
  33256. { "FlushViewOfFile", (SYSCALL)0, 0 },
  33257. #endif
  33258. #define osFlushViewOfFile \
  33259. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  33260. }; /* End of the overrideable system calls */
  33261. /*
  33262. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  33263. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  33264. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  33265. ** system call named zName.
  33266. */
  33267. static int winSetSystemCall(
  33268. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  33269. const char *zName, /* Name of system call to override */
  33270. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  33271. ){
  33272. unsigned int i;
  33273. int rc = SQLITE_NOTFOUND;
  33274. UNUSED_PARAMETER(pNotUsed);
  33275. if( zName==0 ){
  33276. /* If no zName is given, restore all system calls to their default
  33277. ** settings and return NULL
  33278. */
  33279. rc = SQLITE_OK;
  33280. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33281. if( aSyscall[i].pDefault ){
  33282. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  33283. }
  33284. }
  33285. }else{
  33286. /* If zName is specified, operate on only the one system call
  33287. ** specified.
  33288. */
  33289. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33290. if( strcmp(zName, aSyscall[i].zName)==0 ){
  33291. if( aSyscall[i].pDefault==0 ){
  33292. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  33293. }
  33294. rc = SQLITE_OK;
  33295. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  33296. aSyscall[i].pCurrent = pNewFunc;
  33297. break;
  33298. }
  33299. }
  33300. }
  33301. return rc;
  33302. }
  33303. /*
  33304. ** Return the value of a system call. Return NULL if zName is not a
  33305. ** recognized system call name. NULL is also returned if the system call
  33306. ** is currently undefined.
  33307. */
  33308. static sqlite3_syscall_ptr winGetSystemCall(
  33309. sqlite3_vfs *pNotUsed,
  33310. const char *zName
  33311. ){
  33312. unsigned int i;
  33313. UNUSED_PARAMETER(pNotUsed);
  33314. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33315. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  33316. }
  33317. return 0;
  33318. }
  33319. /*
  33320. ** Return the name of the first system call after zName. If zName==NULL
  33321. ** then return the name of the first system call. Return NULL if zName
  33322. ** is the last system call or if zName is not the name of a valid
  33323. ** system call.
  33324. */
  33325. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  33326. int i = -1;
  33327. UNUSED_PARAMETER(p);
  33328. if( zName ){
  33329. for(i=0; i<ArraySize(aSyscall)-1; i++){
  33330. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  33331. }
  33332. }
  33333. for(i++; i<ArraySize(aSyscall); i++){
  33334. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  33335. }
  33336. return 0;
  33337. }
  33338. #ifdef SQLITE_WIN32_MALLOC
  33339. /*
  33340. ** If a Win32 native heap has been configured, this function will attempt to
  33341. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  33342. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  33343. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  33344. ** largest committed free block in the heap, in bytes.
  33345. */
  33346. SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
  33347. int rc = SQLITE_OK;
  33348. UINT nLargest = 0;
  33349. HANDLE hHeap;
  33350. winMemAssertMagic();
  33351. hHeap = winMemGetHeap();
  33352. assert( hHeap!=0 );
  33353. assert( hHeap!=INVALID_HANDLE_VALUE );
  33354. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33355. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33356. #endif
  33357. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33358. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  33359. DWORD lastErrno = osGetLastError();
  33360. if( lastErrno==NO_ERROR ){
  33361. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  33362. (void*)hHeap);
  33363. rc = SQLITE_NOMEM;
  33364. }else{
  33365. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  33366. osGetLastError(), (void*)hHeap);
  33367. rc = SQLITE_ERROR;
  33368. }
  33369. }
  33370. #else
  33371. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  33372. (void*)hHeap);
  33373. rc = SQLITE_NOTFOUND;
  33374. #endif
  33375. if( pnLargest ) *pnLargest = nLargest;
  33376. return rc;
  33377. }
  33378. /*
  33379. ** If a Win32 native heap has been configured, this function will attempt to
  33380. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  33381. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  33382. ** be returned and no changes will be made to the Win32 native heap.
  33383. */
  33384. SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
  33385. int rc;
  33386. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  33387. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  33388. MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
  33389. MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
  33390. sqlite3_mutex_enter(pMaster);
  33391. sqlite3_mutex_enter(pMem);
  33392. winMemAssertMagic();
  33393. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  33394. /*
  33395. ** At this point, there should be no outstanding memory allocations on
  33396. ** the heap. Also, since both the master and memsys locks are currently
  33397. ** being held by us, no other function (i.e. from another thread) should
  33398. ** be able to even access the heap. Attempt to destroy and recreate our
  33399. ** isolated Win32 native heap now.
  33400. */
  33401. assert( winMemGetHeap()!=NULL );
  33402. assert( winMemGetOwned() );
  33403. assert( sqlite3_memory_used()==0 );
  33404. winMemShutdown(winMemGetDataPtr());
  33405. assert( winMemGetHeap()==NULL );
  33406. assert( !winMemGetOwned() );
  33407. assert( sqlite3_memory_used()==0 );
  33408. rc = winMemInit(winMemGetDataPtr());
  33409. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  33410. assert( rc!=SQLITE_OK || winMemGetOwned() );
  33411. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  33412. }else{
  33413. /*
  33414. ** The Win32 native heap cannot be modified because it may be in use.
  33415. */
  33416. rc = SQLITE_BUSY;
  33417. }
  33418. sqlite3_mutex_leave(pMem);
  33419. sqlite3_mutex_leave(pMaster);
  33420. return rc;
  33421. }
  33422. #endif /* SQLITE_WIN32_MALLOC */
  33423. /*
  33424. ** This function outputs the specified (ANSI) string to the Win32 debugger
  33425. ** (if available).
  33426. */
  33427. SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  33428. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  33429. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  33430. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  33431. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  33432. #if defined(SQLITE_WIN32_HAS_ANSI)
  33433. if( nMin>0 ){
  33434. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33435. memcpy(zDbgBuf, zBuf, nMin);
  33436. osOutputDebugStringA(zDbgBuf);
  33437. }else{
  33438. osOutputDebugStringA(zBuf);
  33439. }
  33440. #elif defined(SQLITE_WIN32_HAS_WIDE)
  33441. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33442. if ( osMultiByteToWideChar(
  33443. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  33444. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  33445. return;
  33446. }
  33447. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  33448. #else
  33449. if( nMin>0 ){
  33450. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33451. memcpy(zDbgBuf, zBuf, nMin);
  33452. fprintf(stderr, "%s", zDbgBuf);
  33453. }else{
  33454. fprintf(stderr, "%s", zBuf);
  33455. }
  33456. #endif
  33457. }
  33458. /*
  33459. ** The following routine suspends the current thread for at least ms
  33460. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  33461. */
  33462. #if SQLITE_OS_WINRT
  33463. static HANDLE sleepObj = NULL;
  33464. #endif
  33465. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
  33466. #if SQLITE_OS_WINRT
  33467. if ( sleepObj==NULL ){
  33468. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  33469. SYNCHRONIZE);
  33470. }
  33471. assert( sleepObj!=NULL );
  33472. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  33473. #else
  33474. osSleep(milliseconds);
  33475. #endif
  33476. }
  33477. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  33478. SQLITE_THREADSAFE>0
  33479. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  33480. DWORD rc;
  33481. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  33482. TRUE))==WAIT_IO_COMPLETION ){}
  33483. return rc;
  33484. }
  33485. #endif
  33486. /*
  33487. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  33488. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  33489. **
  33490. ** Here is an interesting observation: Win95, Win98, and WinME lack
  33491. ** the LockFileEx() API. But we can still statically link against that
  33492. ** API as long as we don't call it when running Win95/98/ME. A call to
  33493. ** this routine is used to determine if the host is Win95/98/ME or
  33494. ** WinNT/2K/XP so that we will know whether or not we can safely call
  33495. ** the LockFileEx() API.
  33496. */
  33497. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  33498. # define osIsNT() (1)
  33499. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  33500. # define osIsNT() (1)
  33501. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  33502. # define osIsNT() (0)
  33503. #else
  33504. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  33505. #endif
  33506. /*
  33507. ** This function determines if the machine is running a version of Windows
  33508. ** based on the NT kernel.
  33509. */
  33510. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
  33511. #if SQLITE_OS_WINRT
  33512. /*
  33513. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  33514. ** kernel.
  33515. */
  33516. return 1;
  33517. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  33518. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  33519. #if defined(SQLITE_WIN32_HAS_ANSI)
  33520. OSVERSIONINFOA sInfo;
  33521. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  33522. osGetVersionExA(&sInfo);
  33523. osInterlockedCompareExchange(&sqlite3_os_type,
  33524. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  33525. #elif defined(SQLITE_WIN32_HAS_WIDE)
  33526. OSVERSIONINFOW sInfo;
  33527. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  33528. osGetVersionExW(&sInfo);
  33529. osInterlockedCompareExchange(&sqlite3_os_type,
  33530. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  33531. #endif
  33532. }
  33533. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  33534. #elif SQLITE_TEST
  33535. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  33536. #else
  33537. /*
  33538. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  33539. ** deprecated are always assumed to be based on the NT kernel.
  33540. */
  33541. return 1;
  33542. #endif
  33543. }
  33544. #ifdef SQLITE_WIN32_MALLOC
  33545. /*
  33546. ** Allocate nBytes of memory.
  33547. */
  33548. static void *winMemMalloc(int nBytes){
  33549. HANDLE hHeap;
  33550. void *p;
  33551. winMemAssertMagic();
  33552. hHeap = winMemGetHeap();
  33553. assert( hHeap!=0 );
  33554. assert( hHeap!=INVALID_HANDLE_VALUE );
  33555. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33556. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33557. #endif
  33558. assert( nBytes>=0 );
  33559. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  33560. if( !p ){
  33561. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  33562. nBytes, osGetLastError(), (void*)hHeap);
  33563. }
  33564. return p;
  33565. }
  33566. /*
  33567. ** Free memory.
  33568. */
  33569. static void winMemFree(void *pPrior){
  33570. HANDLE hHeap;
  33571. winMemAssertMagic();
  33572. hHeap = winMemGetHeap();
  33573. assert( hHeap!=0 );
  33574. assert( hHeap!=INVALID_HANDLE_VALUE );
  33575. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33576. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  33577. #endif
  33578. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  33579. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  33580. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  33581. pPrior, osGetLastError(), (void*)hHeap);
  33582. }
  33583. }
  33584. /*
  33585. ** Change the size of an existing memory allocation
  33586. */
  33587. static void *winMemRealloc(void *pPrior, int nBytes){
  33588. HANDLE hHeap;
  33589. void *p;
  33590. winMemAssertMagic();
  33591. hHeap = winMemGetHeap();
  33592. assert( hHeap!=0 );
  33593. assert( hHeap!=INVALID_HANDLE_VALUE );
  33594. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33595. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  33596. #endif
  33597. assert( nBytes>=0 );
  33598. if( !pPrior ){
  33599. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  33600. }else{
  33601. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  33602. }
  33603. if( !p ){
  33604. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  33605. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  33606. (void*)hHeap);
  33607. }
  33608. return p;
  33609. }
  33610. /*
  33611. ** Return the size of an outstanding allocation, in bytes.
  33612. */
  33613. static int winMemSize(void *p){
  33614. HANDLE hHeap;
  33615. SIZE_T n;
  33616. winMemAssertMagic();
  33617. hHeap = winMemGetHeap();
  33618. assert( hHeap!=0 );
  33619. assert( hHeap!=INVALID_HANDLE_VALUE );
  33620. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33621. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  33622. #endif
  33623. if( !p ) return 0;
  33624. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  33625. if( n==(SIZE_T)-1 ){
  33626. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  33627. p, osGetLastError(), (void*)hHeap);
  33628. return 0;
  33629. }
  33630. return (int)n;
  33631. }
  33632. /*
  33633. ** Round up a request size to the next valid allocation size.
  33634. */
  33635. static int winMemRoundup(int n){
  33636. return n;
  33637. }
  33638. /*
  33639. ** Initialize this module.
  33640. */
  33641. static int winMemInit(void *pAppData){
  33642. winMemData *pWinMemData = (winMemData *)pAppData;
  33643. if( !pWinMemData ) return SQLITE_ERROR;
  33644. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  33645. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  33646. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  33647. if( !pWinMemData->hHeap ){
  33648. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  33649. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  33650. if( dwMaximumSize==0 ){
  33651. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  33652. }else if( dwInitialSize>dwMaximumSize ){
  33653. dwInitialSize = dwMaximumSize;
  33654. }
  33655. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  33656. dwInitialSize, dwMaximumSize);
  33657. if( !pWinMemData->hHeap ){
  33658. sqlite3_log(SQLITE_NOMEM,
  33659. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  33660. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  33661. dwMaximumSize);
  33662. return SQLITE_NOMEM;
  33663. }
  33664. pWinMemData->bOwned = TRUE;
  33665. assert( pWinMemData->bOwned );
  33666. }
  33667. #else
  33668. pWinMemData->hHeap = osGetProcessHeap();
  33669. if( !pWinMemData->hHeap ){
  33670. sqlite3_log(SQLITE_NOMEM,
  33671. "failed to GetProcessHeap (%lu)", osGetLastError());
  33672. return SQLITE_NOMEM;
  33673. }
  33674. pWinMemData->bOwned = FALSE;
  33675. assert( !pWinMemData->bOwned );
  33676. #endif
  33677. assert( pWinMemData->hHeap!=0 );
  33678. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  33679. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33680. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33681. #endif
  33682. return SQLITE_OK;
  33683. }
  33684. /*
  33685. ** Deinitialize this module.
  33686. */
  33687. static void winMemShutdown(void *pAppData){
  33688. winMemData *pWinMemData = (winMemData *)pAppData;
  33689. if( !pWinMemData ) return;
  33690. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  33691. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  33692. if( pWinMemData->hHeap ){
  33693. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  33694. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33695. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33696. #endif
  33697. if( pWinMemData->bOwned ){
  33698. if( !osHeapDestroy(pWinMemData->hHeap) ){
  33699. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  33700. osGetLastError(), (void*)pWinMemData->hHeap);
  33701. }
  33702. pWinMemData->bOwned = FALSE;
  33703. }
  33704. pWinMemData->hHeap = NULL;
  33705. }
  33706. }
  33707. /*
  33708. ** Populate the low-level memory allocation function pointers in
  33709. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  33710. ** arguments specify the block of memory to manage.
  33711. **
  33712. ** This routine is only called by sqlite3_config(), and therefore
  33713. ** is not required to be threadsafe (it is not).
  33714. */
  33715. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  33716. static const sqlite3_mem_methods winMemMethods = {
  33717. winMemMalloc,
  33718. winMemFree,
  33719. winMemRealloc,
  33720. winMemSize,
  33721. winMemRoundup,
  33722. winMemInit,
  33723. winMemShutdown,
  33724. &win_mem_data
  33725. };
  33726. return &winMemMethods;
  33727. }
  33728. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  33729. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  33730. }
  33731. #endif /* SQLITE_WIN32_MALLOC */
  33732. /*
  33733. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  33734. **
  33735. ** Space to hold the returned string is obtained from malloc.
  33736. */
  33737. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  33738. int nChar;
  33739. LPWSTR zWideFilename;
  33740. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  33741. if( nChar==0 ){
  33742. return 0;
  33743. }
  33744. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  33745. if( zWideFilename==0 ){
  33746. return 0;
  33747. }
  33748. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  33749. nChar);
  33750. if( nChar==0 ){
  33751. sqlite3_free(zWideFilename);
  33752. zWideFilename = 0;
  33753. }
  33754. return zWideFilename;
  33755. }
  33756. /*
  33757. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  33758. ** obtained from sqlite3_malloc().
  33759. */
  33760. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  33761. int nByte;
  33762. char *zFilename;
  33763. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  33764. if( nByte == 0 ){
  33765. return 0;
  33766. }
  33767. zFilename = sqlite3MallocZero( nByte );
  33768. if( zFilename==0 ){
  33769. return 0;
  33770. }
  33771. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  33772. 0, 0);
  33773. if( nByte == 0 ){
  33774. sqlite3_free(zFilename);
  33775. zFilename = 0;
  33776. }
  33777. return zFilename;
  33778. }
  33779. /*
  33780. ** Convert an ANSI string to Microsoft Unicode, based on the
  33781. ** current codepage settings for file apis.
  33782. **
  33783. ** Space to hold the returned string is obtained
  33784. ** from sqlite3_malloc.
  33785. */
  33786. static LPWSTR winMbcsToUnicode(const char *zFilename){
  33787. int nByte;
  33788. LPWSTR zMbcsFilename;
  33789. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  33790. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  33791. 0)*sizeof(WCHAR);
  33792. if( nByte==0 ){
  33793. return 0;
  33794. }
  33795. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  33796. if( zMbcsFilename==0 ){
  33797. return 0;
  33798. }
  33799. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  33800. nByte);
  33801. if( nByte==0 ){
  33802. sqlite3_free(zMbcsFilename);
  33803. zMbcsFilename = 0;
  33804. }
  33805. return zMbcsFilename;
  33806. }
  33807. /*
  33808. ** Convert Microsoft Unicode to multi-byte character string, based on the
  33809. ** user's ANSI codepage.
  33810. **
  33811. ** Space to hold the returned string is obtained from
  33812. ** sqlite3_malloc().
  33813. */
  33814. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  33815. int nByte;
  33816. char *zFilename;
  33817. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  33818. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  33819. if( nByte == 0 ){
  33820. return 0;
  33821. }
  33822. zFilename = sqlite3MallocZero( nByte );
  33823. if( zFilename==0 ){
  33824. return 0;
  33825. }
  33826. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  33827. nByte, 0, 0);
  33828. if( nByte == 0 ){
  33829. sqlite3_free(zFilename);
  33830. zFilename = 0;
  33831. }
  33832. return zFilename;
  33833. }
  33834. /*
  33835. ** Convert multibyte character string to UTF-8. Space to hold the
  33836. ** returned string is obtained from sqlite3_malloc().
  33837. */
  33838. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  33839. char *zFilenameUtf8;
  33840. LPWSTR zTmpWide;
  33841. zTmpWide = winMbcsToUnicode(zFilename);
  33842. if( zTmpWide==0 ){
  33843. return 0;
  33844. }
  33845. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  33846. sqlite3_free(zTmpWide);
  33847. return zFilenameUtf8;
  33848. }
  33849. /*
  33850. ** Convert UTF-8 to multibyte character string. Space to hold the
  33851. ** returned string is obtained from sqlite3_malloc().
  33852. */
  33853. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  33854. char *zFilenameMbcs;
  33855. LPWSTR zTmpWide;
  33856. zTmpWide = winUtf8ToUnicode(zFilename);
  33857. if( zTmpWide==0 ){
  33858. return 0;
  33859. }
  33860. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  33861. sqlite3_free(zTmpWide);
  33862. return zFilenameMbcs;
  33863. }
  33864. /*
  33865. ** This function sets the data directory or the temporary directory based on
  33866. ** the provided arguments. The type argument must be 1 in order to set the
  33867. ** data directory or 2 in order to set the temporary directory. The zValue
  33868. ** argument is the name of the directory to use. The return value will be
  33869. ** SQLITE_OK if successful.
  33870. */
  33871. SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  33872. char **ppDirectory = 0;
  33873. #ifndef SQLITE_OMIT_AUTOINIT
  33874. int rc = sqlite3_initialize();
  33875. if( rc ) return rc;
  33876. #endif
  33877. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  33878. ppDirectory = &sqlite3_data_directory;
  33879. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  33880. ppDirectory = &sqlite3_temp_directory;
  33881. }
  33882. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  33883. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  33884. );
  33885. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  33886. if( ppDirectory ){
  33887. char *zValueUtf8 = 0;
  33888. if( zValue && zValue[0] ){
  33889. zValueUtf8 = winUnicodeToUtf8(zValue);
  33890. if ( zValueUtf8==0 ){
  33891. return SQLITE_NOMEM;
  33892. }
  33893. }
  33894. sqlite3_free(*ppDirectory);
  33895. *ppDirectory = zValueUtf8;
  33896. return SQLITE_OK;
  33897. }
  33898. return SQLITE_ERROR;
  33899. }
  33900. /*
  33901. ** The return value of winGetLastErrorMsg
  33902. ** is zero if the error message fits in the buffer, or non-zero
  33903. ** otherwise (if the message was truncated).
  33904. */
  33905. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  33906. /* FormatMessage returns 0 on failure. Otherwise it
  33907. ** returns the number of TCHARs written to the output
  33908. ** buffer, excluding the terminating null char.
  33909. */
  33910. DWORD dwLen = 0;
  33911. char *zOut = 0;
  33912. if( osIsNT() ){
  33913. #if SQLITE_OS_WINRT
  33914. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  33915. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  33916. FORMAT_MESSAGE_IGNORE_INSERTS,
  33917. NULL,
  33918. lastErrno,
  33919. 0,
  33920. zTempWide,
  33921. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  33922. 0);
  33923. #else
  33924. LPWSTR zTempWide = NULL;
  33925. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  33926. FORMAT_MESSAGE_FROM_SYSTEM |
  33927. FORMAT_MESSAGE_IGNORE_INSERTS,
  33928. NULL,
  33929. lastErrno,
  33930. 0,
  33931. (LPWSTR) &zTempWide,
  33932. 0,
  33933. 0);
  33934. #endif
  33935. if( dwLen > 0 ){
  33936. /* allocate a buffer and convert to UTF8 */
  33937. sqlite3BeginBenignMalloc();
  33938. zOut = winUnicodeToUtf8(zTempWide);
  33939. sqlite3EndBenignMalloc();
  33940. #if !SQLITE_OS_WINRT
  33941. /* free the system buffer allocated by FormatMessage */
  33942. osLocalFree(zTempWide);
  33943. #endif
  33944. }
  33945. }
  33946. #ifdef SQLITE_WIN32_HAS_ANSI
  33947. else{
  33948. char *zTemp = NULL;
  33949. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  33950. FORMAT_MESSAGE_FROM_SYSTEM |
  33951. FORMAT_MESSAGE_IGNORE_INSERTS,
  33952. NULL,
  33953. lastErrno,
  33954. 0,
  33955. (LPSTR) &zTemp,
  33956. 0,
  33957. 0);
  33958. if( dwLen > 0 ){
  33959. /* allocate a buffer and convert to UTF8 */
  33960. sqlite3BeginBenignMalloc();
  33961. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33962. sqlite3EndBenignMalloc();
  33963. /* free the system buffer allocated by FormatMessage */
  33964. osLocalFree(zTemp);
  33965. }
  33966. }
  33967. #endif
  33968. if( 0 == dwLen ){
  33969. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  33970. }else{
  33971. /* copy a maximum of nBuf chars to output buffer */
  33972. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  33973. /* free the UTF8 buffer */
  33974. sqlite3_free(zOut);
  33975. }
  33976. return 0;
  33977. }
  33978. /*
  33979. **
  33980. ** This function - winLogErrorAtLine() - is only ever called via the macro
  33981. ** winLogError().
  33982. **
  33983. ** This routine is invoked after an error occurs in an OS function.
  33984. ** It logs a message using sqlite3_log() containing the current value of
  33985. ** error code and, if possible, the human-readable equivalent from
  33986. ** FormatMessage.
  33987. **
  33988. ** The first argument passed to the macro should be the error code that
  33989. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  33990. ** The two subsequent arguments should be the name of the OS function that
  33991. ** failed and the associated file-system path, if any.
  33992. */
  33993. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  33994. static int winLogErrorAtLine(
  33995. int errcode, /* SQLite error code */
  33996. DWORD lastErrno, /* Win32 last error */
  33997. const char *zFunc, /* Name of OS function that failed */
  33998. const char *zPath, /* File path associated with error */
  33999. int iLine /* Source line number where error occurred */
  34000. ){
  34001. char zMsg[500]; /* Human readable error text */
  34002. int i; /* Loop counter */
  34003. zMsg[0] = 0;
  34004. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  34005. assert( errcode!=SQLITE_OK );
  34006. if( zPath==0 ) zPath = "";
  34007. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  34008. zMsg[i] = 0;
  34009. sqlite3_log(errcode,
  34010. "os_win.c:%d: (%lu) %s(%s) - %s",
  34011. iLine, lastErrno, zFunc, zPath, zMsg
  34012. );
  34013. return errcode;
  34014. }
  34015. /*
  34016. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  34017. ** will be retried following a locking error - probably caused by
  34018. ** antivirus software. Also the initial delay before the first retry.
  34019. ** The delay increases linearly with each retry.
  34020. */
  34021. #ifndef SQLITE_WIN32_IOERR_RETRY
  34022. # define SQLITE_WIN32_IOERR_RETRY 10
  34023. #endif
  34024. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  34025. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  34026. #endif
  34027. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  34028. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  34029. /*
  34030. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  34031. ** error code obtained via GetLastError() is eligible to be retried. It
  34032. ** must accept the error code DWORD as its only argument and should return
  34033. ** non-zero if the error code is transient in nature and the operation
  34034. ** responsible for generating the original error might succeed upon being
  34035. ** retried. The argument to this macro should be a variable.
  34036. **
  34037. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  34038. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  34039. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  34040. ** may be used to include additional error codes in the set that should
  34041. ** result in the failing I/O operation being retried by the caller. If
  34042. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  34043. ** identical to those of the "winIoerrCanRetry1" macro.
  34044. */
  34045. #if !defined(winIoerrCanRetry1)
  34046. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  34047. ((a)==ERROR_SHARING_VIOLATION) || \
  34048. ((a)==ERROR_LOCK_VIOLATION) || \
  34049. ((a)==ERROR_DEV_NOT_EXIST) || \
  34050. ((a)==ERROR_NETNAME_DELETED) || \
  34051. ((a)==ERROR_SEM_TIMEOUT) || \
  34052. ((a)==ERROR_NETWORK_UNREACHABLE))
  34053. #endif
  34054. /*
  34055. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  34056. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  34057. ** to give up with an error.
  34058. */
  34059. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  34060. DWORD e = osGetLastError();
  34061. if( *pnRetry>=winIoerrRetry ){
  34062. if( pError ){
  34063. *pError = e;
  34064. }
  34065. return 0;
  34066. }
  34067. if( winIoerrCanRetry1(e) ){
  34068. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34069. ++*pnRetry;
  34070. return 1;
  34071. }
  34072. #if defined(winIoerrCanRetry2)
  34073. else if( winIoerrCanRetry2(e) ){
  34074. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34075. ++*pnRetry;
  34076. return 1;
  34077. }
  34078. #endif
  34079. if( pError ){
  34080. *pError = e;
  34081. }
  34082. return 0;
  34083. }
  34084. /*
  34085. ** Log a I/O error retry episode.
  34086. */
  34087. static void winLogIoerr(int nRetry, int lineno){
  34088. if( nRetry ){
  34089. sqlite3_log(SQLITE_NOTICE,
  34090. "delayed %dms for lock/sharing conflict at line %d",
  34091. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  34092. );
  34093. }
  34094. }
  34095. #if SQLITE_OS_WINCE
  34096. /*************************************************************************
  34097. ** This section contains code for WinCE only.
  34098. */
  34099. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  34100. /*
  34101. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  34102. ** create a substitute.
  34103. */
  34104. /* #include <time.h> */
  34105. struct tm *__cdecl localtime(const time_t *t)
  34106. {
  34107. static struct tm y;
  34108. FILETIME uTm, lTm;
  34109. SYSTEMTIME pTm;
  34110. sqlite3_int64 t64;
  34111. t64 = *t;
  34112. t64 = (t64 + 11644473600)*10000000;
  34113. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  34114. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  34115. osFileTimeToLocalFileTime(&uTm,&lTm);
  34116. osFileTimeToSystemTime(&lTm,&pTm);
  34117. y.tm_year = pTm.wYear - 1900;
  34118. y.tm_mon = pTm.wMonth - 1;
  34119. y.tm_wday = pTm.wDayOfWeek;
  34120. y.tm_mday = pTm.wDay;
  34121. y.tm_hour = pTm.wHour;
  34122. y.tm_min = pTm.wMinute;
  34123. y.tm_sec = pTm.wSecond;
  34124. return &y;
  34125. }
  34126. #endif
  34127. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  34128. /*
  34129. ** Acquire a lock on the handle h
  34130. */
  34131. static void winceMutexAcquire(HANDLE h){
  34132. DWORD dwErr;
  34133. do {
  34134. dwErr = osWaitForSingleObject(h, INFINITE);
  34135. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  34136. }
  34137. /*
  34138. ** Release a lock acquired by winceMutexAcquire()
  34139. */
  34140. #define winceMutexRelease(h) ReleaseMutex(h)
  34141. /*
  34142. ** Create the mutex and shared memory used for locking in the file
  34143. ** descriptor pFile
  34144. */
  34145. static int winceCreateLock(const char *zFilename, winFile *pFile){
  34146. LPWSTR zTok;
  34147. LPWSTR zName;
  34148. DWORD lastErrno;
  34149. BOOL bLogged = FALSE;
  34150. BOOL bInit = TRUE;
  34151. zName = winUtf8ToUnicode(zFilename);
  34152. if( zName==0 ){
  34153. /* out of memory */
  34154. return SQLITE_IOERR_NOMEM;
  34155. }
  34156. /* Initialize the local lockdata */
  34157. memset(&pFile->local, 0, sizeof(pFile->local));
  34158. /* Replace the backslashes from the filename and lowercase it
  34159. ** to derive a mutex name. */
  34160. zTok = osCharLowerW(zName);
  34161. for (;*zTok;zTok++){
  34162. if (*zTok == '\\') *zTok = '_';
  34163. }
  34164. /* Create/open the named mutex */
  34165. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  34166. if (!pFile->hMutex){
  34167. pFile->lastErrno = osGetLastError();
  34168. sqlite3_free(zName);
  34169. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  34170. "winceCreateLock1", zFilename);
  34171. }
  34172. /* Acquire the mutex before continuing */
  34173. winceMutexAcquire(pFile->hMutex);
  34174. /* Since the names of named mutexes, semaphores, file mappings etc are
  34175. ** case-sensitive, take advantage of that by uppercasing the mutex name
  34176. ** and using that as the shared filemapping name.
  34177. */
  34178. osCharUpperW(zName);
  34179. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  34180. PAGE_READWRITE, 0, sizeof(winceLock),
  34181. zName);
  34182. /* Set a flag that indicates we're the first to create the memory so it
  34183. ** must be zero-initialized */
  34184. lastErrno = osGetLastError();
  34185. if (lastErrno == ERROR_ALREADY_EXISTS){
  34186. bInit = FALSE;
  34187. }
  34188. sqlite3_free(zName);
  34189. /* If we succeeded in making the shared memory handle, map it. */
  34190. if( pFile->hShared ){
  34191. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  34192. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  34193. /* If mapping failed, close the shared memory handle and erase it */
  34194. if( !pFile->shared ){
  34195. pFile->lastErrno = osGetLastError();
  34196. winLogError(SQLITE_IOERR, pFile->lastErrno,
  34197. "winceCreateLock2", zFilename);
  34198. bLogged = TRUE;
  34199. osCloseHandle(pFile->hShared);
  34200. pFile->hShared = NULL;
  34201. }
  34202. }
  34203. /* If shared memory could not be created, then close the mutex and fail */
  34204. if( pFile->hShared==NULL ){
  34205. if( !bLogged ){
  34206. pFile->lastErrno = lastErrno;
  34207. winLogError(SQLITE_IOERR, pFile->lastErrno,
  34208. "winceCreateLock3", zFilename);
  34209. bLogged = TRUE;
  34210. }
  34211. winceMutexRelease(pFile->hMutex);
  34212. osCloseHandle(pFile->hMutex);
  34213. pFile->hMutex = NULL;
  34214. return SQLITE_IOERR;
  34215. }
  34216. /* Initialize the shared memory if we're supposed to */
  34217. if( bInit ){
  34218. memset(pFile->shared, 0, sizeof(winceLock));
  34219. }
  34220. winceMutexRelease(pFile->hMutex);
  34221. return SQLITE_OK;
  34222. }
  34223. /*
  34224. ** Destroy the part of winFile that deals with wince locks
  34225. */
  34226. static void winceDestroyLock(winFile *pFile){
  34227. if (pFile->hMutex){
  34228. /* Acquire the mutex */
  34229. winceMutexAcquire(pFile->hMutex);
  34230. /* The following blocks should probably assert in debug mode, but they
  34231. are to cleanup in case any locks remained open */
  34232. if (pFile->local.nReaders){
  34233. pFile->shared->nReaders --;
  34234. }
  34235. if (pFile->local.bReserved){
  34236. pFile->shared->bReserved = FALSE;
  34237. }
  34238. if (pFile->local.bPending){
  34239. pFile->shared->bPending = FALSE;
  34240. }
  34241. if (pFile->local.bExclusive){
  34242. pFile->shared->bExclusive = FALSE;
  34243. }
  34244. /* De-reference and close our copy of the shared memory handle */
  34245. osUnmapViewOfFile(pFile->shared);
  34246. osCloseHandle(pFile->hShared);
  34247. /* Done with the mutex */
  34248. winceMutexRelease(pFile->hMutex);
  34249. osCloseHandle(pFile->hMutex);
  34250. pFile->hMutex = NULL;
  34251. }
  34252. }
  34253. /*
  34254. ** An implementation of the LockFile() API of Windows for CE
  34255. */
  34256. static BOOL winceLockFile(
  34257. LPHANDLE phFile,
  34258. DWORD dwFileOffsetLow,
  34259. DWORD dwFileOffsetHigh,
  34260. DWORD nNumberOfBytesToLockLow,
  34261. DWORD nNumberOfBytesToLockHigh
  34262. ){
  34263. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  34264. BOOL bReturn = FALSE;
  34265. UNUSED_PARAMETER(dwFileOffsetHigh);
  34266. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  34267. if (!pFile->hMutex) return TRUE;
  34268. winceMutexAcquire(pFile->hMutex);
  34269. /* Wanting an exclusive lock? */
  34270. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  34271. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  34272. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  34273. pFile->shared->bExclusive = TRUE;
  34274. pFile->local.bExclusive = TRUE;
  34275. bReturn = TRUE;
  34276. }
  34277. }
  34278. /* Want a read-only lock? */
  34279. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  34280. nNumberOfBytesToLockLow == 1){
  34281. if (pFile->shared->bExclusive == 0){
  34282. pFile->local.nReaders ++;
  34283. if (pFile->local.nReaders == 1){
  34284. pFile->shared->nReaders ++;
  34285. }
  34286. bReturn = TRUE;
  34287. }
  34288. }
  34289. /* Want a pending lock? */
  34290. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  34291. && nNumberOfBytesToLockLow == 1){
  34292. /* If no pending lock has been acquired, then acquire it */
  34293. if (pFile->shared->bPending == 0) {
  34294. pFile->shared->bPending = TRUE;
  34295. pFile->local.bPending = TRUE;
  34296. bReturn = TRUE;
  34297. }
  34298. }
  34299. /* Want a reserved lock? */
  34300. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  34301. && nNumberOfBytesToLockLow == 1){
  34302. if (pFile->shared->bReserved == 0) {
  34303. pFile->shared->bReserved = TRUE;
  34304. pFile->local.bReserved = TRUE;
  34305. bReturn = TRUE;
  34306. }
  34307. }
  34308. winceMutexRelease(pFile->hMutex);
  34309. return bReturn;
  34310. }
  34311. /*
  34312. ** An implementation of the UnlockFile API of Windows for CE
  34313. */
  34314. static BOOL winceUnlockFile(
  34315. LPHANDLE phFile,
  34316. DWORD dwFileOffsetLow,
  34317. DWORD dwFileOffsetHigh,
  34318. DWORD nNumberOfBytesToUnlockLow,
  34319. DWORD nNumberOfBytesToUnlockHigh
  34320. ){
  34321. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  34322. BOOL bReturn = FALSE;
  34323. UNUSED_PARAMETER(dwFileOffsetHigh);
  34324. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  34325. if (!pFile->hMutex) return TRUE;
  34326. winceMutexAcquire(pFile->hMutex);
  34327. /* Releasing a reader lock or an exclusive lock */
  34328. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  34329. /* Did we have an exclusive lock? */
  34330. if (pFile->local.bExclusive){
  34331. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  34332. pFile->local.bExclusive = FALSE;
  34333. pFile->shared->bExclusive = FALSE;
  34334. bReturn = TRUE;
  34335. }
  34336. /* Did we just have a reader lock? */
  34337. else if (pFile->local.nReaders){
  34338. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  34339. || nNumberOfBytesToUnlockLow == 1);
  34340. pFile->local.nReaders --;
  34341. if (pFile->local.nReaders == 0)
  34342. {
  34343. pFile->shared->nReaders --;
  34344. }
  34345. bReturn = TRUE;
  34346. }
  34347. }
  34348. /* Releasing a pending lock */
  34349. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  34350. && nNumberOfBytesToUnlockLow == 1){
  34351. if (pFile->local.bPending){
  34352. pFile->local.bPending = FALSE;
  34353. pFile->shared->bPending = FALSE;
  34354. bReturn = TRUE;
  34355. }
  34356. }
  34357. /* Releasing a reserved lock */
  34358. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  34359. && nNumberOfBytesToUnlockLow == 1){
  34360. if (pFile->local.bReserved) {
  34361. pFile->local.bReserved = FALSE;
  34362. pFile->shared->bReserved = FALSE;
  34363. bReturn = TRUE;
  34364. }
  34365. }
  34366. winceMutexRelease(pFile->hMutex);
  34367. return bReturn;
  34368. }
  34369. /*
  34370. ** End of the special code for wince
  34371. *****************************************************************************/
  34372. #endif /* SQLITE_OS_WINCE */
  34373. /*
  34374. ** Lock a file region.
  34375. */
  34376. static BOOL winLockFile(
  34377. LPHANDLE phFile,
  34378. DWORD flags,
  34379. DWORD offsetLow,
  34380. DWORD offsetHigh,
  34381. DWORD numBytesLow,
  34382. DWORD numBytesHigh
  34383. ){
  34384. #if SQLITE_OS_WINCE
  34385. /*
  34386. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34387. ** API LockFile.
  34388. */
  34389. return winceLockFile(phFile, offsetLow, offsetHigh,
  34390. numBytesLow, numBytesHigh);
  34391. #else
  34392. if( osIsNT() ){
  34393. OVERLAPPED ovlp;
  34394. memset(&ovlp, 0, sizeof(OVERLAPPED));
  34395. ovlp.Offset = offsetLow;
  34396. ovlp.OffsetHigh = offsetHigh;
  34397. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  34398. }else{
  34399. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  34400. numBytesHigh);
  34401. }
  34402. #endif
  34403. }
  34404. /*
  34405. ** Unlock a file region.
  34406. */
  34407. static BOOL winUnlockFile(
  34408. LPHANDLE phFile,
  34409. DWORD offsetLow,
  34410. DWORD offsetHigh,
  34411. DWORD numBytesLow,
  34412. DWORD numBytesHigh
  34413. ){
  34414. #if SQLITE_OS_WINCE
  34415. /*
  34416. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34417. ** API UnlockFile.
  34418. */
  34419. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  34420. numBytesLow, numBytesHigh);
  34421. #else
  34422. if( osIsNT() ){
  34423. OVERLAPPED ovlp;
  34424. memset(&ovlp, 0, sizeof(OVERLAPPED));
  34425. ovlp.Offset = offsetLow;
  34426. ovlp.OffsetHigh = offsetHigh;
  34427. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  34428. }else{
  34429. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  34430. numBytesHigh);
  34431. }
  34432. #endif
  34433. }
  34434. /*****************************************************************************
  34435. ** The next group of routines implement the I/O methods specified
  34436. ** by the sqlite3_io_methods object.
  34437. ******************************************************************************/
  34438. /*
  34439. ** Some Microsoft compilers lack this definition.
  34440. */
  34441. #ifndef INVALID_SET_FILE_POINTER
  34442. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  34443. #endif
  34444. /*
  34445. ** Move the current position of the file handle passed as the first
  34446. ** argument to offset iOffset within the file. If successful, return 0.
  34447. ** Otherwise, set pFile->lastErrno and return non-zero.
  34448. */
  34449. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  34450. #if !SQLITE_OS_WINRT
  34451. LONG upperBits; /* Most sig. 32 bits of new offset */
  34452. LONG lowerBits; /* Least sig. 32 bits of new offset */
  34453. DWORD dwRet; /* Value returned by SetFilePointer() */
  34454. DWORD lastErrno; /* Value returned by GetLastError() */
  34455. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  34456. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  34457. lowerBits = (LONG)(iOffset & 0xffffffff);
  34458. /* API oddity: If successful, SetFilePointer() returns a dword
  34459. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  34460. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  34461. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  34462. ** whether an error has actually occurred, it is also necessary to call
  34463. ** GetLastError().
  34464. */
  34465. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  34466. if( (dwRet==INVALID_SET_FILE_POINTER
  34467. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  34468. pFile->lastErrno = lastErrno;
  34469. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  34470. "winSeekFile", pFile->zPath);
  34471. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  34472. return 1;
  34473. }
  34474. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  34475. return 0;
  34476. #else
  34477. /*
  34478. ** Same as above, except that this implementation works for WinRT.
  34479. */
  34480. LARGE_INTEGER x; /* The new offset */
  34481. BOOL bRet; /* Value returned by SetFilePointerEx() */
  34482. x.QuadPart = iOffset;
  34483. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  34484. if(!bRet){
  34485. pFile->lastErrno = osGetLastError();
  34486. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  34487. "winSeekFile", pFile->zPath);
  34488. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  34489. return 1;
  34490. }
  34491. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  34492. return 0;
  34493. #endif
  34494. }
  34495. #if SQLITE_MAX_MMAP_SIZE>0
  34496. /* Forward references to VFS helper methods used for memory mapped files */
  34497. static int winMapfile(winFile*, sqlite3_int64);
  34498. static int winUnmapfile(winFile*);
  34499. #endif
  34500. /*
  34501. ** Close a file.
  34502. **
  34503. ** It is reported that an attempt to close a handle might sometimes
  34504. ** fail. This is a very unreasonable result, but Windows is notorious
  34505. ** for being unreasonable so I do not doubt that it might happen. If
  34506. ** the close fails, we pause for 100 milliseconds and try again. As
  34507. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  34508. ** giving up and returning an error.
  34509. */
  34510. #define MX_CLOSE_ATTEMPT 3
  34511. static int winClose(sqlite3_file *id){
  34512. int rc, cnt = 0;
  34513. winFile *pFile = (winFile*)id;
  34514. assert( id!=0 );
  34515. #ifndef SQLITE_OMIT_WAL
  34516. assert( pFile->pShm==0 );
  34517. #endif
  34518. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  34519. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  34520. osGetCurrentProcessId(), pFile, pFile->h));
  34521. #if SQLITE_MAX_MMAP_SIZE>0
  34522. winUnmapfile(pFile);
  34523. #endif
  34524. do{
  34525. rc = osCloseHandle(pFile->h);
  34526. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  34527. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  34528. #if SQLITE_OS_WINCE
  34529. #define WINCE_DELETION_ATTEMPTS 3
  34530. winceDestroyLock(pFile);
  34531. if( pFile->zDeleteOnClose ){
  34532. int cnt = 0;
  34533. while(
  34534. osDeleteFileW(pFile->zDeleteOnClose)==0
  34535. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  34536. && cnt++ < WINCE_DELETION_ATTEMPTS
  34537. ){
  34538. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  34539. }
  34540. sqlite3_free(pFile->zDeleteOnClose);
  34541. }
  34542. #endif
  34543. if( rc ){
  34544. pFile->h = NULL;
  34545. }
  34546. OpenCounter(-1);
  34547. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  34548. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  34549. return rc ? SQLITE_OK
  34550. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  34551. "winClose", pFile->zPath);
  34552. }
  34553. /*
  34554. ** Read data from a file into a buffer. Return SQLITE_OK if all
  34555. ** bytes were read successfully and SQLITE_IOERR if anything goes
  34556. ** wrong.
  34557. */
  34558. static int winRead(
  34559. sqlite3_file *id, /* File to read from */
  34560. void *pBuf, /* Write content into this buffer */
  34561. int amt, /* Number of bytes to read */
  34562. sqlite3_int64 offset /* Begin reading at this offset */
  34563. ){
  34564. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34565. OVERLAPPED overlapped; /* The offset for ReadFile. */
  34566. #endif
  34567. winFile *pFile = (winFile*)id; /* file handle */
  34568. DWORD nRead; /* Number of bytes actually read from file */
  34569. int nRetry = 0; /* Number of retrys */
  34570. assert( id!=0 );
  34571. assert( amt>0 );
  34572. assert( offset>=0 );
  34573. SimulateIOError(return SQLITE_IOERR_READ);
  34574. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  34575. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  34576. pFile->h, pBuf, amt, offset, pFile->locktype));
  34577. #if SQLITE_MAX_MMAP_SIZE>0
  34578. /* Deal with as much of this read request as possible by transfering
  34579. ** data from the memory mapping using memcpy(). */
  34580. if( offset<pFile->mmapSize ){
  34581. if( offset+amt <= pFile->mmapSize ){
  34582. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  34583. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34584. osGetCurrentProcessId(), pFile, pFile->h));
  34585. return SQLITE_OK;
  34586. }else{
  34587. int nCopy = (int)(pFile->mmapSize - offset);
  34588. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  34589. pBuf = &((u8 *)pBuf)[nCopy];
  34590. amt -= nCopy;
  34591. offset += nCopy;
  34592. }
  34593. }
  34594. #endif
  34595. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34596. if( winSeekFile(pFile, offset) ){
  34597. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  34598. osGetCurrentProcessId(), pFile, pFile->h));
  34599. return SQLITE_FULL;
  34600. }
  34601. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  34602. #else
  34603. memset(&overlapped, 0, sizeof(OVERLAPPED));
  34604. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34605. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34606. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  34607. osGetLastError()!=ERROR_HANDLE_EOF ){
  34608. #endif
  34609. DWORD lastErrno;
  34610. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  34611. pFile->lastErrno = lastErrno;
  34612. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  34613. osGetCurrentProcessId(), pFile, pFile->h));
  34614. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  34615. "winRead", pFile->zPath);
  34616. }
  34617. winLogIoerr(nRetry, __LINE__);
  34618. if( nRead<(DWORD)amt ){
  34619. /* Unread parts of the buffer must be zero-filled */
  34620. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  34621. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  34622. osGetCurrentProcessId(), pFile, pFile->h));
  34623. return SQLITE_IOERR_SHORT_READ;
  34624. }
  34625. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34626. osGetCurrentProcessId(), pFile, pFile->h));
  34627. return SQLITE_OK;
  34628. }
  34629. /*
  34630. ** Write data from a buffer into a file. Return SQLITE_OK on success
  34631. ** or some other error code on failure.
  34632. */
  34633. static int winWrite(
  34634. sqlite3_file *id, /* File to write into */
  34635. const void *pBuf, /* The bytes to be written */
  34636. int amt, /* Number of bytes to write */
  34637. sqlite3_int64 offset /* Offset into the file to begin writing at */
  34638. ){
  34639. int rc = 0; /* True if error has occurred, else false */
  34640. winFile *pFile = (winFile*)id; /* File handle */
  34641. int nRetry = 0; /* Number of retries */
  34642. assert( amt>0 );
  34643. assert( pFile );
  34644. SimulateIOError(return SQLITE_IOERR_WRITE);
  34645. SimulateDiskfullError(return SQLITE_FULL);
  34646. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  34647. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  34648. pFile->h, pBuf, amt, offset, pFile->locktype));
  34649. #if SQLITE_MAX_MMAP_SIZE>0
  34650. /* Deal with as much of this write request as possible by transfering
  34651. ** data from the memory mapping using memcpy(). */
  34652. if( offset<pFile->mmapSize ){
  34653. if( offset+amt <= pFile->mmapSize ){
  34654. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  34655. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34656. osGetCurrentProcessId(), pFile, pFile->h));
  34657. return SQLITE_OK;
  34658. }else{
  34659. int nCopy = (int)(pFile->mmapSize - offset);
  34660. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  34661. pBuf = &((u8 *)pBuf)[nCopy];
  34662. amt -= nCopy;
  34663. offset += nCopy;
  34664. }
  34665. }
  34666. #endif
  34667. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34668. rc = winSeekFile(pFile, offset);
  34669. if( rc==0 ){
  34670. #else
  34671. {
  34672. #endif
  34673. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34674. OVERLAPPED overlapped; /* The offset for WriteFile. */
  34675. #endif
  34676. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  34677. int nRem = amt; /* Number of bytes yet to be written */
  34678. DWORD nWrite; /* Bytes written by each WriteFile() call */
  34679. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  34680. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34681. memset(&overlapped, 0, sizeof(OVERLAPPED));
  34682. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34683. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34684. #endif
  34685. while( nRem>0 ){
  34686. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34687. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  34688. #else
  34689. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  34690. #endif
  34691. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  34692. break;
  34693. }
  34694. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  34695. if( nWrite==0 || nWrite>(DWORD)nRem ){
  34696. lastErrno = osGetLastError();
  34697. break;
  34698. }
  34699. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34700. offset += nWrite;
  34701. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34702. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34703. #endif
  34704. aRem += nWrite;
  34705. nRem -= nWrite;
  34706. }
  34707. if( nRem>0 ){
  34708. pFile->lastErrno = lastErrno;
  34709. rc = 1;
  34710. }
  34711. }
  34712. if( rc ){
  34713. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  34714. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  34715. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  34716. osGetCurrentProcessId(), pFile, pFile->h));
  34717. return winLogError(SQLITE_FULL, pFile->lastErrno,
  34718. "winWrite1", pFile->zPath);
  34719. }
  34720. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  34721. osGetCurrentProcessId(), pFile, pFile->h));
  34722. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  34723. "winWrite2", pFile->zPath);
  34724. }else{
  34725. winLogIoerr(nRetry, __LINE__);
  34726. }
  34727. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34728. osGetCurrentProcessId(), pFile, pFile->h));
  34729. return SQLITE_OK;
  34730. }
  34731. /*
  34732. ** Truncate an open file to a specified size
  34733. */
  34734. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  34735. winFile *pFile = (winFile*)id; /* File handle object */
  34736. int rc = SQLITE_OK; /* Return code for this function */
  34737. DWORD lastErrno;
  34738. assert( pFile );
  34739. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  34740. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  34741. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  34742. /* If the user has configured a chunk-size for this file, truncate the
  34743. ** file so that it consists of an integer number of chunks (i.e. the
  34744. ** actual file size after the operation may be larger than the requested
  34745. ** size).
  34746. */
  34747. if( pFile->szChunk>0 ){
  34748. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  34749. }
  34750. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  34751. if( winSeekFile(pFile, nByte) ){
  34752. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  34753. "winTruncate1", pFile->zPath);
  34754. }else if( 0==osSetEndOfFile(pFile->h) &&
  34755. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  34756. pFile->lastErrno = lastErrno;
  34757. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  34758. "winTruncate2", pFile->zPath);
  34759. }
  34760. #if SQLITE_MAX_MMAP_SIZE>0
  34761. /* If the file was truncated to a size smaller than the currently
  34762. ** mapped region, reduce the effective mapping size as well. SQLite will
  34763. ** use read() and write() to access data beyond this point from now on.
  34764. */
  34765. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  34766. pFile->mmapSize = nByte;
  34767. }
  34768. #endif
  34769. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  34770. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  34771. return rc;
  34772. }
  34773. #ifdef SQLITE_TEST
  34774. /*
  34775. ** Count the number of fullsyncs and normal syncs. This is used to test
  34776. ** that syncs and fullsyncs are occuring at the right times.
  34777. */
  34778. SQLITE_API int sqlite3_sync_count = 0;
  34779. SQLITE_API int sqlite3_fullsync_count = 0;
  34780. #endif
  34781. /*
  34782. ** Make sure all writes to a particular file are committed to disk.
  34783. */
  34784. static int winSync(sqlite3_file *id, int flags){
  34785. #ifndef SQLITE_NO_SYNC
  34786. /*
  34787. ** Used only when SQLITE_NO_SYNC is not defined.
  34788. */
  34789. BOOL rc;
  34790. #endif
  34791. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  34792. defined(SQLITE_HAVE_OS_TRACE)
  34793. /*
  34794. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  34795. ** OSTRACE() macros.
  34796. */
  34797. winFile *pFile = (winFile*)id;
  34798. #else
  34799. UNUSED_PARAMETER(id);
  34800. #endif
  34801. assert( pFile );
  34802. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  34803. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  34804. || (flags&0x0F)==SQLITE_SYNC_FULL
  34805. );
  34806. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  34807. ** line is to test that doing so does not cause any problems.
  34808. */
  34809. SimulateDiskfullError( return SQLITE_FULL );
  34810. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  34811. osGetCurrentProcessId(), pFile, pFile->h, flags,
  34812. pFile->locktype));
  34813. #ifndef SQLITE_TEST
  34814. UNUSED_PARAMETER(flags);
  34815. #else
  34816. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  34817. sqlite3_fullsync_count++;
  34818. }
  34819. sqlite3_sync_count++;
  34820. #endif
  34821. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  34822. ** no-op
  34823. */
  34824. #ifdef SQLITE_NO_SYNC
  34825. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34826. osGetCurrentProcessId(), pFile, pFile->h));
  34827. return SQLITE_OK;
  34828. #else
  34829. #if SQLITE_MAX_MMAP_SIZE>0
  34830. if( pFile->pMapRegion ){
  34831. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  34832. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  34833. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  34834. pFile, pFile->pMapRegion));
  34835. }else{
  34836. pFile->lastErrno = osGetLastError();
  34837. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  34838. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  34839. pFile, pFile->pMapRegion));
  34840. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34841. "winSync1", pFile->zPath);
  34842. }
  34843. }
  34844. #endif
  34845. rc = osFlushFileBuffers(pFile->h);
  34846. SimulateIOError( rc=FALSE );
  34847. if( rc ){
  34848. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34849. osGetCurrentProcessId(), pFile, pFile->h));
  34850. return SQLITE_OK;
  34851. }else{
  34852. pFile->lastErrno = osGetLastError();
  34853. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  34854. osGetCurrentProcessId(), pFile, pFile->h));
  34855. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  34856. "winSync2", pFile->zPath);
  34857. }
  34858. #endif
  34859. }
  34860. /*
  34861. ** Determine the current size of a file in bytes
  34862. */
  34863. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  34864. winFile *pFile = (winFile*)id;
  34865. int rc = SQLITE_OK;
  34866. assert( id!=0 );
  34867. assert( pSize!=0 );
  34868. SimulateIOError(return SQLITE_IOERR_FSTAT);
  34869. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  34870. #if SQLITE_OS_WINRT
  34871. {
  34872. FILE_STANDARD_INFO info;
  34873. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  34874. &info, sizeof(info)) ){
  34875. *pSize = info.EndOfFile.QuadPart;
  34876. }else{
  34877. pFile->lastErrno = osGetLastError();
  34878. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  34879. "winFileSize", pFile->zPath);
  34880. }
  34881. }
  34882. #else
  34883. {
  34884. DWORD upperBits;
  34885. DWORD lowerBits;
  34886. DWORD lastErrno;
  34887. lowerBits = osGetFileSize(pFile->h, &upperBits);
  34888. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  34889. if( (lowerBits == INVALID_FILE_SIZE)
  34890. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  34891. pFile->lastErrno = lastErrno;
  34892. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  34893. "winFileSize", pFile->zPath);
  34894. }
  34895. }
  34896. #endif
  34897. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  34898. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  34899. return rc;
  34900. }
  34901. /*
  34902. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  34903. */
  34904. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  34905. # define LOCKFILE_FAIL_IMMEDIATELY 1
  34906. #endif
  34907. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  34908. # define LOCKFILE_EXCLUSIVE_LOCK 2
  34909. #endif
  34910. /*
  34911. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  34912. ** When the LockFile function was used, it was always expected to fail
  34913. ** immediately if the lock could not be obtained. Also, it always expected to
  34914. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  34915. ** and reflect those expectations; therefore, they should not be changed.
  34916. */
  34917. #ifndef SQLITE_LOCKFILE_FLAGS
  34918. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  34919. LOCKFILE_EXCLUSIVE_LOCK)
  34920. #endif
  34921. /*
  34922. ** Currently, SQLite never calls the LockFileEx function without wanting the
  34923. ** call to fail immediately if the lock cannot be obtained.
  34924. */
  34925. #ifndef SQLITE_LOCKFILEEX_FLAGS
  34926. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  34927. #endif
  34928. /*
  34929. ** Acquire a reader lock.
  34930. ** Different API routines are called depending on whether or not this
  34931. ** is Win9x or WinNT.
  34932. */
  34933. static int winGetReadLock(winFile *pFile){
  34934. int res;
  34935. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  34936. if( osIsNT() ){
  34937. #if SQLITE_OS_WINCE
  34938. /*
  34939. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34940. ** API LockFileEx.
  34941. */
  34942. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  34943. #else
  34944. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  34945. SHARED_SIZE, 0);
  34946. #endif
  34947. }
  34948. #ifdef SQLITE_WIN32_HAS_ANSI
  34949. else{
  34950. int lk;
  34951. sqlite3_randomness(sizeof(lk), &lk);
  34952. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  34953. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  34954. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  34955. }
  34956. #endif
  34957. if( res == 0 ){
  34958. pFile->lastErrno = osGetLastError();
  34959. /* No need to log a failure to lock */
  34960. }
  34961. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  34962. return res;
  34963. }
  34964. /*
  34965. ** Undo a readlock
  34966. */
  34967. static int winUnlockReadLock(winFile *pFile){
  34968. int res;
  34969. DWORD lastErrno;
  34970. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  34971. if( osIsNT() ){
  34972. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  34973. }
  34974. #ifdef SQLITE_WIN32_HAS_ANSI
  34975. else{
  34976. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  34977. }
  34978. #endif
  34979. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  34980. pFile->lastErrno = lastErrno;
  34981. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  34982. "winUnlockReadLock", pFile->zPath);
  34983. }
  34984. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  34985. return res;
  34986. }
  34987. /*
  34988. ** Lock the file with the lock specified by parameter locktype - one
  34989. ** of the following:
  34990. **
  34991. ** (1) SHARED_LOCK
  34992. ** (2) RESERVED_LOCK
  34993. ** (3) PENDING_LOCK
  34994. ** (4) EXCLUSIVE_LOCK
  34995. **
  34996. ** Sometimes when requesting one lock state, additional lock states
  34997. ** are inserted in between. The locking might fail on one of the later
  34998. ** transitions leaving the lock state different from what it started but
  34999. ** still short of its goal. The following chart shows the allowed
  35000. ** transitions and the inserted intermediate states:
  35001. **
  35002. ** UNLOCKED -> SHARED
  35003. ** SHARED -> RESERVED
  35004. ** SHARED -> (PENDING) -> EXCLUSIVE
  35005. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35006. ** PENDING -> EXCLUSIVE
  35007. **
  35008. ** This routine will only increase a lock. The winUnlock() routine
  35009. ** erases all locks at once and returns us immediately to locking level 0.
  35010. ** It is not possible to lower the locking level one step at a time. You
  35011. ** must go straight to locking level 0.
  35012. */
  35013. static int winLock(sqlite3_file *id, int locktype){
  35014. int rc = SQLITE_OK; /* Return code from subroutines */
  35015. int res = 1; /* Result of a Windows lock call */
  35016. int newLocktype; /* Set pFile->locktype to this value before exiting */
  35017. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  35018. winFile *pFile = (winFile*)id;
  35019. DWORD lastErrno = NO_ERROR;
  35020. assert( id!=0 );
  35021. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  35022. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  35023. /* If there is already a lock of this type or more restrictive on the
  35024. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  35025. ** sqlite3OsEnterMutex() hasn't been called yet.
  35026. */
  35027. if( pFile->locktype>=locktype ){
  35028. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  35029. return SQLITE_OK;
  35030. }
  35031. /* Do not allow any kind of write-lock on a read-only database
  35032. */
  35033. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  35034. return SQLITE_IOERR_LOCK;
  35035. }
  35036. /* Make sure the locking sequence is correct
  35037. */
  35038. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  35039. assert( locktype!=PENDING_LOCK );
  35040. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  35041. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  35042. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  35043. ** the PENDING_LOCK byte is temporary.
  35044. */
  35045. newLocktype = pFile->locktype;
  35046. if( (pFile->locktype==NO_LOCK)
  35047. || ( (locktype==EXCLUSIVE_LOCK)
  35048. && (pFile->locktype==RESERVED_LOCK))
  35049. ){
  35050. int cnt = 3;
  35051. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  35052. PENDING_BYTE, 0, 1, 0))==0 ){
  35053. /* Try 3 times to get the pending lock. This is needed to work
  35054. ** around problems caused by indexing and/or anti-virus software on
  35055. ** Windows systems.
  35056. ** If you are using this code as a model for alternative VFSes, do not
  35057. ** copy this retry logic. It is a hack intended for Windows only.
  35058. */
  35059. lastErrno = osGetLastError();
  35060. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  35061. pFile->h, cnt, res));
  35062. if( lastErrno==ERROR_INVALID_HANDLE ){
  35063. pFile->lastErrno = lastErrno;
  35064. rc = SQLITE_IOERR_LOCK;
  35065. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  35066. pFile->h, cnt, sqlite3ErrName(rc)));
  35067. return rc;
  35068. }
  35069. if( cnt ) sqlite3_win32_sleep(1);
  35070. }
  35071. gotPendingLock = res;
  35072. if( !res ){
  35073. lastErrno = osGetLastError();
  35074. }
  35075. }
  35076. /* Acquire a shared lock
  35077. */
  35078. if( locktype==SHARED_LOCK && res ){
  35079. assert( pFile->locktype==NO_LOCK );
  35080. res = winGetReadLock(pFile);
  35081. if( res ){
  35082. newLocktype = SHARED_LOCK;
  35083. }else{
  35084. lastErrno = osGetLastError();
  35085. }
  35086. }
  35087. /* Acquire a RESERVED lock
  35088. */
  35089. if( locktype==RESERVED_LOCK && res ){
  35090. assert( pFile->locktype==SHARED_LOCK );
  35091. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  35092. if( res ){
  35093. newLocktype = RESERVED_LOCK;
  35094. }else{
  35095. lastErrno = osGetLastError();
  35096. }
  35097. }
  35098. /* Acquire a PENDING lock
  35099. */
  35100. if( locktype==EXCLUSIVE_LOCK && res ){
  35101. newLocktype = PENDING_LOCK;
  35102. gotPendingLock = 0;
  35103. }
  35104. /* Acquire an EXCLUSIVE lock
  35105. */
  35106. if( locktype==EXCLUSIVE_LOCK && res ){
  35107. assert( pFile->locktype>=SHARED_LOCK );
  35108. res = winUnlockReadLock(pFile);
  35109. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  35110. SHARED_SIZE, 0);
  35111. if( res ){
  35112. newLocktype = EXCLUSIVE_LOCK;
  35113. }else{
  35114. lastErrno = osGetLastError();
  35115. winGetReadLock(pFile);
  35116. }
  35117. }
  35118. /* If we are holding a PENDING lock that ought to be released, then
  35119. ** release it now.
  35120. */
  35121. if( gotPendingLock && locktype==SHARED_LOCK ){
  35122. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  35123. }
  35124. /* Update the state of the lock has held in the file descriptor then
  35125. ** return the appropriate result code.
  35126. */
  35127. if( res ){
  35128. rc = SQLITE_OK;
  35129. }else{
  35130. pFile->lastErrno = lastErrno;
  35131. rc = SQLITE_BUSY;
  35132. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  35133. pFile->h, locktype, newLocktype));
  35134. }
  35135. pFile->locktype = (u8)newLocktype;
  35136. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  35137. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  35138. return rc;
  35139. }
  35140. /*
  35141. ** This routine checks if there is a RESERVED lock held on the specified
  35142. ** file by this or any other process. If such a lock is held, return
  35143. ** non-zero, otherwise zero.
  35144. */
  35145. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  35146. int res;
  35147. winFile *pFile = (winFile*)id;
  35148. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35149. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  35150. assert( id!=0 );
  35151. if( pFile->locktype>=RESERVED_LOCK ){
  35152. res = 1;
  35153. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  35154. }else{
  35155. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  35156. if( res ){
  35157. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  35158. }
  35159. res = !res;
  35160. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  35161. }
  35162. *pResOut = res;
  35163. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  35164. pFile->h, pResOut, *pResOut));
  35165. return SQLITE_OK;
  35166. }
  35167. /*
  35168. ** Lower the locking level on file descriptor id to locktype. locktype
  35169. ** must be either NO_LOCK or SHARED_LOCK.
  35170. **
  35171. ** If the locking level of the file descriptor is already at or below
  35172. ** the requested locking level, this routine is a no-op.
  35173. **
  35174. ** It is not possible for this routine to fail if the second argument
  35175. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  35176. ** might return SQLITE_IOERR;
  35177. */
  35178. static int winUnlock(sqlite3_file *id, int locktype){
  35179. int type;
  35180. winFile *pFile = (winFile*)id;
  35181. int rc = SQLITE_OK;
  35182. assert( pFile!=0 );
  35183. assert( locktype<=SHARED_LOCK );
  35184. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  35185. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  35186. type = pFile->locktype;
  35187. if( type>=EXCLUSIVE_LOCK ){
  35188. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  35189. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  35190. /* This should never happen. We should always be able to
  35191. ** reacquire the read lock */
  35192. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  35193. "winUnlock", pFile->zPath);
  35194. }
  35195. }
  35196. if( type>=RESERVED_LOCK ){
  35197. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  35198. }
  35199. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  35200. winUnlockReadLock(pFile);
  35201. }
  35202. if( type>=PENDING_LOCK ){
  35203. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  35204. }
  35205. pFile->locktype = (u8)locktype;
  35206. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  35207. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  35208. return rc;
  35209. }
  35210. /*
  35211. ** If *pArg is initially negative then this is a query. Set *pArg to
  35212. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  35213. **
  35214. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  35215. */
  35216. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  35217. if( *pArg<0 ){
  35218. *pArg = (pFile->ctrlFlags & mask)!=0;
  35219. }else if( (*pArg)==0 ){
  35220. pFile->ctrlFlags &= ~mask;
  35221. }else{
  35222. pFile->ctrlFlags |= mask;
  35223. }
  35224. }
  35225. /* Forward references to VFS helper methods used for temporary files */
  35226. static int winGetTempname(sqlite3_vfs *, char **);
  35227. static int winIsDir(const void *);
  35228. static BOOL winIsDriveLetterAndColon(const char *);
  35229. /*
  35230. ** Control and query of the open file handle.
  35231. */
  35232. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  35233. winFile *pFile = (winFile*)id;
  35234. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  35235. switch( op ){
  35236. case SQLITE_FCNTL_LOCKSTATE: {
  35237. *(int*)pArg = pFile->locktype;
  35238. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35239. return SQLITE_OK;
  35240. }
  35241. case SQLITE_LAST_ERRNO: {
  35242. *(int*)pArg = (int)pFile->lastErrno;
  35243. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35244. return SQLITE_OK;
  35245. }
  35246. case SQLITE_FCNTL_CHUNK_SIZE: {
  35247. pFile->szChunk = *(int *)pArg;
  35248. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35249. return SQLITE_OK;
  35250. }
  35251. case SQLITE_FCNTL_SIZE_HINT: {
  35252. if( pFile->szChunk>0 ){
  35253. sqlite3_int64 oldSz;
  35254. int rc = winFileSize(id, &oldSz);
  35255. if( rc==SQLITE_OK ){
  35256. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  35257. if( newSz>oldSz ){
  35258. SimulateIOErrorBenign(1);
  35259. rc = winTruncate(id, newSz);
  35260. SimulateIOErrorBenign(0);
  35261. }
  35262. }
  35263. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35264. return rc;
  35265. }
  35266. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35267. return SQLITE_OK;
  35268. }
  35269. case SQLITE_FCNTL_PERSIST_WAL: {
  35270. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  35271. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35272. return SQLITE_OK;
  35273. }
  35274. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  35275. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  35276. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35277. return SQLITE_OK;
  35278. }
  35279. case SQLITE_FCNTL_VFSNAME: {
  35280. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  35281. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35282. return SQLITE_OK;
  35283. }
  35284. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  35285. int *a = (int*)pArg;
  35286. if( a[0]>0 ){
  35287. winIoerrRetry = a[0];
  35288. }else{
  35289. a[0] = winIoerrRetry;
  35290. }
  35291. if( a[1]>0 ){
  35292. winIoerrRetryDelay = a[1];
  35293. }else{
  35294. a[1] = winIoerrRetryDelay;
  35295. }
  35296. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35297. return SQLITE_OK;
  35298. }
  35299. #ifdef SQLITE_TEST
  35300. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  35301. LPHANDLE phFile = (LPHANDLE)pArg;
  35302. HANDLE hOldFile = pFile->h;
  35303. pFile->h = *phFile;
  35304. *phFile = hOldFile;
  35305. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  35306. hOldFile, pFile->h));
  35307. return SQLITE_OK;
  35308. }
  35309. #endif
  35310. case SQLITE_FCNTL_TEMPFILENAME: {
  35311. char *zTFile = 0;
  35312. int rc = winGetTempname(pFile->pVfs, &zTFile);
  35313. if( rc==SQLITE_OK ){
  35314. *(char**)pArg = zTFile;
  35315. }
  35316. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35317. return rc;
  35318. }
  35319. #if SQLITE_MAX_MMAP_SIZE>0
  35320. case SQLITE_FCNTL_MMAP_SIZE: {
  35321. i64 newLimit = *(i64*)pArg;
  35322. int rc = SQLITE_OK;
  35323. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  35324. newLimit = sqlite3GlobalConfig.mxMmap;
  35325. }
  35326. *(i64*)pArg = pFile->mmapSizeMax;
  35327. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  35328. pFile->mmapSizeMax = newLimit;
  35329. if( pFile->mmapSize>0 ){
  35330. winUnmapfile(pFile);
  35331. rc = winMapfile(pFile, -1);
  35332. }
  35333. }
  35334. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35335. return rc;
  35336. }
  35337. #endif
  35338. }
  35339. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  35340. return SQLITE_NOTFOUND;
  35341. }
  35342. /*
  35343. ** Return the sector size in bytes of the underlying block device for
  35344. ** the specified file. This is almost always 512 bytes, but may be
  35345. ** larger for some devices.
  35346. **
  35347. ** SQLite code assumes this function cannot fail. It also assumes that
  35348. ** if two files are created in the same file-system directory (i.e.
  35349. ** a database and its journal file) that the sector size will be the
  35350. ** same for both.
  35351. */
  35352. static int winSectorSize(sqlite3_file *id){
  35353. (void)id;
  35354. return SQLITE_DEFAULT_SECTOR_SIZE;
  35355. }
  35356. /*
  35357. ** Return a vector of device characteristics.
  35358. */
  35359. static int winDeviceCharacteristics(sqlite3_file *id){
  35360. winFile *p = (winFile*)id;
  35361. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  35362. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  35363. }
  35364. /*
  35365. ** Windows will only let you create file view mappings
  35366. ** on allocation size granularity boundaries.
  35367. ** During sqlite3_os_init() we do a GetSystemInfo()
  35368. ** to get the granularity size.
  35369. */
  35370. static SYSTEM_INFO winSysInfo;
  35371. #ifndef SQLITE_OMIT_WAL
  35372. /*
  35373. ** Helper functions to obtain and relinquish the global mutex. The
  35374. ** global mutex is used to protect the winLockInfo objects used by
  35375. ** this file, all of which may be shared by multiple threads.
  35376. **
  35377. ** Function winShmMutexHeld() is used to assert() that the global mutex
  35378. ** is held when required. This function is only used as part of assert()
  35379. ** statements. e.g.
  35380. **
  35381. ** winShmEnterMutex()
  35382. ** assert( winShmMutexHeld() );
  35383. ** winShmLeaveMutex()
  35384. */
  35385. static void winShmEnterMutex(void){
  35386. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35387. }
  35388. static void winShmLeaveMutex(void){
  35389. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35390. }
  35391. #ifndef NDEBUG
  35392. static int winShmMutexHeld(void) {
  35393. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35394. }
  35395. #endif
  35396. /*
  35397. ** Object used to represent a single file opened and mmapped to provide
  35398. ** shared memory. When multiple threads all reference the same
  35399. ** log-summary, each thread has its own winFile object, but they all
  35400. ** point to a single instance of this object. In other words, each
  35401. ** log-summary is opened only once per process.
  35402. **
  35403. ** winShmMutexHeld() must be true when creating or destroying
  35404. ** this object or while reading or writing the following fields:
  35405. **
  35406. ** nRef
  35407. ** pNext
  35408. **
  35409. ** The following fields are read-only after the object is created:
  35410. **
  35411. ** fid
  35412. ** zFilename
  35413. **
  35414. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  35415. ** winShmMutexHeld() is true when reading or writing any other field
  35416. ** in this structure.
  35417. **
  35418. */
  35419. struct winShmNode {
  35420. sqlite3_mutex *mutex; /* Mutex to access this object */
  35421. char *zFilename; /* Name of the file */
  35422. winFile hFile; /* File handle from winOpen */
  35423. int szRegion; /* Size of shared-memory regions */
  35424. int nRegion; /* Size of array apRegion */
  35425. struct ShmRegion {
  35426. HANDLE hMap; /* File handle from CreateFileMapping */
  35427. void *pMap;
  35428. } *aRegion;
  35429. DWORD lastErrno; /* The Windows errno from the last I/O error */
  35430. int nRef; /* Number of winShm objects pointing to this */
  35431. winShm *pFirst; /* All winShm objects pointing to this */
  35432. winShmNode *pNext; /* Next in list of all winShmNode objects */
  35433. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35434. u8 nextShmId; /* Next available winShm.id value */
  35435. #endif
  35436. };
  35437. /*
  35438. ** A global array of all winShmNode objects.
  35439. **
  35440. ** The winShmMutexHeld() must be true while reading or writing this list.
  35441. */
  35442. static winShmNode *winShmNodeList = 0;
  35443. /*
  35444. ** Structure used internally by this VFS to record the state of an
  35445. ** open shared memory connection.
  35446. **
  35447. ** The following fields are initialized when this object is created and
  35448. ** are read-only thereafter:
  35449. **
  35450. ** winShm.pShmNode
  35451. ** winShm.id
  35452. **
  35453. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  35454. ** while accessing any read/write fields.
  35455. */
  35456. struct winShm {
  35457. winShmNode *pShmNode; /* The underlying winShmNode object */
  35458. winShm *pNext; /* Next winShm with the same winShmNode */
  35459. u8 hasMutex; /* True if holding the winShmNode mutex */
  35460. u16 sharedMask; /* Mask of shared locks held */
  35461. u16 exclMask; /* Mask of exclusive locks held */
  35462. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35463. u8 id; /* Id of this connection with its winShmNode */
  35464. #endif
  35465. };
  35466. /*
  35467. ** Constants used for locking
  35468. */
  35469. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  35470. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  35471. /*
  35472. ** Apply advisory locks for all n bytes beginning at ofst.
  35473. */
  35474. #define _SHM_UNLCK 1
  35475. #define _SHM_RDLCK 2
  35476. #define _SHM_WRLCK 3
  35477. static int winShmSystemLock(
  35478. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  35479. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  35480. int ofst, /* Offset to first byte to be locked/unlocked */
  35481. int nByte /* Number of bytes to lock or unlock */
  35482. ){
  35483. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  35484. /* Access to the winShmNode object is serialized by the caller */
  35485. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  35486. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  35487. pFile->hFile.h, lockType, ofst, nByte));
  35488. /* Release/Acquire the system-level lock */
  35489. if( lockType==_SHM_UNLCK ){
  35490. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  35491. }else{
  35492. /* Initialize the locking parameters */
  35493. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  35494. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  35495. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  35496. }
  35497. if( rc!= 0 ){
  35498. rc = SQLITE_OK;
  35499. }else{
  35500. pFile->lastErrno = osGetLastError();
  35501. rc = SQLITE_BUSY;
  35502. }
  35503. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  35504. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  35505. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  35506. return rc;
  35507. }
  35508. /* Forward references to VFS methods */
  35509. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  35510. static int winDelete(sqlite3_vfs *,const char*,int);
  35511. /*
  35512. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  35513. **
  35514. ** This is not a VFS shared-memory method; it is a utility function called
  35515. ** by VFS shared-memory methods.
  35516. */
  35517. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  35518. winShmNode **pp;
  35519. winShmNode *p;
  35520. assert( winShmMutexHeld() );
  35521. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  35522. osGetCurrentProcessId(), deleteFlag));
  35523. pp = &winShmNodeList;
  35524. while( (p = *pp)!=0 ){
  35525. if( p->nRef==0 ){
  35526. int i;
  35527. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  35528. for(i=0; i<p->nRegion; i++){
  35529. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  35530. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  35531. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  35532. UNUSED_VARIABLE_VALUE(bRc);
  35533. bRc = osCloseHandle(p->aRegion[i].hMap);
  35534. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  35535. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  35536. UNUSED_VARIABLE_VALUE(bRc);
  35537. }
  35538. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  35539. SimulateIOErrorBenign(1);
  35540. winClose((sqlite3_file *)&p->hFile);
  35541. SimulateIOErrorBenign(0);
  35542. }
  35543. if( deleteFlag ){
  35544. SimulateIOErrorBenign(1);
  35545. sqlite3BeginBenignMalloc();
  35546. winDelete(pVfs, p->zFilename, 0);
  35547. sqlite3EndBenignMalloc();
  35548. SimulateIOErrorBenign(0);
  35549. }
  35550. *pp = p->pNext;
  35551. sqlite3_free(p->aRegion);
  35552. sqlite3_free(p);
  35553. }else{
  35554. pp = &p->pNext;
  35555. }
  35556. }
  35557. }
  35558. /*
  35559. ** Open the shared-memory area associated with database file pDbFd.
  35560. **
  35561. ** When opening a new shared-memory file, if no other instances of that
  35562. ** file are currently open, in this process or in other processes, then
  35563. ** the file must be truncated to zero length or have its header cleared.
  35564. */
  35565. static int winOpenSharedMemory(winFile *pDbFd){
  35566. struct winShm *p; /* The connection to be opened */
  35567. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  35568. int rc; /* Result code */
  35569. struct winShmNode *pNew; /* Newly allocated winShmNode */
  35570. int nName; /* Size of zName in bytes */
  35571. assert( pDbFd->pShm==0 ); /* Not previously opened */
  35572. /* Allocate space for the new sqlite3_shm object. Also speculatively
  35573. ** allocate space for a new winShmNode and filename.
  35574. */
  35575. p = sqlite3MallocZero( sizeof(*p) );
  35576. if( p==0 ) return SQLITE_IOERR_NOMEM;
  35577. nName = sqlite3Strlen30(pDbFd->zPath);
  35578. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  35579. if( pNew==0 ){
  35580. sqlite3_free(p);
  35581. return SQLITE_IOERR_NOMEM;
  35582. }
  35583. pNew->zFilename = (char*)&pNew[1];
  35584. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  35585. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  35586. /* Look to see if there is an existing winShmNode that can be used.
  35587. ** If no matching winShmNode currently exists, create a new one.
  35588. */
  35589. winShmEnterMutex();
  35590. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  35591. /* TBD need to come up with better match here. Perhaps
  35592. ** use FILE_ID_BOTH_DIR_INFO Structure.
  35593. */
  35594. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  35595. }
  35596. if( pShmNode ){
  35597. sqlite3_free(pNew);
  35598. }else{
  35599. pShmNode = pNew;
  35600. pNew = 0;
  35601. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  35602. pShmNode->pNext = winShmNodeList;
  35603. winShmNodeList = pShmNode;
  35604. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  35605. if( pShmNode->mutex==0 ){
  35606. rc = SQLITE_IOERR_NOMEM;
  35607. goto shm_open_err;
  35608. }
  35609. rc = winOpen(pDbFd->pVfs,
  35610. pShmNode->zFilename, /* Name of the file (UTF-8) */
  35611. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  35612. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  35613. 0);
  35614. if( SQLITE_OK!=rc ){
  35615. goto shm_open_err;
  35616. }
  35617. /* Check to see if another process is holding the dead-man switch.
  35618. ** If not, truncate the file to zero length.
  35619. */
  35620. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  35621. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  35622. if( rc!=SQLITE_OK ){
  35623. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  35624. "winOpenShm", pDbFd->zPath);
  35625. }
  35626. }
  35627. if( rc==SQLITE_OK ){
  35628. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  35629. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  35630. }
  35631. if( rc ) goto shm_open_err;
  35632. }
  35633. /* Make the new connection a child of the winShmNode */
  35634. p->pShmNode = pShmNode;
  35635. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35636. p->id = pShmNode->nextShmId++;
  35637. #endif
  35638. pShmNode->nRef++;
  35639. pDbFd->pShm = p;
  35640. winShmLeaveMutex();
  35641. /* The reference count on pShmNode has already been incremented under
  35642. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  35643. ** new (struct winShm) object to the pShmNode has been set. All that is
  35644. ** left to do is to link the new object into the linked list starting
  35645. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  35646. ** mutex.
  35647. */
  35648. sqlite3_mutex_enter(pShmNode->mutex);
  35649. p->pNext = pShmNode->pFirst;
  35650. pShmNode->pFirst = p;
  35651. sqlite3_mutex_leave(pShmNode->mutex);
  35652. return SQLITE_OK;
  35653. /* Jump here on any error */
  35654. shm_open_err:
  35655. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  35656. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  35657. sqlite3_free(p);
  35658. sqlite3_free(pNew);
  35659. winShmLeaveMutex();
  35660. return rc;
  35661. }
  35662. /*
  35663. ** Close a connection to shared-memory. Delete the underlying
  35664. ** storage if deleteFlag is true.
  35665. */
  35666. static int winShmUnmap(
  35667. sqlite3_file *fd, /* Database holding shared memory */
  35668. int deleteFlag /* Delete after closing if true */
  35669. ){
  35670. winFile *pDbFd; /* Database holding shared-memory */
  35671. winShm *p; /* The connection to be closed */
  35672. winShmNode *pShmNode; /* The underlying shared-memory file */
  35673. winShm **pp; /* For looping over sibling connections */
  35674. pDbFd = (winFile*)fd;
  35675. p = pDbFd->pShm;
  35676. if( p==0 ) return SQLITE_OK;
  35677. pShmNode = p->pShmNode;
  35678. /* Remove connection p from the set of connections associated
  35679. ** with pShmNode */
  35680. sqlite3_mutex_enter(pShmNode->mutex);
  35681. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  35682. *pp = p->pNext;
  35683. /* Free the connection p */
  35684. sqlite3_free(p);
  35685. pDbFd->pShm = 0;
  35686. sqlite3_mutex_leave(pShmNode->mutex);
  35687. /* If pShmNode->nRef has reached 0, then close the underlying
  35688. ** shared-memory file, too */
  35689. winShmEnterMutex();
  35690. assert( pShmNode->nRef>0 );
  35691. pShmNode->nRef--;
  35692. if( pShmNode->nRef==0 ){
  35693. winShmPurge(pDbFd->pVfs, deleteFlag);
  35694. }
  35695. winShmLeaveMutex();
  35696. return SQLITE_OK;
  35697. }
  35698. /*
  35699. ** Change the lock state for a shared-memory segment.
  35700. */
  35701. static int winShmLock(
  35702. sqlite3_file *fd, /* Database file holding the shared memory */
  35703. int ofst, /* First lock to acquire or release */
  35704. int n, /* Number of locks to acquire or release */
  35705. int flags /* What to do with the lock */
  35706. ){
  35707. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  35708. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  35709. winShm *pX; /* For looping over all siblings */
  35710. winShmNode *pShmNode = p->pShmNode;
  35711. int rc = SQLITE_OK; /* Result code */
  35712. u16 mask; /* Mask of locks to take or release */
  35713. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  35714. assert( n>=1 );
  35715. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  35716. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  35717. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  35718. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  35719. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  35720. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  35721. assert( n>1 || mask==(1<<ofst) );
  35722. sqlite3_mutex_enter(pShmNode->mutex);
  35723. if( flags & SQLITE_SHM_UNLOCK ){
  35724. u16 allMask = 0; /* Mask of locks held by siblings */
  35725. /* See if any siblings hold this same lock */
  35726. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35727. if( pX==p ) continue;
  35728. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  35729. allMask |= pX->sharedMask;
  35730. }
  35731. /* Unlock the system-level locks */
  35732. if( (mask & allMask)==0 ){
  35733. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  35734. }else{
  35735. rc = SQLITE_OK;
  35736. }
  35737. /* Undo the local locks */
  35738. if( rc==SQLITE_OK ){
  35739. p->exclMask &= ~mask;
  35740. p->sharedMask &= ~mask;
  35741. }
  35742. }else if( flags & SQLITE_SHM_SHARED ){
  35743. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  35744. /* Find out which shared locks are already held by sibling connections.
  35745. ** If any sibling already holds an exclusive lock, go ahead and return
  35746. ** SQLITE_BUSY.
  35747. */
  35748. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35749. if( (pX->exclMask & mask)!=0 ){
  35750. rc = SQLITE_BUSY;
  35751. break;
  35752. }
  35753. allShared |= pX->sharedMask;
  35754. }
  35755. /* Get shared locks at the system level, if necessary */
  35756. if( rc==SQLITE_OK ){
  35757. if( (allShared & mask)==0 ){
  35758. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  35759. }else{
  35760. rc = SQLITE_OK;
  35761. }
  35762. }
  35763. /* Get the local shared locks */
  35764. if( rc==SQLITE_OK ){
  35765. p->sharedMask |= mask;
  35766. }
  35767. }else{
  35768. /* Make sure no sibling connections hold locks that will block this
  35769. ** lock. If any do, return SQLITE_BUSY right away.
  35770. */
  35771. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35772. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  35773. rc = SQLITE_BUSY;
  35774. break;
  35775. }
  35776. }
  35777. /* Get the exclusive locks at the system level. Then if successful
  35778. ** also mark the local connection as being locked.
  35779. */
  35780. if( rc==SQLITE_OK ){
  35781. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  35782. if( rc==SQLITE_OK ){
  35783. assert( (p->sharedMask & mask)==0 );
  35784. p->exclMask |= mask;
  35785. }
  35786. }
  35787. }
  35788. sqlite3_mutex_leave(pShmNode->mutex);
  35789. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  35790. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  35791. sqlite3ErrName(rc)));
  35792. return rc;
  35793. }
  35794. /*
  35795. ** Implement a memory barrier or memory fence on shared memory.
  35796. **
  35797. ** All loads and stores begun before the barrier must complete before
  35798. ** any load or store begun after the barrier.
  35799. */
  35800. static void winShmBarrier(
  35801. sqlite3_file *fd /* Database holding the shared memory */
  35802. ){
  35803. UNUSED_PARAMETER(fd);
  35804. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  35805. winShmEnterMutex(); /* Also mutex, for redundancy */
  35806. winShmLeaveMutex();
  35807. }
  35808. /*
  35809. ** This function is called to obtain a pointer to region iRegion of the
  35810. ** shared-memory associated with the database file fd. Shared-memory regions
  35811. ** are numbered starting from zero. Each shared-memory region is szRegion
  35812. ** bytes in size.
  35813. **
  35814. ** If an error occurs, an error code is returned and *pp is set to NULL.
  35815. **
  35816. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  35817. ** region has not been allocated (by any client, including one running in a
  35818. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  35819. ** isWrite is non-zero and the requested shared-memory region has not yet
  35820. ** been allocated, it is allocated by this function.
  35821. **
  35822. ** If the shared-memory region has already been allocated or is allocated by
  35823. ** this call as described above, then it is mapped into this processes
  35824. ** address space (if it is not already), *pp is set to point to the mapped
  35825. ** memory and SQLITE_OK returned.
  35826. */
  35827. static int winShmMap(
  35828. sqlite3_file *fd, /* Handle open on database file */
  35829. int iRegion, /* Region to retrieve */
  35830. int szRegion, /* Size of regions */
  35831. int isWrite, /* True to extend file if necessary */
  35832. void volatile **pp /* OUT: Mapped memory */
  35833. ){
  35834. winFile *pDbFd = (winFile*)fd;
  35835. winShm *pShm = pDbFd->pShm;
  35836. winShmNode *pShmNode;
  35837. int rc = SQLITE_OK;
  35838. if( !pShm ){
  35839. rc = winOpenSharedMemory(pDbFd);
  35840. if( rc!=SQLITE_OK ) return rc;
  35841. pShm = pDbFd->pShm;
  35842. }
  35843. pShmNode = pShm->pShmNode;
  35844. sqlite3_mutex_enter(pShmNode->mutex);
  35845. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  35846. if( pShmNode->nRegion<=iRegion ){
  35847. struct ShmRegion *apNew; /* New aRegion[] array */
  35848. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  35849. sqlite3_int64 sz; /* Current size of wal-index file */
  35850. pShmNode->szRegion = szRegion;
  35851. /* The requested region is not mapped into this processes address space.
  35852. ** Check to see if it has been allocated (i.e. if the wal-index file is
  35853. ** large enough to contain the requested region).
  35854. */
  35855. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  35856. if( rc!=SQLITE_OK ){
  35857. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  35858. "winShmMap1", pDbFd->zPath);
  35859. goto shmpage_out;
  35860. }
  35861. if( sz<nByte ){
  35862. /* The requested memory region does not exist. If isWrite is set to
  35863. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  35864. **
  35865. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  35866. ** the requested memory region.
  35867. */
  35868. if( !isWrite ) goto shmpage_out;
  35869. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  35870. if( rc!=SQLITE_OK ){
  35871. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  35872. "winShmMap2", pDbFd->zPath);
  35873. goto shmpage_out;
  35874. }
  35875. }
  35876. /* Map the requested memory region into this processes address space. */
  35877. apNew = (struct ShmRegion *)sqlite3_realloc64(
  35878. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  35879. );
  35880. if( !apNew ){
  35881. rc = SQLITE_IOERR_NOMEM;
  35882. goto shmpage_out;
  35883. }
  35884. pShmNode->aRegion = apNew;
  35885. while( pShmNode->nRegion<=iRegion ){
  35886. HANDLE hMap = NULL; /* file-mapping handle */
  35887. void *pMap = 0; /* Mapped memory region */
  35888. #if SQLITE_OS_WINRT
  35889. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  35890. NULL, PAGE_READWRITE, nByte, NULL
  35891. );
  35892. #elif defined(SQLITE_WIN32_HAS_WIDE)
  35893. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  35894. NULL, PAGE_READWRITE, 0, nByte, NULL
  35895. );
  35896. #elif defined(SQLITE_WIN32_HAS_ANSI)
  35897. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  35898. NULL, PAGE_READWRITE, 0, nByte, NULL
  35899. );
  35900. #endif
  35901. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  35902. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  35903. hMap ? "ok" : "failed"));
  35904. if( hMap ){
  35905. int iOffset = pShmNode->nRegion*szRegion;
  35906. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  35907. #if SQLITE_OS_WINRT
  35908. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  35909. iOffset - iOffsetShift, szRegion + iOffsetShift
  35910. );
  35911. #else
  35912. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  35913. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  35914. );
  35915. #endif
  35916. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  35917. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  35918. szRegion, pMap ? "ok" : "failed"));
  35919. }
  35920. if( !pMap ){
  35921. pShmNode->lastErrno = osGetLastError();
  35922. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  35923. "winShmMap3", pDbFd->zPath);
  35924. if( hMap ) osCloseHandle(hMap);
  35925. goto shmpage_out;
  35926. }
  35927. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  35928. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  35929. pShmNode->nRegion++;
  35930. }
  35931. }
  35932. shmpage_out:
  35933. if( pShmNode->nRegion>iRegion ){
  35934. int iOffset = iRegion*szRegion;
  35935. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  35936. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  35937. *pp = (void *)&p[iOffsetShift];
  35938. }else{
  35939. *pp = 0;
  35940. }
  35941. sqlite3_mutex_leave(pShmNode->mutex);
  35942. return rc;
  35943. }
  35944. #else
  35945. # define winShmMap 0
  35946. # define winShmLock 0
  35947. # define winShmBarrier 0
  35948. # define winShmUnmap 0
  35949. #endif /* #ifndef SQLITE_OMIT_WAL */
  35950. /*
  35951. ** Cleans up the mapped region of the specified file, if any.
  35952. */
  35953. #if SQLITE_MAX_MMAP_SIZE>0
  35954. static int winUnmapfile(winFile *pFile){
  35955. assert( pFile!=0 );
  35956. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  35957. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  35958. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  35959. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  35960. if( pFile->pMapRegion ){
  35961. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  35962. pFile->lastErrno = osGetLastError();
  35963. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  35964. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  35965. pFile->pMapRegion));
  35966. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35967. "winUnmapfile1", pFile->zPath);
  35968. }
  35969. pFile->pMapRegion = 0;
  35970. pFile->mmapSize = 0;
  35971. pFile->mmapSizeActual = 0;
  35972. }
  35973. if( pFile->hMap!=NULL ){
  35974. if( !osCloseHandle(pFile->hMap) ){
  35975. pFile->lastErrno = osGetLastError();
  35976. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  35977. osGetCurrentProcessId(), pFile, pFile->hMap));
  35978. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35979. "winUnmapfile2", pFile->zPath);
  35980. }
  35981. pFile->hMap = NULL;
  35982. }
  35983. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  35984. osGetCurrentProcessId(), pFile));
  35985. return SQLITE_OK;
  35986. }
  35987. /*
  35988. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  35989. ** is already mapped, the existing mapping is replaced by the new). Or, if
  35990. ** there already exists a mapping for this file, and there are still
  35991. ** outstanding xFetch() references to it, this function is a no-op.
  35992. **
  35993. ** If parameter nByte is non-negative, then it is the requested size of
  35994. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  35995. ** requested size is the size of the file on disk. The actual size of the
  35996. ** created mapping is either the requested size or the value configured
  35997. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  35998. **
  35999. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  36000. ** recreated as a result of outstanding references) or an SQLite error
  36001. ** code otherwise.
  36002. */
  36003. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  36004. sqlite3_int64 nMap = nByte;
  36005. int rc;
  36006. assert( nMap>=0 || pFd->nFetchOut==0 );
  36007. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  36008. osGetCurrentProcessId(), pFd, nByte));
  36009. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  36010. if( nMap<0 ){
  36011. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  36012. if( rc ){
  36013. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  36014. osGetCurrentProcessId(), pFd));
  36015. return SQLITE_IOERR_FSTAT;
  36016. }
  36017. }
  36018. if( nMap>pFd->mmapSizeMax ){
  36019. nMap = pFd->mmapSizeMax;
  36020. }
  36021. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  36022. if( nMap==0 && pFd->mmapSize>0 ){
  36023. winUnmapfile(pFd);
  36024. }
  36025. if( nMap!=pFd->mmapSize ){
  36026. void *pNew = 0;
  36027. DWORD protect = PAGE_READONLY;
  36028. DWORD flags = FILE_MAP_READ;
  36029. winUnmapfile(pFd);
  36030. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  36031. protect = PAGE_READWRITE;
  36032. flags |= FILE_MAP_WRITE;
  36033. }
  36034. #if SQLITE_OS_WINRT
  36035. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  36036. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36037. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  36038. (DWORD)((nMap>>32) & 0xffffffff),
  36039. (DWORD)(nMap & 0xffffffff), NULL);
  36040. #elif defined(SQLITE_WIN32_HAS_ANSI)
  36041. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  36042. (DWORD)((nMap>>32) & 0xffffffff),
  36043. (DWORD)(nMap & 0xffffffff), NULL);
  36044. #endif
  36045. if( pFd->hMap==NULL ){
  36046. pFd->lastErrno = osGetLastError();
  36047. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36048. "winMapfile1", pFd->zPath);
  36049. /* Log the error, but continue normal operation using xRead/xWrite */
  36050. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  36051. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36052. return SQLITE_OK;
  36053. }
  36054. assert( (nMap % winSysInfo.dwPageSize)==0 );
  36055. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  36056. #if SQLITE_OS_WINRT
  36057. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  36058. #else
  36059. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  36060. #endif
  36061. if( pNew==NULL ){
  36062. osCloseHandle(pFd->hMap);
  36063. pFd->hMap = NULL;
  36064. pFd->lastErrno = osGetLastError();
  36065. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36066. "winMapfile2", pFd->zPath);
  36067. /* Log the error, but continue normal operation using xRead/xWrite */
  36068. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  36069. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36070. return SQLITE_OK;
  36071. }
  36072. pFd->pMapRegion = pNew;
  36073. pFd->mmapSize = nMap;
  36074. pFd->mmapSizeActual = nMap;
  36075. }
  36076. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36077. osGetCurrentProcessId(), pFd));
  36078. return SQLITE_OK;
  36079. }
  36080. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  36081. /*
  36082. ** If possible, return a pointer to a mapping of file fd starting at offset
  36083. ** iOff. The mapping must be valid for at least nAmt bytes.
  36084. **
  36085. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  36086. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  36087. ** Finally, if an error does occur, return an SQLite error code. The final
  36088. ** value of *pp is undefined in this case.
  36089. **
  36090. ** If this function does return a pointer, the caller must eventually
  36091. ** release the reference by calling winUnfetch().
  36092. */
  36093. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  36094. #if SQLITE_MAX_MMAP_SIZE>0
  36095. winFile *pFd = (winFile*)fd; /* The underlying database file */
  36096. #endif
  36097. *pp = 0;
  36098. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  36099. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  36100. #if SQLITE_MAX_MMAP_SIZE>0
  36101. if( pFd->mmapSizeMax>0 ){
  36102. if( pFd->pMapRegion==0 ){
  36103. int rc = winMapfile(pFd, -1);
  36104. if( rc!=SQLITE_OK ){
  36105. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  36106. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36107. return rc;
  36108. }
  36109. }
  36110. if( pFd->mmapSize >= iOff+nAmt ){
  36111. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  36112. pFd->nFetchOut++;
  36113. }
  36114. }
  36115. #endif
  36116. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  36117. osGetCurrentProcessId(), fd, pp, *pp));
  36118. return SQLITE_OK;
  36119. }
  36120. /*
  36121. ** If the third argument is non-NULL, then this function releases a
  36122. ** reference obtained by an earlier call to winFetch(). The second
  36123. ** argument passed to this function must be the same as the corresponding
  36124. ** argument that was passed to the winFetch() invocation.
  36125. **
  36126. ** Or, if the third argument is NULL, then this function is being called
  36127. ** to inform the VFS layer that, according to POSIX, any existing mapping
  36128. ** may now be invalid and should be unmapped.
  36129. */
  36130. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  36131. #if SQLITE_MAX_MMAP_SIZE>0
  36132. winFile *pFd = (winFile*)fd; /* The underlying database file */
  36133. /* If p==0 (unmap the entire file) then there must be no outstanding
  36134. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  36135. ** then there must be at least one outstanding. */
  36136. assert( (p==0)==(pFd->nFetchOut==0) );
  36137. /* If p!=0, it must match the iOff value. */
  36138. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  36139. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  36140. osGetCurrentProcessId(), pFd, iOff, p));
  36141. if( p ){
  36142. pFd->nFetchOut--;
  36143. }else{
  36144. /* FIXME: If Windows truly always prevents truncating or deleting a
  36145. ** file while a mapping is held, then the following winUnmapfile() call
  36146. ** is unnecessary can be omitted - potentially improving
  36147. ** performance. */
  36148. winUnmapfile(pFd);
  36149. }
  36150. assert( pFd->nFetchOut>=0 );
  36151. #endif
  36152. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36153. osGetCurrentProcessId(), fd));
  36154. return SQLITE_OK;
  36155. }
  36156. /*
  36157. ** Here ends the implementation of all sqlite3_file methods.
  36158. **
  36159. ********************** End sqlite3_file Methods *******************************
  36160. ******************************************************************************/
  36161. /*
  36162. ** This vector defines all the methods that can operate on an
  36163. ** sqlite3_file for win32.
  36164. */
  36165. static const sqlite3_io_methods winIoMethod = {
  36166. 3, /* iVersion */
  36167. winClose, /* xClose */
  36168. winRead, /* xRead */
  36169. winWrite, /* xWrite */
  36170. winTruncate, /* xTruncate */
  36171. winSync, /* xSync */
  36172. winFileSize, /* xFileSize */
  36173. winLock, /* xLock */
  36174. winUnlock, /* xUnlock */
  36175. winCheckReservedLock, /* xCheckReservedLock */
  36176. winFileControl, /* xFileControl */
  36177. winSectorSize, /* xSectorSize */
  36178. winDeviceCharacteristics, /* xDeviceCharacteristics */
  36179. winShmMap, /* xShmMap */
  36180. winShmLock, /* xShmLock */
  36181. winShmBarrier, /* xShmBarrier */
  36182. winShmUnmap, /* xShmUnmap */
  36183. winFetch, /* xFetch */
  36184. winUnfetch /* xUnfetch */
  36185. };
  36186. /****************************************************************************
  36187. **************************** sqlite3_vfs methods ****************************
  36188. **
  36189. ** This division contains the implementation of methods on the
  36190. ** sqlite3_vfs object.
  36191. */
  36192. #if defined(__CYGWIN__)
  36193. /*
  36194. ** Convert a filename from whatever the underlying operating system
  36195. ** supports for filenames into UTF-8. Space to hold the result is
  36196. ** obtained from malloc and must be freed by the calling function.
  36197. */
  36198. static char *winConvertToUtf8Filename(const void *zFilename){
  36199. char *zConverted = 0;
  36200. if( osIsNT() ){
  36201. zConverted = winUnicodeToUtf8(zFilename);
  36202. }
  36203. #ifdef SQLITE_WIN32_HAS_ANSI
  36204. else{
  36205. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  36206. }
  36207. #endif
  36208. /* caller will handle out of memory */
  36209. return zConverted;
  36210. }
  36211. #endif
  36212. /*
  36213. ** Convert a UTF-8 filename into whatever form the underlying
  36214. ** operating system wants filenames in. Space to hold the result
  36215. ** is obtained from malloc and must be freed by the calling
  36216. ** function.
  36217. */
  36218. static void *winConvertFromUtf8Filename(const char *zFilename){
  36219. void *zConverted = 0;
  36220. if( osIsNT() ){
  36221. zConverted = winUtf8ToUnicode(zFilename);
  36222. }
  36223. #ifdef SQLITE_WIN32_HAS_ANSI
  36224. else{
  36225. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  36226. }
  36227. #endif
  36228. /* caller will handle out of memory */
  36229. return zConverted;
  36230. }
  36231. /*
  36232. ** This function returns non-zero if the specified UTF-8 string buffer
  36233. ** ends with a directory separator character or one was successfully
  36234. ** added to it.
  36235. */
  36236. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  36237. if( zBuf ){
  36238. int nLen = sqlite3Strlen30(zBuf);
  36239. if( nLen>0 ){
  36240. if( winIsDirSep(zBuf[nLen-1]) ){
  36241. return 1;
  36242. }else if( nLen+1<nBuf ){
  36243. zBuf[nLen] = winGetDirSep();
  36244. zBuf[nLen+1] = '\0';
  36245. return 1;
  36246. }
  36247. }
  36248. }
  36249. return 0;
  36250. }
  36251. /*
  36252. ** Create a temporary file name and store the resulting pointer into pzBuf.
  36253. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  36254. */
  36255. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  36256. static char zChars[] =
  36257. "abcdefghijklmnopqrstuvwxyz"
  36258. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36259. "0123456789";
  36260. size_t i, j;
  36261. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  36262. int nMax, nBuf, nDir, nLen;
  36263. char *zBuf;
  36264. /* It's odd to simulate an io-error here, but really this is just
  36265. ** using the io-error infrastructure to test that SQLite handles this
  36266. ** function failing.
  36267. */
  36268. SimulateIOError( return SQLITE_IOERR );
  36269. /* Allocate a temporary buffer to store the fully qualified file
  36270. ** name for the temporary file. If this fails, we cannot continue.
  36271. */
  36272. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  36273. zBuf = sqlite3MallocZero( nBuf );
  36274. if( !zBuf ){
  36275. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36276. return SQLITE_IOERR_NOMEM;
  36277. }
  36278. /* Figure out the effective temporary directory. First, check if one
  36279. ** has been explicitly set by the application; otherwise, use the one
  36280. ** configured by the operating system.
  36281. */
  36282. nDir = nMax - (nPre + 15);
  36283. assert( nDir>0 );
  36284. if( sqlite3_temp_directory ){
  36285. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  36286. if( nDirLen>0 ){
  36287. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  36288. nDirLen++;
  36289. }
  36290. if( nDirLen>nDir ){
  36291. sqlite3_free(zBuf);
  36292. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36293. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  36294. }
  36295. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  36296. }
  36297. }
  36298. #if defined(__CYGWIN__)
  36299. else{
  36300. static const char *azDirs[] = {
  36301. 0, /* getenv("SQLITE_TMPDIR") */
  36302. 0, /* getenv("TMPDIR") */
  36303. 0, /* getenv("TMP") */
  36304. 0, /* getenv("TEMP") */
  36305. 0, /* getenv("USERPROFILE") */
  36306. "/var/tmp",
  36307. "/usr/tmp",
  36308. "/tmp",
  36309. ".",
  36310. 0 /* List terminator */
  36311. };
  36312. unsigned int i;
  36313. const char *zDir = 0;
  36314. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  36315. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  36316. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  36317. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  36318. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  36319. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  36320. void *zConverted;
  36321. if( zDir==0 ) continue;
  36322. /* If the path starts with a drive letter followed by the colon
  36323. ** character, assume it is already a native Win32 path; otherwise,
  36324. ** it must be converted to a native Win32 path via the Cygwin API
  36325. ** prior to using it.
  36326. */
  36327. if( winIsDriveLetterAndColon(zDir) ){
  36328. zConverted = winConvertFromUtf8Filename(zDir);
  36329. if( !zConverted ){
  36330. sqlite3_free(zBuf);
  36331. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36332. return SQLITE_IOERR_NOMEM;
  36333. }
  36334. if( winIsDir(zConverted) ){
  36335. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  36336. sqlite3_free(zConverted);
  36337. break;
  36338. }
  36339. sqlite3_free(zConverted);
  36340. }else{
  36341. zConverted = sqlite3MallocZero( nMax+1 );
  36342. if( !zConverted ){
  36343. sqlite3_free(zBuf);
  36344. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36345. return SQLITE_IOERR_NOMEM;
  36346. }
  36347. if( cygwin_conv_path(
  36348. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  36349. zConverted, nMax+1)<0 ){
  36350. sqlite3_free(zConverted);
  36351. sqlite3_free(zBuf);
  36352. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  36353. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  36354. "winGetTempname2", zDir);
  36355. }
  36356. if( winIsDir(zConverted) ){
  36357. /* At this point, we know the candidate directory exists and should
  36358. ** be used. However, we may need to convert the string containing
  36359. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  36360. */
  36361. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  36362. if( !zUtf8 ){
  36363. sqlite3_free(zConverted);
  36364. sqlite3_free(zBuf);
  36365. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36366. return SQLITE_IOERR_NOMEM;
  36367. }
  36368. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  36369. sqlite3_free(zUtf8);
  36370. sqlite3_free(zConverted);
  36371. break;
  36372. }
  36373. sqlite3_free(zConverted);
  36374. }
  36375. }
  36376. }
  36377. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  36378. else if( osIsNT() ){
  36379. char *zMulti;
  36380. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  36381. if( !zWidePath ){
  36382. sqlite3_free(zBuf);
  36383. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36384. return SQLITE_IOERR_NOMEM;
  36385. }
  36386. if( osGetTempPathW(nMax, zWidePath)==0 ){
  36387. sqlite3_free(zWidePath);
  36388. sqlite3_free(zBuf);
  36389. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  36390. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  36391. "winGetTempname2", 0);
  36392. }
  36393. zMulti = winUnicodeToUtf8(zWidePath);
  36394. if( zMulti ){
  36395. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  36396. sqlite3_free(zMulti);
  36397. sqlite3_free(zWidePath);
  36398. }else{
  36399. sqlite3_free(zWidePath);
  36400. sqlite3_free(zBuf);
  36401. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36402. return SQLITE_IOERR_NOMEM;
  36403. }
  36404. }
  36405. #ifdef SQLITE_WIN32_HAS_ANSI
  36406. else{
  36407. char *zUtf8;
  36408. char *zMbcsPath = sqlite3MallocZero( nMax );
  36409. if( !zMbcsPath ){
  36410. sqlite3_free(zBuf);
  36411. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36412. return SQLITE_IOERR_NOMEM;
  36413. }
  36414. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  36415. sqlite3_free(zBuf);
  36416. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  36417. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  36418. "winGetTempname3", 0);
  36419. }
  36420. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  36421. if( zUtf8 ){
  36422. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  36423. sqlite3_free(zUtf8);
  36424. }else{
  36425. sqlite3_free(zBuf);
  36426. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36427. return SQLITE_IOERR_NOMEM;
  36428. }
  36429. }
  36430. #endif /* SQLITE_WIN32_HAS_ANSI */
  36431. #endif /* !SQLITE_OS_WINRT */
  36432. /*
  36433. ** Check to make sure the temporary directory ends with an appropriate
  36434. ** separator. If it does not and there is not enough space left to add
  36435. ** one, fail.
  36436. */
  36437. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  36438. sqlite3_free(zBuf);
  36439. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36440. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  36441. }
  36442. /*
  36443. ** Check that the output buffer is large enough for the temporary file
  36444. ** name in the following format:
  36445. **
  36446. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  36447. **
  36448. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  36449. ** account for the space used by the 15 character random suffix and the
  36450. ** two trailing NUL characters. The final directory separator character
  36451. ** has already added if it was not already present.
  36452. */
  36453. nLen = sqlite3Strlen30(zBuf);
  36454. if( (nLen + nPre + 17) > nBuf ){
  36455. sqlite3_free(zBuf);
  36456. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36457. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  36458. }
  36459. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  36460. j = sqlite3Strlen30(zBuf);
  36461. sqlite3_randomness(15, &zBuf[j]);
  36462. for(i=0; i<15; i++, j++){
  36463. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  36464. }
  36465. zBuf[j] = 0;
  36466. zBuf[j+1] = 0;
  36467. *pzBuf = zBuf;
  36468. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  36469. return SQLITE_OK;
  36470. }
  36471. /*
  36472. ** Return TRUE if the named file is really a directory. Return false if
  36473. ** it is something other than a directory, or if there is any kind of memory
  36474. ** allocation failure.
  36475. */
  36476. static int winIsDir(const void *zConverted){
  36477. DWORD attr;
  36478. int rc = 0;
  36479. DWORD lastErrno;
  36480. if( osIsNT() ){
  36481. int cnt = 0;
  36482. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36483. memset(&sAttrData, 0, sizeof(sAttrData));
  36484. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  36485. GetFileExInfoStandard,
  36486. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  36487. if( !rc ){
  36488. return 0; /* Invalid name? */
  36489. }
  36490. attr = sAttrData.dwFileAttributes;
  36491. #if SQLITE_OS_WINCE==0
  36492. }else{
  36493. attr = osGetFileAttributesA((char*)zConverted);
  36494. #endif
  36495. }
  36496. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  36497. }
  36498. /*
  36499. ** Open a file.
  36500. */
  36501. static int winOpen(
  36502. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  36503. const char *zName, /* Name of the file (UTF-8) */
  36504. sqlite3_file *id, /* Write the SQLite file handle here */
  36505. int flags, /* Open mode flags */
  36506. int *pOutFlags /* Status return flags */
  36507. ){
  36508. HANDLE h;
  36509. DWORD lastErrno = 0;
  36510. DWORD dwDesiredAccess;
  36511. DWORD dwShareMode;
  36512. DWORD dwCreationDisposition;
  36513. DWORD dwFlagsAndAttributes = 0;
  36514. #if SQLITE_OS_WINCE
  36515. int isTemp = 0;
  36516. #endif
  36517. winFile *pFile = (winFile*)id;
  36518. void *zConverted; /* Filename in OS encoding */
  36519. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  36520. int cnt = 0;
  36521. /* If argument zPath is a NULL pointer, this function is required to open
  36522. ** a temporary file. Use this buffer to store the file name in.
  36523. */
  36524. char *zTmpname = 0; /* For temporary filename, if necessary. */
  36525. int rc = SQLITE_OK; /* Function Return Code */
  36526. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  36527. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36528. #endif
  36529. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36530. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36531. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36532. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36533. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36534. #ifndef NDEBUG
  36535. int isOpenJournal = (isCreate && (
  36536. eType==SQLITE_OPEN_MASTER_JOURNAL
  36537. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36538. || eType==SQLITE_OPEN_WAL
  36539. ));
  36540. #endif
  36541. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  36542. zUtf8Name, id, flags, pOutFlags));
  36543. /* Check the following statements are true:
  36544. **
  36545. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36546. ** (b) if CREATE is set, then READWRITE must also be set, and
  36547. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36548. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36549. */
  36550. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36551. assert(isCreate==0 || isReadWrite);
  36552. assert(isExclusive==0 || isCreate);
  36553. assert(isDelete==0 || isCreate);
  36554. /* The main DB, main journal, WAL file and master journal are never
  36555. ** automatically deleted. Nor are they ever temporary files. */
  36556. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36557. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36558. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36559. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36560. /* Assert that the upper layer has set one of the "file-type" flags. */
  36561. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36562. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36563. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36564. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36565. );
  36566. assert( pFile!=0 );
  36567. memset(pFile, 0, sizeof(winFile));
  36568. pFile->h = INVALID_HANDLE_VALUE;
  36569. #if SQLITE_OS_WINRT
  36570. if( !zUtf8Name && !sqlite3_temp_directory ){
  36571. sqlite3_log(SQLITE_ERROR,
  36572. "sqlite3_temp_directory variable should be set for WinRT");
  36573. }
  36574. #endif
  36575. /* If the second argument to this function is NULL, generate a
  36576. ** temporary file name to use
  36577. */
  36578. if( !zUtf8Name ){
  36579. assert( isDelete && !isOpenJournal );
  36580. rc = winGetTempname(pVfs, &zTmpname);
  36581. if( rc!=SQLITE_OK ){
  36582. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  36583. return rc;
  36584. }
  36585. zUtf8Name = zTmpname;
  36586. }
  36587. /* Database filenames are double-zero terminated if they are not
  36588. ** URIs with parameters. Hence, they can always be passed into
  36589. ** sqlite3_uri_parameter().
  36590. */
  36591. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  36592. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  36593. /* Convert the filename to the system encoding. */
  36594. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  36595. if( zConverted==0 ){
  36596. sqlite3_free(zTmpname);
  36597. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  36598. return SQLITE_IOERR_NOMEM;
  36599. }
  36600. if( winIsDir(zConverted) ){
  36601. sqlite3_free(zConverted);
  36602. sqlite3_free(zTmpname);
  36603. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  36604. return SQLITE_CANTOPEN_ISDIR;
  36605. }
  36606. if( isReadWrite ){
  36607. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  36608. }else{
  36609. dwDesiredAccess = GENERIC_READ;
  36610. }
  36611. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  36612. ** created. SQLite doesn't use it to indicate "exclusive access"
  36613. ** as it is usually understood.
  36614. */
  36615. if( isExclusive ){
  36616. /* Creates a new file, only if it does not already exist. */
  36617. /* If the file exists, it fails. */
  36618. dwCreationDisposition = CREATE_NEW;
  36619. }else if( isCreate ){
  36620. /* Open existing file, or create if it doesn't exist */
  36621. dwCreationDisposition = OPEN_ALWAYS;
  36622. }else{
  36623. /* Opens a file, only if it exists. */
  36624. dwCreationDisposition = OPEN_EXISTING;
  36625. }
  36626. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  36627. if( isDelete ){
  36628. #if SQLITE_OS_WINCE
  36629. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  36630. isTemp = 1;
  36631. #else
  36632. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  36633. | FILE_ATTRIBUTE_HIDDEN
  36634. | FILE_FLAG_DELETE_ON_CLOSE;
  36635. #endif
  36636. }else{
  36637. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  36638. }
  36639. /* Reports from the internet are that performance is always
  36640. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  36641. #if SQLITE_OS_WINCE
  36642. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  36643. #endif
  36644. if( osIsNT() ){
  36645. #if SQLITE_OS_WINRT
  36646. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  36647. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  36648. extendedParameters.dwFileAttributes =
  36649. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  36650. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  36651. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  36652. extendedParameters.lpSecurityAttributes = NULL;
  36653. extendedParameters.hTemplateFile = NULL;
  36654. while( (h = osCreateFile2((LPCWSTR)zConverted,
  36655. dwDesiredAccess,
  36656. dwShareMode,
  36657. dwCreationDisposition,
  36658. &extendedParameters))==INVALID_HANDLE_VALUE &&
  36659. winRetryIoerr(&cnt, &lastErrno) ){
  36660. /* Noop */
  36661. }
  36662. #else
  36663. while( (h = osCreateFileW((LPCWSTR)zConverted,
  36664. dwDesiredAccess,
  36665. dwShareMode, NULL,
  36666. dwCreationDisposition,
  36667. dwFlagsAndAttributes,
  36668. NULL))==INVALID_HANDLE_VALUE &&
  36669. winRetryIoerr(&cnt, &lastErrno) ){
  36670. /* Noop */
  36671. }
  36672. #endif
  36673. }
  36674. #ifdef SQLITE_WIN32_HAS_ANSI
  36675. else{
  36676. while( (h = osCreateFileA((LPCSTR)zConverted,
  36677. dwDesiredAccess,
  36678. dwShareMode, NULL,
  36679. dwCreationDisposition,
  36680. dwFlagsAndAttributes,
  36681. NULL))==INVALID_HANDLE_VALUE &&
  36682. winRetryIoerr(&cnt, &lastErrno) ){
  36683. /* Noop */
  36684. }
  36685. }
  36686. #endif
  36687. winLogIoerr(cnt, __LINE__);
  36688. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  36689. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  36690. if( h==INVALID_HANDLE_VALUE ){
  36691. pFile->lastErrno = lastErrno;
  36692. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  36693. sqlite3_free(zConverted);
  36694. sqlite3_free(zTmpname);
  36695. if( isReadWrite && !isExclusive ){
  36696. return winOpen(pVfs, zName, id,
  36697. ((flags|SQLITE_OPEN_READONLY) &
  36698. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  36699. pOutFlags);
  36700. }else{
  36701. return SQLITE_CANTOPEN_BKPT;
  36702. }
  36703. }
  36704. if( pOutFlags ){
  36705. if( isReadWrite ){
  36706. *pOutFlags = SQLITE_OPEN_READWRITE;
  36707. }else{
  36708. *pOutFlags = SQLITE_OPEN_READONLY;
  36709. }
  36710. }
  36711. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  36712. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  36713. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  36714. #if SQLITE_OS_WINCE
  36715. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  36716. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  36717. ){
  36718. osCloseHandle(h);
  36719. sqlite3_free(zConverted);
  36720. sqlite3_free(zTmpname);
  36721. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  36722. return rc;
  36723. }
  36724. if( isTemp ){
  36725. pFile->zDeleteOnClose = zConverted;
  36726. }else
  36727. #endif
  36728. {
  36729. sqlite3_free(zConverted);
  36730. }
  36731. sqlite3_free(zTmpname);
  36732. pFile->pMethod = &winIoMethod;
  36733. pFile->pVfs = pVfs;
  36734. pFile->h = h;
  36735. if( isReadonly ){
  36736. pFile->ctrlFlags |= WINFILE_RDONLY;
  36737. }
  36738. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36739. pFile->ctrlFlags |= WINFILE_PSOW;
  36740. }
  36741. pFile->lastErrno = NO_ERROR;
  36742. pFile->zPath = zName;
  36743. #if SQLITE_MAX_MMAP_SIZE>0
  36744. pFile->hMap = NULL;
  36745. pFile->pMapRegion = 0;
  36746. pFile->mmapSize = 0;
  36747. pFile->mmapSizeActual = 0;
  36748. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  36749. #endif
  36750. OpenCounter(+1);
  36751. return rc;
  36752. }
  36753. /*
  36754. ** Delete the named file.
  36755. **
  36756. ** Note that Windows does not allow a file to be deleted if some other
  36757. ** process has it open. Sometimes a virus scanner or indexing program
  36758. ** will open a journal file shortly after it is created in order to do
  36759. ** whatever it does. While this other process is holding the
  36760. ** file open, we will be unable to delete it. To work around this
  36761. ** problem, we delay 100 milliseconds and try to delete again. Up
  36762. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  36763. ** up and returning an error.
  36764. */
  36765. static int winDelete(
  36766. sqlite3_vfs *pVfs, /* Not used on win32 */
  36767. const char *zFilename, /* Name of file to delete */
  36768. int syncDir /* Not used on win32 */
  36769. ){
  36770. int cnt = 0;
  36771. int rc;
  36772. DWORD attr;
  36773. DWORD lastErrno = 0;
  36774. void *zConverted;
  36775. UNUSED_PARAMETER(pVfs);
  36776. UNUSED_PARAMETER(syncDir);
  36777. SimulateIOError(return SQLITE_IOERR_DELETE);
  36778. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  36779. zConverted = winConvertFromUtf8Filename(zFilename);
  36780. if( zConverted==0 ){
  36781. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  36782. return SQLITE_IOERR_NOMEM;
  36783. }
  36784. if( osIsNT() ){
  36785. do {
  36786. #if SQLITE_OS_WINRT
  36787. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36788. memset(&sAttrData, 0, sizeof(sAttrData));
  36789. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  36790. &sAttrData) ){
  36791. attr = sAttrData.dwFileAttributes;
  36792. }else{
  36793. lastErrno = osGetLastError();
  36794. if( lastErrno==ERROR_FILE_NOT_FOUND
  36795. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36796. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36797. }else{
  36798. rc = SQLITE_ERROR;
  36799. }
  36800. break;
  36801. }
  36802. #else
  36803. attr = osGetFileAttributesW(zConverted);
  36804. #endif
  36805. if ( attr==INVALID_FILE_ATTRIBUTES ){
  36806. lastErrno = osGetLastError();
  36807. if( lastErrno==ERROR_FILE_NOT_FOUND
  36808. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36809. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36810. }else{
  36811. rc = SQLITE_ERROR;
  36812. }
  36813. break;
  36814. }
  36815. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  36816. rc = SQLITE_ERROR; /* Files only. */
  36817. break;
  36818. }
  36819. if ( osDeleteFileW(zConverted) ){
  36820. rc = SQLITE_OK; /* Deleted OK. */
  36821. break;
  36822. }
  36823. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  36824. rc = SQLITE_ERROR; /* No more retries. */
  36825. break;
  36826. }
  36827. } while(1);
  36828. }
  36829. #ifdef SQLITE_WIN32_HAS_ANSI
  36830. else{
  36831. do {
  36832. attr = osGetFileAttributesA(zConverted);
  36833. if ( attr==INVALID_FILE_ATTRIBUTES ){
  36834. lastErrno = osGetLastError();
  36835. if( lastErrno==ERROR_FILE_NOT_FOUND
  36836. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36837. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36838. }else{
  36839. rc = SQLITE_ERROR;
  36840. }
  36841. break;
  36842. }
  36843. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  36844. rc = SQLITE_ERROR; /* Files only. */
  36845. break;
  36846. }
  36847. if ( osDeleteFileA(zConverted) ){
  36848. rc = SQLITE_OK; /* Deleted OK. */
  36849. break;
  36850. }
  36851. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  36852. rc = SQLITE_ERROR; /* No more retries. */
  36853. break;
  36854. }
  36855. } while(1);
  36856. }
  36857. #endif
  36858. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  36859. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  36860. }else{
  36861. winLogIoerr(cnt, __LINE__);
  36862. }
  36863. sqlite3_free(zConverted);
  36864. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  36865. return rc;
  36866. }
  36867. /*
  36868. ** Check the existence and status of a file.
  36869. */
  36870. static int winAccess(
  36871. sqlite3_vfs *pVfs, /* Not used on win32 */
  36872. const char *zFilename, /* Name of file to check */
  36873. int flags, /* Type of test to make on this file */
  36874. int *pResOut /* OUT: Result */
  36875. ){
  36876. DWORD attr;
  36877. int rc = 0;
  36878. DWORD lastErrno = 0;
  36879. void *zConverted;
  36880. UNUSED_PARAMETER(pVfs);
  36881. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36882. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  36883. zFilename, flags, pResOut));
  36884. zConverted = winConvertFromUtf8Filename(zFilename);
  36885. if( zConverted==0 ){
  36886. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  36887. return SQLITE_IOERR_NOMEM;
  36888. }
  36889. if( osIsNT() ){
  36890. int cnt = 0;
  36891. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36892. memset(&sAttrData, 0, sizeof(sAttrData));
  36893. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  36894. GetFileExInfoStandard,
  36895. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  36896. if( rc ){
  36897. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  36898. ** as if it does not exist.
  36899. */
  36900. if( flags==SQLITE_ACCESS_EXISTS
  36901. && sAttrData.nFileSizeHigh==0
  36902. && sAttrData.nFileSizeLow==0 ){
  36903. attr = INVALID_FILE_ATTRIBUTES;
  36904. }else{
  36905. attr = sAttrData.dwFileAttributes;
  36906. }
  36907. }else{
  36908. winLogIoerr(cnt, __LINE__);
  36909. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  36910. sqlite3_free(zConverted);
  36911. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  36912. zFilename);
  36913. }else{
  36914. attr = INVALID_FILE_ATTRIBUTES;
  36915. }
  36916. }
  36917. }
  36918. #ifdef SQLITE_WIN32_HAS_ANSI
  36919. else{
  36920. attr = osGetFileAttributesA((char*)zConverted);
  36921. }
  36922. #endif
  36923. sqlite3_free(zConverted);
  36924. switch( flags ){
  36925. case SQLITE_ACCESS_READ:
  36926. case SQLITE_ACCESS_EXISTS:
  36927. rc = attr!=INVALID_FILE_ATTRIBUTES;
  36928. break;
  36929. case SQLITE_ACCESS_READWRITE:
  36930. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  36931. (attr & FILE_ATTRIBUTE_READONLY)==0;
  36932. break;
  36933. default:
  36934. assert(!"Invalid flags argument");
  36935. }
  36936. *pResOut = rc;
  36937. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  36938. zFilename, pResOut, *pResOut));
  36939. return SQLITE_OK;
  36940. }
  36941. /*
  36942. ** Returns non-zero if the specified path name starts with a drive letter
  36943. ** followed by a colon character.
  36944. */
  36945. static BOOL winIsDriveLetterAndColon(
  36946. const char *zPathname
  36947. ){
  36948. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  36949. }
  36950. /*
  36951. ** Returns non-zero if the specified path name should be used verbatim. If
  36952. ** non-zero is returned from this function, the calling function must simply
  36953. ** use the provided path name verbatim -OR- resolve it into a full path name
  36954. ** using the GetFullPathName Win32 API function (if available).
  36955. */
  36956. static BOOL winIsVerbatimPathname(
  36957. const char *zPathname
  36958. ){
  36959. /*
  36960. ** If the path name starts with a forward slash or a backslash, it is either
  36961. ** a legal UNC name, a volume relative path, or an absolute path name in the
  36962. ** "Unix" format on Windows. There is no easy way to differentiate between
  36963. ** the final two cases; therefore, we return the safer return value of TRUE
  36964. ** so that callers of this function will simply use it verbatim.
  36965. */
  36966. if ( winIsDirSep(zPathname[0]) ){
  36967. return TRUE;
  36968. }
  36969. /*
  36970. ** If the path name starts with a letter and a colon it is either a volume
  36971. ** relative path or an absolute path. Callers of this function must not
  36972. ** attempt to treat it as a relative path name (i.e. they should simply use
  36973. ** it verbatim).
  36974. */
  36975. if ( winIsDriveLetterAndColon(zPathname) ){
  36976. return TRUE;
  36977. }
  36978. /*
  36979. ** If we get to this point, the path name should almost certainly be a purely
  36980. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  36981. */
  36982. return FALSE;
  36983. }
  36984. /*
  36985. ** Turn a relative pathname into a full pathname. Write the full
  36986. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  36987. ** bytes in size.
  36988. */
  36989. static int winFullPathname(
  36990. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36991. const char *zRelative, /* Possibly relative input path */
  36992. int nFull, /* Size of output buffer in bytes */
  36993. char *zFull /* Output buffer */
  36994. ){
  36995. #if defined(__CYGWIN__)
  36996. SimulateIOError( return SQLITE_ERROR );
  36997. UNUSED_PARAMETER(nFull);
  36998. assert( nFull>=pVfs->mxPathname );
  36999. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37000. /*
  37001. ** NOTE: We are dealing with a relative path name and the data
  37002. ** directory has been set. Therefore, use it as the basis
  37003. ** for converting the relative path name to an absolute
  37004. ** one by prepending the data directory and a slash.
  37005. */
  37006. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37007. if( !zOut ){
  37008. return SQLITE_IOERR_NOMEM;
  37009. }
  37010. if( cygwin_conv_path(
  37011. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  37012. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37013. sqlite3_free(zOut);
  37014. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37015. "winFullPathname1", zRelative);
  37016. }else{
  37017. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37018. if( !zUtf8 ){
  37019. sqlite3_free(zOut);
  37020. return SQLITE_IOERR_NOMEM;
  37021. }
  37022. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37023. sqlite3_data_directory, winGetDirSep(), zUtf8);
  37024. sqlite3_free(zUtf8);
  37025. sqlite3_free(zOut);
  37026. }
  37027. }else{
  37028. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37029. if( !zOut ){
  37030. return SQLITE_IOERR_NOMEM;
  37031. }
  37032. if( cygwin_conv_path(
  37033. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  37034. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37035. sqlite3_free(zOut);
  37036. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37037. "winFullPathname2", zRelative);
  37038. }else{
  37039. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37040. if( !zUtf8 ){
  37041. sqlite3_free(zOut);
  37042. return SQLITE_IOERR_NOMEM;
  37043. }
  37044. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  37045. sqlite3_free(zUtf8);
  37046. sqlite3_free(zOut);
  37047. }
  37048. }
  37049. return SQLITE_OK;
  37050. #endif
  37051. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  37052. SimulateIOError( return SQLITE_ERROR );
  37053. /* WinCE has no concept of a relative pathname, or so I am told. */
  37054. /* WinRT has no way to convert a relative path to an absolute one. */
  37055. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37056. /*
  37057. ** NOTE: We are dealing with a relative path name and the data
  37058. ** directory has been set. Therefore, use it as the basis
  37059. ** for converting the relative path name to an absolute
  37060. ** one by prepending the data directory and a backslash.
  37061. */
  37062. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37063. sqlite3_data_directory, winGetDirSep(), zRelative);
  37064. }else{
  37065. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  37066. }
  37067. return SQLITE_OK;
  37068. #endif
  37069. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  37070. DWORD nByte;
  37071. void *zConverted;
  37072. char *zOut;
  37073. /* If this path name begins with "/X:", where "X" is any alphabetic
  37074. ** character, discard the initial "/" from the pathname.
  37075. */
  37076. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  37077. zRelative++;
  37078. }
  37079. /* It's odd to simulate an io-error here, but really this is just
  37080. ** using the io-error infrastructure to test that SQLite handles this
  37081. ** function failing. This function could fail if, for example, the
  37082. ** current working directory has been unlinked.
  37083. */
  37084. SimulateIOError( return SQLITE_ERROR );
  37085. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37086. /*
  37087. ** NOTE: We are dealing with a relative path name and the data
  37088. ** directory has been set. Therefore, use it as the basis
  37089. ** for converting the relative path name to an absolute
  37090. ** one by prepending the data directory and a backslash.
  37091. */
  37092. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37093. sqlite3_data_directory, winGetDirSep(), zRelative);
  37094. return SQLITE_OK;
  37095. }
  37096. zConverted = winConvertFromUtf8Filename(zRelative);
  37097. if( zConverted==0 ){
  37098. return SQLITE_IOERR_NOMEM;
  37099. }
  37100. if( osIsNT() ){
  37101. LPWSTR zTemp;
  37102. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  37103. if( nByte==0 ){
  37104. sqlite3_free(zConverted);
  37105. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37106. "winFullPathname1", zRelative);
  37107. }
  37108. nByte += 3;
  37109. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  37110. if( zTemp==0 ){
  37111. sqlite3_free(zConverted);
  37112. return SQLITE_IOERR_NOMEM;
  37113. }
  37114. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  37115. if( nByte==0 ){
  37116. sqlite3_free(zConverted);
  37117. sqlite3_free(zTemp);
  37118. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37119. "winFullPathname2", zRelative);
  37120. }
  37121. sqlite3_free(zConverted);
  37122. zOut = winUnicodeToUtf8(zTemp);
  37123. sqlite3_free(zTemp);
  37124. }
  37125. #ifdef SQLITE_WIN32_HAS_ANSI
  37126. else{
  37127. char *zTemp;
  37128. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  37129. if( nByte==0 ){
  37130. sqlite3_free(zConverted);
  37131. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37132. "winFullPathname3", zRelative);
  37133. }
  37134. nByte += 3;
  37135. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  37136. if( zTemp==0 ){
  37137. sqlite3_free(zConverted);
  37138. return SQLITE_IOERR_NOMEM;
  37139. }
  37140. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  37141. if( nByte==0 ){
  37142. sqlite3_free(zConverted);
  37143. sqlite3_free(zTemp);
  37144. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37145. "winFullPathname4", zRelative);
  37146. }
  37147. sqlite3_free(zConverted);
  37148. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  37149. sqlite3_free(zTemp);
  37150. }
  37151. #endif
  37152. if( zOut ){
  37153. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  37154. sqlite3_free(zOut);
  37155. return SQLITE_OK;
  37156. }else{
  37157. return SQLITE_IOERR_NOMEM;
  37158. }
  37159. #endif
  37160. }
  37161. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  37162. /*
  37163. ** Interfaces for opening a shared library, finding entry points
  37164. ** within the shared library, and closing the shared library.
  37165. */
  37166. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  37167. HANDLE h;
  37168. #if defined(__CYGWIN__)
  37169. int nFull = pVfs->mxPathname+1;
  37170. char *zFull = sqlite3MallocZero( nFull );
  37171. void *zConverted = 0;
  37172. if( zFull==0 ){
  37173. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37174. return 0;
  37175. }
  37176. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  37177. sqlite3_free(zFull);
  37178. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37179. return 0;
  37180. }
  37181. zConverted = winConvertFromUtf8Filename(zFull);
  37182. sqlite3_free(zFull);
  37183. #else
  37184. void *zConverted = winConvertFromUtf8Filename(zFilename);
  37185. UNUSED_PARAMETER(pVfs);
  37186. #endif
  37187. if( zConverted==0 ){
  37188. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37189. return 0;
  37190. }
  37191. if( osIsNT() ){
  37192. #if SQLITE_OS_WINRT
  37193. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  37194. #else
  37195. h = osLoadLibraryW((LPCWSTR)zConverted);
  37196. #endif
  37197. }
  37198. #ifdef SQLITE_WIN32_HAS_ANSI
  37199. else{
  37200. h = osLoadLibraryA((char*)zConverted);
  37201. }
  37202. #endif
  37203. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  37204. sqlite3_free(zConverted);
  37205. return (void*)h;
  37206. }
  37207. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  37208. UNUSED_PARAMETER(pVfs);
  37209. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  37210. }
  37211. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  37212. FARPROC proc;
  37213. UNUSED_PARAMETER(pVfs);
  37214. proc = osGetProcAddressA((HANDLE)pH, zSym);
  37215. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  37216. (void*)pH, zSym, (void*)proc));
  37217. return (void(*)(void))proc;
  37218. }
  37219. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  37220. UNUSED_PARAMETER(pVfs);
  37221. osFreeLibrary((HANDLE)pHandle);
  37222. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  37223. }
  37224. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  37225. #define winDlOpen 0
  37226. #define winDlError 0
  37227. #define winDlSym 0
  37228. #define winDlClose 0
  37229. #endif
  37230. /*
  37231. ** Write up to nBuf bytes of randomness into zBuf.
  37232. */
  37233. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37234. int n = 0;
  37235. UNUSED_PARAMETER(pVfs);
  37236. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  37237. n = nBuf;
  37238. memset(zBuf, 0, nBuf);
  37239. #else
  37240. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  37241. SYSTEMTIME x;
  37242. osGetSystemTime(&x);
  37243. memcpy(&zBuf[n], &x, sizeof(x));
  37244. n += sizeof(x);
  37245. }
  37246. if( sizeof(DWORD)<=nBuf-n ){
  37247. DWORD pid = osGetCurrentProcessId();
  37248. memcpy(&zBuf[n], &pid, sizeof(pid));
  37249. n += sizeof(pid);
  37250. }
  37251. #if SQLITE_OS_WINRT
  37252. if( sizeof(ULONGLONG)<=nBuf-n ){
  37253. ULONGLONG cnt = osGetTickCount64();
  37254. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  37255. n += sizeof(cnt);
  37256. }
  37257. #else
  37258. if( sizeof(DWORD)<=nBuf-n ){
  37259. DWORD cnt = osGetTickCount();
  37260. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  37261. n += sizeof(cnt);
  37262. }
  37263. #endif
  37264. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  37265. LARGE_INTEGER i;
  37266. osQueryPerformanceCounter(&i);
  37267. memcpy(&zBuf[n], &i, sizeof(i));
  37268. n += sizeof(i);
  37269. }
  37270. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37271. if( sizeof(UUID)<=nBuf-n ){
  37272. UUID id;
  37273. memset(&id, 0, sizeof(UUID));
  37274. osUuidCreate(&id);
  37275. memcpy(&zBuf[n], &id, sizeof(UUID));
  37276. n += sizeof(UUID);
  37277. }
  37278. if( sizeof(UUID)<=nBuf-n ){
  37279. UUID id;
  37280. memset(&id, 0, sizeof(UUID));
  37281. osUuidCreateSequential(&id);
  37282. memcpy(&zBuf[n], &id, sizeof(UUID));
  37283. n += sizeof(UUID);
  37284. }
  37285. #endif
  37286. #endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
  37287. return n;
  37288. }
  37289. /*
  37290. ** Sleep for a little while. Return the amount of time slept.
  37291. */
  37292. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  37293. sqlite3_win32_sleep((microsec+999)/1000);
  37294. UNUSED_PARAMETER(pVfs);
  37295. return ((microsec+999)/1000)*1000;
  37296. }
  37297. /*
  37298. ** The following variable, if set to a non-zero value, is interpreted as
  37299. ** the number of seconds since 1970 and is used to set the result of
  37300. ** sqlite3OsCurrentTime() during testing.
  37301. */
  37302. #ifdef SQLITE_TEST
  37303. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  37304. #endif
  37305. /*
  37306. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  37307. ** the current time and date as a Julian Day number times 86_400_000. In
  37308. ** other words, write into *piNow the number of milliseconds since the Julian
  37309. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  37310. ** proleptic Gregorian calendar.
  37311. **
  37312. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  37313. ** cannot be found.
  37314. */
  37315. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  37316. /* FILETIME structure is a 64-bit value representing the number of
  37317. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  37318. */
  37319. FILETIME ft;
  37320. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  37321. #ifdef SQLITE_TEST
  37322. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  37323. #endif
  37324. /* 2^32 - to avoid use of LL and warnings in gcc */
  37325. static const sqlite3_int64 max32BitValue =
  37326. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  37327. (sqlite3_int64)294967296;
  37328. #if SQLITE_OS_WINCE
  37329. SYSTEMTIME time;
  37330. osGetSystemTime(&time);
  37331. /* if SystemTimeToFileTime() fails, it returns zero. */
  37332. if (!osSystemTimeToFileTime(&time,&ft)){
  37333. return SQLITE_ERROR;
  37334. }
  37335. #else
  37336. osGetSystemTimeAsFileTime( &ft );
  37337. #endif
  37338. *piNow = winFiletimeEpoch +
  37339. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  37340. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  37341. #ifdef SQLITE_TEST
  37342. if( sqlite3_current_time ){
  37343. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  37344. }
  37345. #endif
  37346. UNUSED_PARAMETER(pVfs);
  37347. return SQLITE_OK;
  37348. }
  37349. /*
  37350. ** Find the current time (in Universal Coordinated Time). Write the
  37351. ** current time and date as a Julian Day number into *prNow and
  37352. ** return 0. Return 1 if the time and date cannot be found.
  37353. */
  37354. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  37355. int rc;
  37356. sqlite3_int64 i;
  37357. rc = winCurrentTimeInt64(pVfs, &i);
  37358. if( !rc ){
  37359. *prNow = i/86400000.0;
  37360. }
  37361. return rc;
  37362. }
  37363. /*
  37364. ** The idea is that this function works like a combination of
  37365. ** GetLastError() and FormatMessage() on Windows (or errno and
  37366. ** strerror_r() on Unix). After an error is returned by an OS
  37367. ** function, SQLite calls this function with zBuf pointing to
  37368. ** a buffer of nBuf bytes. The OS layer should populate the
  37369. ** buffer with a nul-terminated UTF-8 encoded error message
  37370. ** describing the last IO error to have occurred within the calling
  37371. ** thread.
  37372. **
  37373. ** If the error message is too large for the supplied buffer,
  37374. ** it should be truncated. The return value of xGetLastError
  37375. ** is zero if the error message fits in the buffer, or non-zero
  37376. ** otherwise (if the message was truncated). If non-zero is returned,
  37377. ** then it is not necessary to include the nul-terminator character
  37378. ** in the output buffer.
  37379. **
  37380. ** Not supplying an error message will have no adverse effect
  37381. ** on SQLite. It is fine to have an implementation that never
  37382. ** returns an error message:
  37383. **
  37384. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37385. ** assert(zBuf[0]=='\0');
  37386. ** return 0;
  37387. ** }
  37388. **
  37389. ** However if an error message is supplied, it will be incorporated
  37390. ** by sqlite into the error message available to the user using
  37391. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  37392. */
  37393. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37394. UNUSED_PARAMETER(pVfs);
  37395. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  37396. }
  37397. /*
  37398. ** Initialize and deinitialize the operating system interface.
  37399. */
  37400. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  37401. static sqlite3_vfs winVfs = {
  37402. 3, /* iVersion */
  37403. sizeof(winFile), /* szOsFile */
  37404. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  37405. 0, /* pNext */
  37406. "win32", /* zName */
  37407. 0, /* pAppData */
  37408. winOpen, /* xOpen */
  37409. winDelete, /* xDelete */
  37410. winAccess, /* xAccess */
  37411. winFullPathname, /* xFullPathname */
  37412. winDlOpen, /* xDlOpen */
  37413. winDlError, /* xDlError */
  37414. winDlSym, /* xDlSym */
  37415. winDlClose, /* xDlClose */
  37416. winRandomness, /* xRandomness */
  37417. winSleep, /* xSleep */
  37418. winCurrentTime, /* xCurrentTime */
  37419. winGetLastError, /* xGetLastError */
  37420. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  37421. winSetSystemCall, /* xSetSystemCall */
  37422. winGetSystemCall, /* xGetSystemCall */
  37423. winNextSystemCall, /* xNextSystemCall */
  37424. };
  37425. #if defined(SQLITE_WIN32_HAS_WIDE)
  37426. static sqlite3_vfs winLongPathVfs = {
  37427. 3, /* iVersion */
  37428. sizeof(winFile), /* szOsFile */
  37429. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  37430. 0, /* pNext */
  37431. "win32-longpath", /* zName */
  37432. 0, /* pAppData */
  37433. winOpen, /* xOpen */
  37434. winDelete, /* xDelete */
  37435. winAccess, /* xAccess */
  37436. winFullPathname, /* xFullPathname */
  37437. winDlOpen, /* xDlOpen */
  37438. winDlError, /* xDlError */
  37439. winDlSym, /* xDlSym */
  37440. winDlClose, /* xDlClose */
  37441. winRandomness, /* xRandomness */
  37442. winSleep, /* xSleep */
  37443. winCurrentTime, /* xCurrentTime */
  37444. winGetLastError, /* xGetLastError */
  37445. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  37446. winSetSystemCall, /* xSetSystemCall */
  37447. winGetSystemCall, /* xGetSystemCall */
  37448. winNextSystemCall, /* xNextSystemCall */
  37449. };
  37450. #endif
  37451. /* Double-check that the aSyscall[] array has been constructed
  37452. ** correctly. See ticket [bb3a86e890c8e96ab] */
  37453. assert( ArraySize(aSyscall)==80 );
  37454. /* get memory map allocation granularity */
  37455. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  37456. #if SQLITE_OS_WINRT
  37457. osGetNativeSystemInfo(&winSysInfo);
  37458. #else
  37459. osGetSystemInfo(&winSysInfo);
  37460. #endif
  37461. assert( winSysInfo.dwAllocationGranularity>0 );
  37462. assert( winSysInfo.dwPageSize>0 );
  37463. sqlite3_vfs_register(&winVfs, 1);
  37464. #if defined(SQLITE_WIN32_HAS_WIDE)
  37465. sqlite3_vfs_register(&winLongPathVfs, 0);
  37466. #endif
  37467. return SQLITE_OK;
  37468. }
  37469. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  37470. #if SQLITE_OS_WINRT
  37471. if( sleepObj!=NULL ){
  37472. osCloseHandle(sleepObj);
  37473. sleepObj = NULL;
  37474. }
  37475. #endif
  37476. return SQLITE_OK;
  37477. }
  37478. #endif /* SQLITE_OS_WIN */
  37479. /************** End of os_win.c **********************************************/
  37480. /************** Begin file bitvec.c ******************************************/
  37481. /*
  37482. ** 2008 February 16
  37483. **
  37484. ** The author disclaims copyright to this source code. In place of
  37485. ** a legal notice, here is a blessing:
  37486. **
  37487. ** May you do good and not evil.
  37488. ** May you find forgiveness for yourself and forgive others.
  37489. ** May you share freely, never taking more than you give.
  37490. **
  37491. *************************************************************************
  37492. ** This file implements an object that represents a fixed-length
  37493. ** bitmap. Bits are numbered starting with 1.
  37494. **
  37495. ** A bitmap is used to record which pages of a database file have been
  37496. ** journalled during a transaction, or which pages have the "dont-write"
  37497. ** property. Usually only a few pages are meet either condition.
  37498. ** So the bitmap is usually sparse and has low cardinality.
  37499. ** But sometimes (for example when during a DROP of a large table) most
  37500. ** or all of the pages in a database can get journalled. In those cases,
  37501. ** the bitmap becomes dense with high cardinality. The algorithm needs
  37502. ** to handle both cases well.
  37503. **
  37504. ** The size of the bitmap is fixed when the object is created.
  37505. **
  37506. ** All bits are clear when the bitmap is created. Individual bits
  37507. ** may be set or cleared one at a time.
  37508. **
  37509. ** Test operations are about 100 times more common that set operations.
  37510. ** Clear operations are exceedingly rare. There are usually between
  37511. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  37512. ** sometimes grow into tens of thousands or larger. The size of the
  37513. ** Bitvec object is the number of pages in the database file at the
  37514. ** start of a transaction, and is thus usually less than a few thousand,
  37515. ** but can be as large as 2 billion for a really big database.
  37516. */
  37517. /* #include "sqliteInt.h" */
  37518. /* Size of the Bitvec structure in bytes. */
  37519. #define BITVEC_SZ 512
  37520. /* Round the union size down to the nearest pointer boundary, since that's how
  37521. ** it will be aligned within the Bitvec struct. */
  37522. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  37523. /* Type of the array "element" for the bitmap representation.
  37524. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  37525. ** Setting this to the "natural word" size of your CPU may improve
  37526. ** performance. */
  37527. #define BITVEC_TELEM u8
  37528. /* Size, in bits, of the bitmap element. */
  37529. #define BITVEC_SZELEM 8
  37530. /* Number of elements in a bitmap array. */
  37531. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  37532. /* Number of bits in the bitmap array. */
  37533. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  37534. /* Number of u32 values in hash table. */
  37535. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  37536. /* Maximum number of entries in hash table before
  37537. ** sub-dividing and re-hashing. */
  37538. #define BITVEC_MXHASH (BITVEC_NINT/2)
  37539. /* Hashing function for the aHash representation.
  37540. ** Empirical testing showed that the *37 multiplier
  37541. ** (an arbitrary prime)in the hash function provided
  37542. ** no fewer collisions than the no-op *1. */
  37543. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  37544. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  37545. /*
  37546. ** A bitmap is an instance of the following structure.
  37547. **
  37548. ** This bitmap records the existence of zero or more bits
  37549. ** with values between 1 and iSize, inclusive.
  37550. **
  37551. ** There are three possible representations of the bitmap.
  37552. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  37553. ** bitmap. The least significant bit is bit 1.
  37554. **
  37555. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  37556. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  37557. **
  37558. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  37559. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  37560. ** handles up to iDivisor separate values of i. apSub[0] holds
  37561. ** values between 1 and iDivisor. apSub[1] holds values between
  37562. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  37563. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  37564. ** to hold deal with values between 1 and iDivisor.
  37565. */
  37566. struct Bitvec {
  37567. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  37568. u32 nSet; /* Number of bits that are set - only valid for aHash
  37569. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  37570. ** this would be 125. */
  37571. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  37572. /* Should >=0 for apSub element. */
  37573. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  37574. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  37575. union {
  37576. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  37577. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  37578. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  37579. } u;
  37580. };
  37581. /*
  37582. ** Create a new bitmap object able to handle bits between 0 and iSize,
  37583. ** inclusive. Return a pointer to the new object. Return NULL if
  37584. ** malloc fails.
  37585. */
  37586. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  37587. Bitvec *p;
  37588. assert( sizeof(*p)==BITVEC_SZ );
  37589. p = sqlite3MallocZero( sizeof(*p) );
  37590. if( p ){
  37591. p->iSize = iSize;
  37592. }
  37593. return p;
  37594. }
  37595. /*
  37596. ** Check to see if the i-th bit is set. Return true or false.
  37597. ** If p is NULL (if the bitmap has not been created) or if
  37598. ** i is out of range, then return false.
  37599. */
  37600. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  37601. assert( p!=0 );
  37602. i--;
  37603. if( i>=p->iSize ) return 0;
  37604. while( p->iDivisor ){
  37605. u32 bin = i/p->iDivisor;
  37606. i = i%p->iDivisor;
  37607. p = p->u.apSub[bin];
  37608. if (!p) {
  37609. return 0;
  37610. }
  37611. }
  37612. if( p->iSize<=BITVEC_NBIT ){
  37613. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  37614. } else{
  37615. u32 h = BITVEC_HASH(i++);
  37616. while( p->u.aHash[h] ){
  37617. if( p->u.aHash[h]==i ) return 1;
  37618. h = (h+1) % BITVEC_NINT;
  37619. }
  37620. return 0;
  37621. }
  37622. }
  37623. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  37624. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  37625. }
  37626. /*
  37627. ** Set the i-th bit. Return 0 on success and an error code if
  37628. ** anything goes wrong.
  37629. **
  37630. ** This routine might cause sub-bitmaps to be allocated. Failing
  37631. ** to get the memory needed to hold the sub-bitmap is the only
  37632. ** that can go wrong with an insert, assuming p and i are valid.
  37633. **
  37634. ** The calling function must ensure that p is a valid Bitvec object
  37635. ** and that the value for "i" is within range of the Bitvec object.
  37636. ** Otherwise the behavior is undefined.
  37637. */
  37638. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  37639. u32 h;
  37640. if( p==0 ) return SQLITE_OK;
  37641. assert( i>0 );
  37642. assert( i<=p->iSize );
  37643. i--;
  37644. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  37645. u32 bin = i/p->iDivisor;
  37646. i = i%p->iDivisor;
  37647. if( p->u.apSub[bin]==0 ){
  37648. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  37649. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  37650. }
  37651. p = p->u.apSub[bin];
  37652. }
  37653. if( p->iSize<=BITVEC_NBIT ){
  37654. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  37655. return SQLITE_OK;
  37656. }
  37657. h = BITVEC_HASH(i++);
  37658. /* if there wasn't a hash collision, and this doesn't */
  37659. /* completely fill the hash, then just add it without */
  37660. /* worring about sub-dividing and re-hashing. */
  37661. if( !p->u.aHash[h] ){
  37662. if (p->nSet<(BITVEC_NINT-1)) {
  37663. goto bitvec_set_end;
  37664. } else {
  37665. goto bitvec_set_rehash;
  37666. }
  37667. }
  37668. /* there was a collision, check to see if it's already */
  37669. /* in hash, if not, try to find a spot for it */
  37670. do {
  37671. if( p->u.aHash[h]==i ) return SQLITE_OK;
  37672. h++;
  37673. if( h>=BITVEC_NINT ) h = 0;
  37674. } while( p->u.aHash[h] );
  37675. /* we didn't find it in the hash. h points to the first */
  37676. /* available free spot. check to see if this is going to */
  37677. /* make our hash too "full". */
  37678. bitvec_set_rehash:
  37679. if( p->nSet>=BITVEC_MXHASH ){
  37680. unsigned int j;
  37681. int rc;
  37682. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  37683. if( aiValues==0 ){
  37684. return SQLITE_NOMEM;
  37685. }else{
  37686. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  37687. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  37688. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  37689. rc = sqlite3BitvecSet(p, i);
  37690. for(j=0; j<BITVEC_NINT; j++){
  37691. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  37692. }
  37693. sqlite3StackFree(0, aiValues);
  37694. return rc;
  37695. }
  37696. }
  37697. bitvec_set_end:
  37698. p->nSet++;
  37699. p->u.aHash[h] = i;
  37700. return SQLITE_OK;
  37701. }
  37702. /*
  37703. ** Clear the i-th bit.
  37704. **
  37705. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  37706. ** that BitvecClear can use to rebuilt its hash table.
  37707. */
  37708. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  37709. if( p==0 ) return;
  37710. assert( i>0 );
  37711. i--;
  37712. while( p->iDivisor ){
  37713. u32 bin = i/p->iDivisor;
  37714. i = i%p->iDivisor;
  37715. p = p->u.apSub[bin];
  37716. if (!p) {
  37717. return;
  37718. }
  37719. }
  37720. if( p->iSize<=BITVEC_NBIT ){
  37721. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  37722. }else{
  37723. unsigned int j;
  37724. u32 *aiValues = pBuf;
  37725. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  37726. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  37727. p->nSet = 0;
  37728. for(j=0; j<BITVEC_NINT; j++){
  37729. if( aiValues[j] && aiValues[j]!=(i+1) ){
  37730. u32 h = BITVEC_HASH(aiValues[j]-1);
  37731. p->nSet++;
  37732. while( p->u.aHash[h] ){
  37733. h++;
  37734. if( h>=BITVEC_NINT ) h = 0;
  37735. }
  37736. p->u.aHash[h] = aiValues[j];
  37737. }
  37738. }
  37739. }
  37740. }
  37741. /*
  37742. ** Destroy a bitmap object. Reclaim all memory used.
  37743. */
  37744. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  37745. if( p==0 ) return;
  37746. if( p->iDivisor ){
  37747. unsigned int i;
  37748. for(i=0; i<BITVEC_NPTR; i++){
  37749. sqlite3BitvecDestroy(p->u.apSub[i]);
  37750. }
  37751. }
  37752. sqlite3_free(p);
  37753. }
  37754. /*
  37755. ** Return the value of the iSize parameter specified when Bitvec *p
  37756. ** was created.
  37757. */
  37758. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  37759. return p->iSize;
  37760. }
  37761. #ifndef SQLITE_OMIT_BUILTIN_TEST
  37762. /*
  37763. ** Let V[] be an array of unsigned characters sufficient to hold
  37764. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  37765. ** Then the following macros can be used to set, clear, or test
  37766. ** individual bits within V.
  37767. */
  37768. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  37769. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  37770. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  37771. /*
  37772. ** This routine runs an extensive test of the Bitvec code.
  37773. **
  37774. ** The input is an array of integers that acts as a program
  37775. ** to test the Bitvec. The integers are opcodes followed
  37776. ** by 0, 1, or 3 operands, depending on the opcode. Another
  37777. ** opcode follows immediately after the last operand.
  37778. **
  37779. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  37780. ** "halt" opcode and causes the test to end.
  37781. **
  37782. ** 0 Halt and return the number of errors
  37783. ** 1 N S X Set N bits beginning with S and incrementing by X
  37784. ** 2 N S X Clear N bits beginning with S and incrementing by X
  37785. ** 3 N Set N randomly chosen bits
  37786. ** 4 N Clear N randomly chosen bits
  37787. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  37788. **
  37789. ** The opcodes 1 through 4 perform set and clear operations are performed
  37790. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  37791. ** Opcode 5 works on the linear array only, not on the Bitvec.
  37792. ** Opcode 5 is used to deliberately induce a fault in order to
  37793. ** confirm that error detection works.
  37794. **
  37795. ** At the conclusion of the test the linear array is compared
  37796. ** against the Bitvec object. If there are any differences,
  37797. ** an error is returned. If they are the same, zero is returned.
  37798. **
  37799. ** If a memory allocation error occurs, return -1.
  37800. */
  37801. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  37802. Bitvec *pBitvec = 0;
  37803. unsigned char *pV = 0;
  37804. int rc = -1;
  37805. int i, nx, pc, op;
  37806. void *pTmpSpace;
  37807. /* Allocate the Bitvec to be tested and a linear array of
  37808. ** bits to act as the reference */
  37809. pBitvec = sqlite3BitvecCreate( sz );
  37810. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  37811. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  37812. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  37813. /* NULL pBitvec tests */
  37814. sqlite3BitvecSet(0, 1);
  37815. sqlite3BitvecClear(0, 1, pTmpSpace);
  37816. /* Run the program */
  37817. pc = 0;
  37818. while( (op = aOp[pc])!=0 ){
  37819. switch( op ){
  37820. case 1:
  37821. case 2:
  37822. case 5: {
  37823. nx = 4;
  37824. i = aOp[pc+2] - 1;
  37825. aOp[pc+2] += aOp[pc+3];
  37826. break;
  37827. }
  37828. case 3:
  37829. case 4:
  37830. default: {
  37831. nx = 2;
  37832. sqlite3_randomness(sizeof(i), &i);
  37833. break;
  37834. }
  37835. }
  37836. if( (--aOp[pc+1]) > 0 ) nx = 0;
  37837. pc += nx;
  37838. i = (i & 0x7fffffff)%sz;
  37839. if( (op & 1)!=0 ){
  37840. SETBIT(pV, (i+1));
  37841. if( op!=5 ){
  37842. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  37843. }
  37844. }else{
  37845. CLEARBIT(pV, (i+1));
  37846. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  37847. }
  37848. }
  37849. /* Test to make sure the linear array exactly matches the
  37850. ** Bitvec object. Start with the assumption that they do
  37851. ** match (rc==0). Change rc to non-zero if a discrepancy
  37852. ** is found.
  37853. */
  37854. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  37855. + sqlite3BitvecTest(pBitvec, 0)
  37856. + (sqlite3BitvecSize(pBitvec) - sz);
  37857. for(i=1; i<=sz; i++){
  37858. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  37859. rc = i;
  37860. break;
  37861. }
  37862. }
  37863. /* Free allocated structure */
  37864. bitvec_end:
  37865. sqlite3_free(pTmpSpace);
  37866. sqlite3_free(pV);
  37867. sqlite3BitvecDestroy(pBitvec);
  37868. return rc;
  37869. }
  37870. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  37871. /************** End of bitvec.c **********************************************/
  37872. /************** Begin file pcache.c ******************************************/
  37873. /*
  37874. ** 2008 August 05
  37875. **
  37876. ** The author disclaims copyright to this source code. In place of
  37877. ** a legal notice, here is a blessing:
  37878. **
  37879. ** May you do good and not evil.
  37880. ** May you find forgiveness for yourself and forgive others.
  37881. ** May you share freely, never taking more than you give.
  37882. **
  37883. *************************************************************************
  37884. ** This file implements that page cache.
  37885. */
  37886. /* #include "sqliteInt.h" */
  37887. /*
  37888. ** A complete page cache is an instance of this structure.
  37889. */
  37890. struct PCache {
  37891. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  37892. PgHdr *pSynced; /* Last synced page in dirty page list */
  37893. int nRefSum; /* Sum of ref counts over all pages */
  37894. int szCache; /* Configured cache size */
  37895. int szPage; /* Size of every page in this cache */
  37896. int szExtra; /* Size of extra space for each page */
  37897. u8 bPurgeable; /* True if pages are on backing store */
  37898. u8 eCreate; /* eCreate value for for xFetch() */
  37899. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  37900. void *pStress; /* Argument to xStress */
  37901. sqlite3_pcache *pCache; /* Pluggable cache module */
  37902. };
  37903. /********************************** Linked List Management ********************/
  37904. /* Allowed values for second argument to pcacheManageDirtyList() */
  37905. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  37906. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  37907. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  37908. /*
  37909. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  37910. ** argument determines what operation to do. The 0x01 bit means first
  37911. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  37912. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  37913. */
  37914. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  37915. PCache *p = pPage->pCache;
  37916. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  37917. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  37918. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  37919. /* Update the PCache1.pSynced variable if necessary. */
  37920. if( p->pSynced==pPage ){
  37921. PgHdr *pSynced = pPage->pDirtyPrev;
  37922. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  37923. pSynced = pSynced->pDirtyPrev;
  37924. }
  37925. p->pSynced = pSynced;
  37926. }
  37927. if( pPage->pDirtyNext ){
  37928. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  37929. }else{
  37930. assert( pPage==p->pDirtyTail );
  37931. p->pDirtyTail = pPage->pDirtyPrev;
  37932. }
  37933. if( pPage->pDirtyPrev ){
  37934. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  37935. }else{
  37936. assert( pPage==p->pDirty );
  37937. p->pDirty = pPage->pDirtyNext;
  37938. if( p->pDirty==0 && p->bPurgeable ){
  37939. assert( p->eCreate==1 );
  37940. p->eCreate = 2;
  37941. }
  37942. }
  37943. pPage->pDirtyNext = 0;
  37944. pPage->pDirtyPrev = 0;
  37945. }
  37946. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  37947. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  37948. pPage->pDirtyNext = p->pDirty;
  37949. if( pPage->pDirtyNext ){
  37950. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  37951. pPage->pDirtyNext->pDirtyPrev = pPage;
  37952. }else{
  37953. p->pDirtyTail = pPage;
  37954. if( p->bPurgeable ){
  37955. assert( p->eCreate==2 );
  37956. p->eCreate = 1;
  37957. }
  37958. }
  37959. p->pDirty = pPage;
  37960. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  37961. p->pSynced = pPage;
  37962. }
  37963. }
  37964. }
  37965. /*
  37966. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  37967. ** being used for an in-memory database, this function is a no-op.
  37968. */
  37969. static void pcacheUnpin(PgHdr *p){
  37970. if( p->pCache->bPurgeable ){
  37971. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  37972. }
  37973. }
  37974. /*
  37975. ** Compute the number of pages of cache requested. p->szCache is the
  37976. ** cache size requested by the "PRAGMA cache_size" statement.
  37977. **
  37978. **
  37979. */
  37980. static int numberOfCachePages(PCache *p){
  37981. if( p->szCache>=0 ){
  37982. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  37983. ** suggested cache size is set to N. */
  37984. return p->szCache;
  37985. }else{
  37986. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  37987. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  37988. ** bytes of memory. */
  37989. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  37990. }
  37991. }
  37992. /*************************************************** General Interfaces ******
  37993. **
  37994. ** Initialize and shutdown the page cache subsystem. Neither of these
  37995. ** functions are threadsafe.
  37996. */
  37997. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  37998. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  37999. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  38000. ** built-in default page cache is used instead of the application defined
  38001. ** page cache. */
  38002. sqlite3PCacheSetDefault();
  38003. }
  38004. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  38005. }
  38006. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  38007. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  38008. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  38009. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  38010. }
  38011. }
  38012. /*
  38013. ** Return the size in bytes of a PCache object.
  38014. */
  38015. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  38016. /*
  38017. ** Create a new PCache object. Storage space to hold the object
  38018. ** has already been allocated and is passed in as the p pointer.
  38019. ** The caller discovers how much space needs to be allocated by
  38020. ** calling sqlite3PcacheSize().
  38021. */
  38022. SQLITE_PRIVATE int sqlite3PcacheOpen(
  38023. int szPage, /* Size of every page */
  38024. int szExtra, /* Extra space associated with each page */
  38025. int bPurgeable, /* True if pages are on backing store */
  38026. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  38027. void *pStress, /* Argument to xStress */
  38028. PCache *p /* Preallocated space for the PCache */
  38029. ){
  38030. memset(p, 0, sizeof(PCache));
  38031. p->szPage = 1;
  38032. p->szExtra = szExtra;
  38033. p->bPurgeable = bPurgeable;
  38034. p->eCreate = 2;
  38035. p->xStress = xStress;
  38036. p->pStress = pStress;
  38037. p->szCache = 100;
  38038. return sqlite3PcacheSetPageSize(p, szPage);
  38039. }
  38040. /*
  38041. ** Change the page size for PCache object. The caller must ensure that there
  38042. ** are no outstanding page references when this function is called.
  38043. */
  38044. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  38045. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  38046. if( pCache->szPage ){
  38047. sqlite3_pcache *pNew;
  38048. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  38049. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  38050. pCache->bPurgeable
  38051. );
  38052. if( pNew==0 ) return SQLITE_NOMEM;
  38053. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  38054. if( pCache->pCache ){
  38055. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  38056. }
  38057. pCache->pCache = pNew;
  38058. pCache->szPage = szPage;
  38059. }
  38060. return SQLITE_OK;
  38061. }
  38062. /*
  38063. ** Try to obtain a page from the cache.
  38064. **
  38065. ** This routine returns a pointer to an sqlite3_pcache_page object if
  38066. ** such an object is already in cache, or if a new one is created.
  38067. ** This routine returns a NULL pointer if the object was not in cache
  38068. ** and could not be created.
  38069. **
  38070. ** The createFlags should be 0 to check for existing pages and should
  38071. ** be 3 (not 1, but 3) to try to create a new page.
  38072. **
  38073. ** If the createFlag is 0, then NULL is always returned if the page
  38074. ** is not already in the cache. If createFlag is 1, then a new page
  38075. ** is created only if that can be done without spilling dirty pages
  38076. ** and without exceeding the cache size limit.
  38077. **
  38078. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  38079. ** initialize the sqlite3_pcache_page object and convert it into a
  38080. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  38081. ** routines are split this way for performance reasons. When separated
  38082. ** they can both (usually) operate without having to push values to
  38083. ** the stack on entry and pop them back off on exit, which saves a
  38084. ** lot of pushing and popping.
  38085. */
  38086. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  38087. PCache *pCache, /* Obtain the page from this cache */
  38088. Pgno pgno, /* Page number to obtain */
  38089. int createFlag /* If true, create page if it does not exist already */
  38090. ){
  38091. int eCreate;
  38092. assert( pCache!=0 );
  38093. assert( pCache->pCache!=0 );
  38094. assert( createFlag==3 || createFlag==0 );
  38095. assert( pgno>0 );
  38096. /* eCreate defines what to do if the page does not exist.
  38097. ** 0 Do not allocate a new page. (createFlag==0)
  38098. ** 1 Allocate a new page if doing so is inexpensive.
  38099. ** (createFlag==1 AND bPurgeable AND pDirty)
  38100. ** 2 Allocate a new page even it doing so is difficult.
  38101. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  38102. */
  38103. eCreate = createFlag & pCache->eCreate;
  38104. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  38105. assert( createFlag==0 || pCache->eCreate==eCreate );
  38106. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  38107. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  38108. }
  38109. /*
  38110. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  38111. ** page because new clean pages are available for reuse and the cache
  38112. ** size limit has been reached, then this routine can be invoked to
  38113. ** try harder to allocate a page. This routine might invoke the stress
  38114. ** callback to spill dirty pages to the journal. It will then try to
  38115. ** allocate the new page and will only fail to allocate a new page on
  38116. ** an OOM error.
  38117. **
  38118. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  38119. */
  38120. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  38121. PCache *pCache, /* Obtain the page from this cache */
  38122. Pgno pgno, /* Page number to obtain */
  38123. sqlite3_pcache_page **ppPage /* Write result here */
  38124. ){
  38125. PgHdr *pPg;
  38126. if( pCache->eCreate==2 ) return 0;
  38127. /* Find a dirty page to write-out and recycle. First try to find a
  38128. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  38129. ** cleared), but if that is not possible settle for any other
  38130. ** unreferenced dirty page.
  38131. */
  38132. for(pPg=pCache->pSynced;
  38133. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  38134. pPg=pPg->pDirtyPrev
  38135. );
  38136. pCache->pSynced = pPg;
  38137. if( !pPg ){
  38138. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  38139. }
  38140. if( pPg ){
  38141. int rc;
  38142. #ifdef SQLITE_LOG_CACHE_SPILL
  38143. sqlite3_log(SQLITE_FULL,
  38144. "spill page %d making room for %d - cache used: %d/%d",
  38145. pPg->pgno, pgno,
  38146. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  38147. numberOfCachePages(pCache));
  38148. #endif
  38149. rc = pCache->xStress(pCache->pStress, pPg);
  38150. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  38151. return rc;
  38152. }
  38153. }
  38154. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  38155. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  38156. }
  38157. /*
  38158. ** This is a helper routine for sqlite3PcacheFetchFinish()
  38159. **
  38160. ** In the uncommon case where the page being fetched has not been
  38161. ** initialized, this routine is invoked to do the initialization.
  38162. ** This routine is broken out into a separate function since it
  38163. ** requires extra stack manipulation that can be avoided in the common
  38164. ** case.
  38165. */
  38166. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  38167. PCache *pCache, /* Obtain the page from this cache */
  38168. Pgno pgno, /* Page number obtained */
  38169. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  38170. ){
  38171. PgHdr *pPgHdr;
  38172. assert( pPage!=0 );
  38173. pPgHdr = (PgHdr*)pPage->pExtra;
  38174. assert( pPgHdr->pPage==0 );
  38175. memset(pPgHdr, 0, sizeof(PgHdr));
  38176. pPgHdr->pPage = pPage;
  38177. pPgHdr->pData = pPage->pBuf;
  38178. pPgHdr->pExtra = (void *)&pPgHdr[1];
  38179. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  38180. pPgHdr->pCache = pCache;
  38181. pPgHdr->pgno = pgno;
  38182. pPgHdr->flags = PGHDR_CLEAN;
  38183. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  38184. }
  38185. /*
  38186. ** This routine converts the sqlite3_pcache_page object returned by
  38187. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  38188. ** must be called after sqlite3PcacheFetch() in order to get a usable
  38189. ** result.
  38190. */
  38191. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  38192. PCache *pCache, /* Obtain the page from this cache */
  38193. Pgno pgno, /* Page number obtained */
  38194. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  38195. ){
  38196. PgHdr *pPgHdr;
  38197. assert( pPage!=0 );
  38198. pPgHdr = (PgHdr *)pPage->pExtra;
  38199. if( !pPgHdr->pPage ){
  38200. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  38201. }
  38202. pCache->nRefSum++;
  38203. pPgHdr->nRef++;
  38204. return pPgHdr;
  38205. }
  38206. /*
  38207. ** Decrement the reference count on a page. If the page is clean and the
  38208. ** reference count drops to 0, then it is made eligible for recycling.
  38209. */
  38210. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  38211. assert( p->nRef>0 );
  38212. p->pCache->nRefSum--;
  38213. if( (--p->nRef)==0 ){
  38214. if( p->flags&PGHDR_CLEAN ){
  38215. pcacheUnpin(p);
  38216. }else if( p->pDirtyPrev!=0 ){
  38217. /* Move the page to the head of the dirty list. */
  38218. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  38219. }
  38220. }
  38221. }
  38222. /*
  38223. ** Increase the reference count of a supplied page by 1.
  38224. */
  38225. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  38226. assert(p->nRef>0);
  38227. p->nRef++;
  38228. p->pCache->nRefSum++;
  38229. }
  38230. /*
  38231. ** Drop a page from the cache. There must be exactly one reference to the
  38232. ** page. This function deletes that reference, so after it returns the
  38233. ** page pointed to by p is invalid.
  38234. */
  38235. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  38236. assert( p->nRef==1 );
  38237. if( p->flags&PGHDR_DIRTY ){
  38238. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  38239. }
  38240. p->pCache->nRefSum--;
  38241. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  38242. }
  38243. /*
  38244. ** Make sure the page is marked as dirty. If it isn't dirty already,
  38245. ** make it so.
  38246. */
  38247. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  38248. assert( p->nRef>0 );
  38249. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
  38250. p->flags &= ~PGHDR_DONT_WRITE;
  38251. if( p->flags & PGHDR_CLEAN ){
  38252. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  38253. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  38254. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  38255. }
  38256. }
  38257. }
  38258. /*
  38259. ** Make sure the page is marked as clean. If it isn't clean already,
  38260. ** make it so.
  38261. */
  38262. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  38263. if( (p->flags & PGHDR_DIRTY) ){
  38264. assert( (p->flags & PGHDR_CLEAN)==0 );
  38265. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  38266. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  38267. p->flags |= PGHDR_CLEAN;
  38268. if( p->nRef==0 ){
  38269. pcacheUnpin(p);
  38270. }
  38271. }
  38272. }
  38273. /*
  38274. ** Make every page in the cache clean.
  38275. */
  38276. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  38277. PgHdr *p;
  38278. while( (p = pCache->pDirty)!=0 ){
  38279. sqlite3PcacheMakeClean(p);
  38280. }
  38281. }
  38282. /*
  38283. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  38284. */
  38285. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  38286. PgHdr *p;
  38287. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  38288. p->flags &= ~PGHDR_NEED_SYNC;
  38289. }
  38290. pCache->pSynced = pCache->pDirtyTail;
  38291. }
  38292. /*
  38293. ** Change the page number of page p to newPgno.
  38294. */
  38295. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  38296. PCache *pCache = p->pCache;
  38297. assert( p->nRef>0 );
  38298. assert( newPgno>0 );
  38299. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  38300. p->pgno = newPgno;
  38301. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  38302. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  38303. }
  38304. }
  38305. /*
  38306. ** Drop every cache entry whose page number is greater than "pgno". The
  38307. ** caller must ensure that there are no outstanding references to any pages
  38308. ** other than page 1 with a page number greater than pgno.
  38309. **
  38310. ** If there is a reference to page 1 and the pgno parameter passed to this
  38311. ** function is 0, then the data area associated with page 1 is zeroed, but
  38312. ** the page object is not dropped.
  38313. */
  38314. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  38315. if( pCache->pCache ){
  38316. PgHdr *p;
  38317. PgHdr *pNext;
  38318. for(p=pCache->pDirty; p; p=pNext){
  38319. pNext = p->pDirtyNext;
  38320. /* This routine never gets call with a positive pgno except right
  38321. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  38322. ** it must be that pgno==0.
  38323. */
  38324. assert( p->pgno>0 );
  38325. if( ALWAYS(p->pgno>pgno) ){
  38326. assert( p->flags&PGHDR_DIRTY );
  38327. sqlite3PcacheMakeClean(p);
  38328. }
  38329. }
  38330. if( pgno==0 && pCache->nRefSum ){
  38331. sqlite3_pcache_page *pPage1;
  38332. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  38333. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  38334. ** pCache->nRefSum>0 */
  38335. memset(pPage1->pBuf, 0, pCache->szPage);
  38336. pgno = 1;
  38337. }
  38338. }
  38339. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  38340. }
  38341. }
  38342. /*
  38343. ** Close a cache.
  38344. */
  38345. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  38346. assert( pCache->pCache!=0 );
  38347. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  38348. }
  38349. /*
  38350. ** Discard the contents of the cache.
  38351. */
  38352. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  38353. sqlite3PcacheTruncate(pCache, 0);
  38354. }
  38355. /*
  38356. ** Merge two lists of pages connected by pDirty and in pgno order.
  38357. ** Do not both fixing the pDirtyPrev pointers.
  38358. */
  38359. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  38360. PgHdr result, *pTail;
  38361. pTail = &result;
  38362. while( pA && pB ){
  38363. if( pA->pgno<pB->pgno ){
  38364. pTail->pDirty = pA;
  38365. pTail = pA;
  38366. pA = pA->pDirty;
  38367. }else{
  38368. pTail->pDirty = pB;
  38369. pTail = pB;
  38370. pB = pB->pDirty;
  38371. }
  38372. }
  38373. if( pA ){
  38374. pTail->pDirty = pA;
  38375. }else if( pB ){
  38376. pTail->pDirty = pB;
  38377. }else{
  38378. pTail->pDirty = 0;
  38379. }
  38380. return result.pDirty;
  38381. }
  38382. /*
  38383. ** Sort the list of pages in accending order by pgno. Pages are
  38384. ** connected by pDirty pointers. The pDirtyPrev pointers are
  38385. ** corrupted by this sort.
  38386. **
  38387. ** Since there cannot be more than 2^31 distinct pages in a database,
  38388. ** there cannot be more than 31 buckets required by the merge sorter.
  38389. ** One extra bucket is added to catch overflow in case something
  38390. ** ever changes to make the previous sentence incorrect.
  38391. */
  38392. #define N_SORT_BUCKET 32
  38393. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  38394. PgHdr *a[N_SORT_BUCKET], *p;
  38395. int i;
  38396. memset(a, 0, sizeof(a));
  38397. while( pIn ){
  38398. p = pIn;
  38399. pIn = p->pDirty;
  38400. p->pDirty = 0;
  38401. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  38402. if( a[i]==0 ){
  38403. a[i] = p;
  38404. break;
  38405. }else{
  38406. p = pcacheMergeDirtyList(a[i], p);
  38407. a[i] = 0;
  38408. }
  38409. }
  38410. if( NEVER(i==N_SORT_BUCKET-1) ){
  38411. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  38412. ** the input list. But that is impossible.
  38413. */
  38414. a[i] = pcacheMergeDirtyList(a[i], p);
  38415. }
  38416. }
  38417. p = a[0];
  38418. for(i=1; i<N_SORT_BUCKET; i++){
  38419. p = pcacheMergeDirtyList(p, a[i]);
  38420. }
  38421. return p;
  38422. }
  38423. /*
  38424. ** Return a list of all dirty pages in the cache, sorted by page number.
  38425. */
  38426. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  38427. PgHdr *p;
  38428. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  38429. p->pDirty = p->pDirtyNext;
  38430. }
  38431. return pcacheSortDirtyList(pCache->pDirty);
  38432. }
  38433. /*
  38434. ** Return the total number of references to all pages held by the cache.
  38435. **
  38436. ** This is not the total number of pages referenced, but the sum of the
  38437. ** reference count for all pages.
  38438. */
  38439. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  38440. return pCache->nRefSum;
  38441. }
  38442. /*
  38443. ** Return the number of references to the page supplied as an argument.
  38444. */
  38445. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  38446. return p->nRef;
  38447. }
  38448. /*
  38449. ** Return the total number of pages in the cache.
  38450. */
  38451. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  38452. assert( pCache->pCache!=0 );
  38453. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  38454. }
  38455. #ifdef SQLITE_TEST
  38456. /*
  38457. ** Get the suggested cache-size value.
  38458. */
  38459. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  38460. return numberOfCachePages(pCache);
  38461. }
  38462. #endif
  38463. /*
  38464. ** Set the suggested cache-size value.
  38465. */
  38466. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  38467. assert( pCache->pCache!=0 );
  38468. pCache->szCache = mxPage;
  38469. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  38470. numberOfCachePages(pCache));
  38471. }
  38472. /*
  38473. ** Free up as much memory as possible from the page cache.
  38474. */
  38475. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  38476. assert( pCache->pCache!=0 );
  38477. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  38478. }
  38479. /*
  38480. ** Return the size of the header added by this middleware layer
  38481. ** in the page-cache hierarchy.
  38482. */
  38483. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  38484. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  38485. /*
  38486. ** For all dirty pages currently in the cache, invoke the specified
  38487. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  38488. ** defined.
  38489. */
  38490. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  38491. PgHdr *pDirty;
  38492. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  38493. xIter(pDirty);
  38494. }
  38495. }
  38496. #endif
  38497. /************** End of pcache.c **********************************************/
  38498. /************** Begin file pcache1.c *****************************************/
  38499. /*
  38500. ** 2008 November 05
  38501. **
  38502. ** The author disclaims copyright to this source code. In place of
  38503. ** a legal notice, here is a blessing:
  38504. **
  38505. ** May you do good and not evil.
  38506. ** May you find forgiveness for yourself and forgive others.
  38507. ** May you share freely, never taking more than you give.
  38508. **
  38509. *************************************************************************
  38510. **
  38511. ** This file implements the default page cache implementation (the
  38512. ** sqlite3_pcache interface). It also contains part of the implementation
  38513. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  38514. ** If the default page cache implementation is overridden, then neither of
  38515. ** these two features are available.
  38516. **
  38517. ** A Page cache line looks like this:
  38518. **
  38519. ** -------------------------------------------------------------
  38520. ** | database page content | PgHdr1 | MemPage | PgHdr |
  38521. ** -------------------------------------------------------------
  38522. **
  38523. ** The database page content is up front (so that buffer overreads tend to
  38524. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  38525. ** is the extension added by the btree.c module containing information such
  38526. ** as the database page number and how that database page is used. PgHdr
  38527. ** is added by the pcache.c layer and contains information used to keep track
  38528. ** of which pages are "dirty". PgHdr1 is an extension added by this
  38529. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  38530. ** PgHdr1 contains information needed to look up a page by its page number.
  38531. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  38532. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  38533. **
  38534. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  38535. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  38536. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  38537. ** size can vary according to architecture, compile-time options, and
  38538. ** SQLite library version number.
  38539. **
  38540. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  38541. ** using a separate memory allocation from the database page content. This
  38542. ** seeks to overcome the "clownshoe" problem (also called "internal
  38543. ** fragmentation" in academic literature) of allocating a few bytes more
  38544. ** than a power of two with the memory allocator rounding up to the next
  38545. ** power of two, and leaving the rounded-up space unused.
  38546. **
  38547. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  38548. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  38549. **
  38550. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  38551. ** The btree.c module deals with pointers to MemPage objects.
  38552. **
  38553. ** SOURCE OF PAGE CACHE MEMORY:
  38554. **
  38555. ** Memory for a page might come from any of three sources:
  38556. **
  38557. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  38558. ** (2) Global page-cache memory provided using sqlite3_config() with
  38559. ** SQLITE_CONFIG_PAGECACHE.
  38560. ** (3) PCache-local bulk allocation.
  38561. **
  38562. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  38563. ** that is allocated when the page cache is created. The size of the local
  38564. ** bulk allocation can be adjusted using
  38565. **
  38566. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, 0, 0, N).
  38567. **
  38568. ** If N is positive, then N pages worth of memory are allocated using a single
  38569. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  38570. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  38571. ** for as many pages as can be accomodated.
  38572. **
  38573. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  38574. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  38575. ** memory allocator (1).
  38576. **
  38577. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  38578. ** show that method (3) with N==100 provides about a 5% performance boost for
  38579. ** common workloads.
  38580. */
  38581. /* #include "sqliteInt.h" */
  38582. typedef struct PCache1 PCache1;
  38583. typedef struct PgHdr1 PgHdr1;
  38584. typedef struct PgFreeslot PgFreeslot;
  38585. typedef struct PGroup PGroup;
  38586. /*
  38587. ** Each cache entry is represented by an instance of the following
  38588. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  38589. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  38590. ** in memory.
  38591. */
  38592. struct PgHdr1 {
  38593. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  38594. unsigned int iKey; /* Key value (page number) */
  38595. u8 isPinned; /* Page in use, not on the LRU list */
  38596. u8 isBulkLocal; /* This page from bulk local storage */
  38597. u8 isAnchor; /* This is the PGroup.lru element */
  38598. PgHdr1 *pNext; /* Next in hash table chain */
  38599. PCache1 *pCache; /* Cache that currently owns this page */
  38600. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  38601. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  38602. };
  38603. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  38604. ** of one or more PCaches that are able to recycle each other's unpinned
  38605. ** pages when they are under memory pressure. A PGroup is an instance of
  38606. ** the following object.
  38607. **
  38608. ** This page cache implementation works in one of two modes:
  38609. **
  38610. ** (1) Every PCache is the sole member of its own PGroup. There is
  38611. ** one PGroup per PCache.
  38612. **
  38613. ** (2) There is a single global PGroup that all PCaches are a member
  38614. ** of.
  38615. **
  38616. ** Mode 1 uses more memory (since PCache instances are not able to rob
  38617. ** unused pages from other PCaches) but it also operates without a mutex,
  38618. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  38619. ** threadsafe, but recycles pages more efficiently.
  38620. **
  38621. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  38622. ** PGroup which is the pcache1.grp global variable and its mutex is
  38623. ** SQLITE_MUTEX_STATIC_LRU.
  38624. */
  38625. struct PGroup {
  38626. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  38627. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  38628. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  38629. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  38630. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  38631. PgHdr1 lru; /* The beginning and end of the LRU list */
  38632. };
  38633. /* Each page cache is an instance of the following object. Every
  38634. ** open database file (including each in-memory database and each
  38635. ** temporary or transient database) has a single page cache which
  38636. ** is an instance of this object.
  38637. **
  38638. ** Pointers to structures of this type are cast and returned as
  38639. ** opaque sqlite3_pcache* handles.
  38640. */
  38641. struct PCache1 {
  38642. /* Cache configuration parameters. Page size (szPage) and the purgeable
  38643. ** flag (bPurgeable) are set when the cache is created. nMax may be
  38644. ** modified at any time by a call to the pcache1Cachesize() method.
  38645. ** The PGroup mutex must be held when accessing nMax.
  38646. */
  38647. PGroup *pGroup; /* PGroup this cache belongs to */
  38648. int szPage; /* Size of database content section */
  38649. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  38650. int szAlloc; /* Total size of one pcache line */
  38651. int bPurgeable; /* True if cache is purgeable */
  38652. unsigned int nMin; /* Minimum number of pages reserved */
  38653. unsigned int nMax; /* Configured "cache_size" value */
  38654. unsigned int n90pct; /* nMax*9/10 */
  38655. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  38656. /* Hash table of all pages. The following variables may only be accessed
  38657. ** when the accessor is holding the PGroup mutex.
  38658. */
  38659. unsigned int nRecyclable; /* Number of pages in the LRU list */
  38660. unsigned int nPage; /* Total number of pages in apHash */
  38661. unsigned int nHash; /* Number of slots in apHash[] */
  38662. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  38663. PgHdr1 *pFree; /* List of unused pcache-local pages */
  38664. void *pBulk; /* Bulk memory used by pcache-local */
  38665. };
  38666. /*
  38667. ** Free slots in the allocator used to divide up the global page cache
  38668. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  38669. */
  38670. struct PgFreeslot {
  38671. PgFreeslot *pNext; /* Next free slot */
  38672. };
  38673. /*
  38674. ** Global data used by this cache.
  38675. */
  38676. static SQLITE_WSD struct PCacheGlobal {
  38677. PGroup grp; /* The global PGroup for mode (2) */
  38678. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  38679. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  38680. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  38681. ** The nFreeSlot and pFree values do require mutex protection.
  38682. */
  38683. int isInit; /* True if initialized */
  38684. int separateCache; /* Use a new PGroup for each PCache */
  38685. int nInitPage; /* Initial bulk allocation size */
  38686. int szSlot; /* Size of each free slot */
  38687. int nSlot; /* The number of pcache slots */
  38688. int nReserve; /* Try to keep nFreeSlot above this */
  38689. void *pStart, *pEnd; /* Bounds of global page cache memory */
  38690. /* Above requires no mutex. Use mutex below for variable that follow. */
  38691. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  38692. PgFreeslot *pFree; /* Free page blocks */
  38693. int nFreeSlot; /* Number of unused pcache slots */
  38694. /* The following value requires a mutex to change. We skip the mutex on
  38695. ** reading because (1) most platforms read a 32-bit integer atomically and
  38696. ** (2) even if an incorrect value is read, no great harm is done since this
  38697. ** is really just an optimization. */
  38698. int bUnderPressure; /* True if low on PAGECACHE memory */
  38699. } pcache1_g;
  38700. /*
  38701. ** All code in this file should access the global structure above via the
  38702. ** alias "pcache1". This ensures that the WSD emulation is used when
  38703. ** compiling for systems that do not support real WSD.
  38704. */
  38705. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  38706. /*
  38707. ** Macros to enter and leave the PCache LRU mutex.
  38708. */
  38709. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  38710. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  38711. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  38712. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  38713. #else
  38714. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  38715. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  38716. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  38717. #endif
  38718. /******************************************************************************/
  38719. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  38720. /*
  38721. ** This function is called during initialization if a static buffer is
  38722. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  38723. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  38724. ** enough to contain 'n' buffers of 'sz' bytes each.
  38725. **
  38726. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  38727. ** to be serialized already. There is no need for further mutexing.
  38728. */
  38729. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  38730. if( pcache1.isInit ){
  38731. PgFreeslot *p;
  38732. if( pBuf==0 ) sz = n = 0;
  38733. sz = ROUNDDOWN8(sz);
  38734. pcache1.szSlot = sz;
  38735. pcache1.nSlot = pcache1.nFreeSlot = n;
  38736. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  38737. pcache1.pStart = pBuf;
  38738. pcache1.pFree = 0;
  38739. pcache1.bUnderPressure = 0;
  38740. while( n-- ){
  38741. p = (PgFreeslot*)pBuf;
  38742. p->pNext = pcache1.pFree;
  38743. pcache1.pFree = p;
  38744. pBuf = (void*)&((char*)pBuf)[sz];
  38745. }
  38746. pcache1.pEnd = pBuf;
  38747. }
  38748. }
  38749. /*
  38750. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  38751. ** true if pCache->pFree ends up containing one or more free pages.
  38752. */
  38753. static int pcache1InitBulk(PCache1 *pCache){
  38754. i64 szBulk;
  38755. char *zBulk;
  38756. if( pcache1.nInitPage==0 ) return 0;
  38757. /* Do not bother with a bulk allocation if the cache size very small */
  38758. if( pCache->nMax<3 ) return 0;
  38759. sqlite3BeginBenignMalloc();
  38760. if( pcache1.nInitPage>0 ){
  38761. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  38762. }else{
  38763. szBulk = -1024 * (i64)pcache1.nInitPage;
  38764. }
  38765. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  38766. szBulk = pCache->szAlloc*pCache->nMax;
  38767. }
  38768. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  38769. sqlite3EndBenignMalloc();
  38770. if( zBulk ){
  38771. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  38772. int i;
  38773. for(i=0; i<nBulk; i++){
  38774. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  38775. pX->page.pBuf = zBulk;
  38776. pX->page.pExtra = &pX[1];
  38777. pX->isBulkLocal = 1;
  38778. pX->isAnchor = 0;
  38779. pX->pNext = pCache->pFree;
  38780. pCache->pFree = pX;
  38781. zBulk += pCache->szAlloc;
  38782. }
  38783. }
  38784. return pCache->pFree!=0;
  38785. }
  38786. /*
  38787. ** Malloc function used within this file to allocate space from the buffer
  38788. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  38789. ** such buffer exists or there is no space left in it, this function falls
  38790. ** back to sqlite3Malloc().
  38791. **
  38792. ** Multiple threads can run this routine at the same time. Global variables
  38793. ** in pcache1 need to be protected via mutex.
  38794. */
  38795. static void *pcache1Alloc(int nByte){
  38796. void *p = 0;
  38797. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38798. if( nByte<=pcache1.szSlot ){
  38799. sqlite3_mutex_enter(pcache1.mutex);
  38800. p = (PgHdr1 *)pcache1.pFree;
  38801. if( p ){
  38802. pcache1.pFree = pcache1.pFree->pNext;
  38803. pcache1.nFreeSlot--;
  38804. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  38805. assert( pcache1.nFreeSlot>=0 );
  38806. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  38807. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  38808. }
  38809. sqlite3_mutex_leave(pcache1.mutex);
  38810. }
  38811. if( p==0 ){
  38812. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  38813. ** it from sqlite3Malloc instead.
  38814. */
  38815. p = sqlite3Malloc(nByte);
  38816. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  38817. if( p ){
  38818. int sz = sqlite3MallocSize(p);
  38819. sqlite3_mutex_enter(pcache1.mutex);
  38820. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  38821. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  38822. sqlite3_mutex_leave(pcache1.mutex);
  38823. }
  38824. #endif
  38825. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  38826. }
  38827. return p;
  38828. }
  38829. /*
  38830. ** Free an allocated buffer obtained from pcache1Alloc().
  38831. */
  38832. static void pcache1Free(void *p){
  38833. int nFreed = 0;
  38834. if( p==0 ) return;
  38835. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  38836. PgFreeslot *pSlot;
  38837. sqlite3_mutex_enter(pcache1.mutex);
  38838. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  38839. pSlot = (PgFreeslot*)p;
  38840. pSlot->pNext = pcache1.pFree;
  38841. pcache1.pFree = pSlot;
  38842. pcache1.nFreeSlot++;
  38843. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  38844. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  38845. sqlite3_mutex_leave(pcache1.mutex);
  38846. }else{
  38847. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  38848. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  38849. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  38850. nFreed = sqlite3MallocSize(p);
  38851. sqlite3_mutex_enter(pcache1.mutex);
  38852. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  38853. sqlite3_mutex_leave(pcache1.mutex);
  38854. #endif
  38855. sqlite3_free(p);
  38856. }
  38857. }
  38858. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38859. /*
  38860. ** Return the size of a pcache allocation
  38861. */
  38862. static int pcache1MemSize(void *p){
  38863. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  38864. return pcache1.szSlot;
  38865. }else{
  38866. int iSize;
  38867. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  38868. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  38869. iSize = sqlite3MallocSize(p);
  38870. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  38871. return iSize;
  38872. }
  38873. }
  38874. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38875. /*
  38876. ** Allocate a new page object initially associated with cache pCache.
  38877. */
  38878. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  38879. PgHdr1 *p = 0;
  38880. void *pPg;
  38881. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38882. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  38883. p = pCache->pFree;
  38884. pCache->pFree = p->pNext;
  38885. p->pNext = 0;
  38886. }else{
  38887. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38888. /* The group mutex must be released before pcache1Alloc() is called. This
  38889. ** is because it might call sqlite3_release_memory(), which assumes that
  38890. ** this mutex is not held. */
  38891. assert( pcache1.separateCache==0 );
  38892. assert( pCache->pGroup==&pcache1.grp );
  38893. pcache1LeaveMutex(pCache->pGroup);
  38894. #endif
  38895. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  38896. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38897. pPg = pcache1Alloc(pCache->szPage);
  38898. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  38899. if( !pPg || !p ){
  38900. pcache1Free(pPg);
  38901. sqlite3_free(p);
  38902. pPg = 0;
  38903. }
  38904. #else
  38905. pPg = pcache1Alloc(pCache->szAlloc);
  38906. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  38907. #endif
  38908. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  38909. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38910. pcache1EnterMutex(pCache->pGroup);
  38911. #endif
  38912. if( pPg==0 ) return 0;
  38913. p->page.pBuf = pPg;
  38914. p->page.pExtra = &p[1];
  38915. p->isBulkLocal = 0;
  38916. p->isAnchor = 0;
  38917. }
  38918. if( pCache->bPurgeable ){
  38919. pCache->pGroup->nCurrentPage++;
  38920. }
  38921. return p;
  38922. }
  38923. /*
  38924. ** Free a page object allocated by pcache1AllocPage().
  38925. */
  38926. static void pcache1FreePage(PgHdr1 *p){
  38927. PCache1 *pCache;
  38928. assert( p!=0 );
  38929. pCache = p->pCache;
  38930. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  38931. if( p->isBulkLocal ){
  38932. p->pNext = pCache->pFree;
  38933. pCache->pFree = p;
  38934. }else{
  38935. pcache1Free(p->page.pBuf);
  38936. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38937. sqlite3_free(p);
  38938. #endif
  38939. }
  38940. if( pCache->bPurgeable ){
  38941. pCache->pGroup->nCurrentPage--;
  38942. }
  38943. }
  38944. /*
  38945. ** Malloc function used by SQLite to obtain space from the buffer configured
  38946. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  38947. ** exists, this function falls back to sqlite3Malloc().
  38948. */
  38949. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  38950. return pcache1Alloc(sz);
  38951. }
  38952. /*
  38953. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  38954. */
  38955. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  38956. pcache1Free(p);
  38957. }
  38958. /*
  38959. ** Return true if it desirable to avoid allocating a new page cache
  38960. ** entry.
  38961. **
  38962. ** If memory was allocated specifically to the page cache using
  38963. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  38964. ** it is desirable to avoid allocating a new page cache entry because
  38965. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  38966. ** for all page cache needs and we should not need to spill the
  38967. ** allocation onto the heap.
  38968. **
  38969. ** Or, the heap is used for all page cache memory but the heap is
  38970. ** under memory pressure, then again it is desirable to avoid
  38971. ** allocating a new page cache entry in order to avoid stressing
  38972. ** the heap even further.
  38973. */
  38974. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  38975. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  38976. return pcache1.bUnderPressure;
  38977. }else{
  38978. return sqlite3HeapNearlyFull();
  38979. }
  38980. }
  38981. /******************************************************************************/
  38982. /******** General Implementation Functions ************************************/
  38983. /*
  38984. ** This function is used to resize the hash table used by the cache passed
  38985. ** as the first argument.
  38986. **
  38987. ** The PCache mutex must be held when this function is called.
  38988. */
  38989. static void pcache1ResizeHash(PCache1 *p){
  38990. PgHdr1 **apNew;
  38991. unsigned int nNew;
  38992. unsigned int i;
  38993. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  38994. nNew = p->nHash*2;
  38995. if( nNew<256 ){
  38996. nNew = 256;
  38997. }
  38998. pcache1LeaveMutex(p->pGroup);
  38999. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  39000. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  39001. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  39002. pcache1EnterMutex(p->pGroup);
  39003. if( apNew ){
  39004. for(i=0; i<p->nHash; i++){
  39005. PgHdr1 *pPage;
  39006. PgHdr1 *pNext = p->apHash[i];
  39007. while( (pPage = pNext)!=0 ){
  39008. unsigned int h = pPage->iKey % nNew;
  39009. pNext = pPage->pNext;
  39010. pPage->pNext = apNew[h];
  39011. apNew[h] = pPage;
  39012. }
  39013. }
  39014. sqlite3_free(p->apHash);
  39015. p->apHash = apNew;
  39016. p->nHash = nNew;
  39017. }
  39018. }
  39019. /*
  39020. ** This function is used internally to remove the page pPage from the
  39021. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  39022. ** LRU list, then this function is a no-op.
  39023. **
  39024. ** The PGroup mutex must be held when this function is called.
  39025. */
  39026. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  39027. PCache1 *pCache;
  39028. assert( pPage!=0 );
  39029. assert( pPage->isPinned==0 );
  39030. pCache = pPage->pCache;
  39031. assert( pPage->pLruNext );
  39032. assert( pPage->pLruPrev );
  39033. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39034. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  39035. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  39036. pPage->pLruNext = 0;
  39037. pPage->pLruPrev = 0;
  39038. pPage->isPinned = 1;
  39039. assert( pPage->isAnchor==0 );
  39040. assert( pCache->pGroup->lru.isAnchor==1 );
  39041. pCache->nRecyclable--;
  39042. return pPage;
  39043. }
  39044. /*
  39045. ** Remove the page supplied as an argument from the hash table
  39046. ** (PCache1.apHash structure) that it is currently stored in.
  39047. ** Also free the page if freePage is true.
  39048. **
  39049. ** The PGroup mutex must be held when this function is called.
  39050. */
  39051. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  39052. unsigned int h;
  39053. PCache1 *pCache = pPage->pCache;
  39054. PgHdr1 **pp;
  39055. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39056. h = pPage->iKey % pCache->nHash;
  39057. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  39058. *pp = (*pp)->pNext;
  39059. pCache->nPage--;
  39060. if( freeFlag ) pcache1FreePage(pPage);
  39061. }
  39062. /*
  39063. ** If there are currently more than nMaxPage pages allocated, try
  39064. ** to recycle pages to reduce the number allocated to nMaxPage.
  39065. */
  39066. static void pcache1EnforceMaxPage(PCache1 *pCache){
  39067. PGroup *pGroup = pCache->pGroup;
  39068. PgHdr1 *p;
  39069. assert( sqlite3_mutex_held(pGroup->mutex) );
  39070. while( pGroup->nCurrentPage>pGroup->nMaxPage
  39071. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  39072. ){
  39073. assert( p->pCache->pGroup==pGroup );
  39074. assert( p->isPinned==0 );
  39075. pcache1PinPage(p);
  39076. pcache1RemoveFromHash(p, 1);
  39077. }
  39078. if( pCache->nPage==0 && pCache->pBulk ){
  39079. sqlite3_free(pCache->pBulk);
  39080. pCache->pBulk = pCache->pFree = 0;
  39081. }
  39082. }
  39083. /*
  39084. ** Discard all pages from cache pCache with a page number (key value)
  39085. ** greater than or equal to iLimit. Any pinned pages that meet this
  39086. ** criteria are unpinned before they are discarded.
  39087. **
  39088. ** The PCache mutex must be held when this function is called.
  39089. */
  39090. static void pcache1TruncateUnsafe(
  39091. PCache1 *pCache, /* The cache to truncate */
  39092. unsigned int iLimit /* Drop pages with this pgno or larger */
  39093. ){
  39094. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  39095. unsigned int h;
  39096. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39097. for(h=0; h<pCache->nHash; h++){
  39098. PgHdr1 **pp = &pCache->apHash[h];
  39099. PgHdr1 *pPage;
  39100. while( (pPage = *pp)!=0 ){
  39101. if( pPage->iKey>=iLimit ){
  39102. pCache->nPage--;
  39103. *pp = pPage->pNext;
  39104. if( !pPage->isPinned ) pcache1PinPage(pPage);
  39105. pcache1FreePage(pPage);
  39106. }else{
  39107. pp = &pPage->pNext;
  39108. TESTONLY( nPage++; )
  39109. }
  39110. }
  39111. }
  39112. assert( pCache->nPage==nPage );
  39113. }
  39114. /******************************************************************************/
  39115. /******** sqlite3_pcache Methods **********************************************/
  39116. /*
  39117. ** Implementation of the sqlite3_pcache.xInit method.
  39118. */
  39119. static int pcache1Init(void *NotUsed){
  39120. UNUSED_PARAMETER(NotUsed);
  39121. assert( pcache1.isInit==0 );
  39122. memset(&pcache1, 0, sizeof(pcache1));
  39123. /*
  39124. ** The pcache1.separateCache variable is true if each PCache has its own
  39125. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  39126. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  39127. **
  39128. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  39129. **
  39130. ** * Use a unified cache in single-threaded applications that have
  39131. ** configured a start-time buffer for use as page-cache memory using
  39132. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  39133. ** pBuf argument.
  39134. **
  39135. ** * Otherwise use separate caches (mode-1)
  39136. */
  39137. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  39138. pcache1.separateCache = 0;
  39139. #elif SQLITE_THREADSAFE
  39140. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  39141. || sqlite3GlobalConfig.bCoreMutex>0;
  39142. #else
  39143. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  39144. #endif
  39145. #if SQLITE_THREADSAFE
  39146. if( sqlite3GlobalConfig.bCoreMutex ){
  39147. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  39148. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  39149. }
  39150. #endif
  39151. if( pcache1.separateCache
  39152. && sqlite3GlobalConfig.nPage!=0
  39153. && sqlite3GlobalConfig.pPage==0
  39154. ){
  39155. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  39156. }else{
  39157. pcache1.nInitPage = 0;
  39158. }
  39159. pcache1.grp.mxPinned = 10;
  39160. pcache1.isInit = 1;
  39161. return SQLITE_OK;
  39162. }
  39163. /*
  39164. ** Implementation of the sqlite3_pcache.xShutdown method.
  39165. ** Note that the static mutex allocated in xInit does
  39166. ** not need to be freed.
  39167. */
  39168. static void pcache1Shutdown(void *NotUsed){
  39169. UNUSED_PARAMETER(NotUsed);
  39170. assert( pcache1.isInit!=0 );
  39171. memset(&pcache1, 0, sizeof(pcache1));
  39172. }
  39173. /* forward declaration */
  39174. static void pcache1Destroy(sqlite3_pcache *p);
  39175. /*
  39176. ** Implementation of the sqlite3_pcache.xCreate method.
  39177. **
  39178. ** Allocate a new cache.
  39179. */
  39180. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  39181. PCache1 *pCache; /* The newly created page cache */
  39182. PGroup *pGroup; /* The group the new page cache will belong to */
  39183. int sz; /* Bytes of memory required to allocate the new cache */
  39184. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  39185. assert( szExtra < 300 );
  39186. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  39187. pCache = (PCache1 *)sqlite3MallocZero(sz);
  39188. if( pCache ){
  39189. if( pcache1.separateCache ){
  39190. pGroup = (PGroup*)&pCache[1];
  39191. pGroup->mxPinned = 10;
  39192. }else{
  39193. pGroup = &pcache1.grp;
  39194. }
  39195. if( pGroup->lru.isAnchor==0 ){
  39196. pGroup->lru.isAnchor = 1;
  39197. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  39198. }
  39199. pCache->pGroup = pGroup;
  39200. pCache->szPage = szPage;
  39201. pCache->szExtra = szExtra;
  39202. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  39203. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  39204. pcache1EnterMutex(pGroup);
  39205. pcache1ResizeHash(pCache);
  39206. if( bPurgeable ){
  39207. pCache->nMin = 10;
  39208. pGroup->nMinPage += pCache->nMin;
  39209. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39210. }
  39211. pcache1LeaveMutex(pGroup);
  39212. if( pCache->nHash==0 ){
  39213. pcache1Destroy((sqlite3_pcache*)pCache);
  39214. pCache = 0;
  39215. }
  39216. }
  39217. return (sqlite3_pcache *)pCache;
  39218. }
  39219. /*
  39220. ** Implementation of the sqlite3_pcache.xCachesize method.
  39221. **
  39222. ** Configure the cache_size limit for a cache.
  39223. */
  39224. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  39225. PCache1 *pCache = (PCache1 *)p;
  39226. if( pCache->bPurgeable ){
  39227. PGroup *pGroup = pCache->pGroup;
  39228. pcache1EnterMutex(pGroup);
  39229. pGroup->nMaxPage += (nMax - pCache->nMax);
  39230. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39231. pCache->nMax = nMax;
  39232. pCache->n90pct = pCache->nMax*9/10;
  39233. pcache1EnforceMaxPage(pCache);
  39234. pcache1LeaveMutex(pGroup);
  39235. }
  39236. }
  39237. /*
  39238. ** Implementation of the sqlite3_pcache.xShrink method.
  39239. **
  39240. ** Free up as much memory as possible.
  39241. */
  39242. static void pcache1Shrink(sqlite3_pcache *p){
  39243. PCache1 *pCache = (PCache1*)p;
  39244. if( pCache->bPurgeable ){
  39245. PGroup *pGroup = pCache->pGroup;
  39246. int savedMaxPage;
  39247. pcache1EnterMutex(pGroup);
  39248. savedMaxPage = pGroup->nMaxPage;
  39249. pGroup->nMaxPage = 0;
  39250. pcache1EnforceMaxPage(pCache);
  39251. pGroup->nMaxPage = savedMaxPage;
  39252. pcache1LeaveMutex(pGroup);
  39253. }
  39254. }
  39255. /*
  39256. ** Implementation of the sqlite3_pcache.xPagecount method.
  39257. */
  39258. static int pcache1Pagecount(sqlite3_pcache *p){
  39259. int n;
  39260. PCache1 *pCache = (PCache1*)p;
  39261. pcache1EnterMutex(pCache->pGroup);
  39262. n = pCache->nPage;
  39263. pcache1LeaveMutex(pCache->pGroup);
  39264. return n;
  39265. }
  39266. /*
  39267. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  39268. ** in the header of the pcache1Fetch() procedure.
  39269. **
  39270. ** This steps are broken out into a separate procedure because they are
  39271. ** usually not needed, and by avoiding the stack initialization required
  39272. ** for these steps, the main pcache1Fetch() procedure can run faster.
  39273. */
  39274. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  39275. PCache1 *pCache,
  39276. unsigned int iKey,
  39277. int createFlag
  39278. ){
  39279. unsigned int nPinned;
  39280. PGroup *pGroup = pCache->pGroup;
  39281. PgHdr1 *pPage = 0;
  39282. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  39283. assert( pCache->nPage >= pCache->nRecyclable );
  39284. nPinned = pCache->nPage - pCache->nRecyclable;
  39285. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  39286. assert( pCache->n90pct == pCache->nMax*9/10 );
  39287. if( createFlag==1 && (
  39288. nPinned>=pGroup->mxPinned
  39289. || nPinned>=pCache->n90pct
  39290. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  39291. )){
  39292. return 0;
  39293. }
  39294. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  39295. assert( pCache->nHash>0 && pCache->apHash );
  39296. /* Step 4. Try to recycle a page. */
  39297. if( pCache->bPurgeable
  39298. && !pGroup->lru.pLruPrev->isAnchor
  39299. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  39300. ){
  39301. PCache1 *pOther;
  39302. pPage = pGroup->lru.pLruPrev;
  39303. assert( pPage->isPinned==0 );
  39304. pcache1RemoveFromHash(pPage, 0);
  39305. pcache1PinPage(pPage);
  39306. pOther = pPage->pCache;
  39307. if( pOther->szAlloc != pCache->szAlloc ){
  39308. pcache1FreePage(pPage);
  39309. pPage = 0;
  39310. }else{
  39311. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  39312. }
  39313. }
  39314. /* Step 5. If a usable page buffer has still not been found,
  39315. ** attempt to allocate a new one.
  39316. */
  39317. if( !pPage ){
  39318. pPage = pcache1AllocPage(pCache, createFlag==1);
  39319. }
  39320. if( pPage ){
  39321. unsigned int h = iKey % pCache->nHash;
  39322. pCache->nPage++;
  39323. pPage->iKey = iKey;
  39324. pPage->pNext = pCache->apHash[h];
  39325. pPage->pCache = pCache;
  39326. pPage->pLruPrev = 0;
  39327. pPage->pLruNext = 0;
  39328. pPage->isPinned = 1;
  39329. *(void **)pPage->page.pExtra = 0;
  39330. pCache->apHash[h] = pPage;
  39331. if( iKey>pCache->iMaxKey ){
  39332. pCache->iMaxKey = iKey;
  39333. }
  39334. }
  39335. return pPage;
  39336. }
  39337. /*
  39338. ** Implementation of the sqlite3_pcache.xFetch method.
  39339. **
  39340. ** Fetch a page by key value.
  39341. **
  39342. ** Whether or not a new page may be allocated by this function depends on
  39343. ** the value of the createFlag argument. 0 means do not allocate a new
  39344. ** page. 1 means allocate a new page if space is easily available. 2
  39345. ** means to try really hard to allocate a new page.
  39346. **
  39347. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  39348. ** database) there is really no difference between createFlag 1 and 2. So
  39349. ** the calling function (pcache.c) will never have a createFlag of 1 on
  39350. ** a non-purgeable cache.
  39351. **
  39352. ** There are three different approaches to obtaining space for a page,
  39353. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  39354. **
  39355. ** 1. Regardless of the value of createFlag, the cache is searched for a
  39356. ** copy of the requested page. If one is found, it is returned.
  39357. **
  39358. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  39359. ** returned.
  39360. **
  39361. ** 3. If createFlag is 1, and the page is not already in the cache, then
  39362. ** return NULL (do not allocate a new page) if any of the following
  39363. ** conditions are true:
  39364. **
  39365. ** (a) the number of pages pinned by the cache is greater than
  39366. ** PCache1.nMax, or
  39367. **
  39368. ** (b) the number of pages pinned by the cache is greater than
  39369. ** the sum of nMax for all purgeable caches, less the sum of
  39370. ** nMin for all other purgeable caches, or
  39371. **
  39372. ** 4. If none of the first three conditions apply and the cache is marked
  39373. ** as purgeable, and if one of the following is true:
  39374. **
  39375. ** (a) The number of pages allocated for the cache is already
  39376. ** PCache1.nMax, or
  39377. **
  39378. ** (b) The number of pages allocated for all purgeable caches is
  39379. ** already equal to or greater than the sum of nMax for all
  39380. ** purgeable caches,
  39381. **
  39382. ** (c) The system is under memory pressure and wants to avoid
  39383. ** unnecessary pages cache entry allocations
  39384. **
  39385. ** then attempt to recycle a page from the LRU list. If it is the right
  39386. ** size, return the recycled buffer. Otherwise, free the buffer and
  39387. ** proceed to step 5.
  39388. **
  39389. ** 5. Otherwise, allocate and return a new page buffer.
  39390. **
  39391. ** There are two versions of this routine. pcache1FetchWithMutex() is
  39392. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  39393. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  39394. ** invokes the appropriate routine.
  39395. */
  39396. static PgHdr1 *pcache1FetchNoMutex(
  39397. sqlite3_pcache *p,
  39398. unsigned int iKey,
  39399. int createFlag
  39400. ){
  39401. PCache1 *pCache = (PCache1 *)p;
  39402. PgHdr1 *pPage = 0;
  39403. /* Step 1: Search the hash table for an existing entry. */
  39404. pPage = pCache->apHash[iKey % pCache->nHash];
  39405. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  39406. /* Step 2: If the page was found in the hash table, then return it.
  39407. ** If the page was not in the hash table and createFlag is 0, abort.
  39408. ** Otherwise (page not in hash and createFlag!=0) continue with
  39409. ** subsequent steps to try to create the page. */
  39410. if( pPage ){
  39411. if( !pPage->isPinned ){
  39412. return pcache1PinPage(pPage);
  39413. }else{
  39414. return pPage;
  39415. }
  39416. }else if( createFlag ){
  39417. /* Steps 3, 4, and 5 implemented by this subroutine */
  39418. return pcache1FetchStage2(pCache, iKey, createFlag);
  39419. }else{
  39420. return 0;
  39421. }
  39422. }
  39423. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  39424. static PgHdr1 *pcache1FetchWithMutex(
  39425. sqlite3_pcache *p,
  39426. unsigned int iKey,
  39427. int createFlag
  39428. ){
  39429. PCache1 *pCache = (PCache1 *)p;
  39430. PgHdr1 *pPage;
  39431. pcache1EnterMutex(pCache->pGroup);
  39432. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  39433. assert( pPage==0 || pCache->iMaxKey>=iKey );
  39434. pcache1LeaveMutex(pCache->pGroup);
  39435. return pPage;
  39436. }
  39437. #endif
  39438. static sqlite3_pcache_page *pcache1Fetch(
  39439. sqlite3_pcache *p,
  39440. unsigned int iKey,
  39441. int createFlag
  39442. ){
  39443. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  39444. PCache1 *pCache = (PCache1 *)p;
  39445. #endif
  39446. assert( offsetof(PgHdr1,page)==0 );
  39447. assert( pCache->bPurgeable || createFlag!=1 );
  39448. assert( pCache->bPurgeable || pCache->nMin==0 );
  39449. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  39450. assert( pCache->nMin==0 || pCache->bPurgeable );
  39451. assert( pCache->nHash>0 );
  39452. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  39453. if( pCache->pGroup->mutex ){
  39454. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  39455. }else
  39456. #endif
  39457. {
  39458. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  39459. }
  39460. }
  39461. /*
  39462. ** Implementation of the sqlite3_pcache.xUnpin method.
  39463. **
  39464. ** Mark a page as unpinned (eligible for asynchronous recycling).
  39465. */
  39466. static void pcache1Unpin(
  39467. sqlite3_pcache *p,
  39468. sqlite3_pcache_page *pPg,
  39469. int reuseUnlikely
  39470. ){
  39471. PCache1 *pCache = (PCache1 *)p;
  39472. PgHdr1 *pPage = (PgHdr1 *)pPg;
  39473. PGroup *pGroup = pCache->pGroup;
  39474. assert( pPage->pCache==pCache );
  39475. pcache1EnterMutex(pGroup);
  39476. /* It is an error to call this function if the page is already
  39477. ** part of the PGroup LRU list.
  39478. */
  39479. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  39480. assert( pPage->isPinned==1 );
  39481. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  39482. pcache1RemoveFromHash(pPage, 1);
  39483. }else{
  39484. /* Add the page to the PGroup LRU list. */
  39485. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  39486. pPage->pLruPrev = &pGroup->lru;
  39487. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  39488. *ppFirst = pPage;
  39489. pCache->nRecyclable++;
  39490. pPage->isPinned = 0;
  39491. }
  39492. pcache1LeaveMutex(pCache->pGroup);
  39493. }
  39494. /*
  39495. ** Implementation of the sqlite3_pcache.xRekey method.
  39496. */
  39497. static void pcache1Rekey(
  39498. sqlite3_pcache *p,
  39499. sqlite3_pcache_page *pPg,
  39500. unsigned int iOld,
  39501. unsigned int iNew
  39502. ){
  39503. PCache1 *pCache = (PCache1 *)p;
  39504. PgHdr1 *pPage = (PgHdr1 *)pPg;
  39505. PgHdr1 **pp;
  39506. unsigned int h;
  39507. assert( pPage->iKey==iOld );
  39508. assert( pPage->pCache==pCache );
  39509. pcache1EnterMutex(pCache->pGroup);
  39510. h = iOld%pCache->nHash;
  39511. pp = &pCache->apHash[h];
  39512. while( (*pp)!=pPage ){
  39513. pp = &(*pp)->pNext;
  39514. }
  39515. *pp = pPage->pNext;
  39516. h = iNew%pCache->nHash;
  39517. pPage->iKey = iNew;
  39518. pPage->pNext = pCache->apHash[h];
  39519. pCache->apHash[h] = pPage;
  39520. if( iNew>pCache->iMaxKey ){
  39521. pCache->iMaxKey = iNew;
  39522. }
  39523. pcache1LeaveMutex(pCache->pGroup);
  39524. }
  39525. /*
  39526. ** Implementation of the sqlite3_pcache.xTruncate method.
  39527. **
  39528. ** Discard all unpinned pages in the cache with a page number equal to
  39529. ** or greater than parameter iLimit. Any pinned pages with a page number
  39530. ** equal to or greater than iLimit are implicitly unpinned.
  39531. */
  39532. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  39533. PCache1 *pCache = (PCache1 *)p;
  39534. pcache1EnterMutex(pCache->pGroup);
  39535. if( iLimit<=pCache->iMaxKey ){
  39536. pcache1TruncateUnsafe(pCache, iLimit);
  39537. pCache->iMaxKey = iLimit-1;
  39538. }
  39539. pcache1LeaveMutex(pCache->pGroup);
  39540. }
  39541. /*
  39542. ** Implementation of the sqlite3_pcache.xDestroy method.
  39543. **
  39544. ** Destroy a cache allocated using pcache1Create().
  39545. */
  39546. static void pcache1Destroy(sqlite3_pcache *p){
  39547. PCache1 *pCache = (PCache1 *)p;
  39548. PGroup *pGroup = pCache->pGroup;
  39549. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  39550. pcache1EnterMutex(pGroup);
  39551. pcache1TruncateUnsafe(pCache, 0);
  39552. assert( pGroup->nMaxPage >= pCache->nMax );
  39553. pGroup->nMaxPage -= pCache->nMax;
  39554. assert( pGroup->nMinPage >= pCache->nMin );
  39555. pGroup->nMinPage -= pCache->nMin;
  39556. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39557. pcache1EnforceMaxPage(pCache);
  39558. pcache1LeaveMutex(pGroup);
  39559. sqlite3_free(pCache->pBulk);
  39560. sqlite3_free(pCache->apHash);
  39561. sqlite3_free(pCache);
  39562. }
  39563. /*
  39564. ** This function is called during initialization (sqlite3_initialize()) to
  39565. ** install the default pluggable cache module, assuming the user has not
  39566. ** already provided an alternative.
  39567. */
  39568. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  39569. static const sqlite3_pcache_methods2 defaultMethods = {
  39570. 1, /* iVersion */
  39571. 0, /* pArg */
  39572. pcache1Init, /* xInit */
  39573. pcache1Shutdown, /* xShutdown */
  39574. pcache1Create, /* xCreate */
  39575. pcache1Cachesize, /* xCachesize */
  39576. pcache1Pagecount, /* xPagecount */
  39577. pcache1Fetch, /* xFetch */
  39578. pcache1Unpin, /* xUnpin */
  39579. pcache1Rekey, /* xRekey */
  39580. pcache1Truncate, /* xTruncate */
  39581. pcache1Destroy, /* xDestroy */
  39582. pcache1Shrink /* xShrink */
  39583. };
  39584. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  39585. }
  39586. /*
  39587. ** Return the size of the header on each page of this PCACHE implementation.
  39588. */
  39589. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  39590. /*
  39591. ** Return the global mutex used by this PCACHE implementation. The
  39592. ** sqlite3_status() routine needs access to this mutex.
  39593. */
  39594. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  39595. return pcache1.mutex;
  39596. }
  39597. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39598. /*
  39599. ** This function is called to free superfluous dynamically allocated memory
  39600. ** held by the pager system. Memory in use by any SQLite pager allocated
  39601. ** by the current thread may be sqlite3_free()ed.
  39602. **
  39603. ** nReq is the number of bytes of memory required. Once this much has
  39604. ** been released, the function returns. The return value is the total number
  39605. ** of bytes of memory released.
  39606. */
  39607. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  39608. int nFree = 0;
  39609. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  39610. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  39611. if( sqlite3GlobalConfig.nPage==0 ){
  39612. PgHdr1 *p;
  39613. pcache1EnterMutex(&pcache1.grp);
  39614. while( (nReq<0 || nFree<nReq)
  39615. && (p=pcache1.grp.lru.pLruPrev)!=0
  39616. && p->isAnchor==0
  39617. ){
  39618. nFree += pcache1MemSize(p->page.pBuf);
  39619. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  39620. nFree += sqlite3MemSize(p);
  39621. #endif
  39622. assert( p->isPinned==0 );
  39623. pcache1PinPage(p);
  39624. pcache1RemoveFromHash(p, 1);
  39625. }
  39626. pcache1LeaveMutex(&pcache1.grp);
  39627. }
  39628. return nFree;
  39629. }
  39630. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  39631. #ifdef SQLITE_TEST
  39632. /*
  39633. ** This function is used by test procedures to inspect the internal state
  39634. ** of the global cache.
  39635. */
  39636. SQLITE_PRIVATE void sqlite3PcacheStats(
  39637. int *pnCurrent, /* OUT: Total number of pages cached */
  39638. int *pnMax, /* OUT: Global maximum cache size */
  39639. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  39640. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  39641. ){
  39642. PgHdr1 *p;
  39643. int nRecyclable = 0;
  39644. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  39645. assert( p->isPinned==0 );
  39646. nRecyclable++;
  39647. }
  39648. *pnCurrent = pcache1.grp.nCurrentPage;
  39649. *pnMax = (int)pcache1.grp.nMaxPage;
  39650. *pnMin = (int)pcache1.grp.nMinPage;
  39651. *pnRecyclable = nRecyclable;
  39652. }
  39653. #endif
  39654. /************** End of pcache1.c *********************************************/
  39655. /************** Begin file rowset.c ******************************************/
  39656. /*
  39657. ** 2008 December 3
  39658. **
  39659. ** The author disclaims copyright to this source code. In place of
  39660. ** a legal notice, here is a blessing:
  39661. **
  39662. ** May you do good and not evil.
  39663. ** May you find forgiveness for yourself and forgive others.
  39664. ** May you share freely, never taking more than you give.
  39665. **
  39666. *************************************************************************
  39667. **
  39668. ** This module implements an object we call a "RowSet".
  39669. **
  39670. ** The RowSet object is a collection of rowids. Rowids
  39671. ** are inserted into the RowSet in an arbitrary order. Inserts
  39672. ** can be intermixed with tests to see if a given rowid has been
  39673. ** previously inserted into the RowSet.
  39674. **
  39675. ** After all inserts are finished, it is possible to extract the
  39676. ** elements of the RowSet in sorted order. Once this extraction
  39677. ** process has started, no new elements may be inserted.
  39678. **
  39679. ** Hence, the primitive operations for a RowSet are:
  39680. **
  39681. ** CREATE
  39682. ** INSERT
  39683. ** TEST
  39684. ** SMALLEST
  39685. ** DESTROY
  39686. **
  39687. ** The CREATE and DESTROY primitives are the constructor and destructor,
  39688. ** obviously. The INSERT primitive adds a new element to the RowSet.
  39689. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  39690. ** extracts the least value from the RowSet.
  39691. **
  39692. ** The INSERT primitive might allocate additional memory. Memory is
  39693. ** allocated in chunks so most INSERTs do no allocation. There is an
  39694. ** upper bound on the size of allocated memory. No memory is freed
  39695. ** until DESTROY.
  39696. **
  39697. ** The TEST primitive includes a "batch" number. The TEST primitive
  39698. ** will only see elements that were inserted before the last change
  39699. ** in the batch number. In other words, if an INSERT occurs between
  39700. ** two TESTs where the TESTs have the same batch nubmer, then the
  39701. ** value added by the INSERT will not be visible to the second TEST.
  39702. ** The initial batch number is zero, so if the very first TEST contains
  39703. ** a non-zero batch number, it will see all prior INSERTs.
  39704. **
  39705. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  39706. ** that is attempted.
  39707. **
  39708. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  39709. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  39710. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  39711. ** The cost of a TEST using the same batch number is O(logN). The cost
  39712. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  39713. ** primitives are constant time. The cost of DESTROY is O(N).
  39714. **
  39715. ** There is an added cost of O(N) when switching between TEST and
  39716. ** SMALLEST primitives.
  39717. */
  39718. /* #include "sqliteInt.h" */
  39719. /*
  39720. ** Target size for allocation chunks.
  39721. */
  39722. #define ROWSET_ALLOCATION_SIZE 1024
  39723. /*
  39724. ** The number of rowset entries per allocation chunk.
  39725. */
  39726. #define ROWSET_ENTRY_PER_CHUNK \
  39727. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  39728. /*
  39729. ** Each entry in a RowSet is an instance of the following object.
  39730. **
  39731. ** This same object is reused to store a linked list of trees of RowSetEntry
  39732. ** objects. In that alternative use, pRight points to the next entry
  39733. ** in the list, pLeft points to the tree, and v is unused. The
  39734. ** RowSet.pForest value points to the head of this forest list.
  39735. */
  39736. struct RowSetEntry {
  39737. i64 v; /* ROWID value for this entry */
  39738. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  39739. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  39740. };
  39741. /*
  39742. ** RowSetEntry objects are allocated in large chunks (instances of the
  39743. ** following structure) to reduce memory allocation overhead. The
  39744. ** chunks are kept on a linked list so that they can be deallocated
  39745. ** when the RowSet is destroyed.
  39746. */
  39747. struct RowSetChunk {
  39748. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  39749. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  39750. };
  39751. /*
  39752. ** A RowSet in an instance of the following structure.
  39753. **
  39754. ** A typedef of this structure if found in sqliteInt.h.
  39755. */
  39756. struct RowSet {
  39757. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  39758. sqlite3 *db; /* The database connection */
  39759. struct RowSetEntry *pEntry; /* List of entries using pRight */
  39760. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  39761. struct RowSetEntry *pFresh; /* Source of new entry objects */
  39762. struct RowSetEntry *pForest; /* List of binary trees of entries */
  39763. u16 nFresh; /* Number of objects on pFresh */
  39764. u16 rsFlags; /* Various flags */
  39765. int iBatch; /* Current insert batch */
  39766. };
  39767. /*
  39768. ** Allowed values for RowSet.rsFlags
  39769. */
  39770. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  39771. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  39772. /*
  39773. ** Turn bulk memory into a RowSet object. N bytes of memory
  39774. ** are available at pSpace. The db pointer is used as a memory context
  39775. ** for any subsequent allocations that need to occur.
  39776. ** Return a pointer to the new RowSet object.
  39777. **
  39778. ** It must be the case that N is sufficient to make a Rowset. If not
  39779. ** an assertion fault occurs.
  39780. **
  39781. ** If N is larger than the minimum, use the surplus as an initial
  39782. ** allocation of entries available to be filled.
  39783. */
  39784. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  39785. RowSet *p;
  39786. assert( N >= ROUND8(sizeof(*p)) );
  39787. p = pSpace;
  39788. p->pChunk = 0;
  39789. p->db = db;
  39790. p->pEntry = 0;
  39791. p->pLast = 0;
  39792. p->pForest = 0;
  39793. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  39794. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  39795. p->rsFlags = ROWSET_SORTED;
  39796. p->iBatch = 0;
  39797. return p;
  39798. }
  39799. /*
  39800. ** Deallocate all chunks from a RowSet. This frees all memory that
  39801. ** the RowSet has allocated over its lifetime. This routine is
  39802. ** the destructor for the RowSet.
  39803. */
  39804. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  39805. struct RowSetChunk *pChunk, *pNextChunk;
  39806. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  39807. pNextChunk = pChunk->pNextChunk;
  39808. sqlite3DbFree(p->db, pChunk);
  39809. }
  39810. p->pChunk = 0;
  39811. p->nFresh = 0;
  39812. p->pEntry = 0;
  39813. p->pLast = 0;
  39814. p->pForest = 0;
  39815. p->rsFlags = ROWSET_SORTED;
  39816. }
  39817. /*
  39818. ** Allocate a new RowSetEntry object that is associated with the
  39819. ** given RowSet. Return a pointer to the new and completely uninitialized
  39820. ** objected.
  39821. **
  39822. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  39823. ** routine returns NULL.
  39824. */
  39825. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  39826. assert( p!=0 );
  39827. if( p->nFresh==0 ){
  39828. struct RowSetChunk *pNew;
  39829. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  39830. if( pNew==0 ){
  39831. return 0;
  39832. }
  39833. pNew->pNextChunk = p->pChunk;
  39834. p->pChunk = pNew;
  39835. p->pFresh = pNew->aEntry;
  39836. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  39837. }
  39838. p->nFresh--;
  39839. return p->pFresh++;
  39840. }
  39841. /*
  39842. ** Insert a new value into a RowSet.
  39843. **
  39844. ** The mallocFailed flag of the database connection is set if a
  39845. ** memory allocation fails.
  39846. */
  39847. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  39848. struct RowSetEntry *pEntry; /* The new entry */
  39849. struct RowSetEntry *pLast; /* The last prior entry */
  39850. /* This routine is never called after sqlite3RowSetNext() */
  39851. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  39852. pEntry = rowSetEntryAlloc(p);
  39853. if( pEntry==0 ) return;
  39854. pEntry->v = rowid;
  39855. pEntry->pRight = 0;
  39856. pLast = p->pLast;
  39857. if( pLast ){
  39858. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  39859. p->rsFlags &= ~ROWSET_SORTED;
  39860. }
  39861. pLast->pRight = pEntry;
  39862. }else{
  39863. p->pEntry = pEntry;
  39864. }
  39865. p->pLast = pEntry;
  39866. }
  39867. /*
  39868. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  39869. **
  39870. ** The input lists are connected via pRight pointers and are
  39871. ** assumed to each already be in sorted order.
  39872. */
  39873. static struct RowSetEntry *rowSetEntryMerge(
  39874. struct RowSetEntry *pA, /* First sorted list to be merged */
  39875. struct RowSetEntry *pB /* Second sorted list to be merged */
  39876. ){
  39877. struct RowSetEntry head;
  39878. struct RowSetEntry *pTail;
  39879. pTail = &head;
  39880. while( pA && pB ){
  39881. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  39882. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  39883. if( pA->v<pB->v ){
  39884. pTail->pRight = pA;
  39885. pA = pA->pRight;
  39886. pTail = pTail->pRight;
  39887. }else if( pB->v<pA->v ){
  39888. pTail->pRight = pB;
  39889. pB = pB->pRight;
  39890. pTail = pTail->pRight;
  39891. }else{
  39892. pA = pA->pRight;
  39893. }
  39894. }
  39895. if( pA ){
  39896. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  39897. pTail->pRight = pA;
  39898. }else{
  39899. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  39900. pTail->pRight = pB;
  39901. }
  39902. return head.pRight;
  39903. }
  39904. /*
  39905. ** Sort all elements on the list of RowSetEntry objects into order of
  39906. ** increasing v.
  39907. */
  39908. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  39909. unsigned int i;
  39910. struct RowSetEntry *pNext, *aBucket[40];
  39911. memset(aBucket, 0, sizeof(aBucket));
  39912. while( pIn ){
  39913. pNext = pIn->pRight;
  39914. pIn->pRight = 0;
  39915. for(i=0; aBucket[i]; i++){
  39916. pIn = rowSetEntryMerge(aBucket[i], pIn);
  39917. aBucket[i] = 0;
  39918. }
  39919. aBucket[i] = pIn;
  39920. pIn = pNext;
  39921. }
  39922. pIn = 0;
  39923. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  39924. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  39925. }
  39926. return pIn;
  39927. }
  39928. /*
  39929. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  39930. ** Convert this tree into a linked list connected by the pRight pointers
  39931. ** and return pointers to the first and last elements of the new list.
  39932. */
  39933. static void rowSetTreeToList(
  39934. struct RowSetEntry *pIn, /* Root of the input tree */
  39935. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  39936. struct RowSetEntry **ppLast /* Write tail of the output list here */
  39937. ){
  39938. assert( pIn!=0 );
  39939. if( pIn->pLeft ){
  39940. struct RowSetEntry *p;
  39941. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  39942. p->pRight = pIn;
  39943. }else{
  39944. *ppFirst = pIn;
  39945. }
  39946. if( pIn->pRight ){
  39947. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  39948. }else{
  39949. *ppLast = pIn;
  39950. }
  39951. assert( (*ppLast)->pRight==0 );
  39952. }
  39953. /*
  39954. ** Convert a sorted list of elements (connected by pRight) into a binary
  39955. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  39956. ** node taken from the head of *ppList. A depth of 2 means a tree with
  39957. ** three nodes. And so forth.
  39958. **
  39959. ** Use as many entries from the input list as required and update the
  39960. ** *ppList to point to the unused elements of the list. If the input
  39961. ** list contains too few elements, then construct an incomplete tree
  39962. ** and leave *ppList set to NULL.
  39963. **
  39964. ** Return a pointer to the root of the constructed binary tree.
  39965. */
  39966. static struct RowSetEntry *rowSetNDeepTree(
  39967. struct RowSetEntry **ppList,
  39968. int iDepth
  39969. ){
  39970. struct RowSetEntry *p; /* Root of the new tree */
  39971. struct RowSetEntry *pLeft; /* Left subtree */
  39972. if( *ppList==0 ){
  39973. return 0;
  39974. }
  39975. if( iDepth==1 ){
  39976. p = *ppList;
  39977. *ppList = p->pRight;
  39978. p->pLeft = p->pRight = 0;
  39979. return p;
  39980. }
  39981. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  39982. p = *ppList;
  39983. if( p==0 ){
  39984. return pLeft;
  39985. }
  39986. p->pLeft = pLeft;
  39987. *ppList = p->pRight;
  39988. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  39989. return p;
  39990. }
  39991. /*
  39992. ** Convert a sorted list of elements into a binary tree. Make the tree
  39993. ** as deep as it needs to be in order to contain the entire list.
  39994. */
  39995. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  39996. int iDepth; /* Depth of the tree so far */
  39997. struct RowSetEntry *p; /* Current tree root */
  39998. struct RowSetEntry *pLeft; /* Left subtree */
  39999. assert( pList!=0 );
  40000. p = pList;
  40001. pList = p->pRight;
  40002. p->pLeft = p->pRight = 0;
  40003. for(iDepth=1; pList; iDepth++){
  40004. pLeft = p;
  40005. p = pList;
  40006. pList = p->pRight;
  40007. p->pLeft = pLeft;
  40008. p->pRight = rowSetNDeepTree(&pList, iDepth);
  40009. }
  40010. return p;
  40011. }
  40012. /*
  40013. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  40014. ** sort them all together into one big ordered list on p->pEntry.
  40015. **
  40016. ** This routine should only be called once in the life of a RowSet.
  40017. */
  40018. static void rowSetToList(RowSet *p){
  40019. /* This routine is called only once */
  40020. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  40021. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  40022. p->pEntry = rowSetEntrySort(p->pEntry);
  40023. }
  40024. /* While this module could theoretically support it, sqlite3RowSetNext()
  40025. ** is never called after sqlite3RowSetText() for the same RowSet. So
  40026. ** there is never a forest to deal with. Should this change, simply
  40027. ** remove the assert() and the #if 0. */
  40028. assert( p->pForest==0 );
  40029. #if 0
  40030. while( p->pForest ){
  40031. struct RowSetEntry *pTree = p->pForest->pLeft;
  40032. if( pTree ){
  40033. struct RowSetEntry *pHead, *pTail;
  40034. rowSetTreeToList(pTree, &pHead, &pTail);
  40035. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  40036. }
  40037. p->pForest = p->pForest->pRight;
  40038. }
  40039. #endif
  40040. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  40041. }
  40042. /*
  40043. ** Extract the smallest element from the RowSet.
  40044. ** Write the element into *pRowid. Return 1 on success. Return
  40045. ** 0 if the RowSet is already empty.
  40046. **
  40047. ** After this routine has been called, the sqlite3RowSetInsert()
  40048. ** routine may not be called again.
  40049. */
  40050. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  40051. assert( p!=0 );
  40052. /* Merge the forest into a single sorted list on first call */
  40053. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  40054. /* Return the next entry on the list */
  40055. if( p->pEntry ){
  40056. *pRowid = p->pEntry->v;
  40057. p->pEntry = p->pEntry->pRight;
  40058. if( p->pEntry==0 ){
  40059. sqlite3RowSetClear(p);
  40060. }
  40061. return 1;
  40062. }else{
  40063. return 0;
  40064. }
  40065. }
  40066. /*
  40067. ** Check to see if element iRowid was inserted into the rowset as
  40068. ** part of any insert batch prior to iBatch. Return 1 or 0.
  40069. **
  40070. ** If this is the first test of a new batch and if there exist entries
  40071. ** on pRowSet->pEntry, then sort those entries into the forest at
  40072. ** pRowSet->pForest so that they can be tested.
  40073. */
  40074. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  40075. struct RowSetEntry *p, *pTree;
  40076. /* This routine is never called after sqlite3RowSetNext() */
  40077. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  40078. /* Sort entries into the forest on the first test of a new batch
  40079. */
  40080. if( iBatch!=pRowSet->iBatch ){
  40081. p = pRowSet->pEntry;
  40082. if( p ){
  40083. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  40084. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  40085. p = rowSetEntrySort(p);
  40086. }
  40087. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  40088. ppPrevTree = &pTree->pRight;
  40089. if( pTree->pLeft==0 ){
  40090. pTree->pLeft = rowSetListToTree(p);
  40091. break;
  40092. }else{
  40093. struct RowSetEntry *pAux, *pTail;
  40094. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  40095. pTree->pLeft = 0;
  40096. p = rowSetEntryMerge(pAux, p);
  40097. }
  40098. }
  40099. if( pTree==0 ){
  40100. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  40101. if( pTree ){
  40102. pTree->v = 0;
  40103. pTree->pRight = 0;
  40104. pTree->pLeft = rowSetListToTree(p);
  40105. }
  40106. }
  40107. pRowSet->pEntry = 0;
  40108. pRowSet->pLast = 0;
  40109. pRowSet->rsFlags |= ROWSET_SORTED;
  40110. }
  40111. pRowSet->iBatch = iBatch;
  40112. }
  40113. /* Test to see if the iRowid value appears anywhere in the forest.
  40114. ** Return 1 if it does and 0 if not.
  40115. */
  40116. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  40117. p = pTree->pLeft;
  40118. while( p ){
  40119. if( p->v<iRowid ){
  40120. p = p->pRight;
  40121. }else if( p->v>iRowid ){
  40122. p = p->pLeft;
  40123. }else{
  40124. return 1;
  40125. }
  40126. }
  40127. }
  40128. return 0;
  40129. }
  40130. /************** End of rowset.c **********************************************/
  40131. /************** Begin file pager.c *******************************************/
  40132. /*
  40133. ** 2001 September 15
  40134. **
  40135. ** The author disclaims copyright to this source code. In place of
  40136. ** a legal notice, here is a blessing:
  40137. **
  40138. ** May you do good and not evil.
  40139. ** May you find forgiveness for yourself and forgive others.
  40140. ** May you share freely, never taking more than you give.
  40141. **
  40142. *************************************************************************
  40143. ** This is the implementation of the page cache subsystem or "pager".
  40144. **
  40145. ** The pager is used to access a database disk file. It implements
  40146. ** atomic commit and rollback through the use of a journal file that
  40147. ** is separate from the database file. The pager also implements file
  40148. ** locking to prevent two processes from writing the same database
  40149. ** file simultaneously, or one process from reading the database while
  40150. ** another is writing.
  40151. */
  40152. #ifndef SQLITE_OMIT_DISKIO
  40153. /* #include "sqliteInt.h" */
  40154. /************** Include wal.h in the middle of pager.c ***********************/
  40155. /************** Begin file wal.h *********************************************/
  40156. /*
  40157. ** 2010 February 1
  40158. **
  40159. ** The author disclaims copyright to this source code. In place of
  40160. ** a legal notice, here is a blessing:
  40161. **
  40162. ** May you do good and not evil.
  40163. ** May you find forgiveness for yourself and forgive others.
  40164. ** May you share freely, never taking more than you give.
  40165. **
  40166. *************************************************************************
  40167. ** This header file defines the interface to the write-ahead logging
  40168. ** system. Refer to the comments below and the header comment attached to
  40169. ** the implementation of each function in log.c for further details.
  40170. */
  40171. #ifndef _WAL_H_
  40172. #define _WAL_H_
  40173. /* #include "sqliteInt.h" */
  40174. /* Additional values that can be added to the sync_flags argument of
  40175. ** sqlite3WalFrames():
  40176. */
  40177. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  40178. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  40179. #ifdef SQLITE_OMIT_WAL
  40180. # define sqlite3WalOpen(x,y,z) 0
  40181. # define sqlite3WalLimit(x,y)
  40182. # define sqlite3WalClose(w,x,y,z) 0
  40183. # define sqlite3WalBeginReadTransaction(y,z) 0
  40184. # define sqlite3WalEndReadTransaction(z)
  40185. # define sqlite3WalDbsize(y) 0
  40186. # define sqlite3WalBeginWriteTransaction(y) 0
  40187. # define sqlite3WalEndWriteTransaction(x) 0
  40188. # define sqlite3WalUndo(x,y,z) 0
  40189. # define sqlite3WalSavepoint(y,z)
  40190. # define sqlite3WalSavepointUndo(y,z) 0
  40191. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  40192. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  40193. # define sqlite3WalCallback(z) 0
  40194. # define sqlite3WalExclusiveMode(y,z) 0
  40195. # define sqlite3WalHeapMemory(z) 0
  40196. # define sqlite3WalFramesize(z) 0
  40197. # define sqlite3WalFindFrame(x,y,z) 0
  40198. #else
  40199. #define WAL_SAVEPOINT_NDATA 4
  40200. /* Connection to a write-ahead log (WAL) file.
  40201. ** There is one object of this type for each pager.
  40202. */
  40203. typedef struct Wal Wal;
  40204. /* Open and close a connection to a write-ahead log. */
  40205. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  40206. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  40207. /* Set the limiting size of a WAL file. */
  40208. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  40209. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  40210. ** snapshot is like a read-transaction. It is the state of the database
  40211. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  40212. ** preserves the current state even if the other threads or processes
  40213. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  40214. ** transaction and releases the lock.
  40215. */
  40216. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  40217. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  40218. /* Read a page from the write-ahead log, if it is present. */
  40219. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  40220. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  40221. /* If the WAL is not empty, return the size of the database. */
  40222. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  40223. /* Obtain or release the WRITER lock. */
  40224. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  40225. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  40226. /* Undo any frames written (but not committed) to the log */
  40227. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  40228. /* Return an integer that records the current (uncommitted) write
  40229. ** position in the WAL */
  40230. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  40231. /* Move the write position of the WAL back to iFrame. Called in
  40232. ** response to a ROLLBACK TO command. */
  40233. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  40234. /* Write a frame or frames to the log. */
  40235. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  40236. /* Copy pages from the log to the database file */
  40237. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  40238. Wal *pWal, /* Write-ahead log connection */
  40239. int eMode, /* One of PASSIVE, FULL and RESTART */
  40240. int (*xBusy)(void*), /* Function to call when busy */
  40241. void *pBusyArg, /* Context argument for xBusyHandler */
  40242. int sync_flags, /* Flags to sync db file with (or 0) */
  40243. int nBuf, /* Size of buffer nBuf */
  40244. u8 *zBuf, /* Temporary buffer to use */
  40245. int *pnLog, /* OUT: Number of frames in WAL */
  40246. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  40247. );
  40248. /* Return the value to pass to a sqlite3_wal_hook callback, the
  40249. ** number of frames in the WAL at the point of the last commit since
  40250. ** sqlite3WalCallback() was called. If no commits have occurred since
  40251. ** the last call, then return 0.
  40252. */
  40253. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  40254. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  40255. ** by the pager layer on the database file.
  40256. */
  40257. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  40258. /* Return true if the argument is non-NULL and the WAL module is using
  40259. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  40260. ** WAL module is using shared-memory, return false.
  40261. */
  40262. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  40263. #ifdef SQLITE_ENABLE_ZIPVFS
  40264. /* If the WAL file is not empty, return the number of bytes of content
  40265. ** stored in each frame (i.e. the db page-size when the WAL was created).
  40266. */
  40267. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  40268. #endif
  40269. #endif /* ifndef SQLITE_OMIT_WAL */
  40270. #endif /* _WAL_H_ */
  40271. /************** End of wal.h *************************************************/
  40272. /************** Continuing where we left off in pager.c **********************/
  40273. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  40274. **
  40275. ** This comment block describes invariants that hold when using a rollback
  40276. ** journal. These invariants do not apply for journal_mode=WAL,
  40277. ** journal_mode=MEMORY, or journal_mode=OFF.
  40278. **
  40279. ** Within this comment block, a page is deemed to have been synced
  40280. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  40281. ** Otherwise, the page is not synced until the xSync method of the VFS
  40282. ** is called successfully on the file containing the page.
  40283. **
  40284. ** Definition: A page of the database file is said to be "overwriteable" if
  40285. ** one or more of the following are true about the page:
  40286. **
  40287. ** (a) The original content of the page as it was at the beginning of
  40288. ** the transaction has been written into the rollback journal and
  40289. ** synced.
  40290. **
  40291. ** (b) The page was a freelist leaf page at the start of the transaction.
  40292. **
  40293. ** (c) The page number is greater than the largest page that existed in
  40294. ** the database file at the start of the transaction.
  40295. **
  40296. ** (1) A page of the database file is never overwritten unless one of the
  40297. ** following are true:
  40298. **
  40299. ** (a) The page and all other pages on the same sector are overwriteable.
  40300. **
  40301. ** (b) The atomic page write optimization is enabled, and the entire
  40302. ** transaction other than the update of the transaction sequence
  40303. ** number consists of a single page change.
  40304. **
  40305. ** (2) The content of a page written into the rollback journal exactly matches
  40306. ** both the content in the database when the rollback journal was written
  40307. ** and the content in the database at the beginning of the current
  40308. ** transaction.
  40309. **
  40310. ** (3) Writes to the database file are an integer multiple of the page size
  40311. ** in length and are aligned on a page boundary.
  40312. **
  40313. ** (4) Reads from the database file are either aligned on a page boundary and
  40314. ** an integer multiple of the page size in length or are taken from the
  40315. ** first 100 bytes of the database file.
  40316. **
  40317. ** (5) All writes to the database file are synced prior to the rollback journal
  40318. ** being deleted, truncated, or zeroed.
  40319. **
  40320. ** (6) If a master journal file is used, then all writes to the database file
  40321. ** are synced prior to the master journal being deleted.
  40322. **
  40323. ** Definition: Two databases (or the same database at two points it time)
  40324. ** are said to be "logically equivalent" if they give the same answer to
  40325. ** all queries. Note in particular the content of freelist leaf
  40326. ** pages can be changed arbitrarily without affecting the logical equivalence
  40327. ** of the database.
  40328. **
  40329. ** (7) At any time, if any subset, including the empty set and the total set,
  40330. ** of the unsynced changes to a rollback journal are removed and the
  40331. ** journal is rolled back, the resulting database file will be logically
  40332. ** equivalent to the database file at the beginning of the transaction.
  40333. **
  40334. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  40335. ** is called to restore the database file to the same size it was at
  40336. ** the beginning of the transaction. (In some VFSes, the xTruncate
  40337. ** method is a no-op, but that does not change the fact the SQLite will
  40338. ** invoke it.)
  40339. **
  40340. ** (9) Whenever the database file is modified, at least one bit in the range
  40341. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  40342. ** the EXCLUSIVE lock, thus signaling other connections on the same
  40343. ** database to flush their caches.
  40344. **
  40345. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  40346. ** than one billion transactions.
  40347. **
  40348. ** (11) A database file is well-formed at the beginning and at the conclusion
  40349. ** of every transaction.
  40350. **
  40351. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  40352. ** the database file.
  40353. **
  40354. ** (13) A SHARED lock is held on the database file while reading any
  40355. ** content out of the database file.
  40356. **
  40357. ******************************************************************************/
  40358. /*
  40359. ** Macros for troubleshooting. Normally turned off
  40360. */
  40361. #if 0
  40362. int sqlite3PagerTrace=1; /* True to enable tracing */
  40363. #define sqlite3DebugPrintf printf
  40364. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  40365. #else
  40366. #define PAGERTRACE(X)
  40367. #endif
  40368. /*
  40369. ** The following two macros are used within the PAGERTRACE() macros above
  40370. ** to print out file-descriptors.
  40371. **
  40372. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  40373. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  40374. ** struct as its argument.
  40375. */
  40376. #define PAGERID(p) ((int)(p->fd))
  40377. #define FILEHANDLEID(fd) ((int)fd)
  40378. /*
  40379. ** The Pager.eState variable stores the current 'state' of a pager. A
  40380. ** pager may be in any one of the seven states shown in the following
  40381. ** state diagram.
  40382. **
  40383. ** OPEN <------+------+
  40384. ** | | |
  40385. ** V | |
  40386. ** +---------> READER-------+ |
  40387. ** | | |
  40388. ** | V |
  40389. ** |<-------WRITER_LOCKED------> ERROR
  40390. ** | | ^
  40391. ** | V |
  40392. ** |<------WRITER_CACHEMOD-------->|
  40393. ** | | |
  40394. ** | V |
  40395. ** |<-------WRITER_DBMOD---------->|
  40396. ** | | |
  40397. ** | V |
  40398. ** +<------WRITER_FINISHED-------->+
  40399. **
  40400. **
  40401. ** List of state transitions and the C [function] that performs each:
  40402. **
  40403. ** OPEN -> READER [sqlite3PagerSharedLock]
  40404. ** READER -> OPEN [pager_unlock]
  40405. **
  40406. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  40407. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  40408. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  40409. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  40410. ** WRITER_*** -> READER [pager_end_transaction]
  40411. **
  40412. ** WRITER_*** -> ERROR [pager_error]
  40413. ** ERROR -> OPEN [pager_unlock]
  40414. **
  40415. **
  40416. ** OPEN:
  40417. **
  40418. ** The pager starts up in this state. Nothing is guaranteed in this
  40419. ** state - the file may or may not be locked and the database size is
  40420. ** unknown. The database may not be read or written.
  40421. **
  40422. ** * No read or write transaction is active.
  40423. ** * Any lock, or no lock at all, may be held on the database file.
  40424. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  40425. **
  40426. ** READER:
  40427. **
  40428. ** In this state all the requirements for reading the database in
  40429. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  40430. ** was) in exclusive-locking mode, a user-level read transaction is
  40431. ** open. The database size is known in this state.
  40432. **
  40433. ** A connection running with locking_mode=normal enters this state when
  40434. ** it opens a read-transaction on the database and returns to state
  40435. ** OPEN after the read-transaction is completed. However a connection
  40436. ** running in locking_mode=exclusive (including temp databases) remains in
  40437. ** this state even after the read-transaction is closed. The only way
  40438. ** a locking_mode=exclusive connection can transition from READER to OPEN
  40439. ** is via the ERROR state (see below).
  40440. **
  40441. ** * A read transaction may be active (but a write-transaction cannot).
  40442. ** * A SHARED or greater lock is held on the database file.
  40443. ** * The dbSize variable may be trusted (even if a user-level read
  40444. ** transaction is not active). The dbOrigSize and dbFileSize variables
  40445. ** may not be trusted at this point.
  40446. ** * If the database is a WAL database, then the WAL connection is open.
  40447. ** * Even if a read-transaction is not open, it is guaranteed that
  40448. ** there is no hot-journal in the file-system.
  40449. **
  40450. ** WRITER_LOCKED:
  40451. **
  40452. ** The pager moves to this state from READER when a write-transaction
  40453. ** is first opened on the database. In WRITER_LOCKED state, all locks
  40454. ** required to start a write-transaction are held, but no actual
  40455. ** modifications to the cache or database have taken place.
  40456. **
  40457. ** In rollback mode, a RESERVED or (if the transaction was opened with
  40458. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  40459. ** moving to this state, but the journal file is not written to or opened
  40460. ** to in this state. If the transaction is committed or rolled back while
  40461. ** in WRITER_LOCKED state, all that is required is to unlock the database
  40462. ** file.
  40463. **
  40464. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  40465. ** If the connection is running with locking_mode=exclusive, an attempt
  40466. ** is made to obtain an EXCLUSIVE lock on the database file.
  40467. **
  40468. ** * A write transaction is active.
  40469. ** * If the connection is open in rollback-mode, a RESERVED or greater
  40470. ** lock is held on the database file.
  40471. ** * If the connection is open in WAL-mode, a WAL write transaction
  40472. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  40473. ** called).
  40474. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  40475. ** * The contents of the pager cache have not been modified.
  40476. ** * The journal file may or may not be open.
  40477. ** * Nothing (not even the first header) has been written to the journal.
  40478. **
  40479. ** WRITER_CACHEMOD:
  40480. **
  40481. ** A pager moves from WRITER_LOCKED state to this state when a page is
  40482. ** first modified by the upper layer. In rollback mode the journal file
  40483. ** is opened (if it is not already open) and a header written to the
  40484. ** start of it. The database file on disk has not been modified.
  40485. **
  40486. ** * A write transaction is active.
  40487. ** * A RESERVED or greater lock is held on the database file.
  40488. ** * The journal file is open and the first header has been written
  40489. ** to it, but the header has not been synced to disk.
  40490. ** * The contents of the page cache have been modified.
  40491. **
  40492. ** WRITER_DBMOD:
  40493. **
  40494. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  40495. ** when it modifies the contents of the database file. WAL connections
  40496. ** never enter this state (since they do not modify the database file,
  40497. ** just the log file).
  40498. **
  40499. ** * A write transaction is active.
  40500. ** * An EXCLUSIVE or greater lock is held on the database file.
  40501. ** * The journal file is open and the first header has been written
  40502. ** and synced to disk.
  40503. ** * The contents of the page cache have been modified (and possibly
  40504. ** written to disk).
  40505. **
  40506. ** WRITER_FINISHED:
  40507. **
  40508. ** It is not possible for a WAL connection to enter this state.
  40509. **
  40510. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  40511. ** state after the entire transaction has been successfully written into the
  40512. ** database file. In this state the transaction may be committed simply
  40513. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  40514. ** not possible to modify the database further. At this point, the upper
  40515. ** layer must either commit or rollback the transaction.
  40516. **
  40517. ** * A write transaction is active.
  40518. ** * An EXCLUSIVE or greater lock is held on the database file.
  40519. ** * All writing and syncing of journal and database data has finished.
  40520. ** If no error occurred, all that remains is to finalize the journal to
  40521. ** commit the transaction. If an error did occur, the caller will need
  40522. ** to rollback the transaction.
  40523. **
  40524. ** ERROR:
  40525. **
  40526. ** The ERROR state is entered when an IO or disk-full error (including
  40527. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  40528. ** difficult to be sure that the in-memory pager state (cache contents,
  40529. ** db size etc.) are consistent with the contents of the file-system.
  40530. **
  40531. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  40532. ** cannot.
  40533. **
  40534. ** For example, if an IO error occurs while performing a rollback,
  40535. ** the contents of the page-cache may be left in an inconsistent state.
  40536. ** At this point it would be dangerous to change back to READER state
  40537. ** (as usually happens after a rollback). Any subsequent readers might
  40538. ** report database corruption (due to the inconsistent cache), and if
  40539. ** they upgrade to writers, they may inadvertently corrupt the database
  40540. ** file. To avoid this hazard, the pager switches into the ERROR state
  40541. ** instead of READER following such an error.
  40542. **
  40543. ** Once it has entered the ERROR state, any attempt to use the pager
  40544. ** to read or write data returns an error. Eventually, once all
  40545. ** outstanding transactions have been abandoned, the pager is able to
  40546. ** transition back to OPEN state, discarding the contents of the
  40547. ** page-cache and any other in-memory state at the same time. Everything
  40548. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  40549. ** when a read-transaction is next opened on the pager (transitioning
  40550. ** the pager into READER state). At that point the system has recovered
  40551. ** from the error.
  40552. **
  40553. ** Specifically, the pager jumps into the ERROR state if:
  40554. **
  40555. ** 1. An error occurs while attempting a rollback. This happens in
  40556. ** function sqlite3PagerRollback().
  40557. **
  40558. ** 2. An error occurs while attempting to finalize a journal file
  40559. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  40560. **
  40561. ** 3. An error occurs while attempting to write to the journal or
  40562. ** database file in function pagerStress() in order to free up
  40563. ** memory.
  40564. **
  40565. ** In other cases, the error is returned to the b-tree layer. The b-tree
  40566. ** layer then attempts a rollback operation. If the error condition
  40567. ** persists, the pager enters the ERROR state via condition (1) above.
  40568. **
  40569. ** Condition (3) is necessary because it can be triggered by a read-only
  40570. ** statement executed within a transaction. In this case, if the error
  40571. ** code were simply returned to the user, the b-tree layer would not
  40572. ** automatically attempt a rollback, as it assumes that an error in a
  40573. ** read-only statement cannot leave the pager in an internally inconsistent
  40574. ** state.
  40575. **
  40576. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  40577. ** * There are one or more outstanding references to pages (after the
  40578. ** last reference is dropped the pager should move back to OPEN state).
  40579. ** * The pager is not an in-memory pager.
  40580. **
  40581. **
  40582. ** Notes:
  40583. **
  40584. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  40585. ** connection is open in WAL mode. A WAL connection is always in one
  40586. ** of the first four states.
  40587. **
  40588. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  40589. ** state. There are two exceptions: immediately after exclusive-mode has
  40590. ** been turned on (and before any read or write transactions are
  40591. ** executed), and when the pager is leaving the "error state".
  40592. **
  40593. ** * See also: assert_pager_state().
  40594. */
  40595. #define PAGER_OPEN 0
  40596. #define PAGER_READER 1
  40597. #define PAGER_WRITER_LOCKED 2
  40598. #define PAGER_WRITER_CACHEMOD 3
  40599. #define PAGER_WRITER_DBMOD 4
  40600. #define PAGER_WRITER_FINISHED 5
  40601. #define PAGER_ERROR 6
  40602. /*
  40603. ** The Pager.eLock variable is almost always set to one of the
  40604. ** following locking-states, according to the lock currently held on
  40605. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  40606. ** This variable is kept up to date as locks are taken and released by
  40607. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  40608. **
  40609. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  40610. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  40611. ** the operation was successful. In these circumstances pagerLockDb() and
  40612. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  40613. ** when unlocking the file, and only updated when locking the file if the
  40614. ** VFS call is successful. This way, the Pager.eLock variable may be set
  40615. ** to a less exclusive (lower) value than the lock that is actually held
  40616. ** at the system level, but it is never set to a more exclusive value.
  40617. **
  40618. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  40619. ** be a few redundant xLock() calls or a lock may be held for longer than
  40620. ** required, but nothing really goes wrong.
  40621. **
  40622. ** The exception is when the database file is unlocked as the pager moves
  40623. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  40624. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  40625. ** transition, by the same pager or any other). If the call to xUnlock()
  40626. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  40627. ** can confuse the call to xCheckReservedLock() call made later as part
  40628. ** of hot-journal detection.
  40629. **
  40630. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  40631. ** lock held by this process or any others". So xCheckReservedLock may
  40632. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  40633. ** doesn't know it because of a previous error in xUnlock). If this happens
  40634. ** a hot-journal may be mistaken for a journal being created by an active
  40635. ** transaction in another process, causing SQLite to read from the database
  40636. ** without rolling it back.
  40637. **
  40638. ** To work around this, if a call to xUnlock() fails when unlocking the
  40639. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  40640. ** is only changed back to a real locking state after a successful call
  40641. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  40642. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  40643. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  40644. ** lock on the database file before attempting to roll it back. See function
  40645. ** PagerSharedLock() for more detail.
  40646. **
  40647. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  40648. ** PAGER_OPEN state.
  40649. */
  40650. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  40651. /*
  40652. ** A macro used for invoking the codec if there is one
  40653. */
  40654. #ifdef SQLITE_HAS_CODEC
  40655. # define CODEC1(P,D,N,X,E) \
  40656. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  40657. # define CODEC2(P,D,N,X,E,O) \
  40658. if( P->xCodec==0 ){ O=(char*)D; }else \
  40659. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  40660. #else
  40661. # define CODEC1(P,D,N,X,E) /* NO-OP */
  40662. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  40663. #endif
  40664. /*
  40665. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  40666. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  40667. ** This could conceivably cause corruption following a power failure on
  40668. ** such a system. This is currently an undocumented limit.
  40669. */
  40670. #define MAX_SECTOR_SIZE 0x10000
  40671. /*
  40672. ** An instance of the following structure is allocated for each active
  40673. ** savepoint and statement transaction in the system. All such structures
  40674. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  40675. ** resized using sqlite3Realloc().
  40676. **
  40677. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  40678. ** set to 0. If a journal-header is written into the main journal while
  40679. ** the savepoint is active, then iHdrOffset is set to the byte offset
  40680. ** immediately following the last journal record written into the main
  40681. ** journal before the journal-header. This is required during savepoint
  40682. ** rollback (see pagerPlaybackSavepoint()).
  40683. */
  40684. typedef struct PagerSavepoint PagerSavepoint;
  40685. struct PagerSavepoint {
  40686. i64 iOffset; /* Starting offset in main journal */
  40687. i64 iHdrOffset; /* See above */
  40688. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  40689. Pgno nOrig; /* Original number of pages in file */
  40690. Pgno iSubRec; /* Index of first record in sub-journal */
  40691. #ifndef SQLITE_OMIT_WAL
  40692. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  40693. #endif
  40694. };
  40695. /*
  40696. ** Bits of the Pager.doNotSpill flag. See further description below.
  40697. */
  40698. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  40699. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  40700. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  40701. /*
  40702. ** An open page cache is an instance of struct Pager. A description of
  40703. ** some of the more important member variables follows:
  40704. **
  40705. ** eState
  40706. **
  40707. ** The current 'state' of the pager object. See the comment and state
  40708. ** diagram above for a description of the pager state.
  40709. **
  40710. ** eLock
  40711. **
  40712. ** For a real on-disk database, the current lock held on the database file -
  40713. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  40714. **
  40715. ** For a temporary or in-memory database (neither of which require any
  40716. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  40717. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  40718. ** logic into thinking that it already has all the locks it will ever
  40719. ** need (and no reason to release them).
  40720. **
  40721. ** In some (obscure) circumstances, this variable may also be set to
  40722. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  40723. ** details.
  40724. **
  40725. ** changeCountDone
  40726. **
  40727. ** This boolean variable is used to make sure that the change-counter
  40728. ** (the 4-byte header field at byte offset 24 of the database file) is
  40729. ** not updated more often than necessary.
  40730. **
  40731. ** It is set to true when the change-counter field is updated, which
  40732. ** can only happen if an exclusive lock is held on the database file.
  40733. ** It is cleared (set to false) whenever an exclusive lock is
  40734. ** relinquished on the database file. Each time a transaction is committed,
  40735. ** The changeCountDone flag is inspected. If it is true, the work of
  40736. ** updating the change-counter is omitted for the current transaction.
  40737. **
  40738. ** This mechanism means that when running in exclusive mode, a connection
  40739. ** need only update the change-counter once, for the first transaction
  40740. ** committed.
  40741. **
  40742. ** setMaster
  40743. **
  40744. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  40745. ** (or may not) specify a master-journal name to be written into the
  40746. ** journal file before it is synced to disk.
  40747. **
  40748. ** Whether or not a journal file contains a master-journal pointer affects
  40749. ** the way in which the journal file is finalized after the transaction is
  40750. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  40751. ** If a journal file does not contain a master-journal pointer, it is
  40752. ** finalized by overwriting the first journal header with zeroes. If
  40753. ** it does contain a master-journal pointer the journal file is finalized
  40754. ** by truncating it to zero bytes, just as if the connection were
  40755. ** running in "journal_mode=truncate" mode.
  40756. **
  40757. ** Journal files that contain master journal pointers cannot be finalized
  40758. ** simply by overwriting the first journal-header with zeroes, as the
  40759. ** master journal pointer could interfere with hot-journal rollback of any
  40760. ** subsequently interrupted transaction that reuses the journal file.
  40761. **
  40762. ** The flag is cleared as soon as the journal file is finalized (either
  40763. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  40764. ** journal file from being successfully finalized, the setMaster flag
  40765. ** is cleared anyway (and the pager will move to ERROR state).
  40766. **
  40767. ** doNotSpill
  40768. **
  40769. ** This variables control the behavior of cache-spills (calls made by
  40770. ** the pcache module to the pagerStress() routine to write cached data
  40771. ** to the file-system in order to free up memory).
  40772. **
  40773. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  40774. ** writing to the database from pagerStress() is disabled altogether.
  40775. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  40776. ** comes up during savepoint rollback that requires the pcache module
  40777. ** to allocate a new page to prevent the journal file from being written
  40778. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  40779. ** case is a user preference.
  40780. **
  40781. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  40782. ** pagerStress() is permitted, but syncing the journal file is not.
  40783. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  40784. ** is larger than the database page-size in order to prevent a journal sync
  40785. ** from happening in between the journalling of two pages on the same sector.
  40786. **
  40787. ** subjInMemory
  40788. **
  40789. ** This is a boolean variable. If true, then any required sub-journal
  40790. ** is opened as an in-memory journal file. If false, then in-memory
  40791. ** sub-journals are only used for in-memory pager files.
  40792. **
  40793. ** This variable is updated by the upper layer each time a new
  40794. ** write-transaction is opened.
  40795. **
  40796. ** dbSize, dbOrigSize, dbFileSize
  40797. **
  40798. ** Variable dbSize is set to the number of pages in the database file.
  40799. ** It is valid in PAGER_READER and higher states (all states except for
  40800. ** OPEN and ERROR).
  40801. **
  40802. ** dbSize is set based on the size of the database file, which may be
  40803. ** larger than the size of the database (the value stored at offset
  40804. ** 28 of the database header by the btree). If the size of the file
  40805. ** is not an integer multiple of the page-size, the value stored in
  40806. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  40807. ** Except, any file that is greater than 0 bytes in size is considered
  40808. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  40809. ** to dbSize==1).
  40810. **
  40811. ** During a write-transaction, if pages with page-numbers greater than
  40812. ** dbSize are modified in the cache, dbSize is updated accordingly.
  40813. ** Similarly, if the database is truncated using PagerTruncateImage(),
  40814. ** dbSize is updated.
  40815. **
  40816. ** Variables dbOrigSize and dbFileSize are valid in states
  40817. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  40818. ** variable at the start of the transaction. It is used during rollback,
  40819. ** and to determine whether or not pages need to be journalled before
  40820. ** being modified.
  40821. **
  40822. ** Throughout a write-transaction, dbFileSize contains the size of
  40823. ** the file on disk in pages. It is set to a copy of dbSize when the
  40824. ** write-transaction is first opened, and updated when VFS calls are made
  40825. ** to write or truncate the database file on disk.
  40826. **
  40827. ** The only reason the dbFileSize variable is required is to suppress
  40828. ** unnecessary calls to xTruncate() after committing a transaction. If,
  40829. ** when a transaction is committed, the dbFileSize variable indicates
  40830. ** that the database file is larger than the database image (Pager.dbSize),
  40831. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  40832. ** to measure the database file on disk, and then truncates it if required.
  40833. ** dbFileSize is not used when rolling back a transaction. In this case
  40834. ** pager_truncate() is called unconditionally (which means there may be
  40835. ** a call to xFilesize() that is not strictly required). In either case,
  40836. ** pager_truncate() may cause the file to become smaller or larger.
  40837. **
  40838. ** dbHintSize
  40839. **
  40840. ** The dbHintSize variable is used to limit the number of calls made to
  40841. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  40842. **
  40843. ** dbHintSize is set to a copy of the dbSize variable when a
  40844. ** write-transaction is opened (at the same time as dbFileSize and
  40845. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  40846. ** dbHintSize is increased to the number of pages that correspond to the
  40847. ** size-hint passed to the method call. See pager_write_pagelist() for
  40848. ** details.
  40849. **
  40850. ** errCode
  40851. **
  40852. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  40853. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  40854. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  40855. ** sub-codes.
  40856. */
  40857. struct Pager {
  40858. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  40859. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  40860. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  40861. u8 useJournal; /* Use a rollback journal on this file */
  40862. u8 noSync; /* Do not sync the journal if true */
  40863. u8 fullSync; /* Do extra syncs of the journal for robustness */
  40864. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  40865. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  40866. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  40867. u8 tempFile; /* zFilename is a temporary or immutable file */
  40868. u8 noLock; /* Do not lock (except in WAL mode) */
  40869. u8 readOnly; /* True for a read-only database */
  40870. u8 memDb; /* True to inhibit all file I/O */
  40871. /**************************************************************************
  40872. ** The following block contains those class members that change during
  40873. ** routine operation. Class members not in this block are either fixed
  40874. ** when the pager is first created or else only change when there is a
  40875. ** significant mode change (such as changing the page_size, locking_mode,
  40876. ** or the journal_mode). From another view, these class members describe
  40877. ** the "state" of the pager, while other class members describe the
  40878. ** "configuration" of the pager.
  40879. */
  40880. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  40881. u8 eLock; /* Current lock held on database file */
  40882. u8 changeCountDone; /* Set after incrementing the change-counter */
  40883. u8 setMaster; /* True if a m-j name has been written to jrnl */
  40884. u8 doNotSpill; /* Do not spill the cache when non-zero */
  40885. u8 subjInMemory; /* True to use in-memory sub-journals */
  40886. u8 bUseFetch; /* True to use xFetch() */
  40887. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  40888. Pgno dbSize; /* Number of pages in the database */
  40889. Pgno dbOrigSize; /* dbSize before the current transaction */
  40890. Pgno dbFileSize; /* Number of pages in the database file */
  40891. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  40892. int errCode; /* One of several kinds of errors */
  40893. int nRec; /* Pages journalled since last j-header written */
  40894. u32 cksumInit; /* Quasi-random value added to every checksum */
  40895. u32 nSubRec; /* Number of records written to sub-journal */
  40896. Bitvec *pInJournal; /* One bit for each page in the database file */
  40897. sqlite3_file *fd; /* File descriptor for database */
  40898. sqlite3_file *jfd; /* File descriptor for main journal */
  40899. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  40900. i64 journalOff; /* Current write offset in the journal file */
  40901. i64 journalHdr; /* Byte offset to previous journal header */
  40902. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  40903. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  40904. int nSavepoint; /* Number of elements in aSavepoint[] */
  40905. u32 iDataVersion; /* Changes whenever database content changes */
  40906. char dbFileVers[16]; /* Changes whenever database file changes */
  40907. int nMmapOut; /* Number of mmap pages currently outstanding */
  40908. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  40909. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  40910. /*
  40911. ** End of the routinely-changing class members
  40912. ***************************************************************************/
  40913. u16 nExtra; /* Add this many bytes to each in-memory page */
  40914. i16 nReserve; /* Number of unused bytes at end of each page */
  40915. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  40916. u32 sectorSize; /* Assumed sector size during rollback */
  40917. int pageSize; /* Number of bytes in a page */
  40918. Pgno mxPgno; /* Maximum allowed size of the database */
  40919. i64 journalSizeLimit; /* Size limit for persistent journal files */
  40920. char *zFilename; /* Name of the database file */
  40921. char *zJournal; /* Name of the journal file */
  40922. int (*xBusyHandler)(void*); /* Function to call when busy */
  40923. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  40924. int aStat[3]; /* Total cache hits, misses and writes */
  40925. #ifdef SQLITE_TEST
  40926. int nRead; /* Database pages read */
  40927. #endif
  40928. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  40929. #ifdef SQLITE_HAS_CODEC
  40930. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  40931. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  40932. void (*xCodecFree)(void*); /* Destructor for the codec */
  40933. void *pCodec; /* First argument to xCodec... methods */
  40934. #endif
  40935. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  40936. PCache *pPCache; /* Pointer to page cache object */
  40937. #ifndef SQLITE_OMIT_WAL
  40938. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  40939. char *zWal; /* File name for write-ahead log */
  40940. #endif
  40941. };
  40942. /*
  40943. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  40944. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  40945. ** or CACHE_WRITE to sqlite3_db_status().
  40946. */
  40947. #define PAGER_STAT_HIT 0
  40948. #define PAGER_STAT_MISS 1
  40949. #define PAGER_STAT_WRITE 2
  40950. /*
  40951. ** The following global variables hold counters used for
  40952. ** testing purposes only. These variables do not exist in
  40953. ** a non-testing build. These variables are not thread-safe.
  40954. */
  40955. #ifdef SQLITE_TEST
  40956. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  40957. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  40958. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  40959. # define PAGER_INCR(v) v++
  40960. #else
  40961. # define PAGER_INCR(v)
  40962. #endif
  40963. /*
  40964. ** Journal files begin with the following magic string. The data
  40965. ** was obtained from /dev/random. It is used only as a sanity check.
  40966. **
  40967. ** Since version 2.8.0, the journal format contains additional sanity
  40968. ** checking information. If the power fails while the journal is being
  40969. ** written, semi-random garbage data might appear in the journal
  40970. ** file after power is restored. If an attempt is then made
  40971. ** to roll the journal back, the database could be corrupted. The additional
  40972. ** sanity checking data is an attempt to discover the garbage in the
  40973. ** journal and ignore it.
  40974. **
  40975. ** The sanity checking information for the new journal format consists
  40976. ** of a 32-bit checksum on each page of data. The checksum covers both
  40977. ** the page number and the pPager->pageSize bytes of data for the page.
  40978. ** This cksum is initialized to a 32-bit random value that appears in the
  40979. ** journal file right after the header. The random initializer is important,
  40980. ** because garbage data that appears at the end of a journal is likely
  40981. ** data that was once in other files that have now been deleted. If the
  40982. ** garbage data came from an obsolete journal file, the checksums might
  40983. ** be correct. But by initializing the checksum to random value which
  40984. ** is different for every journal, we minimize that risk.
  40985. */
  40986. static const unsigned char aJournalMagic[] = {
  40987. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  40988. };
  40989. /*
  40990. ** The size of the of each page record in the journal is given by
  40991. ** the following macro.
  40992. */
  40993. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  40994. /*
  40995. ** The journal header size for this pager. This is usually the same
  40996. ** size as a single disk sector. See also setSectorSize().
  40997. */
  40998. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  40999. /*
  41000. ** The macro MEMDB is true if we are dealing with an in-memory database.
  41001. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  41002. ** the value of MEMDB will be a constant and the compiler will optimize
  41003. ** out code that would never execute.
  41004. */
  41005. #ifdef SQLITE_OMIT_MEMORYDB
  41006. # define MEMDB 0
  41007. #else
  41008. # define MEMDB pPager->memDb
  41009. #endif
  41010. /*
  41011. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  41012. ** interfaces to access the database using memory-mapped I/O.
  41013. */
  41014. #if SQLITE_MAX_MMAP_SIZE>0
  41015. # define USEFETCH(x) ((x)->bUseFetch)
  41016. #else
  41017. # define USEFETCH(x) 0
  41018. #endif
  41019. /*
  41020. ** The maximum legal page number is (2^31 - 1).
  41021. */
  41022. #define PAGER_MAX_PGNO 2147483647
  41023. /*
  41024. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  41025. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  41026. **
  41027. ** This is so that expressions can be written as:
  41028. **
  41029. ** if( isOpen(pPager->jfd) ){ ...
  41030. **
  41031. ** instead of
  41032. **
  41033. ** if( pPager->jfd->pMethods ){ ...
  41034. */
  41035. #define isOpen(pFd) ((pFd)->pMethods!=0)
  41036. /*
  41037. ** Return true if this pager uses a write-ahead log instead of the usual
  41038. ** rollback journal. Otherwise false.
  41039. */
  41040. #ifndef SQLITE_OMIT_WAL
  41041. static int pagerUseWal(Pager *pPager){
  41042. return (pPager->pWal!=0);
  41043. }
  41044. #else
  41045. # define pagerUseWal(x) 0
  41046. # define pagerRollbackWal(x) 0
  41047. # define pagerWalFrames(v,w,x,y) 0
  41048. # define pagerOpenWalIfPresent(z) SQLITE_OK
  41049. # define pagerBeginReadTransaction(z) SQLITE_OK
  41050. #endif
  41051. #ifndef NDEBUG
  41052. /*
  41053. ** Usage:
  41054. **
  41055. ** assert( assert_pager_state(pPager) );
  41056. **
  41057. ** This function runs many asserts to try to find inconsistencies in
  41058. ** the internal state of the Pager object.
  41059. */
  41060. static int assert_pager_state(Pager *p){
  41061. Pager *pPager = p;
  41062. /* State must be valid. */
  41063. assert( p->eState==PAGER_OPEN
  41064. || p->eState==PAGER_READER
  41065. || p->eState==PAGER_WRITER_LOCKED
  41066. || p->eState==PAGER_WRITER_CACHEMOD
  41067. || p->eState==PAGER_WRITER_DBMOD
  41068. || p->eState==PAGER_WRITER_FINISHED
  41069. || p->eState==PAGER_ERROR
  41070. );
  41071. /* Regardless of the current state, a temp-file connection always behaves
  41072. ** as if it has an exclusive lock on the database file. It never updates
  41073. ** the change-counter field, so the changeCountDone flag is always set.
  41074. */
  41075. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  41076. assert( p->tempFile==0 || pPager->changeCountDone );
  41077. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  41078. ** And if the journal-mode is "OFF", the journal file must not be open.
  41079. */
  41080. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  41081. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  41082. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  41083. ** this means an in-memory pager performs no IO at all, it cannot encounter
  41084. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  41085. ** a journal file. (although the in-memory journal implementation may
  41086. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  41087. ** is therefore not possible for an in-memory pager to enter the ERROR
  41088. ** state.
  41089. */
  41090. if( MEMDB ){
  41091. assert( p->noSync );
  41092. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  41093. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  41094. );
  41095. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  41096. assert( pagerUseWal(p)==0 );
  41097. }
  41098. /* If changeCountDone is set, a RESERVED lock or greater must be held
  41099. ** on the file.
  41100. */
  41101. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  41102. assert( p->eLock!=PENDING_LOCK );
  41103. switch( p->eState ){
  41104. case PAGER_OPEN:
  41105. assert( !MEMDB );
  41106. assert( pPager->errCode==SQLITE_OK );
  41107. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  41108. break;
  41109. case PAGER_READER:
  41110. assert( pPager->errCode==SQLITE_OK );
  41111. assert( p->eLock!=UNKNOWN_LOCK );
  41112. assert( p->eLock>=SHARED_LOCK );
  41113. break;
  41114. case PAGER_WRITER_LOCKED:
  41115. assert( p->eLock!=UNKNOWN_LOCK );
  41116. assert( pPager->errCode==SQLITE_OK );
  41117. if( !pagerUseWal(pPager) ){
  41118. assert( p->eLock>=RESERVED_LOCK );
  41119. }
  41120. assert( pPager->dbSize==pPager->dbOrigSize );
  41121. assert( pPager->dbOrigSize==pPager->dbFileSize );
  41122. assert( pPager->dbOrigSize==pPager->dbHintSize );
  41123. assert( pPager->setMaster==0 );
  41124. break;
  41125. case PAGER_WRITER_CACHEMOD:
  41126. assert( p->eLock!=UNKNOWN_LOCK );
  41127. assert( pPager->errCode==SQLITE_OK );
  41128. if( !pagerUseWal(pPager) ){
  41129. /* It is possible that if journal_mode=wal here that neither the
  41130. ** journal file nor the WAL file are open. This happens during
  41131. ** a rollback transaction that switches from journal_mode=off
  41132. ** to journal_mode=wal.
  41133. */
  41134. assert( p->eLock>=RESERVED_LOCK );
  41135. assert( isOpen(p->jfd)
  41136. || p->journalMode==PAGER_JOURNALMODE_OFF
  41137. || p->journalMode==PAGER_JOURNALMODE_WAL
  41138. );
  41139. }
  41140. assert( pPager->dbOrigSize==pPager->dbFileSize );
  41141. assert( pPager->dbOrigSize==pPager->dbHintSize );
  41142. break;
  41143. case PAGER_WRITER_DBMOD:
  41144. assert( p->eLock==EXCLUSIVE_LOCK );
  41145. assert( pPager->errCode==SQLITE_OK );
  41146. assert( !pagerUseWal(pPager) );
  41147. assert( p->eLock>=EXCLUSIVE_LOCK );
  41148. assert( isOpen(p->jfd)
  41149. || p->journalMode==PAGER_JOURNALMODE_OFF
  41150. || p->journalMode==PAGER_JOURNALMODE_WAL
  41151. );
  41152. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  41153. break;
  41154. case PAGER_WRITER_FINISHED:
  41155. assert( p->eLock==EXCLUSIVE_LOCK );
  41156. assert( pPager->errCode==SQLITE_OK );
  41157. assert( !pagerUseWal(pPager) );
  41158. assert( isOpen(p->jfd)
  41159. || p->journalMode==PAGER_JOURNALMODE_OFF
  41160. || p->journalMode==PAGER_JOURNALMODE_WAL
  41161. );
  41162. break;
  41163. case PAGER_ERROR:
  41164. /* There must be at least one outstanding reference to the pager if
  41165. ** in ERROR state. Otherwise the pager should have already dropped
  41166. ** back to OPEN state.
  41167. */
  41168. assert( pPager->errCode!=SQLITE_OK );
  41169. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  41170. break;
  41171. }
  41172. return 1;
  41173. }
  41174. #endif /* ifndef NDEBUG */
  41175. #ifdef SQLITE_DEBUG
  41176. /*
  41177. ** Return a pointer to a human readable string in a static buffer
  41178. ** containing the state of the Pager object passed as an argument. This
  41179. ** is intended to be used within debuggers. For example, as an alternative
  41180. ** to "print *pPager" in gdb:
  41181. **
  41182. ** (gdb) printf "%s", print_pager_state(pPager)
  41183. */
  41184. static char *print_pager_state(Pager *p){
  41185. static char zRet[1024];
  41186. sqlite3_snprintf(1024, zRet,
  41187. "Filename: %s\n"
  41188. "State: %s errCode=%d\n"
  41189. "Lock: %s\n"
  41190. "Locking mode: locking_mode=%s\n"
  41191. "Journal mode: journal_mode=%s\n"
  41192. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  41193. "Journal: journalOff=%lld journalHdr=%lld\n"
  41194. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  41195. , p->zFilename
  41196. , p->eState==PAGER_OPEN ? "OPEN" :
  41197. p->eState==PAGER_READER ? "READER" :
  41198. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  41199. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  41200. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  41201. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  41202. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  41203. , (int)p->errCode
  41204. , p->eLock==NO_LOCK ? "NO_LOCK" :
  41205. p->eLock==RESERVED_LOCK ? "RESERVED" :
  41206. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  41207. p->eLock==SHARED_LOCK ? "SHARED" :
  41208. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  41209. , p->exclusiveMode ? "exclusive" : "normal"
  41210. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  41211. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  41212. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  41213. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  41214. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  41215. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  41216. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  41217. , p->journalOff, p->journalHdr
  41218. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  41219. );
  41220. return zRet;
  41221. }
  41222. #endif
  41223. /*
  41224. ** Return true if it is necessary to write page *pPg into the sub-journal.
  41225. ** A page needs to be written into the sub-journal if there exists one
  41226. ** or more open savepoints for which:
  41227. **
  41228. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  41229. ** * The bit corresponding to the page-number is not set in
  41230. ** PagerSavepoint.pInSavepoint.
  41231. */
  41232. static int subjRequiresPage(PgHdr *pPg){
  41233. Pager *pPager = pPg->pPager;
  41234. PagerSavepoint *p;
  41235. Pgno pgno = pPg->pgno;
  41236. int i;
  41237. for(i=0; i<pPager->nSavepoint; i++){
  41238. p = &pPager->aSavepoint[i];
  41239. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  41240. return 1;
  41241. }
  41242. }
  41243. return 0;
  41244. }
  41245. #ifdef SQLITE_DEBUG
  41246. /*
  41247. ** Return true if the page is already in the journal file.
  41248. */
  41249. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  41250. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  41251. }
  41252. #endif
  41253. /*
  41254. ** Read a 32-bit integer from the given file descriptor. Store the integer
  41255. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  41256. ** error code is something goes wrong.
  41257. **
  41258. ** All values are stored on disk as big-endian.
  41259. */
  41260. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  41261. unsigned char ac[4];
  41262. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  41263. if( rc==SQLITE_OK ){
  41264. *pRes = sqlite3Get4byte(ac);
  41265. }
  41266. return rc;
  41267. }
  41268. /*
  41269. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  41270. */
  41271. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  41272. /*
  41273. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  41274. ** on success or an error code is something goes wrong.
  41275. */
  41276. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  41277. char ac[4];
  41278. put32bits(ac, val);
  41279. return sqlite3OsWrite(fd, ac, 4, offset);
  41280. }
  41281. /*
  41282. ** Unlock the database file to level eLock, which must be either NO_LOCK
  41283. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  41284. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  41285. **
  41286. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  41287. ** called, do not modify it. See the comment above the #define of
  41288. ** UNKNOWN_LOCK for an explanation of this.
  41289. */
  41290. static int pagerUnlockDb(Pager *pPager, int eLock){
  41291. int rc = SQLITE_OK;
  41292. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  41293. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  41294. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  41295. if( isOpen(pPager->fd) ){
  41296. assert( pPager->eLock>=eLock );
  41297. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  41298. if( pPager->eLock!=UNKNOWN_LOCK ){
  41299. pPager->eLock = (u8)eLock;
  41300. }
  41301. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  41302. }
  41303. return rc;
  41304. }
  41305. /*
  41306. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  41307. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  41308. ** Pager.eLock variable to the new locking state.
  41309. **
  41310. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  41311. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  41312. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  41313. ** of this.
  41314. */
  41315. static int pagerLockDb(Pager *pPager, int eLock){
  41316. int rc = SQLITE_OK;
  41317. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  41318. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  41319. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  41320. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  41321. pPager->eLock = (u8)eLock;
  41322. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  41323. }
  41324. }
  41325. return rc;
  41326. }
  41327. /*
  41328. ** This function determines whether or not the atomic-write optimization
  41329. ** can be used with this pager. The optimization can be used if:
  41330. **
  41331. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  41332. ** a database page may be written atomically, and
  41333. ** (b) the value returned by OsSectorSize() is less than or equal
  41334. ** to the page size.
  41335. **
  41336. ** The optimization is also always enabled for temporary files. It is
  41337. ** an error to call this function if pPager is opened on an in-memory
  41338. ** database.
  41339. **
  41340. ** If the optimization cannot be used, 0 is returned. If it can be used,
  41341. ** then the value returned is the size of the journal file when it
  41342. ** contains rollback data for exactly one page.
  41343. */
  41344. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  41345. static int jrnlBufferSize(Pager *pPager){
  41346. assert( !MEMDB );
  41347. if( !pPager->tempFile ){
  41348. int dc; /* Device characteristics */
  41349. int nSector; /* Sector size */
  41350. int szPage; /* Page size */
  41351. assert( isOpen(pPager->fd) );
  41352. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  41353. nSector = pPager->sectorSize;
  41354. szPage = pPager->pageSize;
  41355. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  41356. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  41357. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  41358. return 0;
  41359. }
  41360. }
  41361. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  41362. }
  41363. #endif
  41364. /*
  41365. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  41366. ** on the cache using a hash function. This is used for testing
  41367. ** and debugging only.
  41368. */
  41369. #ifdef SQLITE_CHECK_PAGES
  41370. /*
  41371. ** Return a 32-bit hash of the page data for pPage.
  41372. */
  41373. static u32 pager_datahash(int nByte, unsigned char *pData){
  41374. u32 hash = 0;
  41375. int i;
  41376. for(i=0; i<nByte; i++){
  41377. hash = (hash*1039) + pData[i];
  41378. }
  41379. return hash;
  41380. }
  41381. static u32 pager_pagehash(PgHdr *pPage){
  41382. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  41383. }
  41384. static void pager_set_pagehash(PgHdr *pPage){
  41385. pPage->pageHash = pager_pagehash(pPage);
  41386. }
  41387. /*
  41388. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  41389. ** is defined, and NDEBUG is not defined, an assert() statement checks
  41390. ** that the page is either dirty or still matches the calculated page-hash.
  41391. */
  41392. #define CHECK_PAGE(x) checkPage(x)
  41393. static void checkPage(PgHdr *pPg){
  41394. Pager *pPager = pPg->pPager;
  41395. assert( pPager->eState!=PAGER_ERROR );
  41396. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  41397. }
  41398. #else
  41399. #define pager_datahash(X,Y) 0
  41400. #define pager_pagehash(X) 0
  41401. #define pager_set_pagehash(X)
  41402. #define CHECK_PAGE(x)
  41403. #endif /* SQLITE_CHECK_PAGES */
  41404. /*
  41405. ** When this is called the journal file for pager pPager must be open.
  41406. ** This function attempts to read a master journal file name from the
  41407. ** end of the file and, if successful, copies it into memory supplied
  41408. ** by the caller. See comments above writeMasterJournal() for the format
  41409. ** used to store a master journal file name at the end of a journal file.
  41410. **
  41411. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  41412. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  41413. ** enough space to write the master journal name). If the master journal
  41414. ** name in the journal is longer than nMaster bytes (including a
  41415. ** nul-terminator), then this is handled as if no master journal name
  41416. ** were present in the journal.
  41417. **
  41418. ** If a master journal file name is present at the end of the journal
  41419. ** file, then it is copied into the buffer pointed to by zMaster. A
  41420. ** nul-terminator byte is appended to the buffer following the master
  41421. ** journal file name.
  41422. **
  41423. ** If it is determined that no master journal file name is present
  41424. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  41425. **
  41426. ** If an error occurs while reading from the journal file, an SQLite
  41427. ** error code is returned.
  41428. */
  41429. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  41430. int rc; /* Return code */
  41431. u32 len; /* Length in bytes of master journal name */
  41432. i64 szJ; /* Total size in bytes of journal file pJrnl */
  41433. u32 cksum; /* MJ checksum value read from journal */
  41434. u32 u; /* Unsigned loop counter */
  41435. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  41436. zMaster[0] = '\0';
  41437. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  41438. || szJ<16
  41439. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  41440. || len>=nMaster
  41441. || len==0
  41442. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  41443. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  41444. || memcmp(aMagic, aJournalMagic, 8)
  41445. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  41446. ){
  41447. return rc;
  41448. }
  41449. /* See if the checksum matches the master journal name */
  41450. for(u=0; u<len; u++){
  41451. cksum -= zMaster[u];
  41452. }
  41453. if( cksum ){
  41454. /* If the checksum doesn't add up, then one or more of the disk sectors
  41455. ** containing the master journal filename is corrupted. This means
  41456. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  41457. ** master-journal filename.
  41458. */
  41459. len = 0;
  41460. }
  41461. zMaster[len] = '\0';
  41462. return SQLITE_OK;
  41463. }
  41464. /*
  41465. ** Return the offset of the sector boundary at or immediately
  41466. ** following the value in pPager->journalOff, assuming a sector
  41467. ** size of pPager->sectorSize bytes.
  41468. **
  41469. ** i.e for a sector size of 512:
  41470. **
  41471. ** Pager.journalOff Return value
  41472. ** ---------------------------------------
  41473. ** 0 0
  41474. ** 512 512
  41475. ** 100 512
  41476. ** 2000 2048
  41477. **
  41478. */
  41479. static i64 journalHdrOffset(Pager *pPager){
  41480. i64 offset = 0;
  41481. i64 c = pPager->journalOff;
  41482. if( c ){
  41483. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  41484. }
  41485. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  41486. assert( offset>=c );
  41487. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  41488. return offset;
  41489. }
  41490. /*
  41491. ** The journal file must be open when this function is called.
  41492. **
  41493. ** This function is a no-op if the journal file has not been written to
  41494. ** within the current transaction (i.e. if Pager.journalOff==0).
  41495. **
  41496. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  41497. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  41498. ** zero the 28-byte header at the start of the journal file. In either case,
  41499. ** if the pager is not in no-sync mode, sync the journal file immediately
  41500. ** after writing or truncating it.
  41501. **
  41502. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  41503. ** following the truncation or zeroing described above the size of the
  41504. ** journal file in bytes is larger than this value, then truncate the
  41505. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  41506. ** not need to be synced following this operation.
  41507. **
  41508. ** If an IO error occurs, abandon processing and return the IO error code.
  41509. ** Otherwise, return SQLITE_OK.
  41510. */
  41511. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  41512. int rc = SQLITE_OK; /* Return code */
  41513. assert( isOpen(pPager->jfd) );
  41514. if( pPager->journalOff ){
  41515. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  41516. IOTRACE(("JZEROHDR %p\n", pPager))
  41517. if( doTruncate || iLimit==0 ){
  41518. rc = sqlite3OsTruncate(pPager->jfd, 0);
  41519. }else{
  41520. static const char zeroHdr[28] = {0};
  41521. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  41522. }
  41523. if( rc==SQLITE_OK && !pPager->noSync ){
  41524. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  41525. }
  41526. /* At this point the transaction is committed but the write lock
  41527. ** is still held on the file. If there is a size limit configured for
  41528. ** the persistent journal and the journal file currently consumes more
  41529. ** space than that limit allows for, truncate it now. There is no need
  41530. ** to sync the file following this operation.
  41531. */
  41532. if( rc==SQLITE_OK && iLimit>0 ){
  41533. i64 sz;
  41534. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  41535. if( rc==SQLITE_OK && sz>iLimit ){
  41536. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  41537. }
  41538. }
  41539. }
  41540. return rc;
  41541. }
  41542. /*
  41543. ** The journal file must be open when this routine is called. A journal
  41544. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  41545. ** current location.
  41546. **
  41547. ** The format for the journal header is as follows:
  41548. ** - 8 bytes: Magic identifying journal format.
  41549. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  41550. ** - 4 bytes: Random number used for page hash.
  41551. ** - 4 bytes: Initial database page count.
  41552. ** - 4 bytes: Sector size used by the process that wrote this journal.
  41553. ** - 4 bytes: Database page size.
  41554. **
  41555. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  41556. */
  41557. static int writeJournalHdr(Pager *pPager){
  41558. int rc = SQLITE_OK; /* Return code */
  41559. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  41560. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  41561. u32 nWrite; /* Bytes of header sector written */
  41562. int ii; /* Loop counter */
  41563. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  41564. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  41565. nHeader = JOURNAL_HDR_SZ(pPager);
  41566. }
  41567. /* If there are active savepoints and any of them were created
  41568. ** since the most recent journal header was written, update the
  41569. ** PagerSavepoint.iHdrOffset fields now.
  41570. */
  41571. for(ii=0; ii<pPager->nSavepoint; ii++){
  41572. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  41573. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  41574. }
  41575. }
  41576. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  41577. /*
  41578. ** Write the nRec Field - the number of page records that follow this
  41579. ** journal header. Normally, zero is written to this value at this time.
  41580. ** After the records are added to the journal (and the journal synced,
  41581. ** if in full-sync mode), the zero is overwritten with the true number
  41582. ** of records (see syncJournal()).
  41583. **
  41584. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  41585. ** reading the journal this value tells SQLite to assume that the
  41586. ** rest of the journal file contains valid page records. This assumption
  41587. ** is dangerous, as if a failure occurred whilst writing to the journal
  41588. ** file it may contain some garbage data. There are two scenarios
  41589. ** where this risk can be ignored:
  41590. **
  41591. ** * When the pager is in no-sync mode. Corruption can follow a
  41592. ** power failure in this case anyway.
  41593. **
  41594. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  41595. ** that garbage data is never appended to the journal file.
  41596. */
  41597. assert( isOpen(pPager->fd) || pPager->noSync );
  41598. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  41599. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  41600. ){
  41601. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  41602. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  41603. }else{
  41604. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  41605. }
  41606. /* The random check-hash initializer */
  41607. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  41608. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  41609. /* The initial database size */
  41610. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  41611. /* The assumed sector size for this process */
  41612. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  41613. /* The page size */
  41614. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  41615. /* Initializing the tail of the buffer is not necessary. Everything
  41616. ** works find if the following memset() is omitted. But initializing
  41617. ** the memory prevents valgrind from complaining, so we are willing to
  41618. ** take the performance hit.
  41619. */
  41620. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  41621. nHeader-(sizeof(aJournalMagic)+20));
  41622. /* In theory, it is only necessary to write the 28 bytes that the
  41623. ** journal header consumes to the journal file here. Then increment the
  41624. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  41625. ** record is written to the following sector (leaving a gap in the file
  41626. ** that will be implicitly filled in by the OS).
  41627. **
  41628. ** However it has been discovered that on some systems this pattern can
  41629. ** be significantly slower than contiguously writing data to the file,
  41630. ** even if that means explicitly writing data to the block of
  41631. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  41632. ** is done.
  41633. **
  41634. ** The loop is required here in case the sector-size is larger than the
  41635. ** database page size. Since the zHeader buffer is only Pager.pageSize
  41636. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  41637. ** to populate the entire journal header sector.
  41638. */
  41639. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  41640. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  41641. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  41642. assert( pPager->journalHdr <= pPager->journalOff );
  41643. pPager->journalOff += nHeader;
  41644. }
  41645. return rc;
  41646. }
  41647. /*
  41648. ** The journal file must be open when this is called. A journal header file
  41649. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  41650. ** file. The current location in the journal file is given by
  41651. ** pPager->journalOff. See comments above function writeJournalHdr() for
  41652. ** a description of the journal header format.
  41653. **
  41654. ** If the header is read successfully, *pNRec is set to the number of
  41655. ** page records following this header and *pDbSize is set to the size of the
  41656. ** database before the transaction began, in pages. Also, pPager->cksumInit
  41657. ** is set to the value read from the journal header. SQLITE_OK is returned
  41658. ** in this case.
  41659. **
  41660. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  41661. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  41662. ** cannot be read from the journal file an error code is returned.
  41663. */
  41664. static int readJournalHdr(
  41665. Pager *pPager, /* Pager object */
  41666. int isHot,
  41667. i64 journalSize, /* Size of the open journal file in bytes */
  41668. u32 *pNRec, /* OUT: Value read from the nRec field */
  41669. u32 *pDbSize /* OUT: Value of original database size field */
  41670. ){
  41671. int rc; /* Return code */
  41672. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  41673. i64 iHdrOff; /* Offset of journal header being read */
  41674. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  41675. /* Advance Pager.journalOff to the start of the next sector. If the
  41676. ** journal file is too small for there to be a header stored at this
  41677. ** point, return SQLITE_DONE.
  41678. */
  41679. pPager->journalOff = journalHdrOffset(pPager);
  41680. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  41681. return SQLITE_DONE;
  41682. }
  41683. iHdrOff = pPager->journalOff;
  41684. /* Read in the first 8 bytes of the journal header. If they do not match
  41685. ** the magic string found at the start of each journal header, return
  41686. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  41687. ** proceed.
  41688. */
  41689. if( isHot || iHdrOff!=pPager->journalHdr ){
  41690. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  41691. if( rc ){
  41692. return rc;
  41693. }
  41694. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  41695. return SQLITE_DONE;
  41696. }
  41697. }
  41698. /* Read the first three 32-bit fields of the journal header: The nRec
  41699. ** field, the checksum-initializer and the database size at the start
  41700. ** of the transaction. Return an error code if anything goes wrong.
  41701. */
  41702. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  41703. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  41704. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  41705. ){
  41706. return rc;
  41707. }
  41708. if( pPager->journalOff==0 ){
  41709. u32 iPageSize; /* Page-size field of journal header */
  41710. u32 iSectorSize; /* Sector-size field of journal header */
  41711. /* Read the page-size and sector-size journal header fields. */
  41712. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  41713. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  41714. ){
  41715. return rc;
  41716. }
  41717. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  41718. ** journal header to zero. In this case, assume that the Pager.pageSize
  41719. ** variable is already set to the correct page size.
  41720. */
  41721. if( iPageSize==0 ){
  41722. iPageSize = pPager->pageSize;
  41723. }
  41724. /* Check that the values read from the page-size and sector-size fields
  41725. ** are within range. To be 'in range', both values need to be a power
  41726. ** of two greater than or equal to 512 or 32, and not greater than their
  41727. ** respective compile time maximum limits.
  41728. */
  41729. if( iPageSize<512 || iSectorSize<32
  41730. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  41731. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  41732. ){
  41733. /* If the either the page-size or sector-size in the journal-header is
  41734. ** invalid, then the process that wrote the journal-header must have
  41735. ** crashed before the header was synced. In this case stop reading
  41736. ** the journal file here.
  41737. */
  41738. return SQLITE_DONE;
  41739. }
  41740. /* Update the page-size to match the value read from the journal.
  41741. ** Use a testcase() macro to make sure that malloc failure within
  41742. ** PagerSetPagesize() is tested.
  41743. */
  41744. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  41745. testcase( rc!=SQLITE_OK );
  41746. /* Update the assumed sector-size to match the value used by
  41747. ** the process that created this journal. If this journal was
  41748. ** created by a process other than this one, then this routine
  41749. ** is being called from within pager_playback(). The local value
  41750. ** of Pager.sectorSize is restored at the end of that routine.
  41751. */
  41752. pPager->sectorSize = iSectorSize;
  41753. }
  41754. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  41755. return rc;
  41756. }
  41757. /*
  41758. ** Write the supplied master journal name into the journal file for pager
  41759. ** pPager at the current location. The master journal name must be the last
  41760. ** thing written to a journal file. If the pager is in full-sync mode, the
  41761. ** journal file descriptor is advanced to the next sector boundary before
  41762. ** anything is written. The format is:
  41763. **
  41764. ** + 4 bytes: PAGER_MJ_PGNO.
  41765. ** + N bytes: Master journal filename in utf-8.
  41766. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  41767. ** + 4 bytes: Master journal name checksum.
  41768. ** + 8 bytes: aJournalMagic[].
  41769. **
  41770. ** The master journal page checksum is the sum of the bytes in the master
  41771. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  41772. **
  41773. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  41774. ** this call is a no-op.
  41775. */
  41776. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  41777. int rc; /* Return code */
  41778. int nMaster; /* Length of string zMaster */
  41779. i64 iHdrOff; /* Offset of header in journal file */
  41780. i64 jrnlSize; /* Size of journal file on disk */
  41781. u32 cksum = 0; /* Checksum of string zMaster */
  41782. assert( pPager->setMaster==0 );
  41783. assert( !pagerUseWal(pPager) );
  41784. if( !zMaster
  41785. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  41786. || !isOpen(pPager->jfd)
  41787. ){
  41788. return SQLITE_OK;
  41789. }
  41790. pPager->setMaster = 1;
  41791. assert( pPager->journalHdr <= pPager->journalOff );
  41792. /* Calculate the length in bytes and the checksum of zMaster */
  41793. for(nMaster=0; zMaster[nMaster]; nMaster++){
  41794. cksum += zMaster[nMaster];
  41795. }
  41796. /* If in full-sync mode, advance to the next disk sector before writing
  41797. ** the master journal name. This is in case the previous page written to
  41798. ** the journal has already been synced.
  41799. */
  41800. if( pPager->fullSync ){
  41801. pPager->journalOff = journalHdrOffset(pPager);
  41802. }
  41803. iHdrOff = pPager->journalOff;
  41804. /* Write the master journal data to the end of the journal file. If
  41805. ** an error occurs, return the error code to the caller.
  41806. */
  41807. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  41808. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  41809. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  41810. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  41811. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  41812. iHdrOff+4+nMaster+8)))
  41813. ){
  41814. return rc;
  41815. }
  41816. pPager->journalOff += (nMaster+20);
  41817. /* If the pager is in peristent-journal mode, then the physical
  41818. ** journal-file may extend past the end of the master-journal name
  41819. ** and 8 bytes of magic data just written to the file. This is
  41820. ** dangerous because the code to rollback a hot-journal file
  41821. ** will not be able to find the master-journal name to determine
  41822. ** whether or not the journal is hot.
  41823. **
  41824. ** Easiest thing to do in this scenario is to truncate the journal
  41825. ** file to the required size.
  41826. */
  41827. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  41828. && jrnlSize>pPager->journalOff
  41829. ){
  41830. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  41831. }
  41832. return rc;
  41833. }
  41834. /*
  41835. ** Discard the entire contents of the in-memory page-cache.
  41836. */
  41837. static void pager_reset(Pager *pPager){
  41838. pPager->iDataVersion++;
  41839. sqlite3BackupRestart(pPager->pBackup);
  41840. sqlite3PcacheClear(pPager->pPCache);
  41841. }
  41842. /*
  41843. ** Return the pPager->iDataVersion value
  41844. */
  41845. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  41846. assert( pPager->eState>PAGER_OPEN );
  41847. return pPager->iDataVersion;
  41848. }
  41849. /*
  41850. ** Free all structures in the Pager.aSavepoint[] array and set both
  41851. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  41852. ** if it is open and the pager is not in exclusive mode.
  41853. */
  41854. static void releaseAllSavepoints(Pager *pPager){
  41855. int ii; /* Iterator for looping through Pager.aSavepoint */
  41856. for(ii=0; ii<pPager->nSavepoint; ii++){
  41857. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  41858. }
  41859. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  41860. sqlite3OsClose(pPager->sjfd);
  41861. }
  41862. sqlite3_free(pPager->aSavepoint);
  41863. pPager->aSavepoint = 0;
  41864. pPager->nSavepoint = 0;
  41865. pPager->nSubRec = 0;
  41866. }
  41867. /*
  41868. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  41869. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  41870. ** or SQLITE_NOMEM if a malloc failure occurs.
  41871. */
  41872. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  41873. int ii; /* Loop counter */
  41874. int rc = SQLITE_OK; /* Result code */
  41875. for(ii=0; ii<pPager->nSavepoint; ii++){
  41876. PagerSavepoint *p = &pPager->aSavepoint[ii];
  41877. if( pgno<=p->nOrig ){
  41878. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  41879. testcase( rc==SQLITE_NOMEM );
  41880. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  41881. }
  41882. }
  41883. return rc;
  41884. }
  41885. /*
  41886. ** This function is a no-op if the pager is in exclusive mode and not
  41887. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  41888. ** state.
  41889. **
  41890. ** If the pager is not in exclusive-access mode, the database file is
  41891. ** completely unlocked. If the file is unlocked and the file-system does
  41892. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  41893. ** closed (if it is open).
  41894. **
  41895. ** If the pager is in ERROR state when this function is called, the
  41896. ** contents of the pager cache are discarded before switching back to
  41897. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  41898. ** or not, any journal file left in the file-system will be treated
  41899. ** as a hot-journal and rolled back the next time a read-transaction
  41900. ** is opened (by this or by any other connection).
  41901. */
  41902. static void pager_unlock(Pager *pPager){
  41903. assert( pPager->eState==PAGER_READER
  41904. || pPager->eState==PAGER_OPEN
  41905. || pPager->eState==PAGER_ERROR
  41906. );
  41907. sqlite3BitvecDestroy(pPager->pInJournal);
  41908. pPager->pInJournal = 0;
  41909. releaseAllSavepoints(pPager);
  41910. if( pagerUseWal(pPager) ){
  41911. assert( !isOpen(pPager->jfd) );
  41912. sqlite3WalEndReadTransaction(pPager->pWal);
  41913. pPager->eState = PAGER_OPEN;
  41914. }else if( !pPager->exclusiveMode ){
  41915. int rc; /* Error code returned by pagerUnlockDb() */
  41916. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  41917. /* If the operating system support deletion of open files, then
  41918. ** close the journal file when dropping the database lock. Otherwise
  41919. ** another connection with journal_mode=delete might delete the file
  41920. ** out from under us.
  41921. */
  41922. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  41923. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  41924. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  41925. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  41926. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  41927. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  41928. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  41929. || 1!=(pPager->journalMode & 5)
  41930. ){
  41931. sqlite3OsClose(pPager->jfd);
  41932. }
  41933. /* If the pager is in the ERROR state and the call to unlock the database
  41934. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  41935. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  41936. ** is necessary.
  41937. */
  41938. rc = pagerUnlockDb(pPager, NO_LOCK);
  41939. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  41940. pPager->eLock = UNKNOWN_LOCK;
  41941. }
  41942. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  41943. ** without clearing the error code. This is intentional - the error
  41944. ** code is cleared and the cache reset in the block below.
  41945. */
  41946. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  41947. pPager->changeCountDone = 0;
  41948. pPager->eState = PAGER_OPEN;
  41949. }
  41950. /* If Pager.errCode is set, the contents of the pager cache cannot be
  41951. ** trusted. Now that there are no outstanding references to the pager,
  41952. ** it can safely move back to PAGER_OPEN state. This happens in both
  41953. ** normal and exclusive-locking mode.
  41954. */
  41955. if( pPager->errCode ){
  41956. assert( !MEMDB );
  41957. pager_reset(pPager);
  41958. pPager->changeCountDone = pPager->tempFile;
  41959. pPager->eState = PAGER_OPEN;
  41960. pPager->errCode = SQLITE_OK;
  41961. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  41962. }
  41963. pPager->journalOff = 0;
  41964. pPager->journalHdr = 0;
  41965. pPager->setMaster = 0;
  41966. }
  41967. /*
  41968. ** This function is called whenever an IOERR or FULL error that requires
  41969. ** the pager to transition into the ERROR state may ahve occurred.
  41970. ** The first argument is a pointer to the pager structure, the second
  41971. ** the error-code about to be returned by a pager API function. The
  41972. ** value returned is a copy of the second argument to this function.
  41973. **
  41974. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  41975. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  41976. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  41977. ** all major API calls on the Pager will immediately return Pager.errCode.
  41978. **
  41979. ** The ERROR state indicates that the contents of the pager-cache
  41980. ** cannot be trusted. This state can be cleared by completely discarding
  41981. ** the contents of the pager-cache. If a transaction was active when
  41982. ** the persistent error occurred, then the rollback journal may need
  41983. ** to be replayed to restore the contents of the database file (as if
  41984. ** it were a hot-journal).
  41985. */
  41986. static int pager_error(Pager *pPager, int rc){
  41987. int rc2 = rc & 0xff;
  41988. assert( rc==SQLITE_OK || !MEMDB );
  41989. assert(
  41990. pPager->errCode==SQLITE_FULL ||
  41991. pPager->errCode==SQLITE_OK ||
  41992. (pPager->errCode & 0xff)==SQLITE_IOERR
  41993. );
  41994. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  41995. pPager->errCode = rc;
  41996. pPager->eState = PAGER_ERROR;
  41997. }
  41998. return rc;
  41999. }
  42000. static int pager_truncate(Pager *pPager, Pgno nPage);
  42001. /*
  42002. ** This routine ends a transaction. A transaction is usually ended by
  42003. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  42004. ** after rollback of a hot-journal, or if an error occurs while opening
  42005. ** the journal file or writing the very first journal-header of a
  42006. ** database transaction.
  42007. **
  42008. ** This routine is never called in PAGER_ERROR state. If it is called
  42009. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  42010. ** exclusive than a RESERVED lock, it is a no-op.
  42011. **
  42012. ** Otherwise, any active savepoints are released.
  42013. **
  42014. ** If the journal file is open, then it is "finalized". Once a journal
  42015. ** file has been finalized it is not possible to use it to roll back a
  42016. ** transaction. Nor will it be considered to be a hot-journal by this
  42017. ** or any other database connection. Exactly how a journal is finalized
  42018. ** depends on whether or not the pager is running in exclusive mode and
  42019. ** the current journal-mode (Pager.journalMode value), as follows:
  42020. **
  42021. ** journalMode==MEMORY
  42022. ** Journal file descriptor is simply closed. This destroys an
  42023. ** in-memory journal.
  42024. **
  42025. ** journalMode==TRUNCATE
  42026. ** Journal file is truncated to zero bytes in size.
  42027. **
  42028. ** journalMode==PERSIST
  42029. ** The first 28 bytes of the journal file are zeroed. This invalidates
  42030. ** the first journal header in the file, and hence the entire journal
  42031. ** file. An invalid journal file cannot be rolled back.
  42032. **
  42033. ** journalMode==DELETE
  42034. ** The journal file is closed and deleted using sqlite3OsDelete().
  42035. **
  42036. ** If the pager is running in exclusive mode, this method of finalizing
  42037. ** the journal file is never used. Instead, if the journalMode is
  42038. ** DELETE and the pager is in exclusive mode, the method described under
  42039. ** journalMode==PERSIST is used instead.
  42040. **
  42041. ** After the journal is finalized, the pager moves to PAGER_READER state.
  42042. ** If running in non-exclusive rollback mode, the lock on the file is
  42043. ** downgraded to a SHARED_LOCK.
  42044. **
  42045. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  42046. ** any of the IO operations to finalize the journal file or unlock the
  42047. ** database then the IO error code is returned to the user. If the
  42048. ** operation to finalize the journal file fails, then the code still
  42049. ** tries to unlock the database file if not in exclusive mode. If the
  42050. ** unlock operation fails as well, then the first error code related
  42051. ** to the first error encountered (the journal finalization one) is
  42052. ** returned.
  42053. */
  42054. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  42055. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  42056. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  42057. /* Do nothing if the pager does not have an open write transaction
  42058. ** or at least a RESERVED lock. This function may be called when there
  42059. ** is no write-transaction active but a RESERVED or greater lock is
  42060. ** held under two circumstances:
  42061. **
  42062. ** 1. After a successful hot-journal rollback, it is called with
  42063. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  42064. **
  42065. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  42066. ** lock switches back to locking_mode=normal and then executes a
  42067. ** read-transaction, this function is called with eState==PAGER_READER
  42068. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  42069. */
  42070. assert( assert_pager_state(pPager) );
  42071. assert( pPager->eState!=PAGER_ERROR );
  42072. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  42073. return SQLITE_OK;
  42074. }
  42075. releaseAllSavepoints(pPager);
  42076. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  42077. if( isOpen(pPager->jfd) ){
  42078. assert( !pagerUseWal(pPager) );
  42079. /* Finalize the journal file. */
  42080. if( sqlite3IsMemJournal(pPager->jfd) ){
  42081. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  42082. sqlite3OsClose(pPager->jfd);
  42083. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  42084. if( pPager->journalOff==0 ){
  42085. rc = SQLITE_OK;
  42086. }else{
  42087. rc = sqlite3OsTruncate(pPager->jfd, 0);
  42088. if( rc==SQLITE_OK && pPager->fullSync ){
  42089. /* Make sure the new file size is written into the inode right away.
  42090. ** Otherwise the journal might resurrect following a power loss and
  42091. ** cause the last transaction to roll back. See
  42092. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  42093. */
  42094. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  42095. }
  42096. }
  42097. pPager->journalOff = 0;
  42098. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  42099. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  42100. ){
  42101. rc = zeroJournalHdr(pPager, hasMaster);
  42102. pPager->journalOff = 0;
  42103. }else{
  42104. /* This branch may be executed with Pager.journalMode==MEMORY if
  42105. ** a hot-journal was just rolled back. In this case the journal
  42106. ** file should be closed and deleted. If this connection writes to
  42107. ** the database file, it will do so using an in-memory journal.
  42108. */
  42109. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  42110. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  42111. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  42112. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  42113. );
  42114. sqlite3OsClose(pPager->jfd);
  42115. if( bDelete ){
  42116. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42117. }
  42118. }
  42119. }
  42120. #ifdef SQLITE_CHECK_PAGES
  42121. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  42122. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  42123. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  42124. if( p ){
  42125. p->pageHash = 0;
  42126. sqlite3PagerUnrefNotNull(p);
  42127. }
  42128. }
  42129. #endif
  42130. sqlite3BitvecDestroy(pPager->pInJournal);
  42131. pPager->pInJournal = 0;
  42132. pPager->nRec = 0;
  42133. sqlite3PcacheCleanAll(pPager->pPCache);
  42134. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  42135. if( pagerUseWal(pPager) ){
  42136. /* Drop the WAL write-lock, if any. Also, if the connection was in
  42137. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  42138. ** lock held on the database file.
  42139. */
  42140. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  42141. assert( rc2==SQLITE_OK );
  42142. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  42143. /* This branch is taken when committing a transaction in rollback-journal
  42144. ** mode if the database file on disk is larger than the database image.
  42145. ** At this point the journal has been finalized and the transaction
  42146. ** successfully committed, but the EXCLUSIVE lock is still held on the
  42147. ** file. So it is safe to truncate the database file to its minimum
  42148. ** required size. */
  42149. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42150. rc = pager_truncate(pPager, pPager->dbSize);
  42151. }
  42152. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  42153. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  42154. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  42155. }
  42156. if( !pPager->exclusiveMode
  42157. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  42158. ){
  42159. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  42160. pPager->changeCountDone = 0;
  42161. }
  42162. pPager->eState = PAGER_READER;
  42163. pPager->setMaster = 0;
  42164. return (rc==SQLITE_OK?rc2:rc);
  42165. }
  42166. /*
  42167. ** Execute a rollback if a transaction is active and unlock the
  42168. ** database file.
  42169. **
  42170. ** If the pager has already entered the ERROR state, do not attempt
  42171. ** the rollback at this time. Instead, pager_unlock() is called. The
  42172. ** call to pager_unlock() will discard all in-memory pages, unlock
  42173. ** the database file and move the pager back to OPEN state. If this
  42174. ** means that there is a hot-journal left in the file-system, the next
  42175. ** connection to obtain a shared lock on the pager (which may be this one)
  42176. ** will roll it back.
  42177. **
  42178. ** If the pager has not already entered the ERROR state, but an IO or
  42179. ** malloc error occurs during a rollback, then this will itself cause
  42180. ** the pager to enter the ERROR state. Which will be cleared by the
  42181. ** call to pager_unlock(), as described above.
  42182. */
  42183. static void pagerUnlockAndRollback(Pager *pPager){
  42184. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  42185. assert( assert_pager_state(pPager) );
  42186. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  42187. sqlite3BeginBenignMalloc();
  42188. sqlite3PagerRollback(pPager);
  42189. sqlite3EndBenignMalloc();
  42190. }else if( !pPager->exclusiveMode ){
  42191. assert( pPager->eState==PAGER_READER );
  42192. pager_end_transaction(pPager, 0, 0);
  42193. }
  42194. }
  42195. pager_unlock(pPager);
  42196. }
  42197. /*
  42198. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  42199. ** of data. Compute and return a checksum based ont the contents of the
  42200. ** page of data and the current value of pPager->cksumInit.
  42201. **
  42202. ** This is not a real checksum. It is really just the sum of the
  42203. ** random initial value (pPager->cksumInit) and every 200th byte
  42204. ** of the page data, starting with byte offset (pPager->pageSize%200).
  42205. ** Each byte is interpreted as an 8-bit unsigned integer.
  42206. **
  42207. ** Changing the formula used to compute this checksum results in an
  42208. ** incompatible journal file format.
  42209. **
  42210. ** If journal corruption occurs due to a power failure, the most likely
  42211. ** scenario is that one end or the other of the record will be changed.
  42212. ** It is much less likely that the two ends of the journal record will be
  42213. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  42214. ** though fast and simple, catches the mostly likely kind of corruption.
  42215. */
  42216. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  42217. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  42218. int i = pPager->pageSize-200; /* Loop counter */
  42219. while( i>0 ){
  42220. cksum += aData[i];
  42221. i -= 200;
  42222. }
  42223. return cksum;
  42224. }
  42225. /*
  42226. ** Report the current page size and number of reserved bytes back
  42227. ** to the codec.
  42228. */
  42229. #ifdef SQLITE_HAS_CODEC
  42230. static void pagerReportSize(Pager *pPager){
  42231. if( pPager->xCodecSizeChng ){
  42232. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  42233. (int)pPager->nReserve);
  42234. }
  42235. }
  42236. #else
  42237. # define pagerReportSize(X) /* No-op if we do not support a codec */
  42238. #endif
  42239. #ifdef SQLITE_HAS_CODEC
  42240. /*
  42241. ** Make sure the number of reserved bits is the same in the destination
  42242. ** pager as it is in the source. This comes up when a VACUUM changes the
  42243. ** number of reserved bits to the "optimal" amount.
  42244. */
  42245. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  42246. if( pDest->nReserve!=pSrc->nReserve ){
  42247. pDest->nReserve = pSrc->nReserve;
  42248. pagerReportSize(pDest);
  42249. }
  42250. }
  42251. #endif
  42252. /*
  42253. ** Read a single page from either the journal file (if isMainJrnl==1) or
  42254. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  42255. ** The page begins at offset *pOffset into the file. The *pOffset
  42256. ** value is increased to the start of the next page in the journal.
  42257. **
  42258. ** The main rollback journal uses checksums - the statement journal does
  42259. ** not.
  42260. **
  42261. ** If the page number of the page record read from the (sub-)journal file
  42262. ** is greater than the current value of Pager.dbSize, then playback is
  42263. ** skipped and SQLITE_OK is returned.
  42264. **
  42265. ** If pDone is not NULL, then it is a record of pages that have already
  42266. ** been played back. If the page at *pOffset has already been played back
  42267. ** (if the corresponding pDone bit is set) then skip the playback.
  42268. ** Make sure the pDone bit corresponding to the *pOffset page is set
  42269. ** prior to returning.
  42270. **
  42271. ** If the page record is successfully read from the (sub-)journal file
  42272. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  42273. ** while reading the record from the (sub-)journal file or while writing
  42274. ** to the database file, then the IO error code is returned. If data
  42275. ** is successfully read from the (sub-)journal file but appears to be
  42276. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  42277. ** two circumstances:
  42278. **
  42279. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  42280. ** * If the record is being rolled back from the main journal file
  42281. ** and the checksum field does not match the record content.
  42282. **
  42283. ** Neither of these two scenarios are possible during a savepoint rollback.
  42284. **
  42285. ** If this is a savepoint rollback, then memory may have to be dynamically
  42286. ** allocated by this function. If this is the case and an allocation fails,
  42287. ** SQLITE_NOMEM is returned.
  42288. */
  42289. static int pager_playback_one_page(
  42290. Pager *pPager, /* The pager being played back */
  42291. i64 *pOffset, /* Offset of record to playback */
  42292. Bitvec *pDone, /* Bitvec of pages already played back */
  42293. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  42294. int isSavepnt /* True for a savepoint rollback */
  42295. ){
  42296. int rc;
  42297. PgHdr *pPg; /* An existing page in the cache */
  42298. Pgno pgno; /* The page number of a page in journal */
  42299. u32 cksum; /* Checksum used for sanity checking */
  42300. char *aData; /* Temporary storage for the page */
  42301. sqlite3_file *jfd; /* The file descriptor for the journal file */
  42302. int isSynced; /* True if journal page is synced */
  42303. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  42304. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  42305. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  42306. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  42307. aData = pPager->pTmpSpace;
  42308. assert( aData ); /* Temp storage must have already been allocated */
  42309. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  42310. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  42311. ** or savepoint rollback done at the request of the caller) or this is
  42312. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  42313. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  42314. ** only reads from the main journal, not the sub-journal.
  42315. */
  42316. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  42317. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  42318. );
  42319. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  42320. /* Read the page number and page data from the journal or sub-journal
  42321. ** file. Return an error code to the caller if an IO error occurs.
  42322. */
  42323. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  42324. rc = read32bits(jfd, *pOffset, &pgno);
  42325. if( rc!=SQLITE_OK ) return rc;
  42326. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  42327. if( rc!=SQLITE_OK ) return rc;
  42328. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  42329. /* Sanity checking on the page. This is more important that I originally
  42330. ** thought. If a power failure occurs while the journal is being written,
  42331. ** it could cause invalid data to be written into the journal. We need to
  42332. ** detect this invalid data (with high probability) and ignore it.
  42333. */
  42334. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  42335. assert( !isSavepnt );
  42336. return SQLITE_DONE;
  42337. }
  42338. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  42339. return SQLITE_OK;
  42340. }
  42341. if( isMainJrnl ){
  42342. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  42343. if( rc ) return rc;
  42344. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  42345. return SQLITE_DONE;
  42346. }
  42347. }
  42348. /* If this page has already been played back before during the current
  42349. ** rollback, then don't bother to play it back again.
  42350. */
  42351. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  42352. return rc;
  42353. }
  42354. /* When playing back page 1, restore the nReserve setting
  42355. */
  42356. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  42357. pPager->nReserve = ((u8*)aData)[20];
  42358. pagerReportSize(pPager);
  42359. }
  42360. /* If the pager is in CACHEMOD state, then there must be a copy of this
  42361. ** page in the pager cache. In this case just update the pager cache,
  42362. ** not the database file. The page is left marked dirty in this case.
  42363. **
  42364. ** An exception to the above rule: If the database is in no-sync mode
  42365. ** and a page is moved during an incremental vacuum then the page may
  42366. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  42367. ** during a Movepage() call, then the page may not be in the cache
  42368. ** either. So the condition described in the above paragraph is not
  42369. ** assert()able.
  42370. **
  42371. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  42372. ** pager cache if it exists and the main file. The page is then marked
  42373. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  42374. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  42375. ** if the pager is in OPEN state.
  42376. **
  42377. ** Ticket #1171: The statement journal might contain page content that is
  42378. ** different from the page content at the start of the transaction.
  42379. ** This occurs when a page is changed prior to the start of a statement
  42380. ** then changed again within the statement. When rolling back such a
  42381. ** statement we must not write to the original database unless we know
  42382. ** for certain that original page contents are synced into the main rollback
  42383. ** journal. Otherwise, a power loss might leave modified data in the
  42384. ** database file without an entry in the rollback journal that can
  42385. ** restore the database to its original form. Two conditions must be
  42386. ** met before writing to the database files. (1) the database must be
  42387. ** locked. (2) we know that the original page content is fully synced
  42388. ** in the main journal either because the page is not in cache or else
  42389. ** the page is marked as needSync==0.
  42390. **
  42391. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  42392. ** is possible to fail a statement on a database that does not yet exist.
  42393. ** Do not attempt to write if database file has never been opened.
  42394. */
  42395. if( pagerUseWal(pPager) ){
  42396. pPg = 0;
  42397. }else{
  42398. pPg = sqlite3PagerLookup(pPager, pgno);
  42399. }
  42400. assert( pPg || !MEMDB );
  42401. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  42402. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  42403. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  42404. (isMainJrnl?"main-journal":"sub-journal")
  42405. ));
  42406. if( isMainJrnl ){
  42407. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  42408. }else{
  42409. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  42410. }
  42411. if( isOpen(pPager->fd)
  42412. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42413. && isSynced
  42414. ){
  42415. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  42416. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  42417. assert( !pagerUseWal(pPager) );
  42418. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  42419. if( pgno>pPager->dbFileSize ){
  42420. pPager->dbFileSize = pgno;
  42421. }
  42422. if( pPager->pBackup ){
  42423. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  42424. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  42425. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  42426. }
  42427. }else if( !isMainJrnl && pPg==0 ){
  42428. /* If this is a rollback of a savepoint and data was not written to
  42429. ** the database and the page is not in-memory, there is a potential
  42430. ** problem. When the page is next fetched by the b-tree layer, it
  42431. ** will be read from the database file, which may or may not be
  42432. ** current.
  42433. **
  42434. ** There are a couple of different ways this can happen. All are quite
  42435. ** obscure. When running in synchronous mode, this can only happen
  42436. ** if the page is on the free-list at the start of the transaction, then
  42437. ** populated, then moved using sqlite3PagerMovepage().
  42438. **
  42439. ** The solution is to add an in-memory page to the cache containing
  42440. ** the data just read from the sub-journal. Mark the page as dirty
  42441. ** and if the pager requires a journal-sync, then mark the page as
  42442. ** requiring a journal-sync before it is written.
  42443. */
  42444. assert( isSavepnt );
  42445. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  42446. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  42447. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  42448. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  42449. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  42450. if( rc!=SQLITE_OK ) return rc;
  42451. pPg->flags &= ~PGHDR_NEED_READ;
  42452. sqlite3PcacheMakeDirty(pPg);
  42453. }
  42454. if( pPg ){
  42455. /* No page should ever be explicitly rolled back that is in use, except
  42456. ** for page 1 which is held in use in order to keep the lock on the
  42457. ** database active. However such a page may be rolled back as a result
  42458. ** of an internal error resulting in an automatic call to
  42459. ** sqlite3PagerRollback().
  42460. */
  42461. void *pData;
  42462. pData = pPg->pData;
  42463. memcpy(pData, (u8*)aData, pPager->pageSize);
  42464. pPager->xReiniter(pPg);
  42465. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  42466. /* If the contents of this page were just restored from the main
  42467. ** journal file, then its content must be as they were when the
  42468. ** transaction was first opened. In this case we can mark the page
  42469. ** as clean, since there will be no need to write it out to the
  42470. ** database.
  42471. **
  42472. ** There is one exception to this rule. If the page is being rolled
  42473. ** back as part of a savepoint (or statement) rollback from an
  42474. ** unsynced portion of the main journal file, then it is not safe
  42475. ** to mark the page as clean. This is because marking the page as
  42476. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  42477. ** already in the journal file (recorded in Pager.pInJournal) and
  42478. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  42479. ** again within this transaction, it will be marked as dirty but
  42480. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  42481. ** be written out into the database file before its journal file
  42482. ** segment is synced. If a crash occurs during or following this,
  42483. ** database corruption may ensue.
  42484. */
  42485. assert( !pagerUseWal(pPager) );
  42486. sqlite3PcacheMakeClean(pPg);
  42487. }
  42488. pager_set_pagehash(pPg);
  42489. /* If this was page 1, then restore the value of Pager.dbFileVers.
  42490. ** Do this before any decoding. */
  42491. if( pgno==1 ){
  42492. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  42493. }
  42494. /* Decode the page just read from disk */
  42495. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  42496. sqlite3PcacheRelease(pPg);
  42497. }
  42498. return rc;
  42499. }
  42500. /*
  42501. ** Parameter zMaster is the name of a master journal file. A single journal
  42502. ** file that referred to the master journal file has just been rolled back.
  42503. ** This routine checks if it is possible to delete the master journal file,
  42504. ** and does so if it is.
  42505. **
  42506. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  42507. ** available for use within this function.
  42508. **
  42509. ** When a master journal file is created, it is populated with the names
  42510. ** of all of its child journals, one after another, formatted as utf-8
  42511. ** encoded text. The end of each child journal file is marked with a
  42512. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  42513. ** file for a transaction involving two databases might be:
  42514. **
  42515. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  42516. **
  42517. ** A master journal file may only be deleted once all of its child
  42518. ** journals have been rolled back.
  42519. **
  42520. ** This function reads the contents of the master-journal file into
  42521. ** memory and loops through each of the child journal names. For
  42522. ** each child journal, it checks if:
  42523. **
  42524. ** * if the child journal exists, and if so
  42525. ** * if the child journal contains a reference to master journal
  42526. ** file zMaster
  42527. **
  42528. ** If a child journal can be found that matches both of the criteria
  42529. ** above, this function returns without doing anything. Otherwise, if
  42530. ** no such child journal can be found, file zMaster is deleted from
  42531. ** the file-system using sqlite3OsDelete().
  42532. **
  42533. ** If an IO error within this function, an error code is returned. This
  42534. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  42535. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  42536. ** occur, SQLITE_OK is returned.
  42537. **
  42538. ** TODO: This function allocates a single block of memory to load
  42539. ** the entire contents of the master journal file. This could be
  42540. ** a couple of kilobytes or so - potentially larger than the page
  42541. ** size.
  42542. */
  42543. static int pager_delmaster(Pager *pPager, const char *zMaster){
  42544. sqlite3_vfs *pVfs = pPager->pVfs;
  42545. int rc; /* Return code */
  42546. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  42547. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  42548. char *zMasterJournal = 0; /* Contents of master journal file */
  42549. i64 nMasterJournal; /* Size of master journal file */
  42550. char *zJournal; /* Pointer to one journal within MJ file */
  42551. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  42552. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  42553. /* Allocate space for both the pJournal and pMaster file descriptors.
  42554. ** If successful, open the master journal file for reading.
  42555. */
  42556. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  42557. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  42558. if( !pMaster ){
  42559. rc = SQLITE_NOMEM;
  42560. }else{
  42561. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  42562. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  42563. }
  42564. if( rc!=SQLITE_OK ) goto delmaster_out;
  42565. /* Load the entire master journal file into space obtained from
  42566. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  42567. ** sufficient space (in zMasterPtr) to hold the names of master
  42568. ** journal files extracted from regular rollback-journals.
  42569. */
  42570. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  42571. if( rc!=SQLITE_OK ) goto delmaster_out;
  42572. nMasterPtr = pVfs->mxPathname+1;
  42573. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  42574. if( !zMasterJournal ){
  42575. rc = SQLITE_NOMEM;
  42576. goto delmaster_out;
  42577. }
  42578. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  42579. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  42580. if( rc!=SQLITE_OK ) goto delmaster_out;
  42581. zMasterJournal[nMasterJournal] = 0;
  42582. zJournal = zMasterJournal;
  42583. while( (zJournal-zMasterJournal)<nMasterJournal ){
  42584. int exists;
  42585. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  42586. if( rc!=SQLITE_OK ){
  42587. goto delmaster_out;
  42588. }
  42589. if( exists ){
  42590. /* One of the journals pointed to by the master journal exists.
  42591. ** Open it and check if it points at the master journal. If
  42592. ** so, return without deleting the master journal file.
  42593. */
  42594. int c;
  42595. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  42596. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  42597. if( rc!=SQLITE_OK ){
  42598. goto delmaster_out;
  42599. }
  42600. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  42601. sqlite3OsClose(pJournal);
  42602. if( rc!=SQLITE_OK ){
  42603. goto delmaster_out;
  42604. }
  42605. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  42606. if( c ){
  42607. /* We have a match. Do not delete the master journal file. */
  42608. goto delmaster_out;
  42609. }
  42610. }
  42611. zJournal += (sqlite3Strlen30(zJournal)+1);
  42612. }
  42613. sqlite3OsClose(pMaster);
  42614. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  42615. delmaster_out:
  42616. sqlite3_free(zMasterJournal);
  42617. if( pMaster ){
  42618. sqlite3OsClose(pMaster);
  42619. assert( !isOpen(pJournal) );
  42620. sqlite3_free(pMaster);
  42621. }
  42622. return rc;
  42623. }
  42624. /*
  42625. ** This function is used to change the actual size of the database
  42626. ** file in the file-system. This only happens when committing a transaction,
  42627. ** or rolling back a transaction (including rolling back a hot-journal).
  42628. **
  42629. ** If the main database file is not open, or the pager is not in either
  42630. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  42631. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  42632. ** If the file on disk is currently larger than nPage pages, then use the VFS
  42633. ** xTruncate() method to truncate it.
  42634. **
  42635. ** Or, it might be the case that the file on disk is smaller than
  42636. ** nPage pages. Some operating system implementations can get confused if
  42637. ** you try to truncate a file to some size that is larger than it
  42638. ** currently is, so detect this case and write a single zero byte to
  42639. ** the end of the new file instead.
  42640. **
  42641. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  42642. ** the database file, return the error code to the caller.
  42643. */
  42644. static int pager_truncate(Pager *pPager, Pgno nPage){
  42645. int rc = SQLITE_OK;
  42646. assert( pPager->eState!=PAGER_ERROR );
  42647. assert( pPager->eState!=PAGER_READER );
  42648. if( isOpen(pPager->fd)
  42649. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42650. ){
  42651. i64 currentSize, newSize;
  42652. int szPage = pPager->pageSize;
  42653. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42654. /* TODO: Is it safe to use Pager.dbFileSize here? */
  42655. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  42656. newSize = szPage*(i64)nPage;
  42657. if( rc==SQLITE_OK && currentSize!=newSize ){
  42658. if( currentSize>newSize ){
  42659. rc = sqlite3OsTruncate(pPager->fd, newSize);
  42660. }else if( (currentSize+szPage)<=newSize ){
  42661. char *pTmp = pPager->pTmpSpace;
  42662. memset(pTmp, 0, szPage);
  42663. testcase( (newSize-szPage) == currentSize );
  42664. testcase( (newSize-szPage) > currentSize );
  42665. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  42666. }
  42667. if( rc==SQLITE_OK ){
  42668. pPager->dbFileSize = nPage;
  42669. }
  42670. }
  42671. }
  42672. return rc;
  42673. }
  42674. /*
  42675. ** Return a sanitized version of the sector-size of OS file pFile. The
  42676. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  42677. */
  42678. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  42679. int iRet = sqlite3OsSectorSize(pFile);
  42680. if( iRet<32 ){
  42681. iRet = 512;
  42682. }else if( iRet>MAX_SECTOR_SIZE ){
  42683. assert( MAX_SECTOR_SIZE>=512 );
  42684. iRet = MAX_SECTOR_SIZE;
  42685. }
  42686. return iRet;
  42687. }
  42688. /*
  42689. ** Set the value of the Pager.sectorSize variable for the given
  42690. ** pager based on the value returned by the xSectorSize method
  42691. ** of the open database file. The sector size will be used
  42692. ** to determine the size and alignment of journal header and
  42693. ** master journal pointers within created journal files.
  42694. **
  42695. ** For temporary files the effective sector size is always 512 bytes.
  42696. **
  42697. ** Otherwise, for non-temporary files, the effective sector size is
  42698. ** the value returned by the xSectorSize() method rounded up to 32 if
  42699. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  42700. ** is greater than MAX_SECTOR_SIZE.
  42701. **
  42702. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  42703. ** the effective sector size to its minimum value (512). The purpose of
  42704. ** pPager->sectorSize is to define the "blast radius" of bytes that
  42705. ** might change if a crash occurs while writing to a single byte in
  42706. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  42707. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  42708. ** size. For backwards compatibility of the rollback journal file format,
  42709. ** we cannot reduce the effective sector size below 512.
  42710. */
  42711. static void setSectorSize(Pager *pPager){
  42712. assert( isOpen(pPager->fd) || pPager->tempFile );
  42713. if( pPager->tempFile
  42714. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  42715. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  42716. ){
  42717. /* Sector size doesn't matter for temporary files. Also, the file
  42718. ** may not have been opened yet, in which case the OsSectorSize()
  42719. ** call will segfault. */
  42720. pPager->sectorSize = 512;
  42721. }else{
  42722. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  42723. }
  42724. }
  42725. /*
  42726. ** Playback the journal and thus restore the database file to
  42727. ** the state it was in before we started making changes.
  42728. **
  42729. ** The journal file format is as follows:
  42730. **
  42731. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  42732. ** (2) 4 byte big-endian integer which is the number of valid page records
  42733. ** in the journal. If this value is 0xffffffff, then compute the
  42734. ** number of page records from the journal size.
  42735. ** (3) 4 byte big-endian integer which is the initial value for the
  42736. ** sanity checksum.
  42737. ** (4) 4 byte integer which is the number of pages to truncate the
  42738. ** database to during a rollback.
  42739. ** (5) 4 byte big-endian integer which is the sector size. The header
  42740. ** is this many bytes in size.
  42741. ** (6) 4 byte big-endian integer which is the page size.
  42742. ** (7) zero padding out to the next sector size.
  42743. ** (8) Zero or more pages instances, each as follows:
  42744. ** + 4 byte page number.
  42745. ** + pPager->pageSize bytes of data.
  42746. ** + 4 byte checksum
  42747. **
  42748. ** When we speak of the journal header, we mean the first 7 items above.
  42749. ** Each entry in the journal is an instance of the 8th item.
  42750. **
  42751. ** Call the value from the second bullet "nRec". nRec is the number of
  42752. ** valid page entries in the journal. In most cases, you can compute the
  42753. ** value of nRec from the size of the journal file. But if a power
  42754. ** failure occurred while the journal was being written, it could be the
  42755. ** case that the size of the journal file had already been increased but
  42756. ** the extra entries had not yet made it safely to disk. In such a case,
  42757. ** the value of nRec computed from the file size would be too large. For
  42758. ** that reason, we always use the nRec value in the header.
  42759. **
  42760. ** If the nRec value is 0xffffffff it means that nRec should be computed
  42761. ** from the file size. This value is used when the user selects the
  42762. ** no-sync option for the journal. A power failure could lead to corruption
  42763. ** in this case. But for things like temporary table (which will be
  42764. ** deleted when the power is restored) we don't care.
  42765. **
  42766. ** If the file opened as the journal file is not a well-formed
  42767. ** journal file then all pages up to the first corrupted page are rolled
  42768. ** back (or no pages if the journal header is corrupted). The journal file
  42769. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  42770. ** been encountered.
  42771. **
  42772. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  42773. ** and an error code is returned.
  42774. **
  42775. ** The isHot parameter indicates that we are trying to rollback a journal
  42776. ** that might be a hot journal. Or, it could be that the journal is
  42777. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  42778. ** If the journal really is hot, reset the pager cache prior rolling
  42779. ** back any content. If the journal is merely persistent, no reset is
  42780. ** needed.
  42781. */
  42782. static int pager_playback(Pager *pPager, int isHot){
  42783. sqlite3_vfs *pVfs = pPager->pVfs;
  42784. i64 szJ; /* Size of the journal file in bytes */
  42785. u32 nRec; /* Number of Records in the journal */
  42786. u32 u; /* Unsigned loop counter */
  42787. Pgno mxPg = 0; /* Size of the original file in pages */
  42788. int rc; /* Result code of a subroutine */
  42789. int res = 1; /* Value returned by sqlite3OsAccess() */
  42790. char *zMaster = 0; /* Name of master journal file if any */
  42791. int needPagerReset; /* True to reset page prior to first page rollback */
  42792. int nPlayback = 0; /* Total number of pages restored from journal */
  42793. /* Figure out how many records are in the journal. Abort early if
  42794. ** the journal is empty.
  42795. */
  42796. assert( isOpen(pPager->jfd) );
  42797. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  42798. if( rc!=SQLITE_OK ){
  42799. goto end_playback;
  42800. }
  42801. /* Read the master journal name from the journal, if it is present.
  42802. ** If a master journal file name is specified, but the file is not
  42803. ** present on disk, then the journal is not hot and does not need to be
  42804. ** played back.
  42805. **
  42806. ** TODO: Technically the following is an error because it assumes that
  42807. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  42808. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  42809. ** mxPathname is 512, which is the same as the minimum allowable value
  42810. ** for pageSize.
  42811. */
  42812. zMaster = pPager->pTmpSpace;
  42813. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  42814. if( rc==SQLITE_OK && zMaster[0] ){
  42815. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  42816. }
  42817. zMaster = 0;
  42818. if( rc!=SQLITE_OK || !res ){
  42819. goto end_playback;
  42820. }
  42821. pPager->journalOff = 0;
  42822. needPagerReset = isHot;
  42823. /* This loop terminates either when a readJournalHdr() or
  42824. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  42825. ** occurs.
  42826. */
  42827. while( 1 ){
  42828. /* Read the next journal header from the journal file. If there are
  42829. ** not enough bytes left in the journal file for a complete header, or
  42830. ** it is corrupted, then a process must have failed while writing it.
  42831. ** This indicates nothing more needs to be rolled back.
  42832. */
  42833. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  42834. if( rc!=SQLITE_OK ){
  42835. if( rc==SQLITE_DONE ){
  42836. rc = SQLITE_OK;
  42837. }
  42838. goto end_playback;
  42839. }
  42840. /* If nRec is 0xffffffff, then this journal was created by a process
  42841. ** working in no-sync mode. This means that the rest of the journal
  42842. ** file consists of pages, there are no more journal headers. Compute
  42843. ** the value of nRec based on this assumption.
  42844. */
  42845. if( nRec==0xffffffff ){
  42846. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  42847. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  42848. }
  42849. /* If nRec is 0 and this rollback is of a transaction created by this
  42850. ** process and if this is the final header in the journal, then it means
  42851. ** that this part of the journal was being filled but has not yet been
  42852. ** synced to disk. Compute the number of pages based on the remaining
  42853. ** size of the file.
  42854. **
  42855. ** The third term of the test was added to fix ticket #2565.
  42856. ** When rolling back a hot journal, nRec==0 always means that the next
  42857. ** chunk of the journal contains zero pages to be rolled back. But
  42858. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  42859. ** the journal, it means that the journal might contain additional
  42860. ** pages that need to be rolled back and that the number of pages
  42861. ** should be computed based on the journal file size.
  42862. */
  42863. if( nRec==0 && !isHot &&
  42864. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  42865. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  42866. }
  42867. /* If this is the first header read from the journal, truncate the
  42868. ** database file back to its original size.
  42869. */
  42870. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  42871. rc = pager_truncate(pPager, mxPg);
  42872. if( rc!=SQLITE_OK ){
  42873. goto end_playback;
  42874. }
  42875. pPager->dbSize = mxPg;
  42876. }
  42877. /* Copy original pages out of the journal and back into the
  42878. ** database file and/or page cache.
  42879. */
  42880. for(u=0; u<nRec; u++){
  42881. if( needPagerReset ){
  42882. pager_reset(pPager);
  42883. needPagerReset = 0;
  42884. }
  42885. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  42886. if( rc==SQLITE_OK ){
  42887. nPlayback++;
  42888. }else{
  42889. if( rc==SQLITE_DONE ){
  42890. pPager->journalOff = szJ;
  42891. break;
  42892. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  42893. /* If the journal has been truncated, simply stop reading and
  42894. ** processing the journal. This might happen if the journal was
  42895. ** not completely written and synced prior to a crash. In that
  42896. ** case, the database should have never been written in the
  42897. ** first place so it is OK to simply abandon the rollback. */
  42898. rc = SQLITE_OK;
  42899. goto end_playback;
  42900. }else{
  42901. /* If we are unable to rollback, quit and return the error
  42902. ** code. This will cause the pager to enter the error state
  42903. ** so that no further harm will be done. Perhaps the next
  42904. ** process to come along will be able to rollback the database.
  42905. */
  42906. goto end_playback;
  42907. }
  42908. }
  42909. }
  42910. }
  42911. /*NOTREACHED*/
  42912. assert( 0 );
  42913. end_playback:
  42914. /* Following a rollback, the database file should be back in its original
  42915. ** state prior to the start of the transaction, so invoke the
  42916. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  42917. ** assertion that the transaction counter was modified.
  42918. */
  42919. #ifdef SQLITE_DEBUG
  42920. if( pPager->fd->pMethods ){
  42921. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  42922. }
  42923. #endif
  42924. /* If this playback is happening automatically as a result of an IO or
  42925. ** malloc error that occurred after the change-counter was updated but
  42926. ** before the transaction was committed, then the change-counter
  42927. ** modification may just have been reverted. If this happens in exclusive
  42928. ** mode, then subsequent transactions performed by the connection will not
  42929. ** update the change-counter at all. This may lead to cache inconsistency
  42930. ** problems for other processes at some point in the future. So, just
  42931. ** in case this has happened, clear the changeCountDone flag now.
  42932. */
  42933. pPager->changeCountDone = pPager->tempFile;
  42934. if( rc==SQLITE_OK ){
  42935. zMaster = pPager->pTmpSpace;
  42936. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  42937. testcase( rc!=SQLITE_OK );
  42938. }
  42939. if( rc==SQLITE_OK
  42940. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42941. ){
  42942. rc = sqlite3PagerSync(pPager, 0);
  42943. }
  42944. if( rc==SQLITE_OK ){
  42945. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  42946. testcase( rc!=SQLITE_OK );
  42947. }
  42948. if( rc==SQLITE_OK && zMaster[0] && res ){
  42949. /* If there was a master journal and this routine will return success,
  42950. ** see if it is possible to delete the master journal.
  42951. */
  42952. rc = pager_delmaster(pPager, zMaster);
  42953. testcase( rc!=SQLITE_OK );
  42954. }
  42955. if( isHot && nPlayback ){
  42956. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  42957. nPlayback, pPager->zJournal);
  42958. }
  42959. /* The Pager.sectorSize variable may have been updated while rolling
  42960. ** back a journal created by a process with a different sector size
  42961. ** value. Reset it to the correct value for this process.
  42962. */
  42963. setSectorSize(pPager);
  42964. return rc;
  42965. }
  42966. /*
  42967. ** Read the content for page pPg out of the database file and into
  42968. ** pPg->pData. A shared lock or greater must be held on the database
  42969. ** file before this function is called.
  42970. **
  42971. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  42972. ** the value read from the database file.
  42973. **
  42974. ** If an IO error occurs, then the IO error is returned to the caller.
  42975. ** Otherwise, SQLITE_OK is returned.
  42976. */
  42977. static int readDbPage(PgHdr *pPg, u32 iFrame){
  42978. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  42979. Pgno pgno = pPg->pgno; /* Page number to read */
  42980. int rc = SQLITE_OK; /* Return code */
  42981. int pgsz = pPager->pageSize; /* Number of bytes to read */
  42982. assert( pPager->eState>=PAGER_READER && !MEMDB );
  42983. assert( isOpen(pPager->fd) );
  42984. #ifndef SQLITE_OMIT_WAL
  42985. if( iFrame ){
  42986. /* Try to pull the page from the write-ahead log. */
  42987. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  42988. }else
  42989. #endif
  42990. {
  42991. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  42992. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  42993. if( rc==SQLITE_IOERR_SHORT_READ ){
  42994. rc = SQLITE_OK;
  42995. }
  42996. }
  42997. if( pgno==1 ){
  42998. if( rc ){
  42999. /* If the read is unsuccessful, set the dbFileVers[] to something
  43000. ** that will never be a valid file version. dbFileVers[] is a copy
  43001. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  43002. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  43003. ** should be page numbers which are never 0xffffffff. So filling
  43004. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  43005. **
  43006. ** For an encrypted database, the situation is more complex: bytes
  43007. ** 24..39 of the database are white noise. But the probability of
  43008. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  43009. ** we should still be ok.
  43010. */
  43011. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  43012. }else{
  43013. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  43014. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  43015. }
  43016. }
  43017. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  43018. PAGER_INCR(sqlite3_pager_readdb_count);
  43019. PAGER_INCR(pPager->nRead);
  43020. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  43021. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  43022. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  43023. return rc;
  43024. }
  43025. /*
  43026. ** Update the value of the change-counter at offsets 24 and 92 in
  43027. ** the header and the sqlite version number at offset 96.
  43028. **
  43029. ** This is an unconditional update. See also the pager_incr_changecounter()
  43030. ** routine which only updates the change-counter if the update is actually
  43031. ** needed, as determined by the pPager->changeCountDone state variable.
  43032. */
  43033. static void pager_write_changecounter(PgHdr *pPg){
  43034. u32 change_counter;
  43035. /* Increment the value just read and write it back to byte 24. */
  43036. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  43037. put32bits(((char*)pPg->pData)+24, change_counter);
  43038. /* Also store the SQLite version number in bytes 96..99 and in
  43039. ** bytes 92..95 store the change counter for which the version number
  43040. ** is valid. */
  43041. put32bits(((char*)pPg->pData)+92, change_counter);
  43042. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  43043. }
  43044. #ifndef SQLITE_OMIT_WAL
  43045. /*
  43046. ** This function is invoked once for each page that has already been
  43047. ** written into the log file when a WAL transaction is rolled back.
  43048. ** Parameter iPg is the page number of said page. The pCtx argument
  43049. ** is actually a pointer to the Pager structure.
  43050. **
  43051. ** If page iPg is present in the cache, and has no outstanding references,
  43052. ** it is discarded. Otherwise, if there are one or more outstanding
  43053. ** references, the page content is reloaded from the database. If the
  43054. ** attempt to reload content from the database is required and fails,
  43055. ** return an SQLite error code. Otherwise, SQLITE_OK.
  43056. */
  43057. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  43058. int rc = SQLITE_OK;
  43059. Pager *pPager = (Pager *)pCtx;
  43060. PgHdr *pPg;
  43061. assert( pagerUseWal(pPager) );
  43062. pPg = sqlite3PagerLookup(pPager, iPg);
  43063. if( pPg ){
  43064. if( sqlite3PcachePageRefcount(pPg)==1 ){
  43065. sqlite3PcacheDrop(pPg);
  43066. }else{
  43067. u32 iFrame = 0;
  43068. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  43069. if( rc==SQLITE_OK ){
  43070. rc = readDbPage(pPg, iFrame);
  43071. }
  43072. if( rc==SQLITE_OK ){
  43073. pPager->xReiniter(pPg);
  43074. }
  43075. sqlite3PagerUnrefNotNull(pPg);
  43076. }
  43077. }
  43078. /* Normally, if a transaction is rolled back, any backup processes are
  43079. ** updated as data is copied out of the rollback journal and into the
  43080. ** database. This is not generally possible with a WAL database, as
  43081. ** rollback involves simply truncating the log file. Therefore, if one
  43082. ** or more frames have already been written to the log (and therefore
  43083. ** also copied into the backup databases) as part of this transaction,
  43084. ** the backups must be restarted.
  43085. */
  43086. sqlite3BackupRestart(pPager->pBackup);
  43087. return rc;
  43088. }
  43089. /*
  43090. ** This function is called to rollback a transaction on a WAL database.
  43091. */
  43092. static int pagerRollbackWal(Pager *pPager){
  43093. int rc; /* Return Code */
  43094. PgHdr *pList; /* List of dirty pages to revert */
  43095. /* For all pages in the cache that are currently dirty or have already
  43096. ** been written (but not committed) to the log file, do one of the
  43097. ** following:
  43098. **
  43099. ** + Discard the cached page (if refcount==0), or
  43100. ** + Reload page content from the database (if refcount>0).
  43101. */
  43102. pPager->dbSize = pPager->dbOrigSize;
  43103. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  43104. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43105. while( pList && rc==SQLITE_OK ){
  43106. PgHdr *pNext = pList->pDirty;
  43107. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  43108. pList = pNext;
  43109. }
  43110. return rc;
  43111. }
  43112. /*
  43113. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  43114. ** the contents of the list of pages headed by pList (connected by pDirty),
  43115. ** this function notifies any active backup processes that the pages have
  43116. ** changed.
  43117. **
  43118. ** The list of pages passed into this routine is always sorted by page number.
  43119. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  43120. */
  43121. static int pagerWalFrames(
  43122. Pager *pPager, /* Pager object */
  43123. PgHdr *pList, /* List of frames to log */
  43124. Pgno nTruncate, /* Database size after this commit */
  43125. int isCommit /* True if this is a commit */
  43126. ){
  43127. int rc; /* Return code */
  43128. int nList; /* Number of pages in pList */
  43129. PgHdr *p; /* For looping over pages */
  43130. assert( pPager->pWal );
  43131. assert( pList );
  43132. #ifdef SQLITE_DEBUG
  43133. /* Verify that the page list is in accending order */
  43134. for(p=pList; p && p->pDirty; p=p->pDirty){
  43135. assert( p->pgno < p->pDirty->pgno );
  43136. }
  43137. #endif
  43138. assert( pList->pDirty==0 || isCommit );
  43139. if( isCommit ){
  43140. /* If a WAL transaction is being committed, there is no point in writing
  43141. ** any pages with page numbers greater than nTruncate into the WAL file.
  43142. ** They will never be read by any client. So remove them from the pDirty
  43143. ** list here. */
  43144. PgHdr **ppNext = &pList;
  43145. nList = 0;
  43146. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  43147. if( p->pgno<=nTruncate ){
  43148. ppNext = &p->pDirty;
  43149. nList++;
  43150. }
  43151. }
  43152. assert( pList );
  43153. }else{
  43154. nList = 1;
  43155. }
  43156. pPager->aStat[PAGER_STAT_WRITE] += nList;
  43157. if( pList->pgno==1 ) pager_write_changecounter(pList);
  43158. rc = sqlite3WalFrames(pPager->pWal,
  43159. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  43160. );
  43161. if( rc==SQLITE_OK && pPager->pBackup ){
  43162. for(p=pList; p; p=p->pDirty){
  43163. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  43164. }
  43165. }
  43166. #ifdef SQLITE_CHECK_PAGES
  43167. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43168. for(p=pList; p; p=p->pDirty){
  43169. pager_set_pagehash(p);
  43170. }
  43171. #endif
  43172. return rc;
  43173. }
  43174. /*
  43175. ** Begin a read transaction on the WAL.
  43176. **
  43177. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  43178. ** makes a snapshot of the database at the current point in time and preserves
  43179. ** that snapshot for use by the reader in spite of concurrently changes by
  43180. ** other writers or checkpointers.
  43181. */
  43182. static int pagerBeginReadTransaction(Pager *pPager){
  43183. int rc; /* Return code */
  43184. int changed = 0; /* True if cache must be reset */
  43185. assert( pagerUseWal(pPager) );
  43186. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  43187. /* sqlite3WalEndReadTransaction() was not called for the previous
  43188. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  43189. ** are in locking_mode=NORMAL and EndRead() was previously called,
  43190. ** the duplicate call is harmless.
  43191. */
  43192. sqlite3WalEndReadTransaction(pPager->pWal);
  43193. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  43194. if( rc!=SQLITE_OK || changed ){
  43195. pager_reset(pPager);
  43196. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  43197. }
  43198. return rc;
  43199. }
  43200. #endif
  43201. /*
  43202. ** This function is called as part of the transition from PAGER_OPEN
  43203. ** to PAGER_READER state to determine the size of the database file
  43204. ** in pages (assuming the page size currently stored in Pager.pageSize).
  43205. **
  43206. ** If no error occurs, SQLITE_OK is returned and the size of the database
  43207. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  43208. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  43209. */
  43210. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  43211. Pgno nPage; /* Value to return via *pnPage */
  43212. /* Query the WAL sub-system for the database size. The WalDbsize()
  43213. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  43214. ** if the database size is not available. The database size is not
  43215. ** available from the WAL sub-system if the log file is empty or
  43216. ** contains no valid committed transactions.
  43217. */
  43218. assert( pPager->eState==PAGER_OPEN );
  43219. assert( pPager->eLock>=SHARED_LOCK );
  43220. nPage = sqlite3WalDbsize(pPager->pWal);
  43221. /* If the number of pages in the database is not available from the
  43222. ** WAL sub-system, determine the page counte based on the size of
  43223. ** the database file. If the size of the database file is not an
  43224. ** integer multiple of the page-size, round up the result.
  43225. */
  43226. if( nPage==0 ){
  43227. i64 n = 0; /* Size of db file in bytes */
  43228. assert( isOpen(pPager->fd) || pPager->tempFile );
  43229. if( isOpen(pPager->fd) ){
  43230. int rc = sqlite3OsFileSize(pPager->fd, &n);
  43231. if( rc!=SQLITE_OK ){
  43232. return rc;
  43233. }
  43234. }
  43235. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  43236. }
  43237. /* If the current number of pages in the file is greater than the
  43238. ** configured maximum pager number, increase the allowed limit so
  43239. ** that the file can be read.
  43240. */
  43241. if( nPage>pPager->mxPgno ){
  43242. pPager->mxPgno = (Pgno)nPage;
  43243. }
  43244. *pnPage = nPage;
  43245. return SQLITE_OK;
  43246. }
  43247. #ifndef SQLITE_OMIT_WAL
  43248. /*
  43249. ** Check if the *-wal file that corresponds to the database opened by pPager
  43250. ** exists if the database is not empy, or verify that the *-wal file does
  43251. ** not exist (by deleting it) if the database file is empty.
  43252. **
  43253. ** If the database is not empty and the *-wal file exists, open the pager
  43254. ** in WAL mode. If the database is empty or if no *-wal file exists and
  43255. ** if no error occurs, make sure Pager.journalMode is not set to
  43256. ** PAGER_JOURNALMODE_WAL.
  43257. **
  43258. ** Return SQLITE_OK or an error code.
  43259. **
  43260. ** The caller must hold a SHARED lock on the database file to call this
  43261. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  43262. ** a WAL on a none-empty database, this ensures there is no race condition
  43263. ** between the xAccess() below and an xDelete() being executed by some
  43264. ** other connection.
  43265. */
  43266. static int pagerOpenWalIfPresent(Pager *pPager){
  43267. int rc = SQLITE_OK;
  43268. assert( pPager->eState==PAGER_OPEN );
  43269. assert( pPager->eLock>=SHARED_LOCK );
  43270. if( !pPager->tempFile ){
  43271. int isWal; /* True if WAL file exists */
  43272. Pgno nPage; /* Size of the database file */
  43273. rc = pagerPagecount(pPager, &nPage);
  43274. if( rc ) return rc;
  43275. if( nPage==0 ){
  43276. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  43277. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  43278. isWal = 0;
  43279. }else{
  43280. rc = sqlite3OsAccess(
  43281. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  43282. );
  43283. }
  43284. if( rc==SQLITE_OK ){
  43285. if( isWal ){
  43286. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  43287. rc = sqlite3PagerOpenWal(pPager, 0);
  43288. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  43289. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  43290. }
  43291. }
  43292. }
  43293. return rc;
  43294. }
  43295. #endif
  43296. /*
  43297. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  43298. ** the entire master journal file. The case pSavepoint==NULL occurs when
  43299. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  43300. ** savepoint.
  43301. **
  43302. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  43303. ** being rolled back), then the rollback consists of up to three stages,
  43304. ** performed in the order specified:
  43305. **
  43306. ** * Pages are played back from the main journal starting at byte
  43307. ** offset PagerSavepoint.iOffset and continuing to
  43308. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  43309. ** file if PagerSavepoint.iHdrOffset is zero.
  43310. **
  43311. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  43312. ** back starting from the journal header immediately following
  43313. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  43314. **
  43315. ** * Pages are then played back from the sub-journal file, starting
  43316. ** with the PagerSavepoint.iSubRec and continuing to the end of
  43317. ** the journal file.
  43318. **
  43319. ** Throughout the rollback process, each time a page is rolled back, the
  43320. ** corresponding bit is set in a bitvec structure (variable pDone in the
  43321. ** implementation below). This is used to ensure that a page is only
  43322. ** rolled back the first time it is encountered in either journal.
  43323. **
  43324. ** If pSavepoint is NULL, then pages are only played back from the main
  43325. ** journal file. There is no need for a bitvec in this case.
  43326. **
  43327. ** In either case, before playback commences the Pager.dbSize variable
  43328. ** is reset to the value that it held at the start of the savepoint
  43329. ** (or transaction). No page with a page-number greater than this value
  43330. ** is played back. If one is encountered it is simply skipped.
  43331. */
  43332. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  43333. i64 szJ; /* Effective size of the main journal */
  43334. i64 iHdrOff; /* End of first segment of main-journal records */
  43335. int rc = SQLITE_OK; /* Return code */
  43336. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  43337. assert( pPager->eState!=PAGER_ERROR );
  43338. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  43339. /* Allocate a bitvec to use to store the set of pages rolled back */
  43340. if( pSavepoint ){
  43341. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  43342. if( !pDone ){
  43343. return SQLITE_NOMEM;
  43344. }
  43345. }
  43346. /* Set the database size back to the value it was before the savepoint
  43347. ** being reverted was opened.
  43348. */
  43349. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  43350. pPager->changeCountDone = pPager->tempFile;
  43351. if( !pSavepoint && pagerUseWal(pPager) ){
  43352. return pagerRollbackWal(pPager);
  43353. }
  43354. /* Use pPager->journalOff as the effective size of the main rollback
  43355. ** journal. The actual file might be larger than this in
  43356. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  43357. ** past pPager->journalOff is off-limits to us.
  43358. */
  43359. szJ = pPager->journalOff;
  43360. assert( pagerUseWal(pPager)==0 || szJ==0 );
  43361. /* Begin by rolling back records from the main journal starting at
  43362. ** PagerSavepoint.iOffset and continuing to the next journal header.
  43363. ** There might be records in the main journal that have a page number
  43364. ** greater than the current database size (pPager->dbSize) but those
  43365. ** will be skipped automatically. Pages are added to pDone as they
  43366. ** are played back.
  43367. */
  43368. if( pSavepoint && !pagerUseWal(pPager) ){
  43369. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  43370. pPager->journalOff = pSavepoint->iOffset;
  43371. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  43372. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  43373. }
  43374. assert( rc!=SQLITE_DONE );
  43375. }else{
  43376. pPager->journalOff = 0;
  43377. }
  43378. /* Continue rolling back records out of the main journal starting at
  43379. ** the first journal header seen and continuing until the effective end
  43380. ** of the main journal file. Continue to skip out-of-range pages and
  43381. ** continue adding pages rolled back to pDone.
  43382. */
  43383. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  43384. u32 ii; /* Loop counter */
  43385. u32 nJRec = 0; /* Number of Journal Records */
  43386. u32 dummy;
  43387. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  43388. assert( rc!=SQLITE_DONE );
  43389. /*
  43390. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  43391. ** test is related to ticket #2565. See the discussion in the
  43392. ** pager_playback() function for additional information.
  43393. */
  43394. if( nJRec==0
  43395. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  43396. ){
  43397. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  43398. }
  43399. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  43400. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  43401. }
  43402. assert( rc!=SQLITE_DONE );
  43403. }
  43404. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  43405. /* Finally, rollback pages from the sub-journal. Page that were
  43406. ** previously rolled back out of the main journal (and are hence in pDone)
  43407. ** will be skipped. Out-of-range pages are also skipped.
  43408. */
  43409. if( pSavepoint ){
  43410. u32 ii; /* Loop counter */
  43411. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  43412. if( pagerUseWal(pPager) ){
  43413. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  43414. }
  43415. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  43416. assert( offset==(i64)ii*(4+pPager->pageSize) );
  43417. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  43418. }
  43419. assert( rc!=SQLITE_DONE );
  43420. }
  43421. sqlite3BitvecDestroy(pDone);
  43422. if( rc==SQLITE_OK ){
  43423. pPager->journalOff = szJ;
  43424. }
  43425. return rc;
  43426. }
  43427. /*
  43428. ** Change the maximum number of in-memory pages that are allowed.
  43429. */
  43430. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  43431. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  43432. }
  43433. /*
  43434. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  43435. */
  43436. static void pagerFixMaplimit(Pager *pPager){
  43437. #if SQLITE_MAX_MMAP_SIZE>0
  43438. sqlite3_file *fd = pPager->fd;
  43439. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  43440. sqlite3_int64 sz;
  43441. sz = pPager->szMmap;
  43442. pPager->bUseFetch = (sz>0);
  43443. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  43444. }
  43445. #endif
  43446. }
  43447. /*
  43448. ** Change the maximum size of any memory mapping made of the database file.
  43449. */
  43450. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  43451. pPager->szMmap = szMmap;
  43452. pagerFixMaplimit(pPager);
  43453. }
  43454. /*
  43455. ** Free as much memory as possible from the pager.
  43456. */
  43457. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  43458. sqlite3PcacheShrink(pPager->pPCache);
  43459. }
  43460. /*
  43461. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  43462. **
  43463. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  43464. ** of the database to damage due to OS crashes or power failures by
  43465. ** changing the number of syncs()s when writing the journals.
  43466. ** There are three levels:
  43467. **
  43468. ** OFF sqlite3OsSync() is never called. This is the default
  43469. ** for temporary and transient files.
  43470. **
  43471. ** NORMAL The journal is synced once before writes begin on the
  43472. ** database. This is normally adequate protection, but
  43473. ** it is theoretically possible, though very unlikely,
  43474. ** that an inopertune power failure could leave the journal
  43475. ** in a state which would cause damage to the database
  43476. ** when it is rolled back.
  43477. **
  43478. ** FULL The journal is synced twice before writes begin on the
  43479. ** database (with some additional information - the nRec field
  43480. ** of the journal header - being written in between the two
  43481. ** syncs). If we assume that writing a
  43482. ** single disk sector is atomic, then this mode provides
  43483. ** assurance that the journal will not be corrupted to the
  43484. ** point of causing damage to the database during rollback.
  43485. **
  43486. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  43487. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  43488. ** prior to the start of checkpoint and that the database file is synced
  43489. ** at the conclusion of the checkpoint if the entire content of the WAL
  43490. ** was written back into the database. But no sync operations occur for
  43491. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  43492. ** file is synced following each commit operation, in addition to the
  43493. ** syncs associated with NORMAL.
  43494. **
  43495. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  43496. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  43497. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  43498. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  43499. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  43500. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  43501. ** the xSync primitive is called and is relevant to all platforms.
  43502. **
  43503. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  43504. ** and FULL=3.
  43505. */
  43506. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  43507. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  43508. Pager *pPager, /* The pager to set safety level for */
  43509. unsigned pgFlags /* Various flags */
  43510. ){
  43511. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  43512. assert( level>=1 && level<=3 );
  43513. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  43514. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  43515. if( pPager->noSync ){
  43516. pPager->syncFlags = 0;
  43517. pPager->ckptSyncFlags = 0;
  43518. }else if( pgFlags & PAGER_FULLFSYNC ){
  43519. pPager->syncFlags = SQLITE_SYNC_FULL;
  43520. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  43521. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  43522. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43523. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  43524. }else{
  43525. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43526. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  43527. }
  43528. pPager->walSyncFlags = pPager->syncFlags;
  43529. if( pPager->fullSync ){
  43530. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  43531. }
  43532. if( pgFlags & PAGER_CACHESPILL ){
  43533. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  43534. }else{
  43535. pPager->doNotSpill |= SPILLFLAG_OFF;
  43536. }
  43537. }
  43538. #endif
  43539. /*
  43540. ** The following global variable is incremented whenever the library
  43541. ** attempts to open a temporary file. This information is used for
  43542. ** testing and analysis only.
  43543. */
  43544. #ifdef SQLITE_TEST
  43545. SQLITE_API int sqlite3_opentemp_count = 0;
  43546. #endif
  43547. /*
  43548. ** Open a temporary file.
  43549. **
  43550. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  43551. ** or some other error code if we fail. The OS will automatically
  43552. ** delete the temporary file when it is closed.
  43553. **
  43554. ** The flags passed to the VFS layer xOpen() call are those specified
  43555. ** by parameter vfsFlags ORed with the following:
  43556. **
  43557. ** SQLITE_OPEN_READWRITE
  43558. ** SQLITE_OPEN_CREATE
  43559. ** SQLITE_OPEN_EXCLUSIVE
  43560. ** SQLITE_OPEN_DELETEONCLOSE
  43561. */
  43562. static int pagerOpentemp(
  43563. Pager *pPager, /* The pager object */
  43564. sqlite3_file *pFile, /* Write the file descriptor here */
  43565. int vfsFlags /* Flags passed through to the VFS */
  43566. ){
  43567. int rc; /* Return code */
  43568. #ifdef SQLITE_TEST
  43569. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  43570. #endif
  43571. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  43572. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  43573. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  43574. assert( rc!=SQLITE_OK || isOpen(pFile) );
  43575. return rc;
  43576. }
  43577. /*
  43578. ** Set the busy handler function.
  43579. **
  43580. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  43581. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  43582. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  43583. ** lock. It does *not* invoke the busy handler when upgrading from
  43584. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  43585. ** (which occurs during hot-journal rollback). Summary:
  43586. **
  43587. ** Transition | Invokes xBusyHandler
  43588. ** --------------------------------------------------------
  43589. ** NO_LOCK -> SHARED_LOCK | Yes
  43590. ** SHARED_LOCK -> RESERVED_LOCK | No
  43591. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  43592. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  43593. **
  43594. ** If the busy-handler callback returns non-zero, the lock is
  43595. ** retried. If it returns zero, then the SQLITE_BUSY error is
  43596. ** returned to the caller of the pager API function.
  43597. */
  43598. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  43599. Pager *pPager, /* Pager object */
  43600. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  43601. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  43602. ){
  43603. pPager->xBusyHandler = xBusyHandler;
  43604. pPager->pBusyHandlerArg = pBusyHandlerArg;
  43605. if( isOpen(pPager->fd) ){
  43606. void **ap = (void **)&pPager->xBusyHandler;
  43607. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  43608. assert( ap[1]==pBusyHandlerArg );
  43609. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  43610. }
  43611. }
  43612. /*
  43613. ** Change the page size used by the Pager object. The new page size
  43614. ** is passed in *pPageSize.
  43615. **
  43616. ** If the pager is in the error state when this function is called, it
  43617. ** is a no-op. The value returned is the error state error code (i.e.
  43618. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  43619. **
  43620. ** Otherwise, if all of the following are true:
  43621. **
  43622. ** * the new page size (value of *pPageSize) is valid (a power
  43623. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  43624. **
  43625. ** * there are no outstanding page references, and
  43626. **
  43627. ** * the database is either not an in-memory database or it is
  43628. ** an in-memory database that currently consists of zero pages.
  43629. **
  43630. ** then the pager object page size is set to *pPageSize.
  43631. **
  43632. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  43633. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  43634. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  43635. ** In all other cases, SQLITE_OK is returned.
  43636. **
  43637. ** If the page size is not changed, either because one of the enumerated
  43638. ** conditions above is not true, the pager was in error state when this
  43639. ** function was called, or because the memory allocation attempt failed,
  43640. ** then *pPageSize is set to the old, retained page size before returning.
  43641. */
  43642. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  43643. int rc = SQLITE_OK;
  43644. /* It is not possible to do a full assert_pager_state() here, as this
  43645. ** function may be called from within PagerOpen(), before the state
  43646. ** of the Pager object is internally consistent.
  43647. **
  43648. ** At one point this function returned an error if the pager was in
  43649. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  43650. ** there is at least one outstanding page reference, this function
  43651. ** is a no-op for that case anyhow.
  43652. */
  43653. u32 pageSize = *pPageSize;
  43654. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  43655. if( (pPager->memDb==0 || pPager->dbSize==0)
  43656. && sqlite3PcacheRefCount(pPager->pPCache)==0
  43657. && pageSize && pageSize!=(u32)pPager->pageSize
  43658. ){
  43659. char *pNew = NULL; /* New temp space */
  43660. i64 nByte = 0;
  43661. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  43662. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  43663. }
  43664. if( rc==SQLITE_OK ){
  43665. pNew = (char *)sqlite3PageMalloc(pageSize);
  43666. if( !pNew ) rc = SQLITE_NOMEM;
  43667. }
  43668. if( rc==SQLITE_OK ){
  43669. pager_reset(pPager);
  43670. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  43671. }
  43672. if( rc==SQLITE_OK ){
  43673. sqlite3PageFree(pPager->pTmpSpace);
  43674. pPager->pTmpSpace = pNew;
  43675. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  43676. pPager->pageSize = pageSize;
  43677. }else{
  43678. sqlite3PageFree(pNew);
  43679. }
  43680. }
  43681. *pPageSize = pPager->pageSize;
  43682. if( rc==SQLITE_OK ){
  43683. if( nReserve<0 ) nReserve = pPager->nReserve;
  43684. assert( nReserve>=0 && nReserve<1000 );
  43685. pPager->nReserve = (i16)nReserve;
  43686. pagerReportSize(pPager);
  43687. pagerFixMaplimit(pPager);
  43688. }
  43689. return rc;
  43690. }
  43691. /*
  43692. ** Return a pointer to the "temporary page" buffer held internally
  43693. ** by the pager. This is a buffer that is big enough to hold the
  43694. ** entire content of a database page. This buffer is used internally
  43695. ** during rollback and will be overwritten whenever a rollback
  43696. ** occurs. But other modules are free to use it too, as long as
  43697. ** no rollbacks are happening.
  43698. */
  43699. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  43700. return pPager->pTmpSpace;
  43701. }
  43702. /*
  43703. ** Attempt to set the maximum database page count if mxPage is positive.
  43704. ** Make no changes if mxPage is zero or negative. And never reduce the
  43705. ** maximum page count below the current size of the database.
  43706. **
  43707. ** Regardless of mxPage, return the current maximum page count.
  43708. */
  43709. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  43710. if( mxPage>0 ){
  43711. pPager->mxPgno = mxPage;
  43712. }
  43713. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  43714. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  43715. return pPager->mxPgno;
  43716. }
  43717. /*
  43718. ** The following set of routines are used to disable the simulated
  43719. ** I/O error mechanism. These routines are used to avoid simulated
  43720. ** errors in places where we do not care about errors.
  43721. **
  43722. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  43723. ** and generate no code.
  43724. */
  43725. #ifdef SQLITE_TEST
  43726. SQLITE_API extern int sqlite3_io_error_pending;
  43727. SQLITE_API extern int sqlite3_io_error_hit;
  43728. static int saved_cnt;
  43729. void disable_simulated_io_errors(void){
  43730. saved_cnt = sqlite3_io_error_pending;
  43731. sqlite3_io_error_pending = -1;
  43732. }
  43733. void enable_simulated_io_errors(void){
  43734. sqlite3_io_error_pending = saved_cnt;
  43735. }
  43736. #else
  43737. # define disable_simulated_io_errors()
  43738. # define enable_simulated_io_errors()
  43739. #endif
  43740. /*
  43741. ** Read the first N bytes from the beginning of the file into memory
  43742. ** that pDest points to.
  43743. **
  43744. ** If the pager was opened on a transient file (zFilename==""), or
  43745. ** opened on a file less than N bytes in size, the output buffer is
  43746. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  43747. ** function is used to read database headers, and a new transient or
  43748. ** zero sized database has a header than consists entirely of zeroes.
  43749. **
  43750. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  43751. ** the error code is returned to the caller and the contents of the
  43752. ** output buffer undefined.
  43753. */
  43754. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  43755. int rc = SQLITE_OK;
  43756. memset(pDest, 0, N);
  43757. assert( isOpen(pPager->fd) || pPager->tempFile );
  43758. /* This routine is only called by btree immediately after creating
  43759. ** the Pager object. There has not been an opportunity to transition
  43760. ** to WAL mode yet.
  43761. */
  43762. assert( !pagerUseWal(pPager) );
  43763. if( isOpen(pPager->fd) ){
  43764. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  43765. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  43766. if( rc==SQLITE_IOERR_SHORT_READ ){
  43767. rc = SQLITE_OK;
  43768. }
  43769. }
  43770. return rc;
  43771. }
  43772. /*
  43773. ** This function may only be called when a read-transaction is open on
  43774. ** the pager. It returns the total number of pages in the database.
  43775. **
  43776. ** However, if the file is between 1 and <page-size> bytes in size, then
  43777. ** this is considered a 1 page file.
  43778. */
  43779. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  43780. assert( pPager->eState>=PAGER_READER );
  43781. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  43782. *pnPage = (int)pPager->dbSize;
  43783. }
  43784. /*
  43785. ** Try to obtain a lock of type locktype on the database file. If
  43786. ** a similar or greater lock is already held, this function is a no-op
  43787. ** (returning SQLITE_OK immediately).
  43788. **
  43789. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  43790. ** the busy callback if the lock is currently not available. Repeat
  43791. ** until the busy callback returns false or until the attempt to
  43792. ** obtain the lock succeeds.
  43793. **
  43794. ** Return SQLITE_OK on success and an error code if we cannot obtain
  43795. ** the lock. If the lock is obtained successfully, set the Pager.state
  43796. ** variable to locktype before returning.
  43797. */
  43798. static int pager_wait_on_lock(Pager *pPager, int locktype){
  43799. int rc; /* Return code */
  43800. /* Check that this is either a no-op (because the requested lock is
  43801. ** already held), or one of the transitions that the busy-handler
  43802. ** may be invoked during, according to the comment above
  43803. ** sqlite3PagerSetBusyhandler().
  43804. */
  43805. assert( (pPager->eLock>=locktype)
  43806. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  43807. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  43808. );
  43809. do {
  43810. rc = pagerLockDb(pPager, locktype);
  43811. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  43812. return rc;
  43813. }
  43814. /*
  43815. ** Function assertTruncateConstraint(pPager) checks that one of the
  43816. ** following is true for all dirty pages currently in the page-cache:
  43817. **
  43818. ** a) The page number is less than or equal to the size of the
  43819. ** current database image, in pages, OR
  43820. **
  43821. ** b) if the page content were written at this time, it would not
  43822. ** be necessary to write the current content out to the sub-journal
  43823. ** (as determined by function subjRequiresPage()).
  43824. **
  43825. ** If the condition asserted by this function were not true, and the
  43826. ** dirty page were to be discarded from the cache via the pagerStress()
  43827. ** routine, pagerStress() would not write the current page content to
  43828. ** the database file. If a savepoint transaction were rolled back after
  43829. ** this happened, the correct behavior would be to restore the current
  43830. ** content of the page. However, since this content is not present in either
  43831. ** the database file or the portion of the rollback journal and
  43832. ** sub-journal rolled back the content could not be restored and the
  43833. ** database image would become corrupt. It is therefore fortunate that
  43834. ** this circumstance cannot arise.
  43835. */
  43836. #if defined(SQLITE_DEBUG)
  43837. static void assertTruncateConstraintCb(PgHdr *pPg){
  43838. assert( pPg->flags&PGHDR_DIRTY );
  43839. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  43840. }
  43841. static void assertTruncateConstraint(Pager *pPager){
  43842. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  43843. }
  43844. #else
  43845. # define assertTruncateConstraint(pPager)
  43846. #endif
  43847. /*
  43848. ** Truncate the in-memory database file image to nPage pages. This
  43849. ** function does not actually modify the database file on disk. It
  43850. ** just sets the internal state of the pager object so that the
  43851. ** truncation will be done when the current transaction is committed.
  43852. **
  43853. ** This function is only called right before committing a transaction.
  43854. ** Once this function has been called, the transaction must either be
  43855. ** rolled back or committed. It is not safe to call this function and
  43856. ** then continue writing to the database.
  43857. */
  43858. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  43859. assert( pPager->dbSize>=nPage );
  43860. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  43861. pPager->dbSize = nPage;
  43862. /* At one point the code here called assertTruncateConstraint() to
  43863. ** ensure that all pages being truncated away by this operation are,
  43864. ** if one or more savepoints are open, present in the savepoint
  43865. ** journal so that they can be restored if the savepoint is rolled
  43866. ** back. This is no longer necessary as this function is now only
  43867. ** called right before committing a transaction. So although the
  43868. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  43869. ** they cannot be rolled back. So the assertTruncateConstraint() call
  43870. ** is no longer correct. */
  43871. }
  43872. /*
  43873. ** This function is called before attempting a hot-journal rollback. It
  43874. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  43875. ** size of the journal file so that the pager_playback() routine knows
  43876. ** that the entire journal file has been synced.
  43877. **
  43878. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  43879. ** that if a power-failure occurs during the rollback, the process that
  43880. ** attempts rollback following system recovery sees the same journal
  43881. ** content as this process.
  43882. **
  43883. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  43884. ** an SQLite error code.
  43885. */
  43886. static int pagerSyncHotJournal(Pager *pPager){
  43887. int rc = SQLITE_OK;
  43888. if( !pPager->noSync ){
  43889. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  43890. }
  43891. if( rc==SQLITE_OK ){
  43892. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  43893. }
  43894. return rc;
  43895. }
  43896. /*
  43897. ** Obtain a reference to a memory mapped page object for page number pgno.
  43898. ** The new object will use the pointer pData, obtained from xFetch().
  43899. ** If successful, set *ppPage to point to the new page reference
  43900. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  43901. ** *ppPage to zero.
  43902. **
  43903. ** Page references obtained by calling this function should be released
  43904. ** by calling pagerReleaseMapPage().
  43905. */
  43906. static int pagerAcquireMapPage(
  43907. Pager *pPager, /* Pager object */
  43908. Pgno pgno, /* Page number */
  43909. void *pData, /* xFetch()'d data for this page */
  43910. PgHdr **ppPage /* OUT: Acquired page object */
  43911. ){
  43912. PgHdr *p; /* Memory mapped page to return */
  43913. if( pPager->pMmapFreelist ){
  43914. *ppPage = p = pPager->pMmapFreelist;
  43915. pPager->pMmapFreelist = p->pDirty;
  43916. p->pDirty = 0;
  43917. memset(p->pExtra, 0, pPager->nExtra);
  43918. }else{
  43919. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  43920. if( p==0 ){
  43921. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  43922. return SQLITE_NOMEM;
  43923. }
  43924. p->pExtra = (void *)&p[1];
  43925. p->flags = PGHDR_MMAP;
  43926. p->nRef = 1;
  43927. p->pPager = pPager;
  43928. }
  43929. assert( p->pExtra==(void *)&p[1] );
  43930. assert( p->pPage==0 );
  43931. assert( p->flags==PGHDR_MMAP );
  43932. assert( p->pPager==pPager );
  43933. assert( p->nRef==1 );
  43934. p->pgno = pgno;
  43935. p->pData = pData;
  43936. pPager->nMmapOut++;
  43937. return SQLITE_OK;
  43938. }
  43939. /*
  43940. ** Release a reference to page pPg. pPg must have been returned by an
  43941. ** earlier call to pagerAcquireMapPage().
  43942. */
  43943. static void pagerReleaseMapPage(PgHdr *pPg){
  43944. Pager *pPager = pPg->pPager;
  43945. pPager->nMmapOut--;
  43946. pPg->pDirty = pPager->pMmapFreelist;
  43947. pPager->pMmapFreelist = pPg;
  43948. assert( pPager->fd->pMethods->iVersion>=3 );
  43949. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  43950. }
  43951. /*
  43952. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  43953. */
  43954. static void pagerFreeMapHdrs(Pager *pPager){
  43955. PgHdr *p;
  43956. PgHdr *pNext;
  43957. for(p=pPager->pMmapFreelist; p; p=pNext){
  43958. pNext = p->pDirty;
  43959. sqlite3_free(p);
  43960. }
  43961. }
  43962. /*
  43963. ** Shutdown the page cache. Free all memory and close all files.
  43964. **
  43965. ** If a transaction was in progress when this routine is called, that
  43966. ** transaction is rolled back. All outstanding pages are invalidated
  43967. ** and their memory is freed. Any attempt to use a page associated
  43968. ** with this page cache after this function returns will likely
  43969. ** result in a coredump.
  43970. **
  43971. ** This function always succeeds. If a transaction is active an attempt
  43972. ** is made to roll it back. If an error occurs during the rollback
  43973. ** a hot journal may be left in the filesystem but no error is returned
  43974. ** to the caller.
  43975. */
  43976. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  43977. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  43978. assert( assert_pager_state(pPager) );
  43979. disable_simulated_io_errors();
  43980. sqlite3BeginBenignMalloc();
  43981. pagerFreeMapHdrs(pPager);
  43982. /* pPager->errCode = 0; */
  43983. pPager->exclusiveMode = 0;
  43984. #ifndef SQLITE_OMIT_WAL
  43985. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  43986. pPager->pWal = 0;
  43987. #endif
  43988. pager_reset(pPager);
  43989. if( MEMDB ){
  43990. pager_unlock(pPager);
  43991. }else{
  43992. /* If it is open, sync the journal file before calling UnlockAndRollback.
  43993. ** If this is not done, then an unsynced portion of the open journal
  43994. ** file may be played back into the database. If a power failure occurs
  43995. ** while this is happening, the database could become corrupt.
  43996. **
  43997. ** If an error occurs while trying to sync the journal, shift the pager
  43998. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  43999. ** database and close the journal file without attempting to roll it
  44000. ** back or finalize it. The next database user will have to do hot-journal
  44001. ** rollback before accessing the database file.
  44002. */
  44003. if( isOpen(pPager->jfd) ){
  44004. pager_error(pPager, pagerSyncHotJournal(pPager));
  44005. }
  44006. pagerUnlockAndRollback(pPager);
  44007. }
  44008. sqlite3EndBenignMalloc();
  44009. enable_simulated_io_errors();
  44010. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  44011. IOTRACE(("CLOSE %p\n", pPager))
  44012. sqlite3OsClose(pPager->jfd);
  44013. sqlite3OsClose(pPager->fd);
  44014. sqlite3PageFree(pTmp);
  44015. sqlite3PcacheClose(pPager->pPCache);
  44016. #ifdef SQLITE_HAS_CODEC
  44017. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  44018. #endif
  44019. assert( !pPager->aSavepoint && !pPager->pInJournal );
  44020. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  44021. sqlite3_free(pPager);
  44022. return SQLITE_OK;
  44023. }
  44024. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  44025. /*
  44026. ** Return the page number for page pPg.
  44027. */
  44028. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  44029. return pPg->pgno;
  44030. }
  44031. #endif
  44032. /*
  44033. ** Increment the reference count for page pPg.
  44034. */
  44035. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  44036. sqlite3PcacheRef(pPg);
  44037. }
  44038. /*
  44039. ** Sync the journal. In other words, make sure all the pages that have
  44040. ** been written to the journal have actually reached the surface of the
  44041. ** disk and can be restored in the event of a hot-journal rollback.
  44042. **
  44043. ** If the Pager.noSync flag is set, then this function is a no-op.
  44044. ** Otherwise, the actions required depend on the journal-mode and the
  44045. ** device characteristics of the file-system, as follows:
  44046. **
  44047. ** * If the journal file is an in-memory journal file, no action need
  44048. ** be taken.
  44049. **
  44050. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  44051. ** then the nRec field of the most recently written journal header
  44052. ** is updated to contain the number of journal records that have
  44053. ** been written following it. If the pager is operating in full-sync
  44054. ** mode, then the journal file is synced before this field is updated.
  44055. **
  44056. ** * If the device does not support the SEQUENTIAL property, then
  44057. ** journal file is synced.
  44058. **
  44059. ** Or, in pseudo-code:
  44060. **
  44061. ** if( NOT <in-memory journal> ){
  44062. ** if( NOT SAFE_APPEND ){
  44063. ** if( <full-sync mode> ) xSync(<journal file>);
  44064. ** <update nRec field>
  44065. ** }
  44066. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  44067. ** }
  44068. **
  44069. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  44070. ** page currently held in memory before returning SQLITE_OK. If an IO
  44071. ** error is encountered, then the IO error code is returned to the caller.
  44072. */
  44073. static int syncJournal(Pager *pPager, int newHdr){
  44074. int rc; /* Return code */
  44075. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44076. || pPager->eState==PAGER_WRITER_DBMOD
  44077. );
  44078. assert( assert_pager_state(pPager) );
  44079. assert( !pagerUseWal(pPager) );
  44080. rc = sqlite3PagerExclusiveLock(pPager);
  44081. if( rc!=SQLITE_OK ) return rc;
  44082. if( !pPager->noSync ){
  44083. assert( !pPager->tempFile );
  44084. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  44085. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  44086. assert( isOpen(pPager->jfd) );
  44087. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  44088. /* This block deals with an obscure problem. If the last connection
  44089. ** that wrote to this database was operating in persistent-journal
  44090. ** mode, then the journal file may at this point actually be larger
  44091. ** than Pager.journalOff bytes. If the next thing in the journal
  44092. ** file happens to be a journal-header (written as part of the
  44093. ** previous connection's transaction), and a crash or power-failure
  44094. ** occurs after nRec is updated but before this connection writes
  44095. ** anything else to the journal file (or commits/rolls back its
  44096. ** transaction), then SQLite may become confused when doing the
  44097. ** hot-journal rollback following recovery. It may roll back all
  44098. ** of this connections data, then proceed to rolling back the old,
  44099. ** out-of-date data that follows it. Database corruption.
  44100. **
  44101. ** To work around this, if the journal file does appear to contain
  44102. ** a valid header following Pager.journalOff, then write a 0x00
  44103. ** byte to the start of it to prevent it from being recognized.
  44104. **
  44105. ** Variable iNextHdrOffset is set to the offset at which this
  44106. ** problematic header will occur, if it exists. aMagic is used
  44107. ** as a temporary buffer to inspect the first couple of bytes of
  44108. ** the potential journal header.
  44109. */
  44110. i64 iNextHdrOffset;
  44111. u8 aMagic[8];
  44112. u8 zHeader[sizeof(aJournalMagic)+4];
  44113. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  44114. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  44115. iNextHdrOffset = journalHdrOffset(pPager);
  44116. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  44117. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  44118. static const u8 zerobyte = 0;
  44119. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  44120. }
  44121. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  44122. return rc;
  44123. }
  44124. /* Write the nRec value into the journal file header. If in
  44125. ** full-synchronous mode, sync the journal first. This ensures that
  44126. ** all data has really hit the disk before nRec is updated to mark
  44127. ** it as a candidate for rollback.
  44128. **
  44129. ** This is not required if the persistent media supports the
  44130. ** SAFE_APPEND property. Because in this case it is not possible
  44131. ** for garbage data to be appended to the file, the nRec field
  44132. ** is populated with 0xFFFFFFFF when the journal header is written
  44133. ** and never needs to be updated.
  44134. */
  44135. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  44136. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  44137. IOTRACE(("JSYNC %p\n", pPager))
  44138. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  44139. if( rc!=SQLITE_OK ) return rc;
  44140. }
  44141. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  44142. rc = sqlite3OsWrite(
  44143. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  44144. );
  44145. if( rc!=SQLITE_OK ) return rc;
  44146. }
  44147. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  44148. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  44149. IOTRACE(("JSYNC %p\n", pPager))
  44150. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  44151. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  44152. );
  44153. if( rc!=SQLITE_OK ) return rc;
  44154. }
  44155. pPager->journalHdr = pPager->journalOff;
  44156. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  44157. pPager->nRec = 0;
  44158. rc = writeJournalHdr(pPager);
  44159. if( rc!=SQLITE_OK ) return rc;
  44160. }
  44161. }else{
  44162. pPager->journalHdr = pPager->journalOff;
  44163. }
  44164. }
  44165. /* Unless the pager is in noSync mode, the journal file was just
  44166. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  44167. ** all pages.
  44168. */
  44169. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  44170. pPager->eState = PAGER_WRITER_DBMOD;
  44171. assert( assert_pager_state(pPager) );
  44172. return SQLITE_OK;
  44173. }
  44174. /*
  44175. ** The argument is the first in a linked list of dirty pages connected
  44176. ** by the PgHdr.pDirty pointer. This function writes each one of the
  44177. ** in-memory pages in the list to the database file. The argument may
  44178. ** be NULL, representing an empty list. In this case this function is
  44179. ** a no-op.
  44180. **
  44181. ** The pager must hold at least a RESERVED lock when this function
  44182. ** is called. Before writing anything to the database file, this lock
  44183. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  44184. ** SQLITE_BUSY is returned and no data is written to the database file.
  44185. **
  44186. ** If the pager is a temp-file pager and the actual file-system file
  44187. ** is not yet open, it is created and opened before any data is
  44188. ** written out.
  44189. **
  44190. ** Once the lock has been upgraded and, if necessary, the file opened,
  44191. ** the pages are written out to the database file in list order. Writing
  44192. ** a page is skipped if it meets either of the following criteria:
  44193. **
  44194. ** * The page number is greater than Pager.dbSize, or
  44195. ** * The PGHDR_DONT_WRITE flag is set on the page.
  44196. **
  44197. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  44198. ** is updated accordingly. If page 1 is written out, then the value cached
  44199. ** in Pager.dbFileVers[] is updated to match the new value stored in
  44200. ** the database file.
  44201. **
  44202. ** If everything is successful, SQLITE_OK is returned. If an IO error
  44203. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  44204. ** be obtained, SQLITE_BUSY is returned.
  44205. */
  44206. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  44207. int rc = SQLITE_OK; /* Return code */
  44208. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  44209. assert( !pagerUseWal(pPager) );
  44210. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44211. assert( pPager->eLock==EXCLUSIVE_LOCK );
  44212. /* If the file is a temp-file has not yet been opened, open it now. It
  44213. ** is not possible for rc to be other than SQLITE_OK if this branch
  44214. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  44215. */
  44216. if( !isOpen(pPager->fd) ){
  44217. assert( pPager->tempFile && rc==SQLITE_OK );
  44218. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  44219. }
  44220. /* Before the first write, give the VFS a hint of what the final
  44221. ** file size will be.
  44222. */
  44223. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  44224. if( rc==SQLITE_OK
  44225. && pPager->dbHintSize<pPager->dbSize
  44226. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  44227. ){
  44228. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  44229. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  44230. pPager->dbHintSize = pPager->dbSize;
  44231. }
  44232. while( rc==SQLITE_OK && pList ){
  44233. Pgno pgno = pList->pgno;
  44234. /* If there are dirty pages in the page cache with page numbers greater
  44235. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  44236. ** make the file smaller (presumably by auto-vacuum code). Do not write
  44237. ** any such pages to the file.
  44238. **
  44239. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  44240. ** set (set by sqlite3PagerDontWrite()).
  44241. */
  44242. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  44243. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  44244. char *pData; /* Data to write */
  44245. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  44246. if( pList->pgno==1 ) pager_write_changecounter(pList);
  44247. /* Encode the database */
  44248. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  44249. /* Write out the page data. */
  44250. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  44251. /* If page 1 was just written, update Pager.dbFileVers to match
  44252. ** the value now stored in the database file. If writing this
  44253. ** page caused the database file to grow, update dbFileSize.
  44254. */
  44255. if( pgno==1 ){
  44256. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  44257. }
  44258. if( pgno>pPager->dbFileSize ){
  44259. pPager->dbFileSize = pgno;
  44260. }
  44261. pPager->aStat[PAGER_STAT_WRITE]++;
  44262. /* Update any backup objects copying the contents of this pager. */
  44263. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  44264. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  44265. PAGERID(pPager), pgno, pager_pagehash(pList)));
  44266. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  44267. PAGER_INCR(sqlite3_pager_writedb_count);
  44268. }else{
  44269. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  44270. }
  44271. pager_set_pagehash(pList);
  44272. pList = pList->pDirty;
  44273. }
  44274. return rc;
  44275. }
  44276. /*
  44277. ** Ensure that the sub-journal file is open. If it is already open, this
  44278. ** function is a no-op.
  44279. **
  44280. ** SQLITE_OK is returned if everything goes according to plan. An
  44281. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  44282. ** fails.
  44283. */
  44284. static int openSubJournal(Pager *pPager){
  44285. int rc = SQLITE_OK;
  44286. if( !isOpen(pPager->sjfd) ){
  44287. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  44288. sqlite3MemJournalOpen(pPager->sjfd);
  44289. }else{
  44290. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  44291. }
  44292. }
  44293. return rc;
  44294. }
  44295. /*
  44296. ** Append a record of the current state of page pPg to the sub-journal.
  44297. **
  44298. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  44299. ** for all open savepoints before returning.
  44300. **
  44301. ** This function returns SQLITE_OK if everything is successful, an IO
  44302. ** error code if the attempt to write to the sub-journal fails, or
  44303. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  44304. ** bitvec.
  44305. */
  44306. static int subjournalPage(PgHdr *pPg){
  44307. int rc = SQLITE_OK;
  44308. Pager *pPager = pPg->pPager;
  44309. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44310. /* Open the sub-journal, if it has not already been opened */
  44311. assert( pPager->useJournal );
  44312. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  44313. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  44314. assert( pagerUseWal(pPager)
  44315. || pageInJournal(pPager, pPg)
  44316. || pPg->pgno>pPager->dbOrigSize
  44317. );
  44318. rc = openSubJournal(pPager);
  44319. /* If the sub-journal was opened successfully (or was already open),
  44320. ** write the journal record into the file. */
  44321. if( rc==SQLITE_OK ){
  44322. void *pData = pPg->pData;
  44323. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  44324. char *pData2;
  44325. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44326. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  44327. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  44328. if( rc==SQLITE_OK ){
  44329. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  44330. }
  44331. }
  44332. }
  44333. if( rc==SQLITE_OK ){
  44334. pPager->nSubRec++;
  44335. assert( pPager->nSavepoint>0 );
  44336. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  44337. }
  44338. return rc;
  44339. }
  44340. static int subjournalPageIfRequired(PgHdr *pPg){
  44341. if( subjRequiresPage(pPg) ){
  44342. return subjournalPage(pPg);
  44343. }else{
  44344. return SQLITE_OK;
  44345. }
  44346. }
  44347. /*
  44348. ** This function is called by the pcache layer when it has reached some
  44349. ** soft memory limit. The first argument is a pointer to a Pager object
  44350. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  44351. ** database). The second argument is a reference to a page that is
  44352. ** currently dirty but has no outstanding references. The page
  44353. ** is always associated with the Pager object passed as the first
  44354. ** argument.
  44355. **
  44356. ** The job of this function is to make pPg clean by writing its contents
  44357. ** out to the database file, if possible. This may involve syncing the
  44358. ** journal file.
  44359. **
  44360. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  44361. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  44362. ** page clean, the IO error code is returned. If the page cannot be
  44363. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  44364. ** is returned by sqlite3PcacheMakeClean() is not called.
  44365. */
  44366. static int pagerStress(void *p, PgHdr *pPg){
  44367. Pager *pPager = (Pager *)p;
  44368. int rc = SQLITE_OK;
  44369. assert( pPg->pPager==pPager );
  44370. assert( pPg->flags&PGHDR_DIRTY );
  44371. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  44372. ** journal (and adding a new header) is not allowed. This occurs
  44373. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  44374. ** pages belonging to the same sector.
  44375. **
  44376. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  44377. ** regardless of whether or not a sync is required. This is set during
  44378. ** a rollback or by user request, respectively.
  44379. **
  44380. ** Spilling is also prohibited when in an error state since that could
  44381. ** lead to database corruption. In the current implementation it
  44382. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  44383. ** while in the error state, hence it is impossible for this routine to
  44384. ** be called in the error state. Nevertheless, we include a NEVER()
  44385. ** test for the error state as a safeguard against future changes.
  44386. */
  44387. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  44388. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  44389. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  44390. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  44391. if( pPager->doNotSpill
  44392. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  44393. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  44394. ){
  44395. return SQLITE_OK;
  44396. }
  44397. pPg->pDirty = 0;
  44398. if( pagerUseWal(pPager) ){
  44399. /* Write a single frame for this page to the log. */
  44400. rc = subjournalPageIfRequired(pPg);
  44401. if( rc==SQLITE_OK ){
  44402. rc = pagerWalFrames(pPager, pPg, 0, 0);
  44403. }
  44404. }else{
  44405. /* Sync the journal file if required. */
  44406. if( pPg->flags&PGHDR_NEED_SYNC
  44407. || pPager->eState==PAGER_WRITER_CACHEMOD
  44408. ){
  44409. rc = syncJournal(pPager, 1);
  44410. }
  44411. /* Write the contents of the page out to the database file. */
  44412. if( rc==SQLITE_OK ){
  44413. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  44414. rc = pager_write_pagelist(pPager, pPg);
  44415. }
  44416. }
  44417. /* Mark the page as clean. */
  44418. if( rc==SQLITE_OK ){
  44419. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  44420. sqlite3PcacheMakeClean(pPg);
  44421. }
  44422. return pager_error(pPager, rc);
  44423. }
  44424. /*
  44425. ** Allocate and initialize a new Pager object and put a pointer to it
  44426. ** in *ppPager. The pager should eventually be freed by passing it
  44427. ** to sqlite3PagerClose().
  44428. **
  44429. ** The zFilename argument is the path to the database file to open.
  44430. ** If zFilename is NULL then a randomly-named temporary file is created
  44431. ** and used as the file to be cached. Temporary files are be deleted
  44432. ** automatically when they are closed. If zFilename is ":memory:" then
  44433. ** all information is held in cache. It is never written to disk.
  44434. ** This can be used to implement an in-memory database.
  44435. **
  44436. ** The nExtra parameter specifies the number of bytes of space allocated
  44437. ** along with each page reference. This space is available to the user
  44438. ** via the sqlite3PagerGetExtra() API.
  44439. **
  44440. ** The flags argument is used to specify properties that affect the
  44441. ** operation of the pager. It should be passed some bitwise combination
  44442. ** of the PAGER_* flags.
  44443. **
  44444. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  44445. ** of the xOpen() method of the supplied VFS when opening files.
  44446. **
  44447. ** If the pager object is allocated and the specified file opened
  44448. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  44449. ** the new pager object. If an error occurs, *ppPager is set to NULL
  44450. ** and error code returned. This function may return SQLITE_NOMEM
  44451. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  44452. ** various SQLITE_IO_XXX errors.
  44453. */
  44454. SQLITE_PRIVATE int sqlite3PagerOpen(
  44455. sqlite3_vfs *pVfs, /* The virtual file system to use */
  44456. Pager **ppPager, /* OUT: Return the Pager structure here */
  44457. const char *zFilename, /* Name of the database file to open */
  44458. int nExtra, /* Extra bytes append to each in-memory page */
  44459. int flags, /* flags controlling this file */
  44460. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  44461. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  44462. ){
  44463. u8 *pPtr;
  44464. Pager *pPager = 0; /* Pager object to allocate and return */
  44465. int rc = SQLITE_OK; /* Return code */
  44466. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  44467. int memDb = 0; /* True if this is an in-memory file */
  44468. int readOnly = 0; /* True if this is a read-only file */
  44469. int journalFileSize; /* Bytes to allocate for each journal fd */
  44470. char *zPathname = 0; /* Full path to database file */
  44471. int nPathname = 0; /* Number of bytes in zPathname */
  44472. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  44473. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  44474. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  44475. const char *zUri = 0; /* URI args to copy */
  44476. int nUri = 0; /* Number of bytes of URI args at *zUri */
  44477. /* Figure out how much space is required for each journal file-handle
  44478. ** (there are two of them, the main journal and the sub-journal). This
  44479. ** is the maximum space required for an in-memory journal file handle
  44480. ** and a regular journal file-handle. Note that a "regular journal-handle"
  44481. ** may be a wrapper capable of caching the first portion of the journal
  44482. ** file in memory to implement the atomic-write optimization (see
  44483. ** source file journal.c).
  44484. */
  44485. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  44486. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  44487. }else{
  44488. journalFileSize = ROUND8(sqlite3MemJournalSize());
  44489. }
  44490. /* Set the output variable to NULL in case an error occurs. */
  44491. *ppPager = 0;
  44492. #ifndef SQLITE_OMIT_MEMORYDB
  44493. if( flags & PAGER_MEMORY ){
  44494. memDb = 1;
  44495. if( zFilename && zFilename[0] ){
  44496. zPathname = sqlite3DbStrDup(0, zFilename);
  44497. if( zPathname==0 ) return SQLITE_NOMEM;
  44498. nPathname = sqlite3Strlen30(zPathname);
  44499. zFilename = 0;
  44500. }
  44501. }
  44502. #endif
  44503. /* Compute and store the full pathname in an allocated buffer pointed
  44504. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  44505. ** leave both nPathname and zPathname set to 0.
  44506. */
  44507. if( zFilename && zFilename[0] ){
  44508. const char *z;
  44509. nPathname = pVfs->mxPathname+1;
  44510. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  44511. if( zPathname==0 ){
  44512. return SQLITE_NOMEM;
  44513. }
  44514. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  44515. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  44516. nPathname = sqlite3Strlen30(zPathname);
  44517. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  44518. while( *z ){
  44519. z += sqlite3Strlen30(z)+1;
  44520. z += sqlite3Strlen30(z)+1;
  44521. }
  44522. nUri = (int)(&z[1] - zUri);
  44523. assert( nUri>=0 );
  44524. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  44525. /* This branch is taken when the journal path required by
  44526. ** the database being opened will be more than pVfs->mxPathname
  44527. ** bytes in length. This means the database cannot be opened,
  44528. ** as it will not be possible to open the journal file or even
  44529. ** check for a hot-journal before reading.
  44530. */
  44531. rc = SQLITE_CANTOPEN_BKPT;
  44532. }
  44533. if( rc!=SQLITE_OK ){
  44534. sqlite3DbFree(0, zPathname);
  44535. return rc;
  44536. }
  44537. }
  44538. /* Allocate memory for the Pager structure, PCache object, the
  44539. ** three file descriptors, the database file name and the journal
  44540. ** file name. The layout in memory is as follows:
  44541. **
  44542. ** Pager object (sizeof(Pager) bytes)
  44543. ** PCache object (sqlite3PcacheSize() bytes)
  44544. ** Database file handle (pVfs->szOsFile bytes)
  44545. ** Sub-journal file handle (journalFileSize bytes)
  44546. ** Main journal file handle (journalFileSize bytes)
  44547. ** Database file name (nPathname+1 bytes)
  44548. ** Journal file name (nPathname+8+1 bytes)
  44549. */
  44550. pPtr = (u8 *)sqlite3MallocZero(
  44551. ROUND8(sizeof(*pPager)) + /* Pager structure */
  44552. ROUND8(pcacheSize) + /* PCache object */
  44553. ROUND8(pVfs->szOsFile) + /* The main db file */
  44554. journalFileSize * 2 + /* The two journal files */
  44555. nPathname + 1 + nUri + /* zFilename */
  44556. nPathname + 8 + 2 /* zJournal */
  44557. #ifndef SQLITE_OMIT_WAL
  44558. + nPathname + 4 + 2 /* zWal */
  44559. #endif
  44560. );
  44561. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  44562. if( !pPtr ){
  44563. sqlite3DbFree(0, zPathname);
  44564. return SQLITE_NOMEM;
  44565. }
  44566. pPager = (Pager*)(pPtr);
  44567. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  44568. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  44569. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  44570. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  44571. pPager->zFilename = (char*)(pPtr += journalFileSize);
  44572. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  44573. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  44574. if( zPathname ){
  44575. assert( nPathname>0 );
  44576. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  44577. memcpy(pPager->zFilename, zPathname, nPathname);
  44578. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  44579. memcpy(pPager->zJournal, zPathname, nPathname);
  44580. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  44581. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  44582. #ifndef SQLITE_OMIT_WAL
  44583. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  44584. memcpy(pPager->zWal, zPathname, nPathname);
  44585. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  44586. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  44587. #endif
  44588. sqlite3DbFree(0, zPathname);
  44589. }
  44590. pPager->pVfs = pVfs;
  44591. pPager->vfsFlags = vfsFlags;
  44592. /* Open the pager file.
  44593. */
  44594. if( zFilename && zFilename[0] ){
  44595. int fout = 0; /* VFS flags returned by xOpen() */
  44596. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  44597. assert( !memDb );
  44598. readOnly = (fout&SQLITE_OPEN_READONLY);
  44599. /* If the file was successfully opened for read/write access,
  44600. ** choose a default page size in case we have to create the
  44601. ** database file. The default page size is the maximum of:
  44602. **
  44603. ** + SQLITE_DEFAULT_PAGE_SIZE,
  44604. ** + The value returned by sqlite3OsSectorSize()
  44605. ** + The largest page size that can be written atomically.
  44606. */
  44607. if( rc==SQLITE_OK ){
  44608. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  44609. if( !readOnly ){
  44610. setSectorSize(pPager);
  44611. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  44612. if( szPageDflt<pPager->sectorSize ){
  44613. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  44614. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  44615. }else{
  44616. szPageDflt = (u32)pPager->sectorSize;
  44617. }
  44618. }
  44619. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44620. {
  44621. int ii;
  44622. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  44623. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  44624. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  44625. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  44626. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  44627. szPageDflt = ii;
  44628. }
  44629. }
  44630. }
  44631. #endif
  44632. }
  44633. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  44634. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  44635. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  44636. vfsFlags |= SQLITE_OPEN_READONLY;
  44637. goto act_like_temp_file;
  44638. }
  44639. }
  44640. }else{
  44641. /* If a temporary file is requested, it is not opened immediately.
  44642. ** In this case we accept the default page size and delay actually
  44643. ** opening the file until the first call to OsWrite().
  44644. **
  44645. ** This branch is also run for an in-memory database. An in-memory
  44646. ** database is the same as a temp-file that is never written out to
  44647. ** disk and uses an in-memory rollback journal.
  44648. **
  44649. ** This branch also runs for files marked as immutable.
  44650. */
  44651. act_like_temp_file:
  44652. tempFile = 1;
  44653. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  44654. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  44655. pPager->noLock = 1; /* Do no locking */
  44656. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  44657. }
  44658. /* The following call to PagerSetPagesize() serves to set the value of
  44659. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  44660. */
  44661. if( rc==SQLITE_OK ){
  44662. assert( pPager->memDb==0 );
  44663. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  44664. testcase( rc!=SQLITE_OK );
  44665. }
  44666. /* Initialize the PCache object. */
  44667. if( rc==SQLITE_OK ){
  44668. assert( nExtra<1000 );
  44669. nExtra = ROUND8(nExtra);
  44670. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  44671. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  44672. }
  44673. /* If an error occurred above, free the Pager structure and close the file.
  44674. */
  44675. if( rc!=SQLITE_OK ){
  44676. sqlite3OsClose(pPager->fd);
  44677. sqlite3PageFree(pPager->pTmpSpace);
  44678. sqlite3_free(pPager);
  44679. return rc;
  44680. }
  44681. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  44682. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  44683. pPager->useJournal = (u8)useJournal;
  44684. /* pPager->stmtOpen = 0; */
  44685. /* pPager->stmtInUse = 0; */
  44686. /* pPager->nRef = 0; */
  44687. /* pPager->stmtSize = 0; */
  44688. /* pPager->stmtJSize = 0; */
  44689. /* pPager->nPage = 0; */
  44690. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  44691. /* pPager->state = PAGER_UNLOCK; */
  44692. /* pPager->errMask = 0; */
  44693. pPager->tempFile = (u8)tempFile;
  44694. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  44695. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  44696. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  44697. pPager->exclusiveMode = (u8)tempFile;
  44698. pPager->changeCountDone = pPager->tempFile;
  44699. pPager->memDb = (u8)memDb;
  44700. pPager->readOnly = (u8)readOnly;
  44701. assert( useJournal || pPager->tempFile );
  44702. pPager->noSync = pPager->tempFile;
  44703. if( pPager->noSync ){
  44704. assert( pPager->fullSync==0 );
  44705. assert( pPager->syncFlags==0 );
  44706. assert( pPager->walSyncFlags==0 );
  44707. assert( pPager->ckptSyncFlags==0 );
  44708. }else{
  44709. pPager->fullSync = 1;
  44710. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  44711. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  44712. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  44713. }
  44714. /* pPager->pFirst = 0; */
  44715. /* pPager->pFirstSynced = 0; */
  44716. /* pPager->pLast = 0; */
  44717. pPager->nExtra = (u16)nExtra;
  44718. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  44719. assert( isOpen(pPager->fd) || tempFile );
  44720. setSectorSize(pPager);
  44721. if( !useJournal ){
  44722. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  44723. }else if( memDb ){
  44724. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  44725. }
  44726. /* pPager->xBusyHandler = 0; */
  44727. /* pPager->pBusyHandlerArg = 0; */
  44728. pPager->xReiniter = xReinit;
  44729. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  44730. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  44731. *ppPager = pPager;
  44732. return SQLITE_OK;
  44733. }
  44734. /* Verify that the database file has not be deleted or renamed out from
  44735. ** under the pager. Return SQLITE_OK if the database is still were it ought
  44736. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  44737. ** code from sqlite3OsAccess()) if the database has gone missing.
  44738. */
  44739. static int databaseIsUnmoved(Pager *pPager){
  44740. int bHasMoved = 0;
  44741. int rc;
  44742. if( pPager->tempFile ) return SQLITE_OK;
  44743. if( pPager->dbSize==0 ) return SQLITE_OK;
  44744. assert( pPager->zFilename && pPager->zFilename[0] );
  44745. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  44746. if( rc==SQLITE_NOTFOUND ){
  44747. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  44748. ** has not been moved. That is the historical behavior of SQLite: prior to
  44749. ** version 3.8.3, it never checked */
  44750. rc = SQLITE_OK;
  44751. }else if( rc==SQLITE_OK && bHasMoved ){
  44752. rc = SQLITE_READONLY_DBMOVED;
  44753. }
  44754. return rc;
  44755. }
  44756. /*
  44757. ** This function is called after transitioning from PAGER_UNLOCK to
  44758. ** PAGER_SHARED state. It tests if there is a hot journal present in
  44759. ** the file-system for the given pager. A hot journal is one that
  44760. ** needs to be played back. According to this function, a hot-journal
  44761. ** file exists if the following criteria are met:
  44762. **
  44763. ** * The journal file exists in the file system, and
  44764. ** * No process holds a RESERVED or greater lock on the database file, and
  44765. ** * The database file itself is greater than 0 bytes in size, and
  44766. ** * The first byte of the journal file exists and is not 0x00.
  44767. **
  44768. ** If the current size of the database file is 0 but a journal file
  44769. ** exists, that is probably an old journal left over from a prior
  44770. ** database with the same name. In this case the journal file is
  44771. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  44772. ** is returned.
  44773. **
  44774. ** This routine does not check if there is a master journal filename
  44775. ** at the end of the file. If there is, and that master journal file
  44776. ** does not exist, then the journal file is not really hot. In this
  44777. ** case this routine will return a false-positive. The pager_playback()
  44778. ** routine will discover that the journal file is not really hot and
  44779. ** will not roll it back.
  44780. **
  44781. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  44782. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  44783. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  44784. ** to determine whether or not a hot-journal file exists, the IO error
  44785. ** code is returned and the value of *pExists is undefined.
  44786. */
  44787. static int hasHotJournal(Pager *pPager, int *pExists){
  44788. sqlite3_vfs * const pVfs = pPager->pVfs;
  44789. int rc = SQLITE_OK; /* Return code */
  44790. int exists = 1; /* True if a journal file is present */
  44791. int jrnlOpen = !!isOpen(pPager->jfd);
  44792. assert( pPager->useJournal );
  44793. assert( isOpen(pPager->fd) );
  44794. assert( pPager->eState==PAGER_OPEN );
  44795. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  44796. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  44797. ));
  44798. *pExists = 0;
  44799. if( !jrnlOpen ){
  44800. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  44801. }
  44802. if( rc==SQLITE_OK && exists ){
  44803. int locked = 0; /* True if some process holds a RESERVED lock */
  44804. /* Race condition here: Another process might have been holding the
  44805. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  44806. ** call above, but then delete the journal and drop the lock before
  44807. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  44808. ** is the case, this routine might think there is a hot journal when
  44809. ** in fact there is none. This results in a false-positive which will
  44810. ** be dealt with by the playback routine. Ticket #3883.
  44811. */
  44812. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  44813. if( rc==SQLITE_OK && !locked ){
  44814. Pgno nPage; /* Number of pages in database file */
  44815. rc = pagerPagecount(pPager, &nPage);
  44816. if( rc==SQLITE_OK ){
  44817. /* If the database is zero pages in size, that means that either (1) the
  44818. ** journal is a remnant from a prior database with the same name where
  44819. ** the database file but not the journal was deleted, or (2) the initial
  44820. ** transaction that populates a new database is being rolled back.
  44821. ** In either case, the journal file can be deleted. However, take care
  44822. ** not to delete the journal file if it is already open due to
  44823. ** journal_mode=PERSIST.
  44824. */
  44825. if( nPage==0 && !jrnlOpen ){
  44826. sqlite3BeginBenignMalloc();
  44827. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  44828. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  44829. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  44830. }
  44831. sqlite3EndBenignMalloc();
  44832. }else{
  44833. /* The journal file exists and no other connection has a reserved
  44834. ** or greater lock on the database file. Now check that there is
  44835. ** at least one non-zero bytes at the start of the journal file.
  44836. ** If there is, then we consider this journal to be hot. If not,
  44837. ** it can be ignored.
  44838. */
  44839. if( !jrnlOpen ){
  44840. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  44841. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  44842. }
  44843. if( rc==SQLITE_OK ){
  44844. u8 first = 0;
  44845. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  44846. if( rc==SQLITE_IOERR_SHORT_READ ){
  44847. rc = SQLITE_OK;
  44848. }
  44849. if( !jrnlOpen ){
  44850. sqlite3OsClose(pPager->jfd);
  44851. }
  44852. *pExists = (first!=0);
  44853. }else if( rc==SQLITE_CANTOPEN ){
  44854. /* If we cannot open the rollback journal file in order to see if
  44855. ** it has a zero header, that might be due to an I/O error, or
  44856. ** it might be due to the race condition described above and in
  44857. ** ticket #3883. Either way, assume that the journal is hot.
  44858. ** This might be a false positive. But if it is, then the
  44859. ** automatic journal playback and recovery mechanism will deal
  44860. ** with it under an EXCLUSIVE lock where we do not need to
  44861. ** worry so much with race conditions.
  44862. */
  44863. *pExists = 1;
  44864. rc = SQLITE_OK;
  44865. }
  44866. }
  44867. }
  44868. }
  44869. }
  44870. return rc;
  44871. }
  44872. /*
  44873. ** This function is called to obtain a shared lock on the database file.
  44874. ** It is illegal to call sqlite3PagerAcquire() until after this function
  44875. ** has been successfully called. If a shared-lock is already held when
  44876. ** this function is called, it is a no-op.
  44877. **
  44878. ** The following operations are also performed by this function.
  44879. **
  44880. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  44881. ** on the database file), then an attempt is made to obtain a
  44882. ** SHARED lock on the database file. Immediately after obtaining
  44883. ** the SHARED lock, the file-system is checked for a hot-journal,
  44884. ** which is played back if present. Following any hot-journal
  44885. ** rollback, the contents of the cache are validated by checking
  44886. ** the 'change-counter' field of the database file header and
  44887. ** discarded if they are found to be invalid.
  44888. **
  44889. ** 2) If the pager is running in exclusive-mode, and there are currently
  44890. ** no outstanding references to any pages, and is in the error state,
  44891. ** then an attempt is made to clear the error state by discarding
  44892. ** the contents of the page cache and rolling back any open journal
  44893. ** file.
  44894. **
  44895. ** If everything is successful, SQLITE_OK is returned. If an IO error
  44896. ** occurs while locking the database, checking for a hot-journal file or
  44897. ** rolling back a journal file, the IO error code is returned.
  44898. */
  44899. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  44900. int rc = SQLITE_OK; /* Return code */
  44901. /* This routine is only called from b-tree and only when there are no
  44902. ** outstanding pages. This implies that the pager state should either
  44903. ** be OPEN or READER. READER is only possible if the pager is or was in
  44904. ** exclusive access mode.
  44905. */
  44906. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  44907. assert( assert_pager_state(pPager) );
  44908. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  44909. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  44910. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  44911. int bHotJournal = 1; /* True if there exists a hot journal-file */
  44912. assert( !MEMDB );
  44913. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  44914. if( rc!=SQLITE_OK ){
  44915. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  44916. goto failed;
  44917. }
  44918. /* If a journal file exists, and there is no RESERVED lock on the
  44919. ** database file, then it either needs to be played back or deleted.
  44920. */
  44921. if( pPager->eLock<=SHARED_LOCK ){
  44922. rc = hasHotJournal(pPager, &bHotJournal);
  44923. }
  44924. if( rc!=SQLITE_OK ){
  44925. goto failed;
  44926. }
  44927. if( bHotJournal ){
  44928. if( pPager->readOnly ){
  44929. rc = SQLITE_READONLY_ROLLBACK;
  44930. goto failed;
  44931. }
  44932. /* Get an EXCLUSIVE lock on the database file. At this point it is
  44933. ** important that a RESERVED lock is not obtained on the way to the
  44934. ** EXCLUSIVE lock. If it were, another process might open the
  44935. ** database file, detect the RESERVED lock, and conclude that the
  44936. ** database is safe to read while this process is still rolling the
  44937. ** hot-journal back.
  44938. **
  44939. ** Because the intermediate RESERVED lock is not requested, any
  44940. ** other process attempting to access the database file will get to
  44941. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  44942. ** on the database file.
  44943. **
  44944. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  44945. ** downgraded to SHARED_LOCK before this function returns.
  44946. */
  44947. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44948. if( rc!=SQLITE_OK ){
  44949. goto failed;
  44950. }
  44951. /* If it is not already open and the file exists on disk, open the
  44952. ** journal for read/write access. Write access is required because
  44953. ** in exclusive-access mode the file descriptor will be kept open
  44954. ** and possibly used for a transaction later on. Also, write-access
  44955. ** is usually required to finalize the journal in journal_mode=persist
  44956. ** mode (and also for journal_mode=truncate on some systems).
  44957. **
  44958. ** If the journal does not exist, it usually means that some
  44959. ** other connection managed to get in and roll it back before
  44960. ** this connection obtained the exclusive lock above. Or, it
  44961. ** may mean that the pager was in the error-state when this
  44962. ** function was called and the journal file does not exist.
  44963. */
  44964. if( !isOpen(pPager->jfd) ){
  44965. sqlite3_vfs * const pVfs = pPager->pVfs;
  44966. int bExists; /* True if journal file exists */
  44967. rc = sqlite3OsAccess(
  44968. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  44969. if( rc==SQLITE_OK && bExists ){
  44970. int fout = 0;
  44971. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  44972. assert( !pPager->tempFile );
  44973. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  44974. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44975. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  44976. rc = SQLITE_CANTOPEN_BKPT;
  44977. sqlite3OsClose(pPager->jfd);
  44978. }
  44979. }
  44980. }
  44981. /* Playback and delete the journal. Drop the database write
  44982. ** lock and reacquire the read lock. Purge the cache before
  44983. ** playing back the hot-journal so that we don't end up with
  44984. ** an inconsistent cache. Sync the hot journal before playing
  44985. ** it back since the process that crashed and left the hot journal
  44986. ** probably did not sync it and we are required to always sync
  44987. ** the journal before playing it back.
  44988. */
  44989. if( isOpen(pPager->jfd) ){
  44990. assert( rc==SQLITE_OK );
  44991. rc = pagerSyncHotJournal(pPager);
  44992. if( rc==SQLITE_OK ){
  44993. rc = pager_playback(pPager, 1);
  44994. pPager->eState = PAGER_OPEN;
  44995. }
  44996. }else if( !pPager->exclusiveMode ){
  44997. pagerUnlockDb(pPager, SHARED_LOCK);
  44998. }
  44999. if( rc!=SQLITE_OK ){
  45000. /* This branch is taken if an error occurs while trying to open
  45001. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  45002. ** pager_unlock() routine will be called before returning to unlock
  45003. ** the file. If the unlock attempt fails, then Pager.eLock must be
  45004. ** set to UNKNOWN_LOCK (see the comment above the #define for
  45005. ** UNKNOWN_LOCK above for an explanation).
  45006. **
  45007. ** In order to get pager_unlock() to do this, set Pager.eState to
  45008. ** PAGER_ERROR now. This is not actually counted as a transition
  45009. ** to ERROR state in the state diagram at the top of this file,
  45010. ** since we know that the same call to pager_unlock() will very
  45011. ** shortly transition the pager object to the OPEN state. Calling
  45012. ** assert_pager_state() would fail now, as it should not be possible
  45013. ** to be in ERROR state when there are zero outstanding page
  45014. ** references.
  45015. */
  45016. pager_error(pPager, rc);
  45017. goto failed;
  45018. }
  45019. assert( pPager->eState==PAGER_OPEN );
  45020. assert( (pPager->eLock==SHARED_LOCK)
  45021. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  45022. );
  45023. }
  45024. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  45025. /* The shared-lock has just been acquired then check to
  45026. ** see if the database has been modified. If the database has changed,
  45027. ** flush the cache. The hasHeldSharedLock flag prevents this from
  45028. ** occurring on the very first access to a file, in order to save a
  45029. ** single unnecessary sqlite3OsRead() call at the start-up.
  45030. **
  45031. ** Database changes are detected by looking at 15 bytes beginning
  45032. ** at offset 24 into the file. The first 4 of these 16 bytes are
  45033. ** a 32-bit counter that is incremented with each change. The
  45034. ** other bytes change randomly with each file change when
  45035. ** a codec is in use.
  45036. **
  45037. ** There is a vanishingly small chance that a change will not be
  45038. ** detected. The chance of an undetected change is so small that
  45039. ** it can be neglected.
  45040. */
  45041. Pgno nPage = 0;
  45042. char dbFileVers[sizeof(pPager->dbFileVers)];
  45043. rc = pagerPagecount(pPager, &nPage);
  45044. if( rc ) goto failed;
  45045. if( nPage>0 ){
  45046. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  45047. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  45048. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  45049. goto failed;
  45050. }
  45051. }else{
  45052. memset(dbFileVers, 0, sizeof(dbFileVers));
  45053. }
  45054. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  45055. pager_reset(pPager);
  45056. /* Unmap the database file. It is possible that external processes
  45057. ** may have truncated the database file and then extended it back
  45058. ** to its original size while this process was not holding a lock.
  45059. ** In this case there may exist a Pager.pMap mapping that appears
  45060. ** to be the right size but is not actually valid. Avoid this
  45061. ** possibility by unmapping the db here. */
  45062. if( USEFETCH(pPager) ){
  45063. sqlite3OsUnfetch(pPager->fd, 0, 0);
  45064. }
  45065. }
  45066. }
  45067. /* If there is a WAL file in the file-system, open this database in WAL
  45068. ** mode. Otherwise, the following function call is a no-op.
  45069. */
  45070. rc = pagerOpenWalIfPresent(pPager);
  45071. #ifndef SQLITE_OMIT_WAL
  45072. assert( pPager->pWal==0 || rc==SQLITE_OK );
  45073. #endif
  45074. }
  45075. if( pagerUseWal(pPager) ){
  45076. assert( rc==SQLITE_OK );
  45077. rc = pagerBeginReadTransaction(pPager);
  45078. }
  45079. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  45080. rc = pagerPagecount(pPager, &pPager->dbSize);
  45081. }
  45082. failed:
  45083. if( rc!=SQLITE_OK ){
  45084. assert( !MEMDB );
  45085. pager_unlock(pPager);
  45086. assert( pPager->eState==PAGER_OPEN );
  45087. }else{
  45088. pPager->eState = PAGER_READER;
  45089. pPager->hasHeldSharedLock = 1;
  45090. }
  45091. return rc;
  45092. }
  45093. /*
  45094. ** If the reference count has reached zero, rollback any active
  45095. ** transaction and unlock the pager.
  45096. **
  45097. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  45098. ** the rollback journal, the unlock is not performed and there is
  45099. ** nothing to rollback, so this routine is a no-op.
  45100. */
  45101. static void pagerUnlockIfUnused(Pager *pPager){
  45102. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  45103. pagerUnlockAndRollback(pPager);
  45104. }
  45105. }
  45106. /*
  45107. ** Acquire a reference to page number pgno in pager pPager (a page
  45108. ** reference has type DbPage*). If the requested reference is
  45109. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  45110. **
  45111. ** If the requested page is already in the cache, it is returned.
  45112. ** Otherwise, a new page object is allocated and populated with data
  45113. ** read from the database file. In some cases, the pcache module may
  45114. ** choose not to allocate a new page object and may reuse an existing
  45115. ** object with no outstanding references.
  45116. **
  45117. ** The extra data appended to a page is always initialized to zeros the
  45118. ** first time a page is loaded into memory. If the page requested is
  45119. ** already in the cache when this function is called, then the extra
  45120. ** data is left as it was when the page object was last used.
  45121. **
  45122. ** If the database image is smaller than the requested page or if a
  45123. ** non-zero value is passed as the noContent parameter and the
  45124. ** requested page is not already stored in the cache, then no
  45125. ** actual disk read occurs. In this case the memory image of the
  45126. ** page is initialized to all zeros.
  45127. **
  45128. ** If noContent is true, it means that we do not care about the contents
  45129. ** of the page. This occurs in two scenarios:
  45130. **
  45131. ** a) When reading a free-list leaf page from the database, and
  45132. **
  45133. ** b) When a savepoint is being rolled back and we need to load
  45134. ** a new page into the cache to be filled with the data read
  45135. ** from the savepoint journal.
  45136. **
  45137. ** If noContent is true, then the data returned is zeroed instead of
  45138. ** being read from the database. Additionally, the bits corresponding
  45139. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  45140. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  45141. ** savepoints are set. This means if the page is made writable at any
  45142. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  45143. ** will not be journaled. This saves IO.
  45144. **
  45145. ** The acquisition might fail for several reasons. In all cases,
  45146. ** an appropriate error code is returned and *ppPage is set to NULL.
  45147. **
  45148. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  45149. ** to find a page in the in-memory cache first. If the page is not already
  45150. ** in memory, this routine goes to disk to read it in whereas Lookup()
  45151. ** just returns 0. This routine acquires a read-lock the first time it
  45152. ** has to go to disk, and could also playback an old journal if necessary.
  45153. ** Since Lookup() never goes to disk, it never has to deal with locks
  45154. ** or journal files.
  45155. */
  45156. SQLITE_PRIVATE int sqlite3PagerAcquire(
  45157. Pager *pPager, /* The pager open on the database file */
  45158. Pgno pgno, /* Page number to fetch */
  45159. DbPage **ppPage, /* Write a pointer to the page here */
  45160. int flags /* PAGER_GET_XXX flags */
  45161. ){
  45162. int rc = SQLITE_OK;
  45163. PgHdr *pPg = 0;
  45164. u32 iFrame = 0; /* Frame to read from WAL file */
  45165. const int noContent = (flags & PAGER_GET_NOCONTENT);
  45166. /* It is acceptable to use a read-only (mmap) page for any page except
  45167. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  45168. ** flag was specified by the caller. And so long as the db is not a
  45169. ** temporary or in-memory database. */
  45170. const int bMmapOk = (pgno>1 && USEFETCH(pPager)
  45171. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  45172. #ifdef SQLITE_HAS_CODEC
  45173. && pPager->xCodec==0
  45174. #endif
  45175. );
  45176. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  45177. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  45178. ** test in the previous statement, and avoid testing pgno==0 in the
  45179. ** common case where pgno is large. */
  45180. if( pgno<=1 && pgno==0 ){
  45181. return SQLITE_CORRUPT_BKPT;
  45182. }
  45183. assert( pPager->eState>=PAGER_READER );
  45184. assert( assert_pager_state(pPager) );
  45185. assert( noContent==0 || bMmapOk==0 );
  45186. assert( pPager->hasHeldSharedLock==1 );
  45187. /* If the pager is in the error state, return an error immediately.
  45188. ** Otherwise, request the page from the PCache layer. */
  45189. if( pPager->errCode!=SQLITE_OK ){
  45190. rc = pPager->errCode;
  45191. }else{
  45192. if( bMmapOk && pagerUseWal(pPager) ){
  45193. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  45194. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45195. }
  45196. if( bMmapOk && iFrame==0 ){
  45197. void *pData = 0;
  45198. rc = sqlite3OsFetch(pPager->fd,
  45199. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  45200. );
  45201. if( rc==SQLITE_OK && pData ){
  45202. if( pPager->eState>PAGER_READER ){
  45203. pPg = sqlite3PagerLookup(pPager, pgno);
  45204. }
  45205. if( pPg==0 ){
  45206. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  45207. }else{
  45208. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  45209. }
  45210. if( pPg ){
  45211. assert( rc==SQLITE_OK );
  45212. *ppPage = pPg;
  45213. return SQLITE_OK;
  45214. }
  45215. }
  45216. if( rc!=SQLITE_OK ){
  45217. goto pager_acquire_err;
  45218. }
  45219. }
  45220. {
  45221. sqlite3_pcache_page *pBase;
  45222. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  45223. if( pBase==0 ){
  45224. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  45225. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45226. if( pBase==0 ){
  45227. pPg = *ppPage = 0;
  45228. rc = SQLITE_NOMEM;
  45229. goto pager_acquire_err;
  45230. }
  45231. }
  45232. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  45233. assert( pPg!=0 );
  45234. }
  45235. }
  45236. if( rc!=SQLITE_OK ){
  45237. /* Either the call to sqlite3PcacheFetch() returned an error or the
  45238. ** pager was already in the error-state when this function was called.
  45239. ** Set pPg to 0 and jump to the exception handler. */
  45240. pPg = 0;
  45241. goto pager_acquire_err;
  45242. }
  45243. assert( pPg==(*ppPage) );
  45244. assert( pPg->pgno==pgno );
  45245. assert( pPg->pPager==pPager || pPg->pPager==0 );
  45246. if( pPg->pPager && !noContent ){
  45247. /* In this case the pcache already contains an initialized copy of
  45248. ** the page. Return without further ado. */
  45249. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  45250. pPager->aStat[PAGER_STAT_HIT]++;
  45251. return SQLITE_OK;
  45252. }else{
  45253. /* The pager cache has created a new page. Its content needs to
  45254. ** be initialized. */
  45255. pPg->pPager = pPager;
  45256. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  45257. ** number greater than this, or the unused locking-page, is requested. */
  45258. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  45259. rc = SQLITE_CORRUPT_BKPT;
  45260. goto pager_acquire_err;
  45261. }
  45262. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  45263. if( pgno>pPager->mxPgno ){
  45264. rc = SQLITE_FULL;
  45265. goto pager_acquire_err;
  45266. }
  45267. if( noContent ){
  45268. /* Failure to set the bits in the InJournal bit-vectors is benign.
  45269. ** It merely means that we might do some extra work to journal a
  45270. ** page that does not need to be journaled. Nevertheless, be sure
  45271. ** to test the case where a malloc error occurs while trying to set
  45272. ** a bit in a bit vector.
  45273. */
  45274. sqlite3BeginBenignMalloc();
  45275. if( pgno<=pPager->dbOrigSize ){
  45276. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  45277. testcase( rc==SQLITE_NOMEM );
  45278. }
  45279. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  45280. testcase( rc==SQLITE_NOMEM );
  45281. sqlite3EndBenignMalloc();
  45282. }
  45283. memset(pPg->pData, 0, pPager->pageSize);
  45284. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  45285. }else{
  45286. if( pagerUseWal(pPager) && bMmapOk==0 ){
  45287. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  45288. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45289. }
  45290. assert( pPg->pPager==pPager );
  45291. pPager->aStat[PAGER_STAT_MISS]++;
  45292. rc = readDbPage(pPg, iFrame);
  45293. if( rc!=SQLITE_OK ){
  45294. goto pager_acquire_err;
  45295. }
  45296. }
  45297. pager_set_pagehash(pPg);
  45298. }
  45299. return SQLITE_OK;
  45300. pager_acquire_err:
  45301. assert( rc!=SQLITE_OK );
  45302. if( pPg ){
  45303. sqlite3PcacheDrop(pPg);
  45304. }
  45305. pagerUnlockIfUnused(pPager);
  45306. *ppPage = 0;
  45307. return rc;
  45308. }
  45309. /*
  45310. ** Acquire a page if it is already in the in-memory cache. Do
  45311. ** not read the page from disk. Return a pointer to the page,
  45312. ** or 0 if the page is not in cache.
  45313. **
  45314. ** See also sqlite3PagerGet(). The difference between this routine
  45315. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  45316. ** in the page if the page is not already in cache. This routine
  45317. ** returns NULL if the page is not in cache or if a disk I/O error
  45318. ** has ever happened.
  45319. */
  45320. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  45321. sqlite3_pcache_page *pPage;
  45322. assert( pPager!=0 );
  45323. assert( pgno!=0 );
  45324. assert( pPager->pPCache!=0 );
  45325. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  45326. assert( pPage==0 || pPager->hasHeldSharedLock );
  45327. if( pPage==0 ) return 0;
  45328. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  45329. }
  45330. /*
  45331. ** Release a page reference.
  45332. **
  45333. ** If the number of references to the page drop to zero, then the
  45334. ** page is added to the LRU list. When all references to all pages
  45335. ** are released, a rollback occurs and the lock on the database is
  45336. ** removed.
  45337. */
  45338. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  45339. Pager *pPager;
  45340. assert( pPg!=0 );
  45341. pPager = pPg->pPager;
  45342. if( pPg->flags & PGHDR_MMAP ){
  45343. pagerReleaseMapPage(pPg);
  45344. }else{
  45345. sqlite3PcacheRelease(pPg);
  45346. }
  45347. pagerUnlockIfUnused(pPager);
  45348. }
  45349. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  45350. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  45351. }
  45352. /*
  45353. ** This function is called at the start of every write transaction.
  45354. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  45355. ** file when this routine is called.
  45356. **
  45357. ** Open the journal file for pager pPager and write a journal header
  45358. ** to the start of it. If there are active savepoints, open the sub-journal
  45359. ** as well. This function is only used when the journal file is being
  45360. ** opened to write a rollback log for a transaction. It is not used
  45361. ** when opening a hot journal file to roll it back.
  45362. **
  45363. ** If the journal file is already open (as it may be in exclusive mode),
  45364. ** then this function just writes a journal header to the start of the
  45365. ** already open file.
  45366. **
  45367. ** Whether or not the journal file is opened by this function, the
  45368. ** Pager.pInJournal bitvec structure is allocated.
  45369. **
  45370. ** Return SQLITE_OK if everything is successful. Otherwise, return
  45371. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  45372. ** an IO error code if opening or writing the journal file fails.
  45373. */
  45374. static int pager_open_journal(Pager *pPager){
  45375. int rc = SQLITE_OK; /* Return code */
  45376. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  45377. assert( pPager->eState==PAGER_WRITER_LOCKED );
  45378. assert( assert_pager_state(pPager) );
  45379. assert( pPager->pInJournal==0 );
  45380. /* If already in the error state, this function is a no-op. But on
  45381. ** the other hand, this routine is never called if we are already in
  45382. ** an error state. */
  45383. if( NEVER(pPager->errCode) ) return pPager->errCode;
  45384. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  45385. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  45386. if( pPager->pInJournal==0 ){
  45387. return SQLITE_NOMEM;
  45388. }
  45389. /* Open the journal file if it is not already open. */
  45390. if( !isOpen(pPager->jfd) ){
  45391. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  45392. sqlite3MemJournalOpen(pPager->jfd);
  45393. }else{
  45394. const int flags = /* VFS flags to open journal file */
  45395. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  45396. (pPager->tempFile ?
  45397. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  45398. (SQLITE_OPEN_MAIN_JOURNAL)
  45399. );
  45400. /* Verify that the database still has the same name as it did when
  45401. ** it was originally opened. */
  45402. rc = databaseIsUnmoved(pPager);
  45403. if( rc==SQLITE_OK ){
  45404. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45405. rc = sqlite3JournalOpen(
  45406. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  45407. );
  45408. #else
  45409. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  45410. #endif
  45411. }
  45412. }
  45413. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  45414. }
  45415. /* Write the first journal header to the journal file and open
  45416. ** the sub-journal if necessary.
  45417. */
  45418. if( rc==SQLITE_OK ){
  45419. /* TODO: Check if all of these are really required. */
  45420. pPager->nRec = 0;
  45421. pPager->journalOff = 0;
  45422. pPager->setMaster = 0;
  45423. pPager->journalHdr = 0;
  45424. rc = writeJournalHdr(pPager);
  45425. }
  45426. }
  45427. if( rc!=SQLITE_OK ){
  45428. sqlite3BitvecDestroy(pPager->pInJournal);
  45429. pPager->pInJournal = 0;
  45430. }else{
  45431. assert( pPager->eState==PAGER_WRITER_LOCKED );
  45432. pPager->eState = PAGER_WRITER_CACHEMOD;
  45433. }
  45434. return rc;
  45435. }
  45436. /*
  45437. ** Begin a write-transaction on the specified pager object. If a
  45438. ** write-transaction has already been opened, this function is a no-op.
  45439. **
  45440. ** If the exFlag argument is false, then acquire at least a RESERVED
  45441. ** lock on the database file. If exFlag is true, then acquire at least
  45442. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  45443. ** functions need be called.
  45444. **
  45445. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  45446. ** within this transaction will be opened as an in-memory file. This
  45447. ** has no effect if the sub-journal is already opened (as it may be when
  45448. ** running in exclusive mode) or if the transaction does not require a
  45449. ** sub-journal. If the subjInMemory argument is zero, then any required
  45450. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  45451. ** or using a temporary file otherwise.
  45452. */
  45453. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  45454. int rc = SQLITE_OK;
  45455. if( pPager->errCode ) return pPager->errCode;
  45456. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  45457. pPager->subjInMemory = (u8)subjInMemory;
  45458. if( ALWAYS(pPager->eState==PAGER_READER) ){
  45459. assert( pPager->pInJournal==0 );
  45460. if( pagerUseWal(pPager) ){
  45461. /* If the pager is configured to use locking_mode=exclusive, and an
  45462. ** exclusive lock on the database is not already held, obtain it now.
  45463. */
  45464. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  45465. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45466. if( rc!=SQLITE_OK ){
  45467. return rc;
  45468. }
  45469. sqlite3WalExclusiveMode(pPager->pWal, 1);
  45470. }
  45471. /* Grab the write lock on the log file. If successful, upgrade to
  45472. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  45473. ** The busy-handler is not invoked if another connection already
  45474. ** holds the write-lock. If possible, the upper layer will call it.
  45475. */
  45476. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  45477. }else{
  45478. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  45479. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  45480. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  45481. ** lock, but not when obtaining the RESERVED lock.
  45482. */
  45483. rc = pagerLockDb(pPager, RESERVED_LOCK);
  45484. if( rc==SQLITE_OK && exFlag ){
  45485. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  45486. }
  45487. }
  45488. if( rc==SQLITE_OK ){
  45489. /* Change to WRITER_LOCKED state.
  45490. **
  45491. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  45492. ** when it has an open transaction, but never to DBMOD or FINISHED.
  45493. ** This is because in those states the code to roll back savepoint
  45494. ** transactions may copy data from the sub-journal into the database
  45495. ** file as well as into the page cache. Which would be incorrect in
  45496. ** WAL mode.
  45497. */
  45498. pPager->eState = PAGER_WRITER_LOCKED;
  45499. pPager->dbHintSize = pPager->dbSize;
  45500. pPager->dbFileSize = pPager->dbSize;
  45501. pPager->dbOrigSize = pPager->dbSize;
  45502. pPager->journalOff = 0;
  45503. }
  45504. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  45505. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  45506. assert( assert_pager_state(pPager) );
  45507. }
  45508. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  45509. return rc;
  45510. }
  45511. /*
  45512. ** Write page pPg onto the end of the rollback journal.
  45513. */
  45514. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  45515. Pager *pPager = pPg->pPager;
  45516. int rc;
  45517. u32 cksum;
  45518. char *pData2;
  45519. i64 iOff = pPager->journalOff;
  45520. /* We should never write to the journal file the page that
  45521. ** contains the database locks. The following assert verifies
  45522. ** that we do not. */
  45523. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  45524. assert( pPager->journalHdr<=pPager->journalOff );
  45525. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  45526. cksum = pager_cksum(pPager, (u8*)pData2);
  45527. /* Even if an IO or diskfull error occurs while journalling the
  45528. ** page in the block above, set the need-sync flag for the page.
  45529. ** Otherwise, when the transaction is rolled back, the logic in
  45530. ** playback_one_page() will think that the page needs to be restored
  45531. ** in the database file. And if an IO error occurs while doing so,
  45532. ** then corruption may follow.
  45533. */
  45534. pPg->flags |= PGHDR_NEED_SYNC;
  45535. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  45536. if( rc!=SQLITE_OK ) return rc;
  45537. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  45538. if( rc!=SQLITE_OK ) return rc;
  45539. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  45540. if( rc!=SQLITE_OK ) return rc;
  45541. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  45542. pPager->journalOff, pPager->pageSize));
  45543. PAGER_INCR(sqlite3_pager_writej_count);
  45544. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  45545. PAGERID(pPager), pPg->pgno,
  45546. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  45547. pPager->journalOff += 8 + pPager->pageSize;
  45548. pPager->nRec++;
  45549. assert( pPager->pInJournal!=0 );
  45550. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  45551. testcase( rc==SQLITE_NOMEM );
  45552. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45553. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  45554. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45555. return rc;
  45556. }
  45557. /*
  45558. ** Mark a single data page as writeable. The page is written into the
  45559. ** main journal or sub-journal as required. If the page is written into
  45560. ** one of the journals, the corresponding bit is set in the
  45561. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  45562. ** of any open savepoints as appropriate.
  45563. */
  45564. static int pager_write(PgHdr *pPg){
  45565. Pager *pPager = pPg->pPager;
  45566. int rc = SQLITE_OK;
  45567. /* This routine is not called unless a write-transaction has already
  45568. ** been started. The journal file may or may not be open at this point.
  45569. ** It is never called in the ERROR state.
  45570. */
  45571. assert( pPager->eState==PAGER_WRITER_LOCKED
  45572. || pPager->eState==PAGER_WRITER_CACHEMOD
  45573. || pPager->eState==PAGER_WRITER_DBMOD
  45574. );
  45575. assert( assert_pager_state(pPager) );
  45576. assert( pPager->errCode==0 );
  45577. assert( pPager->readOnly==0 );
  45578. CHECK_PAGE(pPg);
  45579. /* The journal file needs to be opened. Higher level routines have already
  45580. ** obtained the necessary locks to begin the write-transaction, but the
  45581. ** rollback journal might not yet be open. Open it now if this is the case.
  45582. **
  45583. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  45584. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  45585. ** an error might occur and the pager would end up in WRITER_LOCKED state
  45586. ** with pages marked as dirty in the cache.
  45587. */
  45588. if( pPager->eState==PAGER_WRITER_LOCKED ){
  45589. rc = pager_open_journal(pPager);
  45590. if( rc!=SQLITE_OK ) return rc;
  45591. }
  45592. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  45593. assert( assert_pager_state(pPager) );
  45594. /* Mark the page that is about to be modified as dirty. */
  45595. sqlite3PcacheMakeDirty(pPg);
  45596. /* If a rollback journal is in use, them make sure the page that is about
  45597. ** to change is in the rollback journal, or if the page is a new page off
  45598. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  45599. */
  45600. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  45601. if( pPager->pInJournal!=0
  45602. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  45603. ){
  45604. assert( pagerUseWal(pPager)==0 );
  45605. if( pPg->pgno<=pPager->dbOrigSize ){
  45606. rc = pagerAddPageToRollbackJournal(pPg);
  45607. if( rc!=SQLITE_OK ){
  45608. return rc;
  45609. }
  45610. }else{
  45611. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  45612. pPg->flags |= PGHDR_NEED_SYNC;
  45613. }
  45614. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  45615. PAGERID(pPager), pPg->pgno,
  45616. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  45617. }
  45618. }
  45619. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  45620. ** and before writing the page into the rollback journal. Wait until now,
  45621. ** after the page has been successfully journalled, before setting the
  45622. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  45623. */
  45624. pPg->flags |= PGHDR_WRITEABLE;
  45625. /* If the statement journal is open and the page is not in it,
  45626. ** then write the page into the statement journal.
  45627. */
  45628. if( pPager->nSavepoint>0 ){
  45629. rc = subjournalPageIfRequired(pPg);
  45630. }
  45631. /* Update the database size and return. */
  45632. if( pPager->dbSize<pPg->pgno ){
  45633. pPager->dbSize = pPg->pgno;
  45634. }
  45635. return rc;
  45636. }
  45637. /*
  45638. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  45639. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  45640. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  45641. ** a sector need to be journalled in case of a power loss in the middle of
  45642. ** a write.
  45643. **
  45644. ** Usually, the sector size is less than or equal to the page size, in which
  45645. ** case pages can be individually written. This routine only runs in the
  45646. ** exceptional case where the page size is smaller than the sector size.
  45647. */
  45648. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  45649. int rc = SQLITE_OK; /* Return code */
  45650. Pgno nPageCount; /* Total number of pages in database file */
  45651. Pgno pg1; /* First page of the sector pPg is located on. */
  45652. int nPage = 0; /* Number of pages starting at pg1 to journal */
  45653. int ii; /* Loop counter */
  45654. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  45655. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  45656. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  45657. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  45658. ** a journal header to be written between the pages journaled by
  45659. ** this function.
  45660. */
  45661. assert( !MEMDB );
  45662. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  45663. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  45664. /* This trick assumes that both the page-size and sector-size are
  45665. ** an integer power of 2. It sets variable pg1 to the identifier
  45666. ** of the first page of the sector pPg is located on.
  45667. */
  45668. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  45669. nPageCount = pPager->dbSize;
  45670. if( pPg->pgno>nPageCount ){
  45671. nPage = (pPg->pgno - pg1)+1;
  45672. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  45673. nPage = nPageCount+1-pg1;
  45674. }else{
  45675. nPage = nPagePerSector;
  45676. }
  45677. assert(nPage>0);
  45678. assert(pg1<=pPg->pgno);
  45679. assert((pg1+nPage)>pPg->pgno);
  45680. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  45681. Pgno pg = pg1+ii;
  45682. PgHdr *pPage;
  45683. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  45684. if( pg!=PAGER_MJ_PGNO(pPager) ){
  45685. rc = sqlite3PagerGet(pPager, pg, &pPage);
  45686. if( rc==SQLITE_OK ){
  45687. rc = pager_write(pPage);
  45688. if( pPage->flags&PGHDR_NEED_SYNC ){
  45689. needSync = 1;
  45690. }
  45691. sqlite3PagerUnrefNotNull(pPage);
  45692. }
  45693. }
  45694. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  45695. if( pPage->flags&PGHDR_NEED_SYNC ){
  45696. needSync = 1;
  45697. }
  45698. sqlite3PagerUnrefNotNull(pPage);
  45699. }
  45700. }
  45701. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  45702. ** starting at pg1, then it needs to be set for all of them. Because
  45703. ** writing to any of these nPage pages may damage the others, the
  45704. ** journal file must contain sync()ed copies of all of them
  45705. ** before any of them can be written out to the database file.
  45706. */
  45707. if( rc==SQLITE_OK && needSync ){
  45708. assert( !MEMDB );
  45709. for(ii=0; ii<nPage; ii++){
  45710. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  45711. if( pPage ){
  45712. pPage->flags |= PGHDR_NEED_SYNC;
  45713. sqlite3PagerUnrefNotNull(pPage);
  45714. }
  45715. }
  45716. }
  45717. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  45718. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  45719. return rc;
  45720. }
  45721. /*
  45722. ** Mark a data page as writeable. This routine must be called before
  45723. ** making changes to a page. The caller must check the return value
  45724. ** of this function and be careful not to change any page data unless
  45725. ** this routine returns SQLITE_OK.
  45726. **
  45727. ** The difference between this function and pager_write() is that this
  45728. ** function also deals with the special case where 2 or more pages
  45729. ** fit on a single disk sector. In this case all co-resident pages
  45730. ** must have been written to the journal file before returning.
  45731. **
  45732. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  45733. ** as appropriate. Otherwise, SQLITE_OK.
  45734. */
  45735. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  45736. Pager *pPager = pPg->pPager;
  45737. assert( (pPg->flags & PGHDR_MMAP)==0 );
  45738. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45739. assert( pPager->eState!=PAGER_ERROR );
  45740. assert( assert_pager_state(pPager) );
  45741. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  45742. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  45743. return SQLITE_OK;
  45744. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  45745. return pagerWriteLargeSector(pPg);
  45746. }else{
  45747. return pager_write(pPg);
  45748. }
  45749. }
  45750. /*
  45751. ** Return TRUE if the page given in the argument was previously passed
  45752. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  45753. ** to change the content of the page.
  45754. */
  45755. #ifndef NDEBUG
  45756. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  45757. return pPg->flags & PGHDR_WRITEABLE;
  45758. }
  45759. #endif
  45760. /*
  45761. ** A call to this routine tells the pager that it is not necessary to
  45762. ** write the information on page pPg back to the disk, even though
  45763. ** that page might be marked as dirty. This happens, for example, when
  45764. ** the page has been added as a leaf of the freelist and so its
  45765. ** content no longer matters.
  45766. **
  45767. ** The overlying software layer calls this routine when all of the data
  45768. ** on the given page is unused. The pager marks the page as clean so
  45769. ** that it does not get written to disk.
  45770. **
  45771. ** Tests show that this optimization can quadruple the speed of large
  45772. ** DELETE operations.
  45773. */
  45774. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  45775. Pager *pPager = pPg->pPager;
  45776. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  45777. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  45778. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  45779. pPg->flags |= PGHDR_DONT_WRITE;
  45780. pPg->flags &= ~PGHDR_WRITEABLE;
  45781. pager_set_pagehash(pPg);
  45782. }
  45783. }
  45784. /*
  45785. ** This routine is called to increment the value of the database file
  45786. ** change-counter, stored as a 4-byte big-endian integer starting at
  45787. ** byte offset 24 of the pager file. The secondary change counter at
  45788. ** 92 is also updated, as is the SQLite version number at offset 96.
  45789. **
  45790. ** But this only happens if the pPager->changeCountDone flag is false.
  45791. ** To avoid excess churning of page 1, the update only happens once.
  45792. ** See also the pager_write_changecounter() routine that does an
  45793. ** unconditional update of the change counters.
  45794. **
  45795. ** If the isDirectMode flag is zero, then this is done by calling
  45796. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  45797. ** page data. In this case the file will be updated when the current
  45798. ** transaction is committed.
  45799. **
  45800. ** The isDirectMode flag may only be non-zero if the library was compiled
  45801. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  45802. ** if isDirect is non-zero, then the database file is updated directly
  45803. ** by writing an updated version of page 1 using a call to the
  45804. ** sqlite3OsWrite() function.
  45805. */
  45806. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  45807. int rc = SQLITE_OK;
  45808. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45809. || pPager->eState==PAGER_WRITER_DBMOD
  45810. );
  45811. assert( assert_pager_state(pPager) );
  45812. /* Declare and initialize constant integer 'isDirect'. If the
  45813. ** atomic-write optimization is enabled in this build, then isDirect
  45814. ** is initialized to the value passed as the isDirectMode parameter
  45815. ** to this function. Otherwise, it is always set to zero.
  45816. **
  45817. ** The idea is that if the atomic-write optimization is not
  45818. ** enabled at compile time, the compiler can omit the tests of
  45819. ** 'isDirect' below, as well as the block enclosed in the
  45820. ** "if( isDirect )" condition.
  45821. */
  45822. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  45823. # define DIRECT_MODE 0
  45824. assert( isDirectMode==0 );
  45825. UNUSED_PARAMETER(isDirectMode);
  45826. #else
  45827. # define DIRECT_MODE isDirectMode
  45828. #endif
  45829. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  45830. PgHdr *pPgHdr; /* Reference to page 1 */
  45831. assert( !pPager->tempFile && isOpen(pPager->fd) );
  45832. /* Open page 1 of the file for writing. */
  45833. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  45834. assert( pPgHdr==0 || rc==SQLITE_OK );
  45835. /* If page one was fetched successfully, and this function is not
  45836. ** operating in direct-mode, make page 1 writable. When not in
  45837. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  45838. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  45839. */
  45840. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  45841. rc = sqlite3PagerWrite(pPgHdr);
  45842. }
  45843. if( rc==SQLITE_OK ){
  45844. /* Actually do the update of the change counter */
  45845. pager_write_changecounter(pPgHdr);
  45846. /* If running in direct mode, write the contents of page 1 to the file. */
  45847. if( DIRECT_MODE ){
  45848. const void *zBuf;
  45849. assert( pPager->dbFileSize>0 );
  45850. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  45851. if( rc==SQLITE_OK ){
  45852. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  45853. pPager->aStat[PAGER_STAT_WRITE]++;
  45854. }
  45855. if( rc==SQLITE_OK ){
  45856. /* Update the pager's copy of the change-counter. Otherwise, the
  45857. ** next time a read transaction is opened the cache will be
  45858. ** flushed (as the change-counter values will not match). */
  45859. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  45860. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  45861. pPager->changeCountDone = 1;
  45862. }
  45863. }else{
  45864. pPager->changeCountDone = 1;
  45865. }
  45866. }
  45867. /* Release the page reference. */
  45868. sqlite3PagerUnref(pPgHdr);
  45869. }
  45870. return rc;
  45871. }
  45872. /*
  45873. ** Sync the database file to disk. This is a no-op for in-memory databases
  45874. ** or pages with the Pager.noSync flag set.
  45875. **
  45876. ** If successful, or if called on a pager for which it is a no-op, this
  45877. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  45878. */
  45879. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  45880. int rc = SQLITE_OK;
  45881. if( isOpen(pPager->fd) ){
  45882. void *pArg = (void*)zMaster;
  45883. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  45884. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45885. }
  45886. if( rc==SQLITE_OK && !pPager->noSync ){
  45887. assert( !MEMDB );
  45888. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  45889. }
  45890. return rc;
  45891. }
  45892. /*
  45893. ** This function may only be called while a write-transaction is active in
  45894. ** rollback. If the connection is in WAL mode, this call is a no-op.
  45895. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  45896. ** the database file, an attempt is made to obtain one.
  45897. **
  45898. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  45899. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  45900. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  45901. ** returned.
  45902. */
  45903. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  45904. int rc = SQLITE_OK;
  45905. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45906. || pPager->eState==PAGER_WRITER_DBMOD
  45907. || pPager->eState==PAGER_WRITER_LOCKED
  45908. );
  45909. assert( assert_pager_state(pPager) );
  45910. if( 0==pagerUseWal(pPager) ){
  45911. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  45912. }
  45913. return rc;
  45914. }
  45915. /*
  45916. ** Sync the database file for the pager pPager. zMaster points to the name
  45917. ** of a master journal file that should be written into the individual
  45918. ** journal file. zMaster may be NULL, which is interpreted as no master
  45919. ** journal (a single database transaction).
  45920. **
  45921. ** This routine ensures that:
  45922. **
  45923. ** * The database file change-counter is updated,
  45924. ** * the journal is synced (unless the atomic-write optimization is used),
  45925. ** * all dirty pages are written to the database file,
  45926. ** * the database file is truncated (if required), and
  45927. ** * the database file synced.
  45928. **
  45929. ** The only thing that remains to commit the transaction is to finalize
  45930. ** (delete, truncate or zero the first part of) the journal file (or
  45931. ** delete the master journal file if specified).
  45932. **
  45933. ** Note that if zMaster==NULL, this does not overwrite a previous value
  45934. ** passed to an sqlite3PagerCommitPhaseOne() call.
  45935. **
  45936. ** If the final parameter - noSync - is true, then the database file itself
  45937. ** is not synced. The caller must call sqlite3PagerSync() directly to
  45938. ** sync the database file before calling CommitPhaseTwo() to delete the
  45939. ** journal file in this case.
  45940. */
  45941. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  45942. Pager *pPager, /* Pager object */
  45943. const char *zMaster, /* If not NULL, the master journal name */
  45944. int noSync /* True to omit the xSync on the db file */
  45945. ){
  45946. int rc = SQLITE_OK; /* Return code */
  45947. assert( pPager->eState==PAGER_WRITER_LOCKED
  45948. || pPager->eState==PAGER_WRITER_CACHEMOD
  45949. || pPager->eState==PAGER_WRITER_DBMOD
  45950. || pPager->eState==PAGER_ERROR
  45951. );
  45952. assert( assert_pager_state(pPager) );
  45953. /* If a prior error occurred, report that error again. */
  45954. if( NEVER(pPager->errCode) ) return pPager->errCode;
  45955. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  45956. pPager->zFilename, zMaster, pPager->dbSize));
  45957. /* If no database changes have been made, return early. */
  45958. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  45959. if( MEMDB ){
  45960. /* If this is an in-memory db, or no pages have been written to, or this
  45961. ** function has already been called, it is mostly a no-op. However, any
  45962. ** backup in progress needs to be restarted.
  45963. */
  45964. sqlite3BackupRestart(pPager->pBackup);
  45965. }else{
  45966. if( pagerUseWal(pPager) ){
  45967. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  45968. PgHdr *pPageOne = 0;
  45969. if( pList==0 ){
  45970. /* Must have at least one page for the WAL commit flag.
  45971. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  45972. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  45973. pList = pPageOne;
  45974. pList->pDirty = 0;
  45975. }
  45976. assert( rc==SQLITE_OK );
  45977. if( ALWAYS(pList) ){
  45978. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  45979. }
  45980. sqlite3PagerUnref(pPageOne);
  45981. if( rc==SQLITE_OK ){
  45982. sqlite3PcacheCleanAll(pPager->pPCache);
  45983. }
  45984. }else{
  45985. /* The following block updates the change-counter. Exactly how it
  45986. ** does this depends on whether or not the atomic-update optimization
  45987. ** was enabled at compile time, and if this transaction meets the
  45988. ** runtime criteria to use the operation:
  45989. **
  45990. ** * The file-system supports the atomic-write property for
  45991. ** blocks of size page-size, and
  45992. ** * This commit is not part of a multi-file transaction, and
  45993. ** * Exactly one page has been modified and store in the journal file.
  45994. **
  45995. ** If the optimization was not enabled at compile time, then the
  45996. ** pager_incr_changecounter() function is called to update the change
  45997. ** counter in 'indirect-mode'. If the optimization is compiled in but
  45998. ** is not applicable to this transaction, call sqlite3JournalCreate()
  45999. ** to make sure the journal file has actually been created, then call
  46000. ** pager_incr_changecounter() to update the change-counter in indirect
  46001. ** mode.
  46002. **
  46003. ** Otherwise, if the optimization is both enabled and applicable,
  46004. ** then call pager_incr_changecounter() to update the change-counter
  46005. ** in 'direct' mode. In this case the journal file will never be
  46006. ** created for this transaction.
  46007. */
  46008. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  46009. PgHdr *pPg;
  46010. assert( isOpen(pPager->jfd)
  46011. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  46012. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  46013. );
  46014. if( !zMaster && isOpen(pPager->jfd)
  46015. && pPager->journalOff==jrnlBufferSize(pPager)
  46016. && pPager->dbSize>=pPager->dbOrigSize
  46017. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  46018. ){
  46019. /* Update the db file change counter via the direct-write method. The
  46020. ** following call will modify the in-memory representation of page 1
  46021. ** to include the updated change counter and then write page 1
  46022. ** directly to the database file. Because of the atomic-write
  46023. ** property of the host file-system, this is safe.
  46024. */
  46025. rc = pager_incr_changecounter(pPager, 1);
  46026. }else{
  46027. rc = sqlite3JournalCreate(pPager->jfd);
  46028. if( rc==SQLITE_OK ){
  46029. rc = pager_incr_changecounter(pPager, 0);
  46030. }
  46031. }
  46032. #else
  46033. rc = pager_incr_changecounter(pPager, 0);
  46034. #endif
  46035. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46036. /* Write the master journal name into the journal file. If a master
  46037. ** journal file name has already been written to the journal file,
  46038. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  46039. */
  46040. rc = writeMasterJournal(pPager, zMaster);
  46041. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46042. /* Sync the journal file and write all dirty pages to the database.
  46043. ** If the atomic-update optimization is being used, this sync will not
  46044. ** create the journal file or perform any real IO.
  46045. **
  46046. ** Because the change-counter page was just modified, unless the
  46047. ** atomic-update optimization is used it is almost certain that the
  46048. ** journal requires a sync here. However, in locking_mode=exclusive
  46049. ** on a system under memory pressure it is just possible that this is
  46050. ** not the case. In this case it is likely enough that the redundant
  46051. ** xSync() call will be changed to a no-op by the OS anyhow.
  46052. */
  46053. rc = syncJournal(pPager, 0);
  46054. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46055. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  46056. if( rc!=SQLITE_OK ){
  46057. assert( rc!=SQLITE_IOERR_BLOCKED );
  46058. goto commit_phase_one_exit;
  46059. }
  46060. sqlite3PcacheCleanAll(pPager->pPCache);
  46061. /* If the file on disk is smaller than the database image, use
  46062. ** pager_truncate to grow the file here. This can happen if the database
  46063. ** image was extended as part of the current transaction and then the
  46064. ** last page in the db image moved to the free-list. In this case the
  46065. ** last page is never written out to disk, leaving the database file
  46066. ** undersized. Fix this now if it is the case. */
  46067. if( pPager->dbSize>pPager->dbFileSize ){
  46068. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  46069. assert( pPager->eState==PAGER_WRITER_DBMOD );
  46070. rc = pager_truncate(pPager, nNew);
  46071. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46072. }
  46073. /* Finally, sync the database file. */
  46074. if( !noSync ){
  46075. rc = sqlite3PagerSync(pPager, zMaster);
  46076. }
  46077. IOTRACE(("DBSYNC %p\n", pPager))
  46078. }
  46079. }
  46080. commit_phase_one_exit:
  46081. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  46082. pPager->eState = PAGER_WRITER_FINISHED;
  46083. }
  46084. return rc;
  46085. }
  46086. /*
  46087. ** When this function is called, the database file has been completely
  46088. ** updated to reflect the changes made by the current transaction and
  46089. ** synced to disk. The journal file still exists in the file-system
  46090. ** though, and if a failure occurs at this point it will eventually
  46091. ** be used as a hot-journal and the current transaction rolled back.
  46092. **
  46093. ** This function finalizes the journal file, either by deleting,
  46094. ** truncating or partially zeroing it, so that it cannot be used
  46095. ** for hot-journal rollback. Once this is done the transaction is
  46096. ** irrevocably committed.
  46097. **
  46098. ** If an error occurs, an IO error code is returned and the pager
  46099. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  46100. */
  46101. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  46102. int rc = SQLITE_OK; /* Return code */
  46103. /* This routine should not be called if a prior error has occurred.
  46104. ** But if (due to a coding error elsewhere in the system) it does get
  46105. ** called, just return the same error code without doing anything. */
  46106. if( NEVER(pPager->errCode) ) return pPager->errCode;
  46107. assert( pPager->eState==PAGER_WRITER_LOCKED
  46108. || pPager->eState==PAGER_WRITER_FINISHED
  46109. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  46110. );
  46111. assert( assert_pager_state(pPager) );
  46112. /* An optimization. If the database was not actually modified during
  46113. ** this transaction, the pager is running in exclusive-mode and is
  46114. ** using persistent journals, then this function is a no-op.
  46115. **
  46116. ** The start of the journal file currently contains a single journal
  46117. ** header with the nRec field set to 0. If such a journal is used as
  46118. ** a hot-journal during hot-journal rollback, 0 changes will be made
  46119. ** to the database file. So there is no need to zero the journal
  46120. ** header. Since the pager is in exclusive mode, there is no need
  46121. ** to drop any locks either.
  46122. */
  46123. if( pPager->eState==PAGER_WRITER_LOCKED
  46124. && pPager->exclusiveMode
  46125. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  46126. ){
  46127. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  46128. pPager->eState = PAGER_READER;
  46129. return SQLITE_OK;
  46130. }
  46131. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  46132. pPager->iDataVersion++;
  46133. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  46134. return pager_error(pPager, rc);
  46135. }
  46136. /*
  46137. ** If a write transaction is open, then all changes made within the
  46138. ** transaction are reverted and the current write-transaction is closed.
  46139. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  46140. ** state if an error occurs.
  46141. **
  46142. ** If the pager is already in PAGER_ERROR state when this function is called,
  46143. ** it returns Pager.errCode immediately. No work is performed in this case.
  46144. **
  46145. ** Otherwise, in rollback mode, this function performs two functions:
  46146. **
  46147. ** 1) It rolls back the journal file, restoring all database file and
  46148. ** in-memory cache pages to the state they were in when the transaction
  46149. ** was opened, and
  46150. **
  46151. ** 2) It finalizes the journal file, so that it is not used for hot
  46152. ** rollback at any point in the future.
  46153. **
  46154. ** Finalization of the journal file (task 2) is only performed if the
  46155. ** rollback is successful.
  46156. **
  46157. ** In WAL mode, all cache-entries containing data modified within the
  46158. ** current transaction are either expelled from the cache or reverted to
  46159. ** their pre-transaction state by re-reading data from the database or
  46160. ** WAL files. The WAL transaction is then closed.
  46161. */
  46162. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  46163. int rc = SQLITE_OK; /* Return code */
  46164. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  46165. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  46166. ** the pager is already in the ERROR state, the rollback is not
  46167. ** attempted here. Instead, the error code is returned to the caller.
  46168. */
  46169. assert( assert_pager_state(pPager) );
  46170. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  46171. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  46172. if( pagerUseWal(pPager) ){
  46173. int rc2;
  46174. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  46175. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  46176. if( rc==SQLITE_OK ) rc = rc2;
  46177. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  46178. int eState = pPager->eState;
  46179. rc = pager_end_transaction(pPager, 0, 0);
  46180. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  46181. /* This can happen using journal_mode=off. Move the pager to the error
  46182. ** state to indicate that the contents of the cache may not be trusted.
  46183. ** Any active readers will get SQLITE_ABORT.
  46184. */
  46185. pPager->errCode = SQLITE_ABORT;
  46186. pPager->eState = PAGER_ERROR;
  46187. return rc;
  46188. }
  46189. }else{
  46190. rc = pager_playback(pPager, 0);
  46191. }
  46192. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  46193. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  46194. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  46195. || rc==SQLITE_CANTOPEN
  46196. );
  46197. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  46198. ** cache. So call pager_error() on the way out to make any error persistent.
  46199. */
  46200. return pager_error(pPager, rc);
  46201. }
  46202. /*
  46203. ** Return TRUE if the database file is opened read-only. Return FALSE
  46204. ** if the database is (in theory) writable.
  46205. */
  46206. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  46207. return pPager->readOnly;
  46208. }
  46209. #ifdef SQLITE_DEBUG
  46210. /*
  46211. ** Return the sum of the reference counts for all pages held by pPager.
  46212. */
  46213. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  46214. return sqlite3PcacheRefCount(pPager->pPCache);
  46215. }
  46216. #endif
  46217. /*
  46218. ** Return the approximate number of bytes of memory currently
  46219. ** used by the pager and its associated cache.
  46220. */
  46221. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  46222. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  46223. + 5*sizeof(void*);
  46224. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  46225. + sqlite3MallocSize(pPager)
  46226. + pPager->pageSize;
  46227. }
  46228. /*
  46229. ** Return the number of references to the specified page.
  46230. */
  46231. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  46232. return sqlite3PcachePageRefcount(pPage);
  46233. }
  46234. #ifdef SQLITE_TEST
  46235. /*
  46236. ** This routine is used for testing and analysis only.
  46237. */
  46238. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  46239. static int a[11];
  46240. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  46241. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  46242. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  46243. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  46244. a[4] = pPager->eState;
  46245. a[5] = pPager->errCode;
  46246. a[6] = pPager->aStat[PAGER_STAT_HIT];
  46247. a[7] = pPager->aStat[PAGER_STAT_MISS];
  46248. a[8] = 0; /* Used to be pPager->nOvfl */
  46249. a[9] = pPager->nRead;
  46250. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  46251. return a;
  46252. }
  46253. #endif
  46254. /*
  46255. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  46256. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  46257. ** current cache hit or miss count, according to the value of eStat. If the
  46258. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  46259. ** returning.
  46260. */
  46261. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  46262. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  46263. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  46264. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  46265. );
  46266. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  46267. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  46268. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  46269. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  46270. if( reset ){
  46271. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  46272. }
  46273. }
  46274. /*
  46275. ** Return true if this is an in-memory pager.
  46276. */
  46277. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  46278. return MEMDB;
  46279. }
  46280. /*
  46281. ** Check that there are at least nSavepoint savepoints open. If there are
  46282. ** currently less than nSavepoints open, then open one or more savepoints
  46283. ** to make up the difference. If the number of savepoints is already
  46284. ** equal to nSavepoint, then this function is a no-op.
  46285. **
  46286. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  46287. ** occurs while opening the sub-journal file, then an IO error code is
  46288. ** returned. Otherwise, SQLITE_OK.
  46289. */
  46290. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  46291. int rc = SQLITE_OK; /* Return code */
  46292. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  46293. int ii; /* Iterator variable */
  46294. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  46295. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46296. assert( assert_pager_state(pPager) );
  46297. assert( nSavepoint>nCurrent && pPager->useJournal );
  46298. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  46299. ** if the allocation fails. Otherwise, zero the new portion in case a
  46300. ** malloc failure occurs while populating it in the for(...) loop below.
  46301. */
  46302. aNew = (PagerSavepoint *)sqlite3Realloc(
  46303. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  46304. );
  46305. if( !aNew ){
  46306. return SQLITE_NOMEM;
  46307. }
  46308. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  46309. pPager->aSavepoint = aNew;
  46310. /* Populate the PagerSavepoint structures just allocated. */
  46311. for(ii=nCurrent; ii<nSavepoint; ii++){
  46312. aNew[ii].nOrig = pPager->dbSize;
  46313. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  46314. aNew[ii].iOffset = pPager->journalOff;
  46315. }else{
  46316. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  46317. }
  46318. aNew[ii].iSubRec = pPager->nSubRec;
  46319. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  46320. if( !aNew[ii].pInSavepoint ){
  46321. return SQLITE_NOMEM;
  46322. }
  46323. if( pagerUseWal(pPager) ){
  46324. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  46325. }
  46326. pPager->nSavepoint = ii+1;
  46327. }
  46328. assert( pPager->nSavepoint==nSavepoint );
  46329. assertTruncateConstraint(pPager);
  46330. return rc;
  46331. }
  46332. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  46333. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46334. assert( assert_pager_state(pPager) );
  46335. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  46336. return pagerOpenSavepoint(pPager, nSavepoint);
  46337. }else{
  46338. return SQLITE_OK;
  46339. }
  46340. }
  46341. /*
  46342. ** This function is called to rollback or release (commit) a savepoint.
  46343. ** The savepoint to release or rollback need not be the most recently
  46344. ** created savepoint.
  46345. **
  46346. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  46347. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  46348. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  46349. ** that have occurred since the specified savepoint was created.
  46350. **
  46351. ** The savepoint to rollback or release is identified by parameter
  46352. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  46353. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  46354. ** on the most recently created savepoint. If iSavepoint is greater than
  46355. ** (Pager.nSavepoint-1), then this function is a no-op.
  46356. **
  46357. ** If a negative value is passed to this function, then the current
  46358. ** transaction is rolled back. This is different to calling
  46359. ** sqlite3PagerRollback() because this function does not terminate
  46360. ** the transaction or unlock the database, it just restores the
  46361. ** contents of the database to its original state.
  46362. **
  46363. ** In any case, all savepoints with an index greater than iSavepoint
  46364. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  46365. ** then savepoint iSavepoint is also destroyed.
  46366. **
  46367. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  46368. ** or an IO error code if an IO error occurs while rolling back a
  46369. ** savepoint. If no errors occur, SQLITE_OK is returned.
  46370. */
  46371. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  46372. int rc = pPager->errCode; /* Return code */
  46373. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  46374. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  46375. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  46376. int ii; /* Iterator variable */
  46377. int nNew; /* Number of remaining savepoints after this op. */
  46378. /* Figure out how many savepoints will still be active after this
  46379. ** operation. Store this value in nNew. Then free resources associated
  46380. ** with any savepoints that are destroyed by this operation.
  46381. */
  46382. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  46383. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  46384. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  46385. }
  46386. pPager->nSavepoint = nNew;
  46387. /* If this is a release of the outermost savepoint, truncate
  46388. ** the sub-journal to zero bytes in size. */
  46389. if( op==SAVEPOINT_RELEASE ){
  46390. if( nNew==0 && isOpen(pPager->sjfd) ){
  46391. /* Only truncate if it is an in-memory sub-journal. */
  46392. if( sqlite3IsMemJournal(pPager->sjfd) ){
  46393. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  46394. assert( rc==SQLITE_OK );
  46395. }
  46396. pPager->nSubRec = 0;
  46397. }
  46398. }
  46399. /* Else this is a rollback operation, playback the specified savepoint.
  46400. ** If this is a temp-file, it is possible that the journal file has
  46401. ** not yet been opened. In this case there have been no changes to
  46402. ** the database file, so the playback operation can be skipped.
  46403. */
  46404. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  46405. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  46406. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  46407. assert(rc!=SQLITE_DONE);
  46408. }
  46409. }
  46410. return rc;
  46411. }
  46412. /*
  46413. ** Return the full pathname of the database file.
  46414. **
  46415. ** Except, if the pager is in-memory only, then return an empty string if
  46416. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  46417. ** used to report the filename to the user, for compatibility with legacy
  46418. ** behavior. But when the Btree needs to know the filename for matching to
  46419. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  46420. ** participate in shared-cache.
  46421. */
  46422. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  46423. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  46424. }
  46425. /*
  46426. ** Return the VFS structure for the pager.
  46427. */
  46428. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  46429. return pPager->pVfs;
  46430. }
  46431. /*
  46432. ** Return the file handle for the database file associated
  46433. ** with the pager. This might return NULL if the file has
  46434. ** not yet been opened.
  46435. */
  46436. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  46437. return pPager->fd;
  46438. }
  46439. /*
  46440. ** Return the full pathname of the journal file.
  46441. */
  46442. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  46443. return pPager->zJournal;
  46444. }
  46445. /*
  46446. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  46447. ** if fsync()s are executed normally.
  46448. */
  46449. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  46450. return pPager->noSync;
  46451. }
  46452. #ifdef SQLITE_HAS_CODEC
  46453. /*
  46454. ** Set or retrieve the codec for this pager
  46455. */
  46456. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  46457. Pager *pPager,
  46458. void *(*xCodec)(void*,void*,Pgno,int),
  46459. void (*xCodecSizeChng)(void*,int,int),
  46460. void (*xCodecFree)(void*),
  46461. void *pCodec
  46462. ){
  46463. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  46464. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  46465. pPager->xCodecSizeChng = xCodecSizeChng;
  46466. pPager->xCodecFree = xCodecFree;
  46467. pPager->pCodec = pCodec;
  46468. pagerReportSize(pPager);
  46469. }
  46470. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  46471. return pPager->pCodec;
  46472. }
  46473. /*
  46474. ** This function is called by the wal module when writing page content
  46475. ** into the log file.
  46476. **
  46477. ** This function returns a pointer to a buffer containing the encrypted
  46478. ** page content. If a malloc fails, this function may return NULL.
  46479. */
  46480. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  46481. void *aData = 0;
  46482. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  46483. return aData;
  46484. }
  46485. /*
  46486. ** Return the current pager state
  46487. */
  46488. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  46489. return pPager->eState;
  46490. }
  46491. #endif /* SQLITE_HAS_CODEC */
  46492. #ifndef SQLITE_OMIT_AUTOVACUUM
  46493. /*
  46494. ** Move the page pPg to location pgno in the file.
  46495. **
  46496. ** There must be no references to the page previously located at
  46497. ** pgno (which we call pPgOld) though that page is allowed to be
  46498. ** in cache. If the page previously located at pgno is not already
  46499. ** in the rollback journal, it is not put there by by this routine.
  46500. **
  46501. ** References to the page pPg remain valid. Updating any
  46502. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  46503. ** allocated along with the page) is the responsibility of the caller.
  46504. **
  46505. ** A transaction must be active when this routine is called. It used to be
  46506. ** required that a statement transaction was not active, but this restriction
  46507. ** has been removed (CREATE INDEX needs to move a page when a statement
  46508. ** transaction is active).
  46509. **
  46510. ** If the fourth argument, isCommit, is non-zero, then this page is being
  46511. ** moved as part of a database reorganization just before the transaction
  46512. ** is being committed. In this case, it is guaranteed that the database page
  46513. ** pPg refers to will not be written to again within this transaction.
  46514. **
  46515. ** This function may return SQLITE_NOMEM or an IO error code if an error
  46516. ** occurs. Otherwise, it returns SQLITE_OK.
  46517. */
  46518. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  46519. PgHdr *pPgOld; /* The page being overwritten. */
  46520. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  46521. int rc; /* Return code */
  46522. Pgno origPgno; /* The original page number */
  46523. assert( pPg->nRef>0 );
  46524. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46525. || pPager->eState==PAGER_WRITER_DBMOD
  46526. );
  46527. assert( assert_pager_state(pPager) );
  46528. /* In order to be able to rollback, an in-memory database must journal
  46529. ** the page we are moving from.
  46530. */
  46531. if( MEMDB ){
  46532. rc = sqlite3PagerWrite(pPg);
  46533. if( rc ) return rc;
  46534. }
  46535. /* If the page being moved is dirty and has not been saved by the latest
  46536. ** savepoint, then save the current contents of the page into the
  46537. ** sub-journal now. This is required to handle the following scenario:
  46538. **
  46539. ** BEGIN;
  46540. ** <journal page X, then modify it in memory>
  46541. ** SAVEPOINT one;
  46542. ** <Move page X to location Y>
  46543. ** ROLLBACK TO one;
  46544. **
  46545. ** If page X were not written to the sub-journal here, it would not
  46546. ** be possible to restore its contents when the "ROLLBACK TO one"
  46547. ** statement were is processed.
  46548. **
  46549. ** subjournalPage() may need to allocate space to store pPg->pgno into
  46550. ** one or more savepoint bitvecs. This is the reason this function
  46551. ** may return SQLITE_NOMEM.
  46552. */
  46553. if( (pPg->flags & PGHDR_DIRTY)!=0
  46554. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  46555. ){
  46556. return rc;
  46557. }
  46558. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  46559. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  46560. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  46561. /* If the journal needs to be sync()ed before page pPg->pgno can
  46562. ** be written to, store pPg->pgno in local variable needSyncPgno.
  46563. **
  46564. ** If the isCommit flag is set, there is no need to remember that
  46565. ** the journal needs to be sync()ed before database page pPg->pgno
  46566. ** can be written to. The caller has already promised not to write to it.
  46567. */
  46568. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  46569. needSyncPgno = pPg->pgno;
  46570. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  46571. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  46572. assert( pPg->flags&PGHDR_DIRTY );
  46573. }
  46574. /* If the cache contains a page with page-number pgno, remove it
  46575. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  46576. ** page pgno before the 'move' operation, it needs to be retained
  46577. ** for the page moved there.
  46578. */
  46579. pPg->flags &= ~PGHDR_NEED_SYNC;
  46580. pPgOld = sqlite3PagerLookup(pPager, pgno);
  46581. assert( !pPgOld || pPgOld->nRef==1 );
  46582. if( pPgOld ){
  46583. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  46584. if( MEMDB ){
  46585. /* Do not discard pages from an in-memory database since we might
  46586. ** need to rollback later. Just move the page out of the way. */
  46587. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  46588. }else{
  46589. sqlite3PcacheDrop(pPgOld);
  46590. }
  46591. }
  46592. origPgno = pPg->pgno;
  46593. sqlite3PcacheMove(pPg, pgno);
  46594. sqlite3PcacheMakeDirty(pPg);
  46595. /* For an in-memory database, make sure the original page continues
  46596. ** to exist, in case the transaction needs to roll back. Use pPgOld
  46597. ** as the original page since it has already been allocated.
  46598. */
  46599. if( MEMDB ){
  46600. assert( pPgOld );
  46601. sqlite3PcacheMove(pPgOld, origPgno);
  46602. sqlite3PagerUnrefNotNull(pPgOld);
  46603. }
  46604. if( needSyncPgno ){
  46605. /* If needSyncPgno is non-zero, then the journal file needs to be
  46606. ** sync()ed before any data is written to database file page needSyncPgno.
  46607. ** Currently, no such page exists in the page-cache and the
  46608. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  46609. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  46610. ** flag.
  46611. **
  46612. ** If the attempt to load the page into the page-cache fails, (due
  46613. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  46614. ** array. Otherwise, if the page is loaded and written again in
  46615. ** this transaction, it may be written to the database file before
  46616. ** it is synced into the journal file. This way, it may end up in
  46617. ** the journal file twice, but that is not a problem.
  46618. */
  46619. PgHdr *pPgHdr;
  46620. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  46621. if( rc!=SQLITE_OK ){
  46622. if( needSyncPgno<=pPager->dbOrigSize ){
  46623. assert( pPager->pTmpSpace!=0 );
  46624. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  46625. }
  46626. return rc;
  46627. }
  46628. pPgHdr->flags |= PGHDR_NEED_SYNC;
  46629. sqlite3PcacheMakeDirty(pPgHdr);
  46630. sqlite3PagerUnrefNotNull(pPgHdr);
  46631. }
  46632. return SQLITE_OK;
  46633. }
  46634. #endif
  46635. /*
  46636. ** The page handle passed as the first argument refers to a dirty page
  46637. ** with a page number other than iNew. This function changes the page's
  46638. ** page number to iNew and sets the value of the PgHdr.flags field to
  46639. ** the value passed as the third parameter.
  46640. */
  46641. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  46642. assert( pPg->pgno!=iNew );
  46643. pPg->flags = flags;
  46644. sqlite3PcacheMove(pPg, iNew);
  46645. }
  46646. /*
  46647. ** Return a pointer to the data for the specified page.
  46648. */
  46649. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  46650. assert( pPg->nRef>0 || pPg->pPager->memDb );
  46651. return pPg->pData;
  46652. }
  46653. /*
  46654. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  46655. ** allocated along with the specified page.
  46656. */
  46657. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  46658. return pPg->pExtra;
  46659. }
  46660. /*
  46661. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  46662. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  46663. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  46664. ** the locking-mode is set to the value specified.
  46665. **
  46666. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  46667. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  46668. ** locking-mode.
  46669. */
  46670. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  46671. assert( eMode==PAGER_LOCKINGMODE_QUERY
  46672. || eMode==PAGER_LOCKINGMODE_NORMAL
  46673. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  46674. assert( PAGER_LOCKINGMODE_QUERY<0 );
  46675. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  46676. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  46677. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  46678. pPager->exclusiveMode = (u8)eMode;
  46679. }
  46680. return (int)pPager->exclusiveMode;
  46681. }
  46682. /*
  46683. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  46684. **
  46685. ** PAGER_JOURNALMODE_DELETE
  46686. ** PAGER_JOURNALMODE_TRUNCATE
  46687. ** PAGER_JOURNALMODE_PERSIST
  46688. ** PAGER_JOURNALMODE_OFF
  46689. ** PAGER_JOURNALMODE_MEMORY
  46690. ** PAGER_JOURNALMODE_WAL
  46691. **
  46692. ** The journalmode is set to the value specified if the change is allowed.
  46693. ** The change may be disallowed for the following reasons:
  46694. **
  46695. ** * An in-memory database can only have its journal_mode set to _OFF
  46696. ** or _MEMORY.
  46697. **
  46698. ** * Temporary databases cannot have _WAL journalmode.
  46699. **
  46700. ** The returned indicate the current (possibly updated) journal-mode.
  46701. */
  46702. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  46703. u8 eOld = pPager->journalMode; /* Prior journalmode */
  46704. #ifdef SQLITE_DEBUG
  46705. /* The print_pager_state() routine is intended to be used by the debugger
  46706. ** only. We invoke it once here to suppress a compiler warning. */
  46707. print_pager_state(pPager);
  46708. #endif
  46709. /* The eMode parameter is always valid */
  46710. assert( eMode==PAGER_JOURNALMODE_DELETE
  46711. || eMode==PAGER_JOURNALMODE_TRUNCATE
  46712. || eMode==PAGER_JOURNALMODE_PERSIST
  46713. || eMode==PAGER_JOURNALMODE_OFF
  46714. || eMode==PAGER_JOURNALMODE_WAL
  46715. || eMode==PAGER_JOURNALMODE_MEMORY );
  46716. /* This routine is only called from the OP_JournalMode opcode, and
  46717. ** the logic there will never allow a temporary file to be changed
  46718. ** to WAL mode.
  46719. */
  46720. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  46721. /* Do allow the journalmode of an in-memory database to be set to
  46722. ** anything other than MEMORY or OFF
  46723. */
  46724. if( MEMDB ){
  46725. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  46726. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  46727. eMode = eOld;
  46728. }
  46729. }
  46730. if( eMode!=eOld ){
  46731. /* Change the journal mode. */
  46732. assert( pPager->eState!=PAGER_ERROR );
  46733. pPager->journalMode = (u8)eMode;
  46734. /* When transistioning from TRUNCATE or PERSIST to any other journal
  46735. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  46736. ** delete the journal file.
  46737. */
  46738. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  46739. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  46740. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  46741. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  46742. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  46743. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  46744. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  46745. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  46746. /* In this case we would like to delete the journal file. If it is
  46747. ** not possible, then that is not a problem. Deleting the journal file
  46748. ** here is an optimization only.
  46749. **
  46750. ** Before deleting the journal file, obtain a RESERVED lock on the
  46751. ** database file. This ensures that the journal file is not deleted
  46752. ** while it is in use by some other client.
  46753. */
  46754. sqlite3OsClose(pPager->jfd);
  46755. if( pPager->eLock>=RESERVED_LOCK ){
  46756. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  46757. }else{
  46758. int rc = SQLITE_OK;
  46759. int state = pPager->eState;
  46760. assert( state==PAGER_OPEN || state==PAGER_READER );
  46761. if( state==PAGER_OPEN ){
  46762. rc = sqlite3PagerSharedLock(pPager);
  46763. }
  46764. if( pPager->eState==PAGER_READER ){
  46765. assert( rc==SQLITE_OK );
  46766. rc = pagerLockDb(pPager, RESERVED_LOCK);
  46767. }
  46768. if( rc==SQLITE_OK ){
  46769. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  46770. }
  46771. if( rc==SQLITE_OK && state==PAGER_READER ){
  46772. pagerUnlockDb(pPager, SHARED_LOCK);
  46773. }else if( state==PAGER_OPEN ){
  46774. pager_unlock(pPager);
  46775. }
  46776. assert( state==pPager->eState );
  46777. }
  46778. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  46779. sqlite3OsClose(pPager->jfd);
  46780. }
  46781. }
  46782. /* Return the new journal mode */
  46783. return (int)pPager->journalMode;
  46784. }
  46785. /*
  46786. ** Return the current journal mode.
  46787. */
  46788. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  46789. return (int)pPager->journalMode;
  46790. }
  46791. /*
  46792. ** Return TRUE if the pager is in a state where it is OK to change the
  46793. ** journalmode. Journalmode changes can only happen when the database
  46794. ** is unmodified.
  46795. */
  46796. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  46797. assert( assert_pager_state(pPager) );
  46798. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  46799. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  46800. return 1;
  46801. }
  46802. /*
  46803. ** Get/set the size-limit used for persistent journal files.
  46804. **
  46805. ** Setting the size limit to -1 means no limit is enforced.
  46806. ** An attempt to set a limit smaller than -1 is a no-op.
  46807. */
  46808. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  46809. if( iLimit>=-1 ){
  46810. pPager->journalSizeLimit = iLimit;
  46811. sqlite3WalLimit(pPager->pWal, iLimit);
  46812. }
  46813. return pPager->journalSizeLimit;
  46814. }
  46815. /*
  46816. ** Return a pointer to the pPager->pBackup variable. The backup module
  46817. ** in backup.c maintains the content of this variable. This module
  46818. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  46819. ** sqlite3BackupUpdate() only.
  46820. */
  46821. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  46822. return &pPager->pBackup;
  46823. }
  46824. #ifndef SQLITE_OMIT_VACUUM
  46825. /*
  46826. ** Unless this is an in-memory or temporary database, clear the pager cache.
  46827. */
  46828. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  46829. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  46830. }
  46831. #endif
  46832. #ifndef SQLITE_OMIT_WAL
  46833. /*
  46834. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  46835. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  46836. ** or wal_blocking_checkpoint() API functions.
  46837. **
  46838. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  46839. */
  46840. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  46841. int rc = SQLITE_OK;
  46842. if( pPager->pWal ){
  46843. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  46844. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  46845. pPager->pBusyHandlerArg,
  46846. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  46847. pnLog, pnCkpt
  46848. );
  46849. }
  46850. return rc;
  46851. }
  46852. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  46853. return sqlite3WalCallback(pPager->pWal);
  46854. }
  46855. /*
  46856. ** Return true if the underlying VFS for the given pager supports the
  46857. ** primitives necessary for write-ahead logging.
  46858. */
  46859. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  46860. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  46861. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  46862. }
  46863. /*
  46864. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  46865. ** is obtained instead, immediately release it.
  46866. */
  46867. static int pagerExclusiveLock(Pager *pPager){
  46868. int rc; /* Return code */
  46869. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  46870. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  46871. if( rc!=SQLITE_OK ){
  46872. /* If the attempt to grab the exclusive lock failed, release the
  46873. ** pending lock that may have been obtained instead. */
  46874. pagerUnlockDb(pPager, SHARED_LOCK);
  46875. }
  46876. return rc;
  46877. }
  46878. /*
  46879. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  46880. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  46881. ** lock on the database file and use heap-memory to store the wal-index
  46882. ** in. Otherwise, use the normal shared-memory.
  46883. */
  46884. static int pagerOpenWal(Pager *pPager){
  46885. int rc = SQLITE_OK;
  46886. assert( pPager->pWal==0 && pPager->tempFile==0 );
  46887. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  46888. /* If the pager is already in exclusive-mode, the WAL module will use
  46889. ** heap-memory for the wal-index instead of the VFS shared-memory
  46890. ** implementation. Take the exclusive lock now, before opening the WAL
  46891. ** file, to make sure this is safe.
  46892. */
  46893. if( pPager->exclusiveMode ){
  46894. rc = pagerExclusiveLock(pPager);
  46895. }
  46896. /* Open the connection to the log file. If this operation fails,
  46897. ** (e.g. due to malloc() failure), return an error code.
  46898. */
  46899. if( rc==SQLITE_OK ){
  46900. rc = sqlite3WalOpen(pPager->pVfs,
  46901. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  46902. pPager->journalSizeLimit, &pPager->pWal
  46903. );
  46904. }
  46905. pagerFixMaplimit(pPager);
  46906. return rc;
  46907. }
  46908. /*
  46909. ** The caller must be holding a SHARED lock on the database file to call
  46910. ** this function.
  46911. **
  46912. ** If the pager passed as the first argument is open on a real database
  46913. ** file (not a temp file or an in-memory database), and the WAL file
  46914. ** is not already open, make an attempt to open it now. If successful,
  46915. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  46916. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  46917. ** not modified in either case.
  46918. **
  46919. ** If the pager is open on a temp-file (or in-memory database), or if
  46920. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  46921. ** without doing anything.
  46922. */
  46923. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  46924. Pager *pPager, /* Pager object */
  46925. int *pbOpen /* OUT: Set to true if call is a no-op */
  46926. ){
  46927. int rc = SQLITE_OK; /* Return code */
  46928. assert( assert_pager_state(pPager) );
  46929. assert( pPager->eState==PAGER_OPEN || pbOpen );
  46930. assert( pPager->eState==PAGER_READER || !pbOpen );
  46931. assert( pbOpen==0 || *pbOpen==0 );
  46932. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  46933. if( !pPager->tempFile && !pPager->pWal ){
  46934. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  46935. /* Close any rollback journal previously open */
  46936. sqlite3OsClose(pPager->jfd);
  46937. rc = pagerOpenWal(pPager);
  46938. if( rc==SQLITE_OK ){
  46939. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  46940. pPager->eState = PAGER_OPEN;
  46941. }
  46942. }else{
  46943. *pbOpen = 1;
  46944. }
  46945. return rc;
  46946. }
  46947. /*
  46948. ** This function is called to close the connection to the log file prior
  46949. ** to switching from WAL to rollback mode.
  46950. **
  46951. ** Before closing the log file, this function attempts to take an
  46952. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  46953. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  46954. ** If successful, the EXCLUSIVE lock is not released before returning.
  46955. */
  46956. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  46957. int rc = SQLITE_OK;
  46958. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  46959. /* If the log file is not already open, but does exist in the file-system,
  46960. ** it may need to be checkpointed before the connection can switch to
  46961. ** rollback mode. Open it now so this can happen.
  46962. */
  46963. if( !pPager->pWal ){
  46964. int logexists = 0;
  46965. rc = pagerLockDb(pPager, SHARED_LOCK);
  46966. if( rc==SQLITE_OK ){
  46967. rc = sqlite3OsAccess(
  46968. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  46969. );
  46970. }
  46971. if( rc==SQLITE_OK && logexists ){
  46972. rc = pagerOpenWal(pPager);
  46973. }
  46974. }
  46975. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  46976. ** the database file, the log and log-summary files will be deleted.
  46977. */
  46978. if( rc==SQLITE_OK && pPager->pWal ){
  46979. rc = pagerExclusiveLock(pPager);
  46980. if( rc==SQLITE_OK ){
  46981. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  46982. pPager->pageSize, (u8*)pPager->pTmpSpace);
  46983. pPager->pWal = 0;
  46984. pagerFixMaplimit(pPager);
  46985. }
  46986. }
  46987. return rc;
  46988. }
  46989. #endif /* !SQLITE_OMIT_WAL */
  46990. #ifdef SQLITE_ENABLE_ZIPVFS
  46991. /*
  46992. ** A read-lock must be held on the pager when this function is called. If
  46993. ** the pager is in WAL mode and the WAL file currently contains one or more
  46994. ** frames, return the size in bytes of the page images stored within the
  46995. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  46996. ** is empty, return 0.
  46997. */
  46998. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  46999. assert( pPager->eState>=PAGER_READER );
  47000. return sqlite3WalFramesize(pPager->pWal);
  47001. }
  47002. #endif
  47003. #endif /* SQLITE_OMIT_DISKIO */
  47004. /************** End of pager.c ***********************************************/
  47005. /************** Begin file wal.c *********************************************/
  47006. /*
  47007. ** 2010 February 1
  47008. **
  47009. ** The author disclaims copyright to this source code. In place of
  47010. ** a legal notice, here is a blessing:
  47011. **
  47012. ** May you do good and not evil.
  47013. ** May you find forgiveness for yourself and forgive others.
  47014. ** May you share freely, never taking more than you give.
  47015. **
  47016. *************************************************************************
  47017. **
  47018. ** This file contains the implementation of a write-ahead log (WAL) used in
  47019. ** "journal_mode=WAL" mode.
  47020. **
  47021. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  47022. **
  47023. ** A WAL file consists of a header followed by zero or more "frames".
  47024. ** Each frame records the revised content of a single page from the
  47025. ** database file. All changes to the database are recorded by writing
  47026. ** frames into the WAL. Transactions commit when a frame is written that
  47027. ** contains a commit marker. A single WAL can and usually does record
  47028. ** multiple transactions. Periodically, the content of the WAL is
  47029. ** transferred back into the database file in an operation called a
  47030. ** "checkpoint".
  47031. **
  47032. ** A single WAL file can be used multiple times. In other words, the
  47033. ** WAL can fill up with frames and then be checkpointed and then new
  47034. ** frames can overwrite the old ones. A WAL always grows from beginning
  47035. ** toward the end. Checksums and counters attached to each frame are
  47036. ** used to determine which frames within the WAL are valid and which
  47037. ** are leftovers from prior checkpoints.
  47038. **
  47039. ** The WAL header is 32 bytes in size and consists of the following eight
  47040. ** big-endian 32-bit unsigned integer values:
  47041. **
  47042. ** 0: Magic number. 0x377f0682 or 0x377f0683
  47043. ** 4: File format version. Currently 3007000
  47044. ** 8: Database page size. Example: 1024
  47045. ** 12: Checkpoint sequence number
  47046. ** 16: Salt-1, random integer incremented with each checkpoint
  47047. ** 20: Salt-2, a different random integer changing with each ckpt
  47048. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  47049. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  47050. **
  47051. ** Immediately following the wal-header are zero or more frames. Each
  47052. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  47053. ** of page data. The frame-header is six big-endian 32-bit unsigned
  47054. ** integer values, as follows:
  47055. **
  47056. ** 0: Page number.
  47057. ** 4: For commit records, the size of the database image in pages
  47058. ** after the commit. For all other records, zero.
  47059. ** 8: Salt-1 (copied from the header)
  47060. ** 12: Salt-2 (copied from the header)
  47061. ** 16: Checksum-1.
  47062. ** 20: Checksum-2.
  47063. **
  47064. ** A frame is considered valid if and only if the following conditions are
  47065. ** true:
  47066. **
  47067. ** (1) The salt-1 and salt-2 values in the frame-header match
  47068. ** salt values in the wal-header
  47069. **
  47070. ** (2) The checksum values in the final 8 bytes of the frame-header
  47071. ** exactly match the checksum computed consecutively on the
  47072. ** WAL header and the first 8 bytes and the content of all frames
  47073. ** up to and including the current frame.
  47074. **
  47075. ** The checksum is computed using 32-bit big-endian integers if the
  47076. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  47077. ** is computed using little-endian if the magic number is 0x377f0682.
  47078. ** The checksum values are always stored in the frame header in a
  47079. ** big-endian format regardless of which byte order is used to compute
  47080. ** the checksum. The checksum is computed by interpreting the input as
  47081. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  47082. ** algorithm used for the checksum is as follows:
  47083. **
  47084. ** for i from 0 to n-1 step 2:
  47085. ** s0 += x[i] + s1;
  47086. ** s1 += x[i+1] + s0;
  47087. ** endfor
  47088. **
  47089. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  47090. ** in reverse order (the largest fibonacci weight occurs on the first element
  47091. ** of the sequence being summed.) The s1 value spans all 32-bit
  47092. ** terms of the sequence whereas s0 omits the final term.
  47093. **
  47094. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  47095. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  47096. ** The VFS.xSync operations serve as write barriers - all writes launched
  47097. ** before the xSync must complete before any write that launches after the
  47098. ** xSync begins.
  47099. **
  47100. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  47101. ** value is randomized. This prevents old and new frames in the WAL from
  47102. ** being considered valid at the same time and being checkpointing together
  47103. ** following a crash.
  47104. **
  47105. ** READER ALGORITHM
  47106. **
  47107. ** To read a page from the database (call it page number P), a reader
  47108. ** first checks the WAL to see if it contains page P. If so, then the
  47109. ** last valid instance of page P that is a followed by a commit frame
  47110. ** or is a commit frame itself becomes the value read. If the WAL
  47111. ** contains no copies of page P that are valid and which are a commit
  47112. ** frame or are followed by a commit frame, then page P is read from
  47113. ** the database file.
  47114. **
  47115. ** To start a read transaction, the reader records the index of the last
  47116. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  47117. ** for all subsequent read operations. New transactions can be appended
  47118. ** to the WAL, but as long as the reader uses its original mxFrame value
  47119. ** and ignores the newly appended content, it will see a consistent snapshot
  47120. ** of the database from a single point in time. This technique allows
  47121. ** multiple concurrent readers to view different versions of the database
  47122. ** content simultaneously.
  47123. **
  47124. ** The reader algorithm in the previous paragraphs works correctly, but
  47125. ** because frames for page P can appear anywhere within the WAL, the
  47126. ** reader has to scan the entire WAL looking for page P frames. If the
  47127. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  47128. ** and read performance suffers. To overcome this problem, a separate
  47129. ** data structure called the wal-index is maintained to expedite the
  47130. ** search for frames of a particular page.
  47131. **
  47132. ** WAL-INDEX FORMAT
  47133. **
  47134. ** Conceptually, the wal-index is shared memory, though VFS implementations
  47135. ** might choose to implement the wal-index using a mmapped file. Because
  47136. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  47137. ** on a network filesystem. All users of the database must be able to
  47138. ** share memory.
  47139. **
  47140. ** The wal-index is transient. After a crash, the wal-index can (and should
  47141. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  47142. ** to either truncate or zero the header of the wal-index when the last
  47143. ** connection to it closes. Because the wal-index is transient, it can
  47144. ** use an architecture-specific format; it does not have to be cross-platform.
  47145. ** Hence, unlike the database and WAL file formats which store all values
  47146. ** as big endian, the wal-index can store multi-byte values in the native
  47147. ** byte order of the host computer.
  47148. **
  47149. ** The purpose of the wal-index is to answer this question quickly: Given
  47150. ** a page number P and a maximum frame index M, return the index of the
  47151. ** last frame in the wal before frame M for page P in the WAL, or return
  47152. ** NULL if there are no frames for page P in the WAL prior to M.
  47153. **
  47154. ** The wal-index consists of a header region, followed by an one or
  47155. ** more index blocks.
  47156. **
  47157. ** The wal-index header contains the total number of frames within the WAL
  47158. ** in the mxFrame field.
  47159. **
  47160. ** Each index block except for the first contains information on
  47161. ** HASHTABLE_NPAGE frames. The first index block contains information on
  47162. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  47163. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  47164. ** first index block are the same size as all other index blocks in the
  47165. ** wal-index.
  47166. **
  47167. ** Each index block contains two sections, a page-mapping that contains the
  47168. ** database page number associated with each wal frame, and a hash-table
  47169. ** that allows readers to query an index block for a specific page number.
  47170. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  47171. ** for the first index block) 32-bit page numbers. The first entry in the
  47172. ** first index-block contains the database page number corresponding to the
  47173. ** first frame in the WAL file. The first entry in the second index block
  47174. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  47175. ** the log, and so on.
  47176. **
  47177. ** The last index block in a wal-index usually contains less than the full
  47178. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  47179. ** depending on the contents of the WAL file. This does not change the
  47180. ** allocated size of the page-mapping array - the page-mapping array merely
  47181. ** contains unused entries.
  47182. **
  47183. ** Even without using the hash table, the last frame for page P
  47184. ** can be found by scanning the page-mapping sections of each index block
  47185. ** starting with the last index block and moving toward the first, and
  47186. ** within each index block, starting at the end and moving toward the
  47187. ** beginning. The first entry that equals P corresponds to the frame
  47188. ** holding the content for that page.
  47189. **
  47190. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  47191. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  47192. ** hash table for each page number in the mapping section, so the hash
  47193. ** table is never more than half full. The expected number of collisions
  47194. ** prior to finding a match is 1. Each entry of the hash table is an
  47195. ** 1-based index of an entry in the mapping section of the same
  47196. ** index block. Let K be the 1-based index of the largest entry in
  47197. ** the mapping section. (For index blocks other than the last, K will
  47198. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  47199. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  47200. ** contain a value of 0.
  47201. **
  47202. ** To look for page P in the hash table, first compute a hash iKey on
  47203. ** P as follows:
  47204. **
  47205. ** iKey = (P * 383) % HASHTABLE_NSLOT
  47206. **
  47207. ** Then start scanning entries of the hash table, starting with iKey
  47208. ** (wrapping around to the beginning when the end of the hash table is
  47209. ** reached) until an unused hash slot is found. Let the first unused slot
  47210. ** be at index iUnused. (iUnused might be less than iKey if there was
  47211. ** wrap-around.) Because the hash table is never more than half full,
  47212. ** the search is guaranteed to eventually hit an unused entry. Let
  47213. ** iMax be the value between iKey and iUnused, closest to iUnused,
  47214. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  47215. ** no hash slot such that aHash[i]==p) then page P is not in the
  47216. ** current index block. Otherwise the iMax-th mapping entry of the
  47217. ** current index block corresponds to the last entry that references
  47218. ** page P.
  47219. **
  47220. ** A hash search begins with the last index block and moves toward the
  47221. ** first index block, looking for entries corresponding to page P. On
  47222. ** average, only two or three slots in each index block need to be
  47223. ** examined in order to either find the last entry for page P, or to
  47224. ** establish that no such entry exists in the block. Each index block
  47225. ** holds over 4000 entries. So two or three index blocks are sufficient
  47226. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  47227. ** comparisons (on average) suffice to either locate a frame in the
  47228. ** WAL or to establish that the frame does not exist in the WAL. This
  47229. ** is much faster than scanning the entire 10MB WAL.
  47230. **
  47231. ** Note that entries are added in order of increasing K. Hence, one
  47232. ** reader might be using some value K0 and a second reader that started
  47233. ** at a later time (after additional transactions were added to the WAL
  47234. ** and to the wal-index) might be using a different value K1, where K1>K0.
  47235. ** Both readers can use the same hash table and mapping section to get
  47236. ** the correct result. There may be entries in the hash table with
  47237. ** K>K0 but to the first reader, those entries will appear to be unused
  47238. ** slots in the hash table and so the first reader will get an answer as
  47239. ** if no values greater than K0 had ever been inserted into the hash table
  47240. ** in the first place - which is what reader one wants. Meanwhile, the
  47241. ** second reader using K1 will see additional values that were inserted
  47242. ** later, which is exactly what reader two wants.
  47243. **
  47244. ** When a rollback occurs, the value of K is decreased. Hash table entries
  47245. ** that correspond to frames greater than the new K value are removed
  47246. ** from the hash table at this point.
  47247. */
  47248. #ifndef SQLITE_OMIT_WAL
  47249. /* #include "wal.h" */
  47250. /*
  47251. ** Trace output macros
  47252. */
  47253. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47254. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  47255. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  47256. #else
  47257. # define WALTRACE(X)
  47258. #endif
  47259. /*
  47260. ** The maximum (and only) versions of the wal and wal-index formats
  47261. ** that may be interpreted by this version of SQLite.
  47262. **
  47263. ** If a client begins recovering a WAL file and finds that (a) the checksum
  47264. ** values in the wal-header are correct and (b) the version field is not
  47265. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  47266. **
  47267. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  47268. ** checksum test is successful) and finds that the version field is not
  47269. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  47270. ** returns SQLITE_CANTOPEN.
  47271. */
  47272. #define WAL_MAX_VERSION 3007000
  47273. #define WALINDEX_MAX_VERSION 3007000
  47274. /*
  47275. ** Indices of various locking bytes. WAL_NREADER is the number
  47276. ** of available reader locks and should be at least 3.
  47277. */
  47278. #define WAL_WRITE_LOCK 0
  47279. #define WAL_ALL_BUT_WRITE 1
  47280. #define WAL_CKPT_LOCK 1
  47281. #define WAL_RECOVER_LOCK 2
  47282. #define WAL_READ_LOCK(I) (3+(I))
  47283. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  47284. /* Object declarations */
  47285. typedef struct WalIndexHdr WalIndexHdr;
  47286. typedef struct WalIterator WalIterator;
  47287. typedef struct WalCkptInfo WalCkptInfo;
  47288. /*
  47289. ** The following object holds a copy of the wal-index header content.
  47290. **
  47291. ** The actual header in the wal-index consists of two copies of this
  47292. ** object.
  47293. **
  47294. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  47295. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  47296. ** added in 3.7.1 when support for 64K pages was added.
  47297. */
  47298. struct WalIndexHdr {
  47299. u32 iVersion; /* Wal-index version */
  47300. u32 unused; /* Unused (padding) field */
  47301. u32 iChange; /* Counter incremented each transaction */
  47302. u8 isInit; /* 1 when initialized */
  47303. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  47304. u16 szPage; /* Database page size in bytes. 1==64K */
  47305. u32 mxFrame; /* Index of last valid frame in the WAL */
  47306. u32 nPage; /* Size of database in pages */
  47307. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  47308. u32 aSalt[2]; /* Two salt values copied from WAL header */
  47309. u32 aCksum[2]; /* Checksum over all prior fields */
  47310. };
  47311. /*
  47312. ** A copy of the following object occurs in the wal-index immediately
  47313. ** following the second copy of the WalIndexHdr. This object stores
  47314. ** information used by checkpoint.
  47315. **
  47316. ** nBackfill is the number of frames in the WAL that have been written
  47317. ** back into the database. (We call the act of moving content from WAL to
  47318. ** database "backfilling".) The nBackfill number is never greater than
  47319. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  47320. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  47321. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  47322. ** mxFrame back to zero when the WAL is reset.
  47323. **
  47324. ** There is one entry in aReadMark[] for each reader lock. If a reader
  47325. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  47326. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  47327. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  47328. ** a special case; its value is never used and it exists as a place-holder
  47329. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  47330. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  47331. ** directly from the database.
  47332. **
  47333. ** The value of aReadMark[K] may only be changed by a thread that
  47334. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  47335. ** aReadMark[K] cannot changed while there is a reader is using that mark
  47336. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  47337. **
  47338. ** The checkpointer may only transfer frames from WAL to database where
  47339. ** the frame numbers are less than or equal to every aReadMark[] that is
  47340. ** in use (that is, every aReadMark[j] for which there is a corresponding
  47341. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  47342. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  47343. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  47344. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  47345. ** in the WAL has been backfilled into the database) then new readers
  47346. ** will choose aReadMark[0] which has value 0 and hence such reader will
  47347. ** get all their all content directly from the database file and ignore
  47348. ** the WAL.
  47349. **
  47350. ** Writers normally append new frames to the end of the WAL. However,
  47351. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  47352. ** written back into the database) and if no readers are using the WAL
  47353. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  47354. ** the writer will first "reset" the WAL back to the beginning and start
  47355. ** writing new content beginning at frame 1.
  47356. **
  47357. ** We assume that 32-bit loads are atomic and so no locks are needed in
  47358. ** order to read from any aReadMark[] entries.
  47359. */
  47360. struct WalCkptInfo {
  47361. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  47362. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  47363. };
  47364. #define READMARK_NOT_USED 0xffffffff
  47365. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  47366. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  47367. ** only support mandatory file-locks, we do not read or write data
  47368. ** from the region of the file on which locks are applied.
  47369. */
  47370. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  47371. #define WALINDEX_LOCK_RESERVED 16
  47372. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  47373. /* Size of header before each frame in wal */
  47374. #define WAL_FRAME_HDRSIZE 24
  47375. /* Size of write ahead log header, including checksum. */
  47376. /* #define WAL_HDRSIZE 24 */
  47377. #define WAL_HDRSIZE 32
  47378. /* WAL magic value. Either this value, or the same value with the least
  47379. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  47380. ** big-endian format in the first 4 bytes of a WAL file.
  47381. **
  47382. ** If the LSB is set, then the checksums for each frame within the WAL
  47383. ** file are calculated by treating all data as an array of 32-bit
  47384. ** big-endian words. Otherwise, they are calculated by interpreting
  47385. ** all data as 32-bit little-endian words.
  47386. */
  47387. #define WAL_MAGIC 0x377f0682
  47388. /*
  47389. ** Return the offset of frame iFrame in the write-ahead log file,
  47390. ** assuming a database page size of szPage bytes. The offset returned
  47391. ** is to the start of the write-ahead log frame-header.
  47392. */
  47393. #define walFrameOffset(iFrame, szPage) ( \
  47394. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  47395. )
  47396. /*
  47397. ** An open write-ahead log file is represented by an instance of the
  47398. ** following object.
  47399. */
  47400. struct Wal {
  47401. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  47402. sqlite3_file *pDbFd; /* File handle for the database file */
  47403. sqlite3_file *pWalFd; /* File handle for WAL file */
  47404. u32 iCallback; /* Value to pass to log callback (or 0) */
  47405. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  47406. int nWiData; /* Size of array apWiData */
  47407. int szFirstBlock; /* Size of first block written to WAL file */
  47408. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  47409. u32 szPage; /* Database page size */
  47410. i16 readLock; /* Which read lock is being held. -1 for none */
  47411. u8 syncFlags; /* Flags to use to sync header writes */
  47412. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  47413. u8 writeLock; /* True if in a write transaction */
  47414. u8 ckptLock; /* True if holding a checkpoint lock */
  47415. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  47416. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  47417. u8 syncHeader; /* Fsync the WAL header if true */
  47418. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  47419. WalIndexHdr hdr; /* Wal-index header for current transaction */
  47420. u32 minFrame; /* Ignore wal frames before this one */
  47421. const char *zWalName; /* Name of WAL file */
  47422. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  47423. #ifdef SQLITE_DEBUG
  47424. u8 lockError; /* True if a locking error has occurred */
  47425. #endif
  47426. };
  47427. /*
  47428. ** Candidate values for Wal.exclusiveMode.
  47429. */
  47430. #define WAL_NORMAL_MODE 0
  47431. #define WAL_EXCLUSIVE_MODE 1
  47432. #define WAL_HEAPMEMORY_MODE 2
  47433. /*
  47434. ** Possible values for WAL.readOnly
  47435. */
  47436. #define WAL_RDWR 0 /* Normal read/write connection */
  47437. #define WAL_RDONLY 1 /* The WAL file is readonly */
  47438. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  47439. /*
  47440. ** Each page of the wal-index mapping contains a hash-table made up of
  47441. ** an array of HASHTABLE_NSLOT elements of the following type.
  47442. */
  47443. typedef u16 ht_slot;
  47444. /*
  47445. ** This structure is used to implement an iterator that loops through
  47446. ** all frames in the WAL in database page order. Where two or more frames
  47447. ** correspond to the same database page, the iterator visits only the
  47448. ** frame most recently written to the WAL (in other words, the frame with
  47449. ** the largest index).
  47450. **
  47451. ** The internals of this structure are only accessed by:
  47452. **
  47453. ** walIteratorInit() - Create a new iterator,
  47454. ** walIteratorNext() - Step an iterator,
  47455. ** walIteratorFree() - Free an iterator.
  47456. **
  47457. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  47458. */
  47459. struct WalIterator {
  47460. int iPrior; /* Last result returned from the iterator */
  47461. int nSegment; /* Number of entries in aSegment[] */
  47462. struct WalSegment {
  47463. int iNext; /* Next slot in aIndex[] not yet returned */
  47464. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  47465. u32 *aPgno; /* Array of page numbers. */
  47466. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  47467. int iZero; /* Frame number associated with aPgno[0] */
  47468. } aSegment[1]; /* One for every 32KB page in the wal-index */
  47469. };
  47470. /*
  47471. ** Define the parameters of the hash tables in the wal-index file. There
  47472. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  47473. ** wal-index.
  47474. **
  47475. ** Changing any of these constants will alter the wal-index format and
  47476. ** create incompatibilities.
  47477. */
  47478. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  47479. #define HASHTABLE_HASH_1 383 /* Should be prime */
  47480. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  47481. /*
  47482. ** The block of page numbers associated with the first hash-table in a
  47483. ** wal-index is smaller than usual. This is so that there is a complete
  47484. ** hash-table on each aligned 32KB page of the wal-index.
  47485. */
  47486. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  47487. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  47488. #define WALINDEX_PGSZ ( \
  47489. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  47490. )
  47491. /*
  47492. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  47493. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  47494. ** numbered from zero.
  47495. **
  47496. ** If this call is successful, *ppPage is set to point to the wal-index
  47497. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  47498. ** then an SQLite error code is returned and *ppPage is set to 0.
  47499. */
  47500. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  47501. int rc = SQLITE_OK;
  47502. /* Enlarge the pWal->apWiData[] array if required */
  47503. if( pWal->nWiData<=iPage ){
  47504. int nByte = sizeof(u32*)*(iPage+1);
  47505. volatile u32 **apNew;
  47506. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  47507. if( !apNew ){
  47508. *ppPage = 0;
  47509. return SQLITE_NOMEM;
  47510. }
  47511. memset((void*)&apNew[pWal->nWiData], 0,
  47512. sizeof(u32*)*(iPage+1-pWal->nWiData));
  47513. pWal->apWiData = apNew;
  47514. pWal->nWiData = iPage+1;
  47515. }
  47516. /* Request a pointer to the required page from the VFS */
  47517. if( pWal->apWiData[iPage]==0 ){
  47518. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  47519. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  47520. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  47521. }else{
  47522. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  47523. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  47524. );
  47525. if( rc==SQLITE_READONLY ){
  47526. pWal->readOnly |= WAL_SHM_RDONLY;
  47527. rc = SQLITE_OK;
  47528. }
  47529. }
  47530. }
  47531. *ppPage = pWal->apWiData[iPage];
  47532. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  47533. return rc;
  47534. }
  47535. /*
  47536. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  47537. */
  47538. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  47539. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  47540. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  47541. }
  47542. /*
  47543. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  47544. */
  47545. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  47546. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  47547. return (volatile WalIndexHdr*)pWal->apWiData[0];
  47548. }
  47549. /*
  47550. ** The argument to this macro must be of type u32. On a little-endian
  47551. ** architecture, it returns the u32 value that results from interpreting
  47552. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  47553. ** returns the value that would be produced by interpreting the 4 bytes
  47554. ** of the input value as a little-endian integer.
  47555. */
  47556. #define BYTESWAP32(x) ( \
  47557. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  47558. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  47559. )
  47560. /*
  47561. ** Generate or extend an 8 byte checksum based on the data in
  47562. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  47563. ** initial values of 0 and 0 if aIn==NULL).
  47564. **
  47565. ** The checksum is written back into aOut[] before returning.
  47566. **
  47567. ** nByte must be a positive multiple of 8.
  47568. */
  47569. static void walChecksumBytes(
  47570. int nativeCksum, /* True for native byte-order, false for non-native */
  47571. u8 *a, /* Content to be checksummed */
  47572. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  47573. const u32 *aIn, /* Initial checksum value input */
  47574. u32 *aOut /* OUT: Final checksum value output */
  47575. ){
  47576. u32 s1, s2;
  47577. u32 *aData = (u32 *)a;
  47578. u32 *aEnd = (u32 *)&a[nByte];
  47579. if( aIn ){
  47580. s1 = aIn[0];
  47581. s2 = aIn[1];
  47582. }else{
  47583. s1 = s2 = 0;
  47584. }
  47585. assert( nByte>=8 );
  47586. assert( (nByte&0x00000007)==0 );
  47587. if( nativeCksum ){
  47588. do {
  47589. s1 += *aData++ + s2;
  47590. s2 += *aData++ + s1;
  47591. }while( aData<aEnd );
  47592. }else{
  47593. do {
  47594. s1 += BYTESWAP32(aData[0]) + s2;
  47595. s2 += BYTESWAP32(aData[1]) + s1;
  47596. aData += 2;
  47597. }while( aData<aEnd );
  47598. }
  47599. aOut[0] = s1;
  47600. aOut[1] = s2;
  47601. }
  47602. static void walShmBarrier(Wal *pWal){
  47603. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  47604. sqlite3OsShmBarrier(pWal->pDbFd);
  47605. }
  47606. }
  47607. /*
  47608. ** Write the header information in pWal->hdr into the wal-index.
  47609. **
  47610. ** The checksum on pWal->hdr is updated before it is written.
  47611. */
  47612. static void walIndexWriteHdr(Wal *pWal){
  47613. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  47614. const int nCksum = offsetof(WalIndexHdr, aCksum);
  47615. assert( pWal->writeLock );
  47616. pWal->hdr.isInit = 1;
  47617. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  47618. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  47619. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  47620. walShmBarrier(pWal);
  47621. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  47622. }
  47623. /*
  47624. ** This function encodes a single frame header and writes it to a buffer
  47625. ** supplied by the caller. A frame-header is made up of a series of
  47626. ** 4-byte big-endian integers, as follows:
  47627. **
  47628. ** 0: Page number.
  47629. ** 4: For commit records, the size of the database image in pages
  47630. ** after the commit. For all other records, zero.
  47631. ** 8: Salt-1 (copied from the wal-header)
  47632. ** 12: Salt-2 (copied from the wal-header)
  47633. ** 16: Checksum-1.
  47634. ** 20: Checksum-2.
  47635. */
  47636. static void walEncodeFrame(
  47637. Wal *pWal, /* The write-ahead log */
  47638. u32 iPage, /* Database page number for frame */
  47639. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  47640. u8 *aData, /* Pointer to page data */
  47641. u8 *aFrame /* OUT: Write encoded frame here */
  47642. ){
  47643. int nativeCksum; /* True for native byte-order checksums */
  47644. u32 *aCksum = pWal->hdr.aFrameCksum;
  47645. assert( WAL_FRAME_HDRSIZE==24 );
  47646. sqlite3Put4byte(&aFrame[0], iPage);
  47647. sqlite3Put4byte(&aFrame[4], nTruncate);
  47648. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  47649. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  47650. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  47651. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  47652. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  47653. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  47654. }
  47655. /*
  47656. ** Check to see if the frame with header in aFrame[] and content
  47657. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  47658. ** *pnTruncate and return true. Return if the frame is not valid.
  47659. */
  47660. static int walDecodeFrame(
  47661. Wal *pWal, /* The write-ahead log */
  47662. u32 *piPage, /* OUT: Database page number for frame */
  47663. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  47664. u8 *aData, /* Pointer to page data (for checksum) */
  47665. u8 *aFrame /* Frame data */
  47666. ){
  47667. int nativeCksum; /* True for native byte-order checksums */
  47668. u32 *aCksum = pWal->hdr.aFrameCksum;
  47669. u32 pgno; /* Page number of the frame */
  47670. assert( WAL_FRAME_HDRSIZE==24 );
  47671. /* A frame is only valid if the salt values in the frame-header
  47672. ** match the salt values in the wal-header.
  47673. */
  47674. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  47675. return 0;
  47676. }
  47677. /* A frame is only valid if the page number is creater than zero.
  47678. */
  47679. pgno = sqlite3Get4byte(&aFrame[0]);
  47680. if( pgno==0 ){
  47681. return 0;
  47682. }
  47683. /* A frame is only valid if a checksum of the WAL header,
  47684. ** all prior frams, the first 16 bytes of this frame-header,
  47685. ** and the frame-data matches the checksum in the last 8
  47686. ** bytes of this frame-header.
  47687. */
  47688. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  47689. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  47690. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  47691. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  47692. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  47693. ){
  47694. /* Checksum failed. */
  47695. return 0;
  47696. }
  47697. /* If we reach this point, the frame is valid. Return the page number
  47698. ** and the new database size.
  47699. */
  47700. *piPage = pgno;
  47701. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  47702. return 1;
  47703. }
  47704. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47705. /*
  47706. ** Names of locks. This routine is used to provide debugging output and is not
  47707. ** a part of an ordinary build.
  47708. */
  47709. static const char *walLockName(int lockIdx){
  47710. if( lockIdx==WAL_WRITE_LOCK ){
  47711. return "WRITE-LOCK";
  47712. }else if( lockIdx==WAL_CKPT_LOCK ){
  47713. return "CKPT-LOCK";
  47714. }else if( lockIdx==WAL_RECOVER_LOCK ){
  47715. return "RECOVER-LOCK";
  47716. }else{
  47717. static char zName[15];
  47718. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  47719. lockIdx-WAL_READ_LOCK(0));
  47720. return zName;
  47721. }
  47722. }
  47723. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  47724. /*
  47725. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  47726. ** A lock cannot be moved directly between shared and exclusive - it must go
  47727. ** through the unlocked state first.
  47728. **
  47729. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  47730. */
  47731. static int walLockShared(Wal *pWal, int lockIdx){
  47732. int rc;
  47733. if( pWal->exclusiveMode ) return SQLITE_OK;
  47734. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  47735. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  47736. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  47737. walLockName(lockIdx), rc ? "failed" : "ok"));
  47738. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  47739. return rc;
  47740. }
  47741. static void walUnlockShared(Wal *pWal, int lockIdx){
  47742. if( pWal->exclusiveMode ) return;
  47743. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  47744. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  47745. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  47746. }
  47747. static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
  47748. int rc;
  47749. if( pWal->exclusiveMode ) return SQLITE_OK;
  47750. if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
  47751. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  47752. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  47753. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  47754. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  47755. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  47756. return rc;
  47757. }
  47758. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  47759. if( pWal->exclusiveMode ) return;
  47760. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  47761. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  47762. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  47763. walLockName(lockIdx), n));
  47764. }
  47765. /*
  47766. ** Compute a hash on a page number. The resulting hash value must land
  47767. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  47768. ** the hash to the next value in the event of a collision.
  47769. */
  47770. static int walHash(u32 iPage){
  47771. assert( iPage>0 );
  47772. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  47773. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  47774. }
  47775. static int walNextHash(int iPriorHash){
  47776. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  47777. }
  47778. /*
  47779. ** Return pointers to the hash table and page number array stored on
  47780. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  47781. ** numbered starting from 0.
  47782. **
  47783. ** Set output variable *paHash to point to the start of the hash table
  47784. ** in the wal-index file. Set *piZero to one less than the frame
  47785. ** number of the first frame indexed by this hash table. If a
  47786. ** slot in the hash table is set to N, it refers to frame number
  47787. ** (*piZero+N) in the log.
  47788. **
  47789. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  47790. ** first frame indexed by the hash table, frame (*piZero+1).
  47791. */
  47792. static int walHashGet(
  47793. Wal *pWal, /* WAL handle */
  47794. int iHash, /* Find the iHash'th table */
  47795. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  47796. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  47797. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  47798. ){
  47799. int rc; /* Return code */
  47800. volatile u32 *aPgno;
  47801. rc = walIndexPage(pWal, iHash, &aPgno);
  47802. assert( rc==SQLITE_OK || iHash>0 );
  47803. if( rc==SQLITE_OK ){
  47804. u32 iZero;
  47805. volatile ht_slot *aHash;
  47806. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  47807. if( iHash==0 ){
  47808. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  47809. iZero = 0;
  47810. }else{
  47811. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  47812. }
  47813. *paPgno = &aPgno[-1];
  47814. *paHash = aHash;
  47815. *piZero = iZero;
  47816. }
  47817. return rc;
  47818. }
  47819. /*
  47820. ** Return the number of the wal-index page that contains the hash-table
  47821. ** and page-number array that contain entries corresponding to WAL frame
  47822. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  47823. ** are numbered starting from 0.
  47824. */
  47825. static int walFramePage(u32 iFrame){
  47826. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  47827. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  47828. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  47829. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  47830. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  47831. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  47832. );
  47833. return iHash;
  47834. }
  47835. /*
  47836. ** Return the page number associated with frame iFrame in this WAL.
  47837. */
  47838. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  47839. int iHash = walFramePage(iFrame);
  47840. if( iHash==0 ){
  47841. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  47842. }
  47843. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  47844. }
  47845. /*
  47846. ** Remove entries from the hash table that point to WAL slots greater
  47847. ** than pWal->hdr.mxFrame.
  47848. **
  47849. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  47850. ** to a rollback or savepoint.
  47851. **
  47852. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  47853. ** updated. Any later hash tables will be automatically cleared when
  47854. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  47855. ** actually needed.
  47856. */
  47857. static void walCleanupHash(Wal *pWal){
  47858. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  47859. volatile u32 *aPgno = 0; /* Page number array for hash table */
  47860. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  47861. int iLimit = 0; /* Zero values greater than this */
  47862. int nByte; /* Number of bytes to zero in aPgno[] */
  47863. int i; /* Used to iterate through aHash[] */
  47864. assert( pWal->writeLock );
  47865. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  47866. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  47867. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  47868. if( pWal->hdr.mxFrame==0 ) return;
  47869. /* Obtain pointers to the hash-table and page-number array containing
  47870. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  47871. ** that the page said hash-table and array reside on is already mapped.
  47872. */
  47873. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  47874. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  47875. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  47876. /* Zero all hash-table entries that correspond to frame numbers greater
  47877. ** than pWal->hdr.mxFrame.
  47878. */
  47879. iLimit = pWal->hdr.mxFrame - iZero;
  47880. assert( iLimit>0 );
  47881. for(i=0; i<HASHTABLE_NSLOT; i++){
  47882. if( aHash[i]>iLimit ){
  47883. aHash[i] = 0;
  47884. }
  47885. }
  47886. /* Zero the entries in the aPgno array that correspond to frames with
  47887. ** frame numbers greater than pWal->hdr.mxFrame.
  47888. */
  47889. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  47890. memset((void *)&aPgno[iLimit+1], 0, nByte);
  47891. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47892. /* Verify that the every entry in the mapping region is still reachable
  47893. ** via the hash table even after the cleanup.
  47894. */
  47895. if( iLimit ){
  47896. int j; /* Loop counter */
  47897. int iKey; /* Hash key */
  47898. for(j=1; j<=iLimit; j++){
  47899. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  47900. if( aHash[iKey]==j ) break;
  47901. }
  47902. assert( aHash[iKey]==j );
  47903. }
  47904. }
  47905. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  47906. }
  47907. /*
  47908. ** Set an entry in the wal-index that will map database page number
  47909. ** pPage into WAL frame iFrame.
  47910. */
  47911. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  47912. int rc; /* Return code */
  47913. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  47914. volatile u32 *aPgno = 0; /* Page number array */
  47915. volatile ht_slot *aHash = 0; /* Hash table */
  47916. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  47917. /* Assuming the wal-index file was successfully mapped, populate the
  47918. ** page number array and hash table entry.
  47919. */
  47920. if( rc==SQLITE_OK ){
  47921. int iKey; /* Hash table key */
  47922. int idx; /* Value to write to hash-table slot */
  47923. int nCollide; /* Number of hash collisions */
  47924. idx = iFrame - iZero;
  47925. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  47926. /* If this is the first entry to be added to this hash-table, zero the
  47927. ** entire hash table and aPgno[] array before proceeding.
  47928. */
  47929. if( idx==1 ){
  47930. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  47931. memset((void*)&aPgno[1], 0, nByte);
  47932. }
  47933. /* If the entry in aPgno[] is already set, then the previous writer
  47934. ** must have exited unexpectedly in the middle of a transaction (after
  47935. ** writing one or more dirty pages to the WAL to free up memory).
  47936. ** Remove the remnants of that writers uncommitted transaction from
  47937. ** the hash-table before writing any new entries.
  47938. */
  47939. if( aPgno[idx] ){
  47940. walCleanupHash(pWal);
  47941. assert( !aPgno[idx] );
  47942. }
  47943. /* Write the aPgno[] array entry and the hash-table slot. */
  47944. nCollide = idx;
  47945. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  47946. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  47947. }
  47948. aPgno[idx] = iPage;
  47949. aHash[iKey] = (ht_slot)idx;
  47950. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47951. /* Verify that the number of entries in the hash table exactly equals
  47952. ** the number of entries in the mapping region.
  47953. */
  47954. {
  47955. int i; /* Loop counter */
  47956. int nEntry = 0; /* Number of entries in the hash table */
  47957. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  47958. assert( nEntry==idx );
  47959. }
  47960. /* Verify that the every entry in the mapping region is reachable
  47961. ** via the hash table. This turns out to be a really, really expensive
  47962. ** thing to check, so only do this occasionally - not on every
  47963. ** iteration.
  47964. */
  47965. if( (idx&0x3ff)==0 ){
  47966. int i; /* Loop counter */
  47967. for(i=1; i<=idx; i++){
  47968. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  47969. if( aHash[iKey]==i ) break;
  47970. }
  47971. assert( aHash[iKey]==i );
  47972. }
  47973. }
  47974. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  47975. }
  47976. return rc;
  47977. }
  47978. /*
  47979. ** Recover the wal-index by reading the write-ahead log file.
  47980. **
  47981. ** This routine first tries to establish an exclusive lock on the
  47982. ** wal-index to prevent other threads/processes from doing anything
  47983. ** with the WAL or wal-index while recovery is running. The
  47984. ** WAL_RECOVER_LOCK is also held so that other threads will know
  47985. ** that this thread is running recovery. If unable to establish
  47986. ** the necessary locks, this routine returns SQLITE_BUSY.
  47987. */
  47988. static int walIndexRecover(Wal *pWal){
  47989. int rc; /* Return Code */
  47990. i64 nSize; /* Size of log file */
  47991. u32 aFrameCksum[2] = {0, 0};
  47992. int iLock; /* Lock offset to lock for checkpoint */
  47993. int nLock; /* Number of locks to hold */
  47994. /* Obtain an exclusive lock on all byte in the locking range not already
  47995. ** locked by the caller. The caller is guaranteed to have locked the
  47996. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  47997. ** If successful, the same bytes that are locked here are unlocked before
  47998. ** this function returns.
  47999. */
  48000. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  48001. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  48002. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  48003. assert( pWal->writeLock );
  48004. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  48005. nLock = SQLITE_SHM_NLOCK - iLock;
  48006. rc = walLockExclusive(pWal, iLock, nLock, 0);
  48007. if( rc ){
  48008. return rc;
  48009. }
  48010. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  48011. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  48012. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  48013. if( rc!=SQLITE_OK ){
  48014. goto recovery_error;
  48015. }
  48016. if( nSize>WAL_HDRSIZE ){
  48017. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  48018. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  48019. int szFrame; /* Number of bytes in buffer aFrame[] */
  48020. u8 *aData; /* Pointer to data part of aFrame buffer */
  48021. int iFrame; /* Index of last frame read */
  48022. i64 iOffset; /* Next offset to read from log file */
  48023. int szPage; /* Page size according to the log */
  48024. u32 magic; /* Magic value read from WAL header */
  48025. u32 version; /* Magic value read from WAL header */
  48026. int isValid; /* True if this frame is valid */
  48027. /* Read in the WAL header. */
  48028. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  48029. if( rc!=SQLITE_OK ){
  48030. goto recovery_error;
  48031. }
  48032. /* If the database page size is not a power of two, or is greater than
  48033. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  48034. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  48035. ** WAL file.
  48036. */
  48037. magic = sqlite3Get4byte(&aBuf[0]);
  48038. szPage = sqlite3Get4byte(&aBuf[8]);
  48039. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  48040. || szPage&(szPage-1)
  48041. || szPage>SQLITE_MAX_PAGE_SIZE
  48042. || szPage<512
  48043. ){
  48044. goto finished;
  48045. }
  48046. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  48047. pWal->szPage = szPage;
  48048. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  48049. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  48050. /* Verify that the WAL header checksum is correct */
  48051. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  48052. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  48053. );
  48054. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  48055. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  48056. ){
  48057. goto finished;
  48058. }
  48059. /* Verify that the version number on the WAL format is one that
  48060. ** are able to understand */
  48061. version = sqlite3Get4byte(&aBuf[4]);
  48062. if( version!=WAL_MAX_VERSION ){
  48063. rc = SQLITE_CANTOPEN_BKPT;
  48064. goto finished;
  48065. }
  48066. /* Malloc a buffer to read frames into. */
  48067. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48068. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  48069. if( !aFrame ){
  48070. rc = SQLITE_NOMEM;
  48071. goto recovery_error;
  48072. }
  48073. aData = &aFrame[WAL_FRAME_HDRSIZE];
  48074. /* Read all frames from the log file. */
  48075. iFrame = 0;
  48076. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  48077. u32 pgno; /* Database page number for frame */
  48078. u32 nTruncate; /* dbsize field from frame header */
  48079. /* Read and decode the next log frame. */
  48080. iFrame++;
  48081. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  48082. if( rc!=SQLITE_OK ) break;
  48083. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  48084. if( !isValid ) break;
  48085. rc = walIndexAppend(pWal, iFrame, pgno);
  48086. if( rc!=SQLITE_OK ) break;
  48087. /* If nTruncate is non-zero, this is a commit record. */
  48088. if( nTruncate ){
  48089. pWal->hdr.mxFrame = iFrame;
  48090. pWal->hdr.nPage = nTruncate;
  48091. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  48092. testcase( szPage<=32768 );
  48093. testcase( szPage>=65536 );
  48094. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  48095. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  48096. }
  48097. }
  48098. sqlite3_free(aFrame);
  48099. }
  48100. finished:
  48101. if( rc==SQLITE_OK ){
  48102. volatile WalCkptInfo *pInfo;
  48103. int i;
  48104. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  48105. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  48106. walIndexWriteHdr(pWal);
  48107. /* Reset the checkpoint-header. This is safe because this thread is
  48108. ** currently holding locks that exclude all other readers, writers and
  48109. ** checkpointers.
  48110. */
  48111. pInfo = walCkptInfo(pWal);
  48112. pInfo->nBackfill = 0;
  48113. pInfo->aReadMark[0] = 0;
  48114. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  48115. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  48116. /* If more than one frame was recovered from the log file, report an
  48117. ** event via sqlite3_log(). This is to help with identifying performance
  48118. ** problems caused by applications routinely shutting down without
  48119. ** checkpointing the log file.
  48120. */
  48121. if( pWal->hdr.nPage ){
  48122. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  48123. "recovered %d frames from WAL file %s",
  48124. pWal->hdr.mxFrame, pWal->zWalName
  48125. );
  48126. }
  48127. }
  48128. recovery_error:
  48129. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  48130. walUnlockExclusive(pWal, iLock, nLock);
  48131. return rc;
  48132. }
  48133. /*
  48134. ** Close an open wal-index.
  48135. */
  48136. static void walIndexClose(Wal *pWal, int isDelete){
  48137. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  48138. int i;
  48139. for(i=0; i<pWal->nWiData; i++){
  48140. sqlite3_free((void *)pWal->apWiData[i]);
  48141. pWal->apWiData[i] = 0;
  48142. }
  48143. }else{
  48144. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  48145. }
  48146. }
  48147. /*
  48148. ** Open a connection to the WAL file zWalName. The database file must
  48149. ** already be opened on connection pDbFd. The buffer that zWalName points
  48150. ** to must remain valid for the lifetime of the returned Wal* handle.
  48151. **
  48152. ** A SHARED lock should be held on the database file when this function
  48153. ** is called. The purpose of this SHARED lock is to prevent any other
  48154. ** client from unlinking the WAL or wal-index file. If another process
  48155. ** were to do this just after this client opened one of these files, the
  48156. ** system would be badly broken.
  48157. **
  48158. ** If the log file is successfully opened, SQLITE_OK is returned and
  48159. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  48160. ** an SQLite error code is returned and *ppWal is left unmodified.
  48161. */
  48162. SQLITE_PRIVATE int sqlite3WalOpen(
  48163. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  48164. sqlite3_file *pDbFd, /* The open database file */
  48165. const char *zWalName, /* Name of the WAL file */
  48166. int bNoShm, /* True to run in heap-memory mode */
  48167. i64 mxWalSize, /* Truncate WAL to this size on reset */
  48168. Wal **ppWal /* OUT: Allocated Wal handle */
  48169. ){
  48170. int rc; /* Return Code */
  48171. Wal *pRet; /* Object to allocate and return */
  48172. int flags; /* Flags passed to OsOpen() */
  48173. assert( zWalName && zWalName[0] );
  48174. assert( pDbFd );
  48175. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  48176. ** this source file. Verify that the #defines of the locking byte offsets
  48177. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  48178. */
  48179. #ifdef WIN_SHM_BASE
  48180. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  48181. #endif
  48182. #ifdef UNIX_SHM_BASE
  48183. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  48184. #endif
  48185. /* Allocate an instance of struct Wal to return. */
  48186. *ppWal = 0;
  48187. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  48188. if( !pRet ){
  48189. return SQLITE_NOMEM;
  48190. }
  48191. pRet->pVfs = pVfs;
  48192. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  48193. pRet->pDbFd = pDbFd;
  48194. pRet->readLock = -1;
  48195. pRet->mxWalSize = mxWalSize;
  48196. pRet->zWalName = zWalName;
  48197. pRet->syncHeader = 1;
  48198. pRet->padToSectorBoundary = 1;
  48199. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  48200. /* Open file handle on the write-ahead log file. */
  48201. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  48202. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  48203. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  48204. pRet->readOnly = WAL_RDONLY;
  48205. }
  48206. if( rc!=SQLITE_OK ){
  48207. walIndexClose(pRet, 0);
  48208. sqlite3OsClose(pRet->pWalFd);
  48209. sqlite3_free(pRet);
  48210. }else{
  48211. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  48212. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  48213. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  48214. pRet->padToSectorBoundary = 0;
  48215. }
  48216. *ppWal = pRet;
  48217. WALTRACE(("WAL%d: opened\n", pRet));
  48218. }
  48219. return rc;
  48220. }
  48221. /*
  48222. ** Change the size to which the WAL file is trucated on each reset.
  48223. */
  48224. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  48225. if( pWal ) pWal->mxWalSize = iLimit;
  48226. }
  48227. /*
  48228. ** Find the smallest page number out of all pages held in the WAL that
  48229. ** has not been returned by any prior invocation of this method on the
  48230. ** same WalIterator object. Write into *piFrame the frame index where
  48231. ** that page was last written into the WAL. Write into *piPage the page
  48232. ** number.
  48233. **
  48234. ** Return 0 on success. If there are no pages in the WAL with a page
  48235. ** number larger than *piPage, then return 1.
  48236. */
  48237. static int walIteratorNext(
  48238. WalIterator *p, /* Iterator */
  48239. u32 *piPage, /* OUT: The page number of the next page */
  48240. u32 *piFrame /* OUT: Wal frame index of next page */
  48241. ){
  48242. u32 iMin; /* Result pgno must be greater than iMin */
  48243. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  48244. int i; /* For looping through segments */
  48245. iMin = p->iPrior;
  48246. assert( iMin<0xffffffff );
  48247. for(i=p->nSegment-1; i>=0; i--){
  48248. struct WalSegment *pSegment = &p->aSegment[i];
  48249. while( pSegment->iNext<pSegment->nEntry ){
  48250. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  48251. if( iPg>iMin ){
  48252. if( iPg<iRet ){
  48253. iRet = iPg;
  48254. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  48255. }
  48256. break;
  48257. }
  48258. pSegment->iNext++;
  48259. }
  48260. }
  48261. *piPage = p->iPrior = iRet;
  48262. return (iRet==0xFFFFFFFF);
  48263. }
  48264. /*
  48265. ** This function merges two sorted lists into a single sorted list.
  48266. **
  48267. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  48268. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  48269. ** is guaranteed for all J<K:
  48270. **
  48271. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  48272. ** aContent[aRight[J]] < aContent[aRight[K]]
  48273. **
  48274. ** This routine overwrites aRight[] with a new (probably longer) sequence
  48275. ** of indices such that the aRight[] contains every index that appears in
  48276. ** either aLeft[] or the old aRight[] and such that the second condition
  48277. ** above is still met.
  48278. **
  48279. ** The aContent[aLeft[X]] values will be unique for all X. And the
  48280. ** aContent[aRight[X]] values will be unique too. But there might be
  48281. ** one or more combinations of X and Y such that
  48282. **
  48283. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  48284. **
  48285. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  48286. */
  48287. static void walMerge(
  48288. const u32 *aContent, /* Pages in wal - keys for the sort */
  48289. ht_slot *aLeft, /* IN: Left hand input list */
  48290. int nLeft, /* IN: Elements in array *paLeft */
  48291. ht_slot **paRight, /* IN/OUT: Right hand input list */
  48292. int *pnRight, /* IN/OUT: Elements in *paRight */
  48293. ht_slot *aTmp /* Temporary buffer */
  48294. ){
  48295. int iLeft = 0; /* Current index in aLeft */
  48296. int iRight = 0; /* Current index in aRight */
  48297. int iOut = 0; /* Current index in output buffer */
  48298. int nRight = *pnRight;
  48299. ht_slot *aRight = *paRight;
  48300. assert( nLeft>0 && nRight>0 );
  48301. while( iRight<nRight || iLeft<nLeft ){
  48302. ht_slot logpage;
  48303. Pgno dbpage;
  48304. if( (iLeft<nLeft)
  48305. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  48306. ){
  48307. logpage = aLeft[iLeft++];
  48308. }else{
  48309. logpage = aRight[iRight++];
  48310. }
  48311. dbpage = aContent[logpage];
  48312. aTmp[iOut++] = logpage;
  48313. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  48314. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  48315. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  48316. }
  48317. *paRight = aLeft;
  48318. *pnRight = iOut;
  48319. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  48320. }
  48321. /*
  48322. ** Sort the elements in list aList using aContent[] as the sort key.
  48323. ** Remove elements with duplicate keys, preferring to keep the
  48324. ** larger aList[] values.
  48325. **
  48326. ** The aList[] entries are indices into aContent[]. The values in
  48327. ** aList[] are to be sorted so that for all J<K:
  48328. **
  48329. ** aContent[aList[J]] < aContent[aList[K]]
  48330. **
  48331. ** For any X and Y such that
  48332. **
  48333. ** aContent[aList[X]] == aContent[aList[Y]]
  48334. **
  48335. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  48336. ** the smaller.
  48337. */
  48338. static void walMergesort(
  48339. const u32 *aContent, /* Pages in wal */
  48340. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  48341. ht_slot *aList, /* IN/OUT: List to sort */
  48342. int *pnList /* IN/OUT: Number of elements in aList[] */
  48343. ){
  48344. struct Sublist {
  48345. int nList; /* Number of elements in aList */
  48346. ht_slot *aList; /* Pointer to sub-list content */
  48347. };
  48348. const int nList = *pnList; /* Size of input list */
  48349. int nMerge = 0; /* Number of elements in list aMerge */
  48350. ht_slot *aMerge = 0; /* List to be merged */
  48351. int iList; /* Index into input list */
  48352. u32 iSub = 0; /* Index into aSub array */
  48353. struct Sublist aSub[13]; /* Array of sub-lists */
  48354. memset(aSub, 0, sizeof(aSub));
  48355. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  48356. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  48357. for(iList=0; iList<nList; iList++){
  48358. nMerge = 1;
  48359. aMerge = &aList[iList];
  48360. for(iSub=0; iList & (1<<iSub); iSub++){
  48361. struct Sublist *p;
  48362. assert( iSub<ArraySize(aSub) );
  48363. p = &aSub[iSub];
  48364. assert( p->aList && p->nList<=(1<<iSub) );
  48365. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  48366. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  48367. }
  48368. aSub[iSub].aList = aMerge;
  48369. aSub[iSub].nList = nMerge;
  48370. }
  48371. for(iSub++; iSub<ArraySize(aSub); iSub++){
  48372. if( nList & (1<<iSub) ){
  48373. struct Sublist *p;
  48374. assert( iSub<ArraySize(aSub) );
  48375. p = &aSub[iSub];
  48376. assert( p->nList<=(1<<iSub) );
  48377. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  48378. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  48379. }
  48380. }
  48381. assert( aMerge==aList );
  48382. *pnList = nMerge;
  48383. #ifdef SQLITE_DEBUG
  48384. {
  48385. int i;
  48386. for(i=1; i<*pnList; i++){
  48387. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  48388. }
  48389. }
  48390. #endif
  48391. }
  48392. /*
  48393. ** Free an iterator allocated by walIteratorInit().
  48394. */
  48395. static void walIteratorFree(WalIterator *p){
  48396. sqlite3_free(p);
  48397. }
  48398. /*
  48399. ** Construct a WalInterator object that can be used to loop over all
  48400. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  48401. ** lock.
  48402. **
  48403. ** On success, make *pp point to the newly allocated WalInterator object
  48404. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  48405. ** returns an error, the value of *pp is undefined.
  48406. **
  48407. ** The calling routine should invoke walIteratorFree() to destroy the
  48408. ** WalIterator object when it has finished with it.
  48409. */
  48410. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  48411. WalIterator *p; /* Return value */
  48412. int nSegment; /* Number of segments to merge */
  48413. u32 iLast; /* Last frame in log */
  48414. int nByte; /* Number of bytes to allocate */
  48415. int i; /* Iterator variable */
  48416. ht_slot *aTmp; /* Temp space used by merge-sort */
  48417. int rc = SQLITE_OK; /* Return Code */
  48418. /* This routine only runs while holding the checkpoint lock. And
  48419. ** it only runs if there is actually content in the log (mxFrame>0).
  48420. */
  48421. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  48422. iLast = pWal->hdr.mxFrame;
  48423. /* Allocate space for the WalIterator object. */
  48424. nSegment = walFramePage(iLast) + 1;
  48425. nByte = sizeof(WalIterator)
  48426. + (nSegment-1)*sizeof(struct WalSegment)
  48427. + iLast*sizeof(ht_slot);
  48428. p = (WalIterator *)sqlite3_malloc64(nByte);
  48429. if( !p ){
  48430. return SQLITE_NOMEM;
  48431. }
  48432. memset(p, 0, nByte);
  48433. p->nSegment = nSegment;
  48434. /* Allocate temporary space used by the merge-sort routine. This block
  48435. ** of memory will be freed before this function returns.
  48436. */
  48437. aTmp = (ht_slot *)sqlite3_malloc64(
  48438. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  48439. );
  48440. if( !aTmp ){
  48441. rc = SQLITE_NOMEM;
  48442. }
  48443. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  48444. volatile ht_slot *aHash;
  48445. u32 iZero;
  48446. volatile u32 *aPgno;
  48447. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  48448. if( rc==SQLITE_OK ){
  48449. int j; /* Counter variable */
  48450. int nEntry; /* Number of entries in this segment */
  48451. ht_slot *aIndex; /* Sorted index for this segment */
  48452. aPgno++;
  48453. if( (i+1)==nSegment ){
  48454. nEntry = (int)(iLast - iZero);
  48455. }else{
  48456. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  48457. }
  48458. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  48459. iZero++;
  48460. for(j=0; j<nEntry; j++){
  48461. aIndex[j] = (ht_slot)j;
  48462. }
  48463. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  48464. p->aSegment[i].iZero = iZero;
  48465. p->aSegment[i].nEntry = nEntry;
  48466. p->aSegment[i].aIndex = aIndex;
  48467. p->aSegment[i].aPgno = (u32 *)aPgno;
  48468. }
  48469. }
  48470. sqlite3_free(aTmp);
  48471. if( rc!=SQLITE_OK ){
  48472. walIteratorFree(p);
  48473. }
  48474. *pp = p;
  48475. return rc;
  48476. }
  48477. /*
  48478. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  48479. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  48480. ** busy-handler function. Invoke it and retry the lock until either the
  48481. ** lock is successfully obtained or the busy-handler returns 0.
  48482. */
  48483. static int walBusyLock(
  48484. Wal *pWal, /* WAL connection */
  48485. int (*xBusy)(void*), /* Function to call when busy */
  48486. void *pBusyArg, /* Context argument for xBusyHandler */
  48487. int lockIdx, /* Offset of first byte to lock */
  48488. int n /* Number of bytes to lock */
  48489. ){
  48490. int rc;
  48491. do {
  48492. rc = walLockExclusive(pWal, lockIdx, n, 0);
  48493. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  48494. return rc;
  48495. }
  48496. /*
  48497. ** The cache of the wal-index header must be valid to call this function.
  48498. ** Return the page-size in bytes used by the database.
  48499. */
  48500. static int walPagesize(Wal *pWal){
  48501. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  48502. }
  48503. /*
  48504. ** The following is guaranteed when this function is called:
  48505. **
  48506. ** a) the WRITER lock is held,
  48507. ** b) the entire log file has been checkpointed, and
  48508. ** c) any existing readers are reading exclusively from the database
  48509. ** file - there are no readers that may attempt to read a frame from
  48510. ** the log file.
  48511. **
  48512. ** This function updates the shared-memory structures so that the next
  48513. ** client to write to the database (which may be this one) does so by
  48514. ** writing frames into the start of the log file.
  48515. **
  48516. ** The value of parameter salt1 is used as the aSalt[1] value in the
  48517. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  48518. ** one obtained from sqlite3_randomness()).
  48519. */
  48520. static void walRestartHdr(Wal *pWal, u32 salt1){
  48521. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  48522. int i; /* Loop counter */
  48523. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  48524. pWal->nCkpt++;
  48525. pWal->hdr.mxFrame = 0;
  48526. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  48527. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  48528. walIndexWriteHdr(pWal);
  48529. pInfo->nBackfill = 0;
  48530. pInfo->aReadMark[1] = 0;
  48531. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  48532. assert( pInfo->aReadMark[0]==0 );
  48533. }
  48534. /*
  48535. ** Copy as much content as we can from the WAL back into the database file
  48536. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  48537. **
  48538. ** The amount of information copies from WAL to database might be limited
  48539. ** by active readers. This routine will never overwrite a database page
  48540. ** that a concurrent reader might be using.
  48541. **
  48542. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  48543. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  48544. ** checkpoints are always run by a background thread or background
  48545. ** process, foreground threads will never block on a lengthy fsync call.
  48546. **
  48547. ** Fsync is called on the WAL before writing content out of the WAL and
  48548. ** into the database. This ensures that if the new content is persistent
  48549. ** in the WAL and can be recovered following a power-loss or hard reset.
  48550. **
  48551. ** Fsync is also called on the database file if (and only if) the entire
  48552. ** WAL content is copied into the database file. This second fsync makes
  48553. ** it safe to delete the WAL since the new content will persist in the
  48554. ** database file.
  48555. **
  48556. ** This routine uses and updates the nBackfill field of the wal-index header.
  48557. ** This is the only routine that will increase the value of nBackfill.
  48558. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  48559. ** its value.)
  48560. **
  48561. ** The caller must be holding sufficient locks to ensure that no other
  48562. ** checkpoint is running (in any other thread or process) at the same
  48563. ** time.
  48564. */
  48565. static int walCheckpoint(
  48566. Wal *pWal, /* Wal connection */
  48567. int eMode, /* One of PASSIVE, FULL or RESTART */
  48568. int (*xBusy)(void*), /* Function to call when busy */
  48569. void *pBusyArg, /* Context argument for xBusyHandler */
  48570. int sync_flags, /* Flags for OsSync() (or 0) */
  48571. u8 *zBuf /* Temporary buffer to use */
  48572. ){
  48573. int rc = SQLITE_OK; /* Return code */
  48574. int szPage; /* Database page-size */
  48575. WalIterator *pIter = 0; /* Wal iterator context */
  48576. u32 iDbpage = 0; /* Next database page to write */
  48577. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  48578. u32 mxSafeFrame; /* Max frame that can be backfilled */
  48579. u32 mxPage; /* Max database page to write */
  48580. int i; /* Loop counter */
  48581. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  48582. szPage = walPagesize(pWal);
  48583. testcase( szPage<=32768 );
  48584. testcase( szPage>=65536 );
  48585. pInfo = walCkptInfo(pWal);
  48586. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  48587. /* Allocate the iterator */
  48588. rc = walIteratorInit(pWal, &pIter);
  48589. if( rc!=SQLITE_OK ){
  48590. return rc;
  48591. }
  48592. assert( pIter );
  48593. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  48594. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  48595. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  48596. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  48597. ** safe to write into the database. Frames beyond mxSafeFrame might
  48598. ** overwrite database pages that are in use by active readers and thus
  48599. ** cannot be backfilled from the WAL.
  48600. */
  48601. mxSafeFrame = pWal->hdr.mxFrame;
  48602. mxPage = pWal->hdr.nPage;
  48603. for(i=1; i<WAL_NREADER; i++){
  48604. /* Thread-sanitizer reports that the following is an unsafe read,
  48605. ** as some other thread may be in the process of updating the value
  48606. ** of the aReadMark[] slot. The assumption here is that if that is
  48607. ** happening, the other client may only be increasing the value,
  48608. ** not decreasing it. So assuming either that either the "old" or
  48609. ** "new" version of the value is read, and not some arbitrary value
  48610. ** that would never be written by a real client, things are still
  48611. ** safe. */
  48612. u32 y = pInfo->aReadMark[i];
  48613. if( mxSafeFrame>y ){
  48614. assert( y<=pWal->hdr.mxFrame );
  48615. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  48616. if( rc==SQLITE_OK ){
  48617. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  48618. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  48619. }else if( rc==SQLITE_BUSY ){
  48620. mxSafeFrame = y;
  48621. xBusy = 0;
  48622. }else{
  48623. goto walcheckpoint_out;
  48624. }
  48625. }
  48626. }
  48627. if( pInfo->nBackfill<mxSafeFrame
  48628. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  48629. ){
  48630. i64 nSize; /* Current size of database file */
  48631. u32 nBackfill = pInfo->nBackfill;
  48632. /* Sync the WAL to disk */
  48633. if( sync_flags ){
  48634. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  48635. }
  48636. /* If the database may grow as a result of this checkpoint, hint
  48637. ** about the eventual size of the db file to the VFS layer.
  48638. */
  48639. if( rc==SQLITE_OK ){
  48640. i64 nReq = ((i64)mxPage * szPage);
  48641. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  48642. if( rc==SQLITE_OK && nSize<nReq ){
  48643. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  48644. }
  48645. }
  48646. /* Iterate through the contents of the WAL, copying data to the db file */
  48647. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  48648. i64 iOffset;
  48649. assert( walFramePgno(pWal, iFrame)==iDbpage );
  48650. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  48651. continue;
  48652. }
  48653. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  48654. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  48655. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  48656. if( rc!=SQLITE_OK ) break;
  48657. iOffset = (iDbpage-1)*(i64)szPage;
  48658. testcase( IS_BIG_INT(iOffset) );
  48659. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  48660. if( rc!=SQLITE_OK ) break;
  48661. }
  48662. /* If work was actually accomplished... */
  48663. if( rc==SQLITE_OK ){
  48664. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  48665. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  48666. testcase( IS_BIG_INT(szDb) );
  48667. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  48668. if( rc==SQLITE_OK && sync_flags ){
  48669. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  48670. }
  48671. }
  48672. if( rc==SQLITE_OK ){
  48673. pInfo->nBackfill = mxSafeFrame;
  48674. }
  48675. }
  48676. /* Release the reader lock held while backfilling */
  48677. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  48678. }
  48679. if( rc==SQLITE_BUSY ){
  48680. /* Reset the return code so as not to report a checkpoint failure
  48681. ** just because there are active readers. */
  48682. rc = SQLITE_OK;
  48683. }
  48684. }
  48685. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  48686. ** entire wal file has been copied into the database file, then block
  48687. ** until all readers have finished using the wal file. This ensures that
  48688. ** the next process to write to the database restarts the wal file.
  48689. */
  48690. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  48691. assert( pWal->writeLock );
  48692. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  48693. rc = SQLITE_BUSY;
  48694. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  48695. u32 salt1;
  48696. sqlite3_randomness(4, &salt1);
  48697. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48698. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  48699. if( rc==SQLITE_OK ){
  48700. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  48701. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  48702. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  48703. ** truncates the log file to zero bytes just prior to a
  48704. ** successful return.
  48705. **
  48706. ** In theory, it might be safe to do this without updating the
  48707. ** wal-index header in shared memory, as all subsequent reader or
  48708. ** writer clients should see that the entire log file has been
  48709. ** checkpointed and behave accordingly. This seems unsafe though,
  48710. ** as it would leave the system in a state where the contents of
  48711. ** the wal-index header do not match the contents of the
  48712. ** file-system. To avoid this, update the wal-index header to
  48713. ** indicate that the log file contains zero valid frames. */
  48714. walRestartHdr(pWal, salt1);
  48715. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  48716. }
  48717. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48718. }
  48719. }
  48720. }
  48721. walcheckpoint_out:
  48722. walIteratorFree(pIter);
  48723. return rc;
  48724. }
  48725. /*
  48726. ** If the WAL file is currently larger than nMax bytes in size, truncate
  48727. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  48728. */
  48729. static void walLimitSize(Wal *pWal, i64 nMax){
  48730. i64 sz;
  48731. int rx;
  48732. sqlite3BeginBenignMalloc();
  48733. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  48734. if( rx==SQLITE_OK && (sz > nMax ) ){
  48735. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  48736. }
  48737. sqlite3EndBenignMalloc();
  48738. if( rx ){
  48739. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  48740. }
  48741. }
  48742. /*
  48743. ** Close a connection to a log file.
  48744. */
  48745. SQLITE_PRIVATE int sqlite3WalClose(
  48746. Wal *pWal, /* Wal to close */
  48747. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  48748. int nBuf,
  48749. u8 *zBuf /* Buffer of at least nBuf bytes */
  48750. ){
  48751. int rc = SQLITE_OK;
  48752. if( pWal ){
  48753. int isDelete = 0; /* True to unlink wal and wal-index files */
  48754. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  48755. ** ordinary, rollback-mode locking methods, this guarantees that the
  48756. ** connection associated with this log file is the only connection to
  48757. ** the database. In this case checkpoint the database and unlink both
  48758. ** the wal and wal-index files.
  48759. **
  48760. ** The EXCLUSIVE lock is not released before returning.
  48761. */
  48762. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  48763. if( rc==SQLITE_OK ){
  48764. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  48765. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  48766. }
  48767. rc = sqlite3WalCheckpoint(
  48768. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  48769. );
  48770. if( rc==SQLITE_OK ){
  48771. int bPersist = -1;
  48772. sqlite3OsFileControlHint(
  48773. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  48774. );
  48775. if( bPersist!=1 ){
  48776. /* Try to delete the WAL file if the checkpoint completed and
  48777. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  48778. ** mode (!bPersist) */
  48779. isDelete = 1;
  48780. }else if( pWal->mxWalSize>=0 ){
  48781. /* Try to truncate the WAL file to zero bytes if the checkpoint
  48782. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  48783. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  48784. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  48785. ** to zero bytes as truncating to the journal_size_limit might
  48786. ** leave a corrupt WAL file on disk. */
  48787. walLimitSize(pWal, 0);
  48788. }
  48789. }
  48790. }
  48791. walIndexClose(pWal, isDelete);
  48792. sqlite3OsClose(pWal->pWalFd);
  48793. if( isDelete ){
  48794. sqlite3BeginBenignMalloc();
  48795. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  48796. sqlite3EndBenignMalloc();
  48797. }
  48798. WALTRACE(("WAL%p: closed\n", pWal));
  48799. sqlite3_free((void *)pWal->apWiData);
  48800. sqlite3_free(pWal);
  48801. }
  48802. return rc;
  48803. }
  48804. /*
  48805. ** Try to read the wal-index header. Return 0 on success and 1 if
  48806. ** there is a problem.
  48807. **
  48808. ** The wal-index is in shared memory. Another thread or process might
  48809. ** be writing the header at the same time this procedure is trying to
  48810. ** read it, which might result in inconsistency. A dirty read is detected
  48811. ** by verifying that both copies of the header are the same and also by
  48812. ** a checksum on the header.
  48813. **
  48814. ** If and only if the read is consistent and the header is different from
  48815. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  48816. ** and *pChanged is set to 1.
  48817. **
  48818. ** If the checksum cannot be verified return non-zero. If the header
  48819. ** is read successfully and the checksum verified, return zero.
  48820. */
  48821. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  48822. u32 aCksum[2]; /* Checksum on the header content */
  48823. WalIndexHdr h1, h2; /* Two copies of the header content */
  48824. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  48825. /* The first page of the wal-index must be mapped at this point. */
  48826. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48827. /* Read the header. This might happen concurrently with a write to the
  48828. ** same area of shared memory on a different CPU in a SMP,
  48829. ** meaning it is possible that an inconsistent snapshot is read
  48830. ** from the file. If this happens, return non-zero.
  48831. **
  48832. ** There are two copies of the header at the beginning of the wal-index.
  48833. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  48834. ** Memory barriers are used to prevent the compiler or the hardware from
  48835. ** reordering the reads and writes.
  48836. */
  48837. aHdr = walIndexHdr(pWal);
  48838. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  48839. walShmBarrier(pWal);
  48840. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  48841. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  48842. return 1; /* Dirty read */
  48843. }
  48844. if( h1.isInit==0 ){
  48845. return 1; /* Malformed header - probably all zeros */
  48846. }
  48847. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  48848. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  48849. return 1; /* Checksum does not match */
  48850. }
  48851. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  48852. *pChanged = 1;
  48853. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  48854. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  48855. testcase( pWal->szPage<=32768 );
  48856. testcase( pWal->szPage>=65536 );
  48857. }
  48858. /* The header was successfully read. Return zero. */
  48859. return 0;
  48860. }
  48861. /*
  48862. ** Read the wal-index header from the wal-index and into pWal->hdr.
  48863. ** If the wal-header appears to be corrupt, try to reconstruct the
  48864. ** wal-index from the WAL before returning.
  48865. **
  48866. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  48867. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  48868. ** to 0.
  48869. **
  48870. ** If the wal-index header is successfully read, return SQLITE_OK.
  48871. ** Otherwise an SQLite error code.
  48872. */
  48873. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  48874. int rc; /* Return code */
  48875. int badHdr; /* True if a header read failed */
  48876. volatile u32 *page0; /* Chunk of wal-index containing header */
  48877. /* Ensure that page 0 of the wal-index (the page that contains the
  48878. ** wal-index header) is mapped. Return early if an error occurs here.
  48879. */
  48880. assert( pChanged );
  48881. rc = walIndexPage(pWal, 0, &page0);
  48882. if( rc!=SQLITE_OK ){
  48883. return rc;
  48884. };
  48885. assert( page0 || pWal->writeLock==0 );
  48886. /* If the first page of the wal-index has been mapped, try to read the
  48887. ** wal-index header immediately, without holding any lock. This usually
  48888. ** works, but may fail if the wal-index header is corrupt or currently
  48889. ** being modified by another thread or process.
  48890. */
  48891. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  48892. /* If the first attempt failed, it might have been due to a race
  48893. ** with a writer. So get a WRITE lock and try again.
  48894. */
  48895. assert( badHdr==0 || pWal->writeLock==0 );
  48896. if( badHdr ){
  48897. if( pWal->readOnly & WAL_SHM_RDONLY ){
  48898. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  48899. walUnlockShared(pWal, WAL_WRITE_LOCK);
  48900. rc = SQLITE_READONLY_RECOVERY;
  48901. }
  48902. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
  48903. pWal->writeLock = 1;
  48904. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  48905. badHdr = walIndexTryHdr(pWal, pChanged);
  48906. if( badHdr ){
  48907. /* If the wal-index header is still malformed even while holding
  48908. ** a WRITE lock, it can only mean that the header is corrupted and
  48909. ** needs to be reconstructed. So run recovery to do exactly that.
  48910. */
  48911. rc = walIndexRecover(pWal);
  48912. *pChanged = 1;
  48913. }
  48914. }
  48915. pWal->writeLock = 0;
  48916. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48917. }
  48918. }
  48919. /* If the header is read successfully, check the version number to make
  48920. ** sure the wal-index was not constructed with some future format that
  48921. ** this version of SQLite cannot understand.
  48922. */
  48923. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  48924. rc = SQLITE_CANTOPEN_BKPT;
  48925. }
  48926. return rc;
  48927. }
  48928. /*
  48929. ** This is the value that walTryBeginRead returns when it needs to
  48930. ** be retried.
  48931. */
  48932. #define WAL_RETRY (-1)
  48933. /*
  48934. ** Attempt to start a read transaction. This might fail due to a race or
  48935. ** other transient condition. When that happens, it returns WAL_RETRY to
  48936. ** indicate to the caller that it is safe to retry immediately.
  48937. **
  48938. ** On success return SQLITE_OK. On a permanent failure (such an
  48939. ** I/O error or an SQLITE_BUSY because another process is running
  48940. ** recovery) return a positive error code.
  48941. **
  48942. ** The useWal parameter is true to force the use of the WAL and disable
  48943. ** the case where the WAL is bypassed because it has been completely
  48944. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  48945. ** to make a copy of the wal-index header into pWal->hdr. If the
  48946. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  48947. ** to the caller that the local paget cache is obsolete and needs to be
  48948. ** flushed.) When useWal==1, the wal-index header is assumed to already
  48949. ** be loaded and the pChanged parameter is unused.
  48950. **
  48951. ** The caller must set the cnt parameter to the number of prior calls to
  48952. ** this routine during the current read attempt that returned WAL_RETRY.
  48953. ** This routine will start taking more aggressive measures to clear the
  48954. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  48955. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  48956. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  48957. ** and is not honoring the locking protocol. There is a vanishingly small
  48958. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  48959. ** bad luck when there is lots of contention for the wal-index, but that
  48960. ** possibility is so small that it can be safely neglected, we believe.
  48961. **
  48962. ** On success, this routine obtains a read lock on
  48963. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  48964. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  48965. ** that means the Wal does not hold any read lock. The reader must not
  48966. ** access any database page that is modified by a WAL frame up to and
  48967. ** including frame number aReadMark[pWal->readLock]. The reader will
  48968. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  48969. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  48970. ** completely and get all content directly from the database file.
  48971. ** If the useWal parameter is 1 then the WAL will never be ignored and
  48972. ** this routine will always set pWal->readLock>0 on success.
  48973. ** When the read transaction is completed, the caller must release the
  48974. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  48975. **
  48976. ** This routine uses the nBackfill and aReadMark[] fields of the header
  48977. ** to select a particular WAL_READ_LOCK() that strives to let the
  48978. ** checkpoint process do as much work as possible. This routine might
  48979. ** update values of the aReadMark[] array in the header, but if it does
  48980. ** so it takes care to hold an exclusive lock on the corresponding
  48981. ** WAL_READ_LOCK() while changing values.
  48982. */
  48983. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  48984. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  48985. u32 mxReadMark; /* Largest aReadMark[] value */
  48986. int mxI; /* Index of largest aReadMark[] value */
  48987. int i; /* Loop counter */
  48988. int rc = SQLITE_OK; /* Return code */
  48989. assert( pWal->readLock<0 ); /* Not currently locked */
  48990. /* Take steps to avoid spinning forever if there is a protocol error.
  48991. **
  48992. ** Circumstances that cause a RETRY should only last for the briefest
  48993. ** instances of time. No I/O or other system calls are done while the
  48994. ** locks are held, so the locks should not be held for very long. But
  48995. ** if we are unlucky, another process that is holding a lock might get
  48996. ** paged out or take a page-fault that is time-consuming to resolve,
  48997. ** during the few nanoseconds that it is holding the lock. In that case,
  48998. ** it might take longer than normal for the lock to free.
  48999. **
  49000. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  49001. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  49002. ** is more of a scheduler yield than an actual delay. But on the 10th
  49003. ** an subsequent retries, the delays start becoming longer and longer,
  49004. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  49005. ** The total delay time before giving up is less than 10 seconds.
  49006. */
  49007. if( cnt>5 ){
  49008. int nDelay = 1; /* Pause time in microseconds */
  49009. if( cnt>100 ){
  49010. VVA_ONLY( pWal->lockError = 1; )
  49011. return SQLITE_PROTOCOL;
  49012. }
  49013. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  49014. sqlite3OsSleep(pWal->pVfs, nDelay);
  49015. }
  49016. if( !useWal ){
  49017. rc = walIndexReadHdr(pWal, pChanged);
  49018. if( rc==SQLITE_BUSY ){
  49019. /* If there is not a recovery running in another thread or process
  49020. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  49021. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  49022. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  49023. ** would be technically correct. But the race is benign since with
  49024. ** WAL_RETRY this routine will be called again and will probably be
  49025. ** right on the second iteration.
  49026. */
  49027. if( pWal->apWiData[0]==0 ){
  49028. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  49029. ** We assume this is a transient condition, so return WAL_RETRY. The
  49030. ** xShmMap() implementation used by the default unix and win32 VFS
  49031. ** modules may return SQLITE_BUSY due to a race condition in the
  49032. ** code that determines whether or not the shared-memory region
  49033. ** must be zeroed before the requested page is returned.
  49034. */
  49035. rc = WAL_RETRY;
  49036. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  49037. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  49038. rc = WAL_RETRY;
  49039. }else if( rc==SQLITE_BUSY ){
  49040. rc = SQLITE_BUSY_RECOVERY;
  49041. }
  49042. }
  49043. if( rc!=SQLITE_OK ){
  49044. return rc;
  49045. }
  49046. }
  49047. pInfo = walCkptInfo(pWal);
  49048. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  49049. /* The WAL has been completely backfilled (or it is empty).
  49050. ** and can be safely ignored.
  49051. */
  49052. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  49053. walShmBarrier(pWal);
  49054. if( rc==SQLITE_OK ){
  49055. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  49056. /* It is not safe to allow the reader to continue here if frames
  49057. ** may have been appended to the log before READ_LOCK(0) was obtained.
  49058. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  49059. ** which implies that the database file contains a trustworthy
  49060. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  49061. ** happening, this is usually correct.
  49062. **
  49063. ** However, if frames have been appended to the log (or if the log
  49064. ** is wrapped and written for that matter) before the READ_LOCK(0)
  49065. ** is obtained, that is not necessarily true. A checkpointer may
  49066. ** have started to backfill the appended frames but crashed before
  49067. ** it finished. Leaving a corrupt image in the database file.
  49068. */
  49069. walUnlockShared(pWal, WAL_READ_LOCK(0));
  49070. return WAL_RETRY;
  49071. }
  49072. pWal->readLock = 0;
  49073. return SQLITE_OK;
  49074. }else if( rc!=SQLITE_BUSY ){
  49075. return rc;
  49076. }
  49077. }
  49078. /* If we get this far, it means that the reader will want to use
  49079. ** the WAL to get at content from recent commits. The job now is
  49080. ** to select one of the aReadMark[] entries that is closest to
  49081. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  49082. */
  49083. mxReadMark = 0;
  49084. mxI = 0;
  49085. for(i=1; i<WAL_NREADER; i++){
  49086. u32 thisMark = pInfo->aReadMark[i];
  49087. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  49088. assert( thisMark!=READMARK_NOT_USED );
  49089. mxReadMark = thisMark;
  49090. mxI = i;
  49091. }
  49092. }
  49093. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  49094. {
  49095. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  49096. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  49097. ){
  49098. for(i=1; i<WAL_NREADER; i++){
  49099. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
  49100. if( rc==SQLITE_OK ){
  49101. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  49102. mxI = i;
  49103. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  49104. break;
  49105. }else if( rc!=SQLITE_BUSY ){
  49106. return rc;
  49107. }
  49108. }
  49109. }
  49110. if( mxI==0 ){
  49111. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  49112. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  49113. }
  49114. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  49115. if( rc ){
  49116. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  49117. }
  49118. /* Now that the read-lock has been obtained, check that neither the
  49119. ** value in the aReadMark[] array or the contents of the wal-index
  49120. ** header have changed.
  49121. **
  49122. ** It is necessary to check that the wal-index header did not change
  49123. ** between the time it was read and when the shared-lock was obtained
  49124. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  49125. ** that the log file may have been wrapped by a writer, or that frames
  49126. ** that occur later in the log than pWal->hdr.mxFrame may have been
  49127. ** copied into the database by a checkpointer. If either of these things
  49128. ** happened, then reading the database with the current value of
  49129. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  49130. ** instead.
  49131. **
  49132. ** Before checking that the live wal-index header has not changed
  49133. ** since it was read, set Wal.minFrame to the first frame in the wal
  49134. ** file that has not yet been checkpointed. This client will not need
  49135. ** to read any frames earlier than minFrame from the wal file - they
  49136. ** can be safely read directly from the database file.
  49137. **
  49138. ** Because a ShmBarrier() call is made between taking the copy of
  49139. ** nBackfill and checking that the wal-header in shared-memory still
  49140. ** matches the one cached in pWal->hdr, it is guaranteed that the
  49141. ** checkpointer that set nBackfill was not working with a wal-index
  49142. ** header newer than that cached in pWal->hdr. If it were, that could
  49143. ** cause a problem. The checkpointer could omit to checkpoint
  49144. ** a version of page X that lies before pWal->minFrame (call that version
  49145. ** A) on the basis that there is a newer version (version B) of the same
  49146. ** page later in the wal file. But if version B happens to like past
  49147. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  49148. ** that it can read version A from the database file. However, since
  49149. ** we can guarantee that the checkpointer that set nBackfill could not
  49150. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  49151. */
  49152. pWal->minFrame = pInfo->nBackfill+1;
  49153. walShmBarrier(pWal);
  49154. if( pInfo->aReadMark[mxI]!=mxReadMark
  49155. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  49156. ){
  49157. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  49158. return WAL_RETRY;
  49159. }else{
  49160. assert( mxReadMark<=pWal->hdr.mxFrame );
  49161. pWal->readLock = (i16)mxI;
  49162. }
  49163. }
  49164. return rc;
  49165. }
  49166. /*
  49167. ** Begin a read transaction on the database.
  49168. **
  49169. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  49170. ** it takes a snapshot of the state of the WAL and wal-index for the current
  49171. ** instant in time. The current thread will continue to use this snapshot.
  49172. ** Other threads might append new content to the WAL and wal-index but
  49173. ** that extra content is ignored by the current thread.
  49174. **
  49175. ** If the database contents have changes since the previous read
  49176. ** transaction, then *pChanged is set to 1 before returning. The
  49177. ** Pager layer will use this to know that is cache is stale and
  49178. ** needs to be flushed.
  49179. */
  49180. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  49181. int rc; /* Return code */
  49182. int cnt = 0; /* Number of TryBeginRead attempts */
  49183. do{
  49184. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  49185. }while( rc==WAL_RETRY );
  49186. testcase( (rc&0xff)==SQLITE_BUSY );
  49187. testcase( (rc&0xff)==SQLITE_IOERR );
  49188. testcase( rc==SQLITE_PROTOCOL );
  49189. testcase( rc==SQLITE_OK );
  49190. return rc;
  49191. }
  49192. /*
  49193. ** Finish with a read transaction. All this does is release the
  49194. ** read-lock.
  49195. */
  49196. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  49197. sqlite3WalEndWriteTransaction(pWal);
  49198. if( pWal->readLock>=0 ){
  49199. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  49200. pWal->readLock = -1;
  49201. }
  49202. }
  49203. /*
  49204. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  49205. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  49206. ** to zero.
  49207. **
  49208. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  49209. ** error does occur, the final value of *piRead is undefined.
  49210. */
  49211. SQLITE_PRIVATE int sqlite3WalFindFrame(
  49212. Wal *pWal, /* WAL handle */
  49213. Pgno pgno, /* Database page number to read data for */
  49214. u32 *piRead /* OUT: Frame number (or zero) */
  49215. ){
  49216. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  49217. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  49218. int iHash; /* Used to loop through N hash tables */
  49219. int iMinHash;
  49220. /* This routine is only be called from within a read transaction. */
  49221. assert( pWal->readLock>=0 || pWal->lockError );
  49222. /* If the "last page" field of the wal-index header snapshot is 0, then
  49223. ** no data will be read from the wal under any circumstances. Return early
  49224. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  49225. ** then the WAL is ignored by the reader so return early, as if the
  49226. ** WAL were empty.
  49227. */
  49228. if( iLast==0 || pWal->readLock==0 ){
  49229. *piRead = 0;
  49230. return SQLITE_OK;
  49231. }
  49232. /* Search the hash table or tables for an entry matching page number
  49233. ** pgno. Each iteration of the following for() loop searches one
  49234. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  49235. **
  49236. ** This code might run concurrently to the code in walIndexAppend()
  49237. ** that adds entries to the wal-index (and possibly to this hash
  49238. ** table). This means the value just read from the hash
  49239. ** slot (aHash[iKey]) may have been added before or after the
  49240. ** current read transaction was opened. Values added after the
  49241. ** read transaction was opened may have been written incorrectly -
  49242. ** i.e. these slots may contain garbage data. However, we assume
  49243. ** that any slots written before the current read transaction was
  49244. ** opened remain unmodified.
  49245. **
  49246. ** For the reasons above, the if(...) condition featured in the inner
  49247. ** loop of the following block is more stringent that would be required
  49248. ** if we had exclusive access to the hash-table:
  49249. **
  49250. ** (aPgno[iFrame]==pgno):
  49251. ** This condition filters out normal hash-table collisions.
  49252. **
  49253. ** (iFrame<=iLast):
  49254. ** This condition filters out entries that were added to the hash
  49255. ** table after the current read-transaction had started.
  49256. */
  49257. iMinHash = walFramePage(pWal->minFrame);
  49258. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  49259. volatile ht_slot *aHash; /* Pointer to hash table */
  49260. volatile u32 *aPgno; /* Pointer to array of page numbers */
  49261. u32 iZero; /* Frame number corresponding to aPgno[0] */
  49262. int iKey; /* Hash slot index */
  49263. int nCollide; /* Number of hash collisions remaining */
  49264. int rc; /* Error code */
  49265. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  49266. if( rc!=SQLITE_OK ){
  49267. return rc;
  49268. }
  49269. nCollide = HASHTABLE_NSLOT;
  49270. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  49271. u32 iFrame = aHash[iKey] + iZero;
  49272. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  49273. assert( iFrame>iRead || CORRUPT_DB );
  49274. iRead = iFrame;
  49275. }
  49276. if( (nCollide--)==0 ){
  49277. return SQLITE_CORRUPT_BKPT;
  49278. }
  49279. }
  49280. }
  49281. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  49282. /* If expensive assert() statements are available, do a linear search
  49283. ** of the wal-index file content. Make sure the results agree with the
  49284. ** result obtained using the hash indexes above. */
  49285. {
  49286. u32 iRead2 = 0;
  49287. u32 iTest;
  49288. assert( pWal->minFrame>0 );
  49289. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  49290. if( walFramePgno(pWal, iTest)==pgno ){
  49291. iRead2 = iTest;
  49292. break;
  49293. }
  49294. }
  49295. assert( iRead==iRead2 );
  49296. }
  49297. #endif
  49298. *piRead = iRead;
  49299. return SQLITE_OK;
  49300. }
  49301. /*
  49302. ** Read the contents of frame iRead from the wal file into buffer pOut
  49303. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  49304. ** error code otherwise.
  49305. */
  49306. SQLITE_PRIVATE int sqlite3WalReadFrame(
  49307. Wal *pWal, /* WAL handle */
  49308. u32 iRead, /* Frame to read */
  49309. int nOut, /* Size of buffer pOut in bytes */
  49310. u8 *pOut /* Buffer to write page data to */
  49311. ){
  49312. int sz;
  49313. i64 iOffset;
  49314. sz = pWal->hdr.szPage;
  49315. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  49316. testcase( sz<=32768 );
  49317. testcase( sz>=65536 );
  49318. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  49319. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  49320. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  49321. }
  49322. /*
  49323. ** Return the size of the database in pages (or zero, if unknown).
  49324. */
  49325. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  49326. if( pWal && ALWAYS(pWal->readLock>=0) ){
  49327. return pWal->hdr.nPage;
  49328. }
  49329. return 0;
  49330. }
  49331. /*
  49332. ** This function starts a write transaction on the WAL.
  49333. **
  49334. ** A read transaction must have already been started by a prior call
  49335. ** to sqlite3WalBeginReadTransaction().
  49336. **
  49337. ** If another thread or process has written into the database since
  49338. ** the read transaction was started, then it is not possible for this
  49339. ** thread to write as doing so would cause a fork. So this routine
  49340. ** returns SQLITE_BUSY in that case and no write transaction is started.
  49341. **
  49342. ** There can only be a single writer active at a time.
  49343. */
  49344. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  49345. int rc;
  49346. /* Cannot start a write transaction without first holding a read
  49347. ** transaction. */
  49348. assert( pWal->readLock>=0 );
  49349. if( pWal->readOnly ){
  49350. return SQLITE_READONLY;
  49351. }
  49352. /* Only one writer allowed at a time. Get the write lock. Return
  49353. ** SQLITE_BUSY if unable.
  49354. */
  49355. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
  49356. if( rc ){
  49357. return rc;
  49358. }
  49359. pWal->writeLock = 1;
  49360. /* If another connection has written to the database file since the
  49361. ** time the read transaction on this connection was started, then
  49362. ** the write is disallowed.
  49363. */
  49364. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  49365. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49366. pWal->writeLock = 0;
  49367. rc = SQLITE_BUSY_SNAPSHOT;
  49368. }
  49369. return rc;
  49370. }
  49371. /*
  49372. ** End a write transaction. The commit has already been done. This
  49373. ** routine merely releases the lock.
  49374. */
  49375. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  49376. if( pWal->writeLock ){
  49377. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49378. pWal->writeLock = 0;
  49379. pWal->truncateOnCommit = 0;
  49380. }
  49381. return SQLITE_OK;
  49382. }
  49383. /*
  49384. ** If any data has been written (but not committed) to the log file, this
  49385. ** function moves the write-pointer back to the start of the transaction.
  49386. **
  49387. ** Additionally, the callback function is invoked for each frame written
  49388. ** to the WAL since the start of the transaction. If the callback returns
  49389. ** other than SQLITE_OK, it is not invoked again and the error code is
  49390. ** returned to the caller.
  49391. **
  49392. ** Otherwise, if the callback function does not return an error, this
  49393. ** function returns SQLITE_OK.
  49394. */
  49395. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  49396. int rc = SQLITE_OK;
  49397. if( ALWAYS(pWal->writeLock) ){
  49398. Pgno iMax = pWal->hdr.mxFrame;
  49399. Pgno iFrame;
  49400. /* Restore the clients cache of the wal-index header to the state it
  49401. ** was in before the client began writing to the database.
  49402. */
  49403. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  49404. for(iFrame=pWal->hdr.mxFrame+1;
  49405. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  49406. iFrame++
  49407. ){
  49408. /* This call cannot fail. Unless the page for which the page number
  49409. ** is passed as the second argument is (a) in the cache and
  49410. ** (b) has an outstanding reference, then xUndo is either a no-op
  49411. ** (if (a) is false) or simply expels the page from the cache (if (b)
  49412. ** is false).
  49413. **
  49414. ** If the upper layer is doing a rollback, it is guaranteed that there
  49415. ** are no outstanding references to any page other than page 1. And
  49416. ** page 1 is never written to the log until the transaction is
  49417. ** committed. As a result, the call to xUndo may not fail.
  49418. */
  49419. assert( walFramePgno(pWal, iFrame)!=1 );
  49420. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  49421. }
  49422. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  49423. }
  49424. return rc;
  49425. }
  49426. /*
  49427. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  49428. ** values. This function populates the array with values required to
  49429. ** "rollback" the write position of the WAL handle back to the current
  49430. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  49431. */
  49432. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  49433. assert( pWal->writeLock );
  49434. aWalData[0] = pWal->hdr.mxFrame;
  49435. aWalData[1] = pWal->hdr.aFrameCksum[0];
  49436. aWalData[2] = pWal->hdr.aFrameCksum[1];
  49437. aWalData[3] = pWal->nCkpt;
  49438. }
  49439. /*
  49440. ** Move the write position of the WAL back to the point identified by
  49441. ** the values in the aWalData[] array. aWalData must point to an array
  49442. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  49443. ** by a call to WalSavepoint().
  49444. */
  49445. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  49446. int rc = SQLITE_OK;
  49447. assert( pWal->writeLock );
  49448. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  49449. if( aWalData[3]!=pWal->nCkpt ){
  49450. /* This savepoint was opened immediately after the write-transaction
  49451. ** was started. Right after that, the writer decided to wrap around
  49452. ** to the start of the log. Update the savepoint values to match.
  49453. */
  49454. aWalData[0] = 0;
  49455. aWalData[3] = pWal->nCkpt;
  49456. }
  49457. if( aWalData[0]<pWal->hdr.mxFrame ){
  49458. pWal->hdr.mxFrame = aWalData[0];
  49459. pWal->hdr.aFrameCksum[0] = aWalData[1];
  49460. pWal->hdr.aFrameCksum[1] = aWalData[2];
  49461. walCleanupHash(pWal);
  49462. }
  49463. return rc;
  49464. }
  49465. /*
  49466. ** This function is called just before writing a set of frames to the log
  49467. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  49468. ** to the current log file, it is possible to overwrite the start of the
  49469. ** existing log file with the new frames (i.e. "reset" the log). If so,
  49470. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  49471. ** unchanged.
  49472. **
  49473. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  49474. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  49475. ** if an error occurs.
  49476. */
  49477. static int walRestartLog(Wal *pWal){
  49478. int rc = SQLITE_OK;
  49479. int cnt;
  49480. if( pWal->readLock==0 ){
  49481. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  49482. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  49483. if( pInfo->nBackfill>0 ){
  49484. u32 salt1;
  49485. sqlite3_randomness(4, &salt1);
  49486. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
  49487. if( rc==SQLITE_OK ){
  49488. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  49489. ** readers are currently using the WAL), then the transactions
  49490. ** frames will overwrite the start of the existing log. Update the
  49491. ** wal-index header to reflect this.
  49492. **
  49493. ** In theory it would be Ok to update the cache of the header only
  49494. ** at this point. But updating the actual wal-index header is also
  49495. ** safe and means there is no special case for sqlite3WalUndo()
  49496. ** to handle if this transaction is rolled back. */
  49497. walRestartHdr(pWal, salt1);
  49498. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  49499. }else if( rc!=SQLITE_BUSY ){
  49500. return rc;
  49501. }
  49502. }
  49503. walUnlockShared(pWal, WAL_READ_LOCK(0));
  49504. pWal->readLock = -1;
  49505. cnt = 0;
  49506. do{
  49507. int notUsed;
  49508. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  49509. }while( rc==WAL_RETRY );
  49510. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  49511. testcase( (rc&0xff)==SQLITE_IOERR );
  49512. testcase( rc==SQLITE_PROTOCOL );
  49513. testcase( rc==SQLITE_OK );
  49514. }
  49515. return rc;
  49516. }
  49517. /*
  49518. ** Information about the current state of the WAL file and where
  49519. ** the next fsync should occur - passed from sqlite3WalFrames() into
  49520. ** walWriteToLog().
  49521. */
  49522. typedef struct WalWriter {
  49523. Wal *pWal; /* The complete WAL information */
  49524. sqlite3_file *pFd; /* The WAL file to which we write */
  49525. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  49526. int syncFlags; /* Flags for the fsync */
  49527. int szPage; /* Size of one page */
  49528. } WalWriter;
  49529. /*
  49530. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  49531. ** Do a sync when crossing the p->iSyncPoint boundary.
  49532. **
  49533. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  49534. ** first write the part before iSyncPoint, then sync, then write the
  49535. ** rest.
  49536. */
  49537. static int walWriteToLog(
  49538. WalWriter *p, /* WAL to write to */
  49539. void *pContent, /* Content to be written */
  49540. int iAmt, /* Number of bytes to write */
  49541. sqlite3_int64 iOffset /* Start writing at this offset */
  49542. ){
  49543. int rc;
  49544. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  49545. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  49546. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  49547. if( rc ) return rc;
  49548. iOffset += iFirstAmt;
  49549. iAmt -= iFirstAmt;
  49550. pContent = (void*)(iFirstAmt + (char*)pContent);
  49551. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  49552. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  49553. if( iAmt==0 || rc ) return rc;
  49554. }
  49555. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  49556. return rc;
  49557. }
  49558. /*
  49559. ** Write out a single frame of the WAL
  49560. */
  49561. static int walWriteOneFrame(
  49562. WalWriter *p, /* Where to write the frame */
  49563. PgHdr *pPage, /* The page of the frame to be written */
  49564. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  49565. sqlite3_int64 iOffset /* Byte offset at which to write */
  49566. ){
  49567. int rc; /* Result code from subfunctions */
  49568. void *pData; /* Data actually written */
  49569. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  49570. #if defined(SQLITE_HAS_CODEC)
  49571. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  49572. #else
  49573. pData = pPage->pData;
  49574. #endif
  49575. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  49576. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  49577. if( rc ) return rc;
  49578. /* Write the page data */
  49579. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  49580. return rc;
  49581. }
  49582. /*
  49583. ** Write a set of frames to the log. The caller must hold the write-lock
  49584. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  49585. */
  49586. SQLITE_PRIVATE int sqlite3WalFrames(
  49587. Wal *pWal, /* Wal handle to write to */
  49588. int szPage, /* Database page-size in bytes */
  49589. PgHdr *pList, /* List of dirty pages to write */
  49590. Pgno nTruncate, /* Database size after this commit */
  49591. int isCommit, /* True if this is a commit */
  49592. int sync_flags /* Flags to pass to OsSync() (or 0) */
  49593. ){
  49594. int rc; /* Used to catch return codes */
  49595. u32 iFrame; /* Next frame address */
  49596. PgHdr *p; /* Iterator to run through pList with. */
  49597. PgHdr *pLast = 0; /* Last frame in list */
  49598. int nExtra = 0; /* Number of extra copies of last page */
  49599. int szFrame; /* The size of a single frame */
  49600. i64 iOffset; /* Next byte to write in WAL file */
  49601. WalWriter w; /* The writer */
  49602. assert( pList );
  49603. assert( pWal->writeLock );
  49604. /* If this frame set completes a transaction, then nTruncate>0. If
  49605. ** nTruncate==0 then this frame set does not complete the transaction. */
  49606. assert( (isCommit!=0)==(nTruncate!=0) );
  49607. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  49608. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  49609. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  49610. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  49611. }
  49612. #endif
  49613. /* See if it is possible to write these frames into the start of the
  49614. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  49615. */
  49616. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  49617. return rc;
  49618. }
  49619. /* If this is the first frame written into the log, write the WAL
  49620. ** header to the start of the WAL file. See comments at the top of
  49621. ** this source file for a description of the WAL header format.
  49622. */
  49623. iFrame = pWal->hdr.mxFrame;
  49624. if( iFrame==0 ){
  49625. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  49626. u32 aCksum[2]; /* Checksum for wal-header */
  49627. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  49628. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  49629. sqlite3Put4byte(&aWalHdr[8], szPage);
  49630. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  49631. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  49632. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  49633. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  49634. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  49635. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  49636. pWal->szPage = szPage;
  49637. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  49638. pWal->hdr.aFrameCksum[0] = aCksum[0];
  49639. pWal->hdr.aFrameCksum[1] = aCksum[1];
  49640. pWal->truncateOnCommit = 1;
  49641. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  49642. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  49643. if( rc!=SQLITE_OK ){
  49644. return rc;
  49645. }
  49646. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  49647. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  49648. ** an out-of-order write following a WAL restart could result in
  49649. ** database corruption. See the ticket:
  49650. **
  49651. ** http://localhost:591/sqlite/info/ff5be73dee
  49652. */
  49653. if( pWal->syncHeader && sync_flags ){
  49654. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  49655. if( rc ) return rc;
  49656. }
  49657. }
  49658. assert( (int)pWal->szPage==szPage );
  49659. /* Setup information needed to write frames into the WAL */
  49660. w.pWal = pWal;
  49661. w.pFd = pWal->pWalFd;
  49662. w.iSyncPoint = 0;
  49663. w.syncFlags = sync_flags;
  49664. w.szPage = szPage;
  49665. iOffset = walFrameOffset(iFrame+1, szPage);
  49666. szFrame = szPage + WAL_FRAME_HDRSIZE;
  49667. /* Write all frames into the log file exactly once */
  49668. for(p=pList; p; p=p->pDirty){
  49669. int nDbSize; /* 0 normally. Positive == commit flag */
  49670. iFrame++;
  49671. assert( iOffset==walFrameOffset(iFrame, szPage) );
  49672. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  49673. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  49674. if( rc ) return rc;
  49675. pLast = p;
  49676. iOffset += szFrame;
  49677. }
  49678. /* If this is the end of a transaction, then we might need to pad
  49679. ** the transaction and/or sync the WAL file.
  49680. **
  49681. ** Padding and syncing only occur if this set of frames complete a
  49682. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  49683. ** or synchronous==OFF, then no padding or syncing are needed.
  49684. **
  49685. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  49686. ** needed and only the sync is done. If padding is needed, then the
  49687. ** final frame is repeated (with its commit mark) until the next sector
  49688. ** boundary is crossed. Only the part of the WAL prior to the last
  49689. ** sector boundary is synced; the part of the last frame that extends
  49690. ** past the sector boundary is written after the sync.
  49691. */
  49692. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  49693. if( pWal->padToSectorBoundary ){
  49694. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  49695. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  49696. while( iOffset<w.iSyncPoint ){
  49697. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  49698. if( rc ) return rc;
  49699. iOffset += szFrame;
  49700. nExtra++;
  49701. }
  49702. }else{
  49703. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  49704. }
  49705. }
  49706. /* If this frame set completes the first transaction in the WAL and
  49707. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  49708. ** journal size limit, if possible.
  49709. */
  49710. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  49711. i64 sz = pWal->mxWalSize;
  49712. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  49713. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  49714. }
  49715. walLimitSize(pWal, sz);
  49716. pWal->truncateOnCommit = 0;
  49717. }
  49718. /* Append data to the wal-index. It is not necessary to lock the
  49719. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  49720. ** guarantees that there are no other writers, and no data that may
  49721. ** be in use by existing readers is being overwritten.
  49722. */
  49723. iFrame = pWal->hdr.mxFrame;
  49724. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  49725. iFrame++;
  49726. rc = walIndexAppend(pWal, iFrame, p->pgno);
  49727. }
  49728. while( rc==SQLITE_OK && nExtra>0 ){
  49729. iFrame++;
  49730. nExtra--;
  49731. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  49732. }
  49733. if( rc==SQLITE_OK ){
  49734. /* Update the private copy of the header. */
  49735. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  49736. testcase( szPage<=32768 );
  49737. testcase( szPage>=65536 );
  49738. pWal->hdr.mxFrame = iFrame;
  49739. if( isCommit ){
  49740. pWal->hdr.iChange++;
  49741. pWal->hdr.nPage = nTruncate;
  49742. }
  49743. /* If this is a commit, update the wal-index header too. */
  49744. if( isCommit ){
  49745. walIndexWriteHdr(pWal);
  49746. pWal->iCallback = iFrame;
  49747. }
  49748. }
  49749. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  49750. return rc;
  49751. }
  49752. /*
  49753. ** This routine is called to implement sqlite3_wal_checkpoint() and
  49754. ** related interfaces.
  49755. **
  49756. ** Obtain a CHECKPOINT lock and then backfill as much information as
  49757. ** we can from WAL into the database.
  49758. **
  49759. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  49760. ** callback. In this case this function runs a blocking checkpoint.
  49761. */
  49762. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  49763. Wal *pWal, /* Wal connection */
  49764. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  49765. int (*xBusy)(void*), /* Function to call when busy */
  49766. void *pBusyArg, /* Context argument for xBusyHandler */
  49767. int sync_flags, /* Flags to sync db file with (or 0) */
  49768. int nBuf, /* Size of temporary buffer */
  49769. u8 *zBuf, /* Temporary buffer to use */
  49770. int *pnLog, /* OUT: Number of frames in WAL */
  49771. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  49772. ){
  49773. int rc; /* Return code */
  49774. int isChanged = 0; /* True if a new wal-index header is loaded */
  49775. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  49776. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  49777. assert( pWal->ckptLock==0 );
  49778. assert( pWal->writeLock==0 );
  49779. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  49780. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  49781. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  49782. if( pWal->readOnly ) return SQLITE_READONLY;
  49783. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  49784. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  49785. ** "checkpoint" lock on the database file. */
  49786. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
  49787. if( rc ){
  49788. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  49789. ** checkpoint operation at the same time, the lock cannot be obtained and
  49790. ** SQLITE_BUSY is returned.
  49791. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  49792. ** it will not be invoked in this case.
  49793. */
  49794. testcase( rc==SQLITE_BUSY );
  49795. testcase( xBusy!=0 );
  49796. return rc;
  49797. }
  49798. pWal->ckptLock = 1;
  49799. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  49800. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  49801. ** file.
  49802. **
  49803. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  49804. ** immediately, and a busy-handler is configured, it is invoked and the
  49805. ** writer lock retried until either the busy-handler returns 0 or the
  49806. ** lock is successfully obtained.
  49807. */
  49808. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  49809. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  49810. if( rc==SQLITE_OK ){
  49811. pWal->writeLock = 1;
  49812. }else if( rc==SQLITE_BUSY ){
  49813. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  49814. xBusy2 = 0;
  49815. rc = SQLITE_OK;
  49816. }
  49817. }
  49818. /* Read the wal-index header. */
  49819. if( rc==SQLITE_OK ){
  49820. rc = walIndexReadHdr(pWal, &isChanged);
  49821. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  49822. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  49823. }
  49824. }
  49825. /* Copy data from the log to the database file. */
  49826. if( rc==SQLITE_OK ){
  49827. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  49828. rc = SQLITE_CORRUPT_BKPT;
  49829. }else{
  49830. rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  49831. }
  49832. /* If no error occurred, set the output variables. */
  49833. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  49834. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  49835. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  49836. }
  49837. }
  49838. if( isChanged ){
  49839. /* If a new wal-index header was loaded before the checkpoint was
  49840. ** performed, then the pager-cache associated with pWal is now
  49841. ** out of date. So zero the cached wal-index header to ensure that
  49842. ** next time the pager opens a snapshot on this database it knows that
  49843. ** the cache needs to be reset.
  49844. */
  49845. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  49846. }
  49847. /* Release the locks. */
  49848. sqlite3WalEndWriteTransaction(pWal);
  49849. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  49850. pWal->ckptLock = 0;
  49851. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  49852. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  49853. }
  49854. /* Return the value to pass to a sqlite3_wal_hook callback, the
  49855. ** number of frames in the WAL at the point of the last commit since
  49856. ** sqlite3WalCallback() was called. If no commits have occurred since
  49857. ** the last call, then return 0.
  49858. */
  49859. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  49860. u32 ret = 0;
  49861. if( pWal ){
  49862. ret = pWal->iCallback;
  49863. pWal->iCallback = 0;
  49864. }
  49865. return (int)ret;
  49866. }
  49867. /*
  49868. ** This function is called to change the WAL subsystem into or out
  49869. ** of locking_mode=EXCLUSIVE.
  49870. **
  49871. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  49872. ** into locking_mode=NORMAL. This means that we must acquire a lock
  49873. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  49874. ** or if the acquisition of the lock fails, then return 0. If the
  49875. ** transition out of exclusive-mode is successful, return 1. This
  49876. ** operation must occur while the pager is still holding the exclusive
  49877. ** lock on the main database file.
  49878. **
  49879. ** If op is one, then change from locking_mode=NORMAL into
  49880. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  49881. ** be released. Return 1 if the transition is made and 0 if the
  49882. ** WAL is already in exclusive-locking mode - meaning that this
  49883. ** routine is a no-op. The pager must already hold the exclusive lock
  49884. ** on the main database file before invoking this operation.
  49885. **
  49886. ** If op is negative, then do a dry-run of the op==1 case but do
  49887. ** not actually change anything. The pager uses this to see if it
  49888. ** should acquire the database exclusive lock prior to invoking
  49889. ** the op==1 case.
  49890. */
  49891. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  49892. int rc;
  49893. assert( pWal->writeLock==0 );
  49894. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  49895. /* pWal->readLock is usually set, but might be -1 if there was a
  49896. ** prior error while attempting to acquire are read-lock. This cannot
  49897. ** happen if the connection is actually in exclusive mode (as no xShmLock
  49898. ** locks are taken in this case). Nor should the pager attempt to
  49899. ** upgrade to exclusive-mode following such an error.
  49900. */
  49901. assert( pWal->readLock>=0 || pWal->lockError );
  49902. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  49903. if( op==0 ){
  49904. if( pWal->exclusiveMode ){
  49905. pWal->exclusiveMode = 0;
  49906. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  49907. pWal->exclusiveMode = 1;
  49908. }
  49909. rc = pWal->exclusiveMode==0;
  49910. }else{
  49911. /* Already in locking_mode=NORMAL */
  49912. rc = 0;
  49913. }
  49914. }else if( op>0 ){
  49915. assert( pWal->exclusiveMode==0 );
  49916. assert( pWal->readLock>=0 );
  49917. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  49918. pWal->exclusiveMode = 1;
  49919. rc = 1;
  49920. }else{
  49921. rc = pWal->exclusiveMode==0;
  49922. }
  49923. return rc;
  49924. }
  49925. /*
  49926. ** Return true if the argument is non-NULL and the WAL module is using
  49927. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  49928. ** WAL module is using shared-memory, return false.
  49929. */
  49930. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  49931. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  49932. }
  49933. #ifdef SQLITE_ENABLE_ZIPVFS
  49934. /*
  49935. ** If the argument is not NULL, it points to a Wal object that holds a
  49936. ** read-lock. This function returns the database page-size if it is known,
  49937. ** or zero if it is not (or if pWal is NULL).
  49938. */
  49939. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  49940. assert( pWal==0 || pWal->readLock>=0 );
  49941. return (pWal ? pWal->szPage : 0);
  49942. }
  49943. #endif
  49944. #endif /* #ifndef SQLITE_OMIT_WAL */
  49945. /************** End of wal.c *************************************************/
  49946. /************** Begin file btmutex.c *****************************************/
  49947. /*
  49948. ** 2007 August 27
  49949. **
  49950. ** The author disclaims copyright to this source code. In place of
  49951. ** a legal notice, here is a blessing:
  49952. **
  49953. ** May you do good and not evil.
  49954. ** May you find forgiveness for yourself and forgive others.
  49955. ** May you share freely, never taking more than you give.
  49956. **
  49957. *************************************************************************
  49958. **
  49959. ** This file contains code used to implement mutexes on Btree objects.
  49960. ** This code really belongs in btree.c. But btree.c is getting too
  49961. ** big and we want to break it down some. This packaged seemed like
  49962. ** a good breakout.
  49963. */
  49964. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  49965. /************** Begin file btreeInt.h ****************************************/
  49966. /*
  49967. ** 2004 April 6
  49968. **
  49969. ** The author disclaims copyright to this source code. In place of
  49970. ** a legal notice, here is a blessing:
  49971. **
  49972. ** May you do good and not evil.
  49973. ** May you find forgiveness for yourself and forgive others.
  49974. ** May you share freely, never taking more than you give.
  49975. **
  49976. *************************************************************************
  49977. ** This file implements an external (disk-based) database using BTrees.
  49978. ** For a detailed discussion of BTrees, refer to
  49979. **
  49980. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  49981. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  49982. ** Publishing Company, Reading, Massachusetts.
  49983. **
  49984. ** The basic idea is that each page of the file contains N database
  49985. ** entries and N+1 pointers to subpages.
  49986. **
  49987. ** ----------------------------------------------------------------
  49988. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  49989. ** ----------------------------------------------------------------
  49990. **
  49991. ** All of the keys on the page that Ptr(0) points to have values less
  49992. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  49993. ** values greater than Key(0) and less than Key(1). All of the keys
  49994. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  49995. ** so forth.
  49996. **
  49997. ** Finding a particular key requires reading O(log(M)) pages from the
  49998. ** disk where M is the number of entries in the tree.
  49999. **
  50000. ** In this implementation, a single file can hold one or more separate
  50001. ** BTrees. Each BTree is identified by the index of its root page. The
  50002. ** key and data for any entry are combined to form the "payload". A
  50003. ** fixed amount of payload can be carried directly on the database
  50004. ** page. If the payload is larger than the preset amount then surplus
  50005. ** bytes are stored on overflow pages. The payload for an entry
  50006. ** and the preceding pointer are combined to form a "Cell". Each
  50007. ** page has a small header which contains the Ptr(N) pointer and other
  50008. ** information such as the size of key and data.
  50009. **
  50010. ** FORMAT DETAILS
  50011. **
  50012. ** The file is divided into pages. The first page is called page 1,
  50013. ** the second is page 2, and so forth. A page number of zero indicates
  50014. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  50015. ** Each page can be either a btree page, a freelist page, an overflow
  50016. ** page, or a pointer-map page.
  50017. **
  50018. ** The first page is always a btree page. The first 100 bytes of the first
  50019. ** page contain a special header (the "file header") that describes the file.
  50020. ** The format of the file header is as follows:
  50021. **
  50022. ** OFFSET SIZE DESCRIPTION
  50023. ** 0 16 Header string: "SQLite format 3\000"
  50024. ** 16 2 Page size in bytes. (1 means 65536)
  50025. ** 18 1 File format write version
  50026. ** 19 1 File format read version
  50027. ** 20 1 Bytes of unused space at the end of each page
  50028. ** 21 1 Max embedded payload fraction (must be 64)
  50029. ** 22 1 Min embedded payload fraction (must be 32)
  50030. ** 23 1 Min leaf payload fraction (must be 32)
  50031. ** 24 4 File change counter
  50032. ** 28 4 Reserved for future use
  50033. ** 32 4 First freelist page
  50034. ** 36 4 Number of freelist pages in the file
  50035. ** 40 60 15 4-byte meta values passed to higher layers
  50036. **
  50037. ** 40 4 Schema cookie
  50038. ** 44 4 File format of schema layer
  50039. ** 48 4 Size of page cache
  50040. ** 52 4 Largest root-page (auto/incr_vacuum)
  50041. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  50042. ** 60 4 User version
  50043. ** 64 4 Incremental vacuum mode
  50044. ** 68 4 Application-ID
  50045. ** 72 20 unused
  50046. ** 92 4 The version-valid-for number
  50047. ** 96 4 SQLITE_VERSION_NUMBER
  50048. **
  50049. ** All of the integer values are big-endian (most significant byte first).
  50050. **
  50051. ** The file change counter is incremented when the database is changed
  50052. ** This counter allows other processes to know when the file has changed
  50053. ** and thus when they need to flush their cache.
  50054. **
  50055. ** The max embedded payload fraction is the amount of the total usable
  50056. ** space in a page that can be consumed by a single cell for standard
  50057. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  50058. ** is to limit the maximum cell size so that at least 4 cells will fit
  50059. ** on one page. Thus the default max embedded payload fraction is 64.
  50060. **
  50061. ** If the payload for a cell is larger than the max payload, then extra
  50062. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  50063. ** as many bytes as possible are moved into the overflow pages without letting
  50064. ** the cell size drop below the min embedded payload fraction.
  50065. **
  50066. ** The min leaf payload fraction is like the min embedded payload fraction
  50067. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  50068. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  50069. ** not specified in the header.
  50070. **
  50071. ** Each btree pages is divided into three sections: The header, the
  50072. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  50073. ** file header that occurs before the page header.
  50074. **
  50075. ** |----------------|
  50076. ** | file header | 100 bytes. Page 1 only.
  50077. ** |----------------|
  50078. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  50079. ** |----------------|
  50080. ** | cell pointer | | 2 bytes per cell. Sorted order.
  50081. ** | array | | Grows downward
  50082. ** | | v
  50083. ** |----------------|
  50084. ** | unallocated |
  50085. ** | space |
  50086. ** |----------------| ^ Grows upwards
  50087. ** | cell content | | Arbitrary order interspersed with freeblocks.
  50088. ** | area | | and free space fragments.
  50089. ** |----------------|
  50090. **
  50091. ** The page headers looks like this:
  50092. **
  50093. ** OFFSET SIZE DESCRIPTION
  50094. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  50095. ** 1 2 byte offset to the first freeblock
  50096. ** 3 2 number of cells on this page
  50097. ** 5 2 first byte of the cell content area
  50098. ** 7 1 number of fragmented free bytes
  50099. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  50100. **
  50101. ** The flags define the format of this btree page. The leaf flag means that
  50102. ** this page has no children. The zerodata flag means that this page carries
  50103. ** only keys and no data. The intkey flag means that the key is an integer
  50104. ** which is stored in the key size entry of the cell header rather than in
  50105. ** the payload area.
  50106. **
  50107. ** The cell pointer array begins on the first byte after the page header.
  50108. ** The cell pointer array contains zero or more 2-byte numbers which are
  50109. ** offsets from the beginning of the page to the cell content in the cell
  50110. ** content area. The cell pointers occur in sorted order. The system strives
  50111. ** to keep free space after the last cell pointer so that new cells can
  50112. ** be easily added without having to defragment the page.
  50113. **
  50114. ** Cell content is stored at the very end of the page and grows toward the
  50115. ** beginning of the page.
  50116. **
  50117. ** Unused space within the cell content area is collected into a linked list of
  50118. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  50119. ** to the first freeblock is given in the header. Freeblocks occur in
  50120. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  50121. ** any group of 3 or fewer unused bytes in the cell content area cannot
  50122. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  50123. ** a fragment. The total number of bytes in all fragments is recorded.
  50124. ** in the page header at offset 7.
  50125. **
  50126. ** SIZE DESCRIPTION
  50127. ** 2 Byte offset of the next freeblock
  50128. ** 2 Bytes in this freeblock
  50129. **
  50130. ** Cells are of variable length. Cells are stored in the cell content area at
  50131. ** the end of the page. Pointers to the cells are in the cell pointer array
  50132. ** that immediately follows the page header. Cells is not necessarily
  50133. ** contiguous or in order, but cell pointers are contiguous and in order.
  50134. **
  50135. ** Cell content makes use of variable length integers. A variable
  50136. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  50137. ** byte are used. The integer consists of all bytes that have bit 8 set and
  50138. ** the first byte with bit 8 clear. The most significant byte of the integer
  50139. ** appears first. A variable-length integer may not be more than 9 bytes long.
  50140. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  50141. ** allows a 64-bit integer to be encoded in 9 bytes.
  50142. **
  50143. ** 0x00 becomes 0x00000000
  50144. ** 0x7f becomes 0x0000007f
  50145. ** 0x81 0x00 becomes 0x00000080
  50146. ** 0x82 0x00 becomes 0x00000100
  50147. ** 0x80 0x7f becomes 0x0000007f
  50148. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  50149. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  50150. **
  50151. ** Variable length integers are used for rowids and to hold the number of
  50152. ** bytes of key and data in a btree cell.
  50153. **
  50154. ** The content of a cell looks like this:
  50155. **
  50156. ** SIZE DESCRIPTION
  50157. ** 4 Page number of the left child. Omitted if leaf flag is set.
  50158. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  50159. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  50160. ** * Payload
  50161. ** 4 First page of the overflow chain. Omitted if no overflow
  50162. **
  50163. ** Overflow pages form a linked list. Each page except the last is completely
  50164. ** filled with data (pagesize - 4 bytes). The last page can have as little
  50165. ** as 1 byte of data.
  50166. **
  50167. ** SIZE DESCRIPTION
  50168. ** 4 Page number of next overflow page
  50169. ** * Data
  50170. **
  50171. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  50172. ** file header points to the first in a linked list of trunk page. Each trunk
  50173. ** page points to multiple leaf pages. The content of a leaf page is
  50174. ** unspecified. A trunk page looks like this:
  50175. **
  50176. ** SIZE DESCRIPTION
  50177. ** 4 Page number of next trunk page
  50178. ** 4 Number of leaf pointers on this page
  50179. ** * zero or more pages numbers of leaves
  50180. */
  50181. /* #include "sqliteInt.h" */
  50182. /* The following value is the maximum cell size assuming a maximum page
  50183. ** size give above.
  50184. */
  50185. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  50186. /* The maximum number of cells on a single page of the database. This
  50187. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  50188. ** plus 2 bytes for the index to the cell in the page header). Such
  50189. ** small cells will be rare, but they are possible.
  50190. */
  50191. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  50192. /* Forward declarations */
  50193. typedef struct MemPage MemPage;
  50194. typedef struct BtLock BtLock;
  50195. typedef struct CellInfo CellInfo;
  50196. /*
  50197. ** This is a magic string that appears at the beginning of every
  50198. ** SQLite database in order to identify the file as a real database.
  50199. **
  50200. ** You can change this value at compile-time by specifying a
  50201. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  50202. ** header must be exactly 16 bytes including the zero-terminator so
  50203. ** the string itself should be 15 characters long. If you change
  50204. ** the header, then your custom library will not be able to read
  50205. ** databases generated by the standard tools and the standard tools
  50206. ** will not be able to read databases created by your custom library.
  50207. */
  50208. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  50209. # define SQLITE_FILE_HEADER "SQLite format 3"
  50210. #endif
  50211. /*
  50212. ** Page type flags. An ORed combination of these flags appear as the
  50213. ** first byte of on-disk image of every BTree page.
  50214. */
  50215. #define PTF_INTKEY 0x01
  50216. #define PTF_ZERODATA 0x02
  50217. #define PTF_LEAFDATA 0x04
  50218. #define PTF_LEAF 0x08
  50219. /*
  50220. ** As each page of the file is loaded into memory, an instance of the following
  50221. ** structure is appended and initialized to zero. This structure stores
  50222. ** information about the page that is decoded from the raw file page.
  50223. **
  50224. ** The pParent field points back to the parent page. This allows us to
  50225. ** walk up the BTree from any leaf to the root. Care must be taken to
  50226. ** unref() the parent page pointer when this page is no longer referenced.
  50227. ** The pageDestructor() routine handles that chore.
  50228. **
  50229. ** Access to all fields of this structure is controlled by the mutex
  50230. ** stored in MemPage.pBt->mutex.
  50231. */
  50232. struct MemPage {
  50233. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  50234. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  50235. u8 intKey; /* True if table b-trees. False for index b-trees */
  50236. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  50237. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  50238. u8 leaf; /* True if a leaf page */
  50239. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  50240. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  50241. u8 max1bytePayload; /* min(maxLocal,127) */
  50242. u8 bBusy; /* Prevent endless loops on corrupt database files */
  50243. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  50244. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  50245. u16 cellOffset; /* Index in aData of first cell pointer */
  50246. u16 nFree; /* Number of free bytes on the page */
  50247. u16 nCell; /* Number of cells on this page, local and ovfl */
  50248. u16 maskPage; /* Mask for page offset */
  50249. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  50250. ** non-overflow cell */
  50251. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  50252. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  50253. u8 *aData; /* Pointer to disk image of the page data */
  50254. u8 *aDataEnd; /* One byte past the end of usable data */
  50255. u8 *aCellIdx; /* The cell index area */
  50256. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  50257. DbPage *pDbPage; /* Pager page handle */
  50258. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  50259. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  50260. Pgno pgno; /* Page number for this page */
  50261. };
  50262. /*
  50263. ** The in-memory image of a disk page has the auxiliary information appended
  50264. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  50265. ** that extra information.
  50266. */
  50267. #define EXTRA_SIZE sizeof(MemPage)
  50268. /*
  50269. ** A linked list of the following structures is stored at BtShared.pLock.
  50270. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  50271. ** is opened on the table with root page BtShared.iTable. Locks are removed
  50272. ** from this list when a transaction is committed or rolled back, or when
  50273. ** a btree handle is closed.
  50274. */
  50275. struct BtLock {
  50276. Btree *pBtree; /* Btree handle holding this lock */
  50277. Pgno iTable; /* Root page of table */
  50278. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  50279. BtLock *pNext; /* Next in BtShared.pLock list */
  50280. };
  50281. /* Candidate values for BtLock.eLock */
  50282. #define READ_LOCK 1
  50283. #define WRITE_LOCK 2
  50284. /* A Btree handle
  50285. **
  50286. ** A database connection contains a pointer to an instance of
  50287. ** this object for every database file that it has open. This structure
  50288. ** is opaque to the database connection. The database connection cannot
  50289. ** see the internals of this structure and only deals with pointers to
  50290. ** this structure.
  50291. **
  50292. ** For some database files, the same underlying database cache might be
  50293. ** shared between multiple connections. In that case, each connection
  50294. ** has it own instance of this object. But each instance of this object
  50295. ** points to the same BtShared object. The database cache and the
  50296. ** schema associated with the database file are all contained within
  50297. ** the BtShared object.
  50298. **
  50299. ** All fields in this structure are accessed under sqlite3.mutex.
  50300. ** The pBt pointer itself may not be changed while there exists cursors
  50301. ** in the referenced BtShared that point back to this Btree since those
  50302. ** cursors have to go through this Btree to find their BtShared and
  50303. ** they often do so without holding sqlite3.mutex.
  50304. */
  50305. struct Btree {
  50306. sqlite3 *db; /* The database connection holding this btree */
  50307. BtShared *pBt; /* Sharable content of this btree */
  50308. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  50309. u8 sharable; /* True if we can share pBt with another db */
  50310. u8 locked; /* True if db currently has pBt locked */
  50311. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  50312. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  50313. int nBackup; /* Number of backup operations reading this btree */
  50314. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  50315. Btree *pNext; /* List of other sharable Btrees from the same db */
  50316. Btree *pPrev; /* Back pointer of the same list */
  50317. #ifndef SQLITE_OMIT_SHARED_CACHE
  50318. BtLock lock; /* Object used to lock page 1 */
  50319. #endif
  50320. };
  50321. /*
  50322. ** Btree.inTrans may take one of the following values.
  50323. **
  50324. ** If the shared-data extension is enabled, there may be multiple users
  50325. ** of the Btree structure. At most one of these may open a write transaction,
  50326. ** but any number may have active read transactions.
  50327. */
  50328. #define TRANS_NONE 0
  50329. #define TRANS_READ 1
  50330. #define TRANS_WRITE 2
  50331. /*
  50332. ** An instance of this object represents a single database file.
  50333. **
  50334. ** A single database file can be in use at the same time by two
  50335. ** or more database connections. When two or more connections are
  50336. ** sharing the same database file, each connection has it own
  50337. ** private Btree object for the file and each of those Btrees points
  50338. ** to this one BtShared object. BtShared.nRef is the number of
  50339. ** connections currently sharing this database file.
  50340. **
  50341. ** Fields in this structure are accessed under the BtShared.mutex
  50342. ** mutex, except for nRef and pNext which are accessed under the
  50343. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  50344. ** may not be modified once it is initially set as long as nRef>0.
  50345. ** The pSchema field may be set once under BtShared.mutex and
  50346. ** thereafter is unchanged as long as nRef>0.
  50347. **
  50348. ** isPending:
  50349. **
  50350. ** If a BtShared client fails to obtain a write-lock on a database
  50351. ** table (because there exists one or more read-locks on the table),
  50352. ** the shared-cache enters 'pending-lock' state and isPending is
  50353. ** set to true.
  50354. **
  50355. ** The shared-cache leaves the 'pending lock' state when either of
  50356. ** the following occur:
  50357. **
  50358. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  50359. ** 2) The number of locks held by other connections drops to zero.
  50360. **
  50361. ** while in the 'pending-lock' state, no connection may start a new
  50362. ** transaction.
  50363. **
  50364. ** This feature is included to help prevent writer-starvation.
  50365. */
  50366. struct BtShared {
  50367. Pager *pPager; /* The page cache */
  50368. sqlite3 *db; /* Database connection currently using this Btree */
  50369. BtCursor *pCursor; /* A list of all open cursors */
  50370. MemPage *pPage1; /* First page of the database */
  50371. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  50372. #ifndef SQLITE_OMIT_AUTOVACUUM
  50373. u8 autoVacuum; /* True if auto-vacuum is enabled */
  50374. u8 incrVacuum; /* True if incr-vacuum is enabled */
  50375. u8 bDoTruncate; /* True to truncate db on commit */
  50376. #endif
  50377. u8 inTransaction; /* Transaction state */
  50378. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  50379. #ifdef SQLITE_HAS_CODEC
  50380. u8 optimalReserve; /* Desired amount of reserved space per page */
  50381. #endif
  50382. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  50383. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  50384. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  50385. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  50386. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  50387. u32 pageSize; /* Total number of bytes on a page */
  50388. u32 usableSize; /* Number of usable bytes on each page */
  50389. int nTransaction; /* Number of open transactions (read + write) */
  50390. u32 nPage; /* Number of pages in the database */
  50391. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  50392. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  50393. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  50394. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  50395. #ifndef SQLITE_OMIT_SHARED_CACHE
  50396. int nRef; /* Number of references to this structure */
  50397. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  50398. BtLock *pLock; /* List of locks held on this shared-btree struct */
  50399. Btree *pWriter; /* Btree with currently open write transaction */
  50400. #endif
  50401. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  50402. };
  50403. /*
  50404. ** Allowed values for BtShared.btsFlags
  50405. */
  50406. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  50407. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  50408. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  50409. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  50410. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  50411. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  50412. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  50413. /*
  50414. ** An instance of the following structure is used to hold information
  50415. ** about a cell. The parseCellPtr() function fills in this structure
  50416. ** based on information extract from the raw disk page.
  50417. */
  50418. struct CellInfo {
  50419. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  50420. u8 *pPayload; /* Pointer to the start of payload */
  50421. u32 nPayload; /* Bytes of payload */
  50422. u16 nLocal; /* Amount of payload held locally, not on overflow */
  50423. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  50424. u16 nSize; /* Size of the cell content on the main b-tree page */
  50425. };
  50426. /*
  50427. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  50428. ** this will be declared corrupt. This value is calculated based on a
  50429. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  50430. ** root-node and 3 for all other internal nodes.
  50431. **
  50432. ** If a tree that appears to be taller than this is encountered, it is
  50433. ** assumed that the database is corrupt.
  50434. */
  50435. #define BTCURSOR_MAX_DEPTH 20
  50436. /*
  50437. ** A cursor is a pointer to a particular entry within a particular
  50438. ** b-tree within a database file.
  50439. **
  50440. ** The entry is identified by its MemPage and the index in
  50441. ** MemPage.aCell[] of the entry.
  50442. **
  50443. ** A single database file can be shared by two more database connections,
  50444. ** but cursors cannot be shared. Each cursor is associated with a
  50445. ** particular database connection identified BtCursor.pBtree.db.
  50446. **
  50447. ** Fields in this structure are accessed under the BtShared.mutex
  50448. ** found at self->pBt->mutex.
  50449. **
  50450. ** skipNext meaning:
  50451. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  50452. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  50453. ** eState==FAULT: Cursor fault with skipNext as error code.
  50454. */
  50455. struct BtCursor {
  50456. Btree *pBtree; /* The Btree to which this cursor belongs */
  50457. BtShared *pBt; /* The BtShared this cursor points to */
  50458. BtCursor *pNext; /* Forms a linked list of all cursors */
  50459. Pgno *aOverflow; /* Cache of overflow page locations */
  50460. CellInfo info; /* A parse of the cell we are pointing at */
  50461. i64 nKey; /* Size of pKey, or last integer key */
  50462. void *pKey; /* Saved key that was cursor last known position */
  50463. Pgno pgnoRoot; /* The root page of this tree */
  50464. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  50465. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  50466. ** Error code if eState==CURSOR_FAULT */
  50467. u8 curFlags; /* zero or more BTCF_* flags defined below */
  50468. u8 curPagerFlags; /* Flags to send to sqlite3PagerAcquire() */
  50469. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  50470. u8 hints; /* As configured by CursorSetHints() */
  50471. /* All fields above are zeroed when the cursor is allocated. See
  50472. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  50473. ** initialized. */
  50474. i8 iPage; /* Index of current page in apPage */
  50475. u8 curIntKey; /* Value of apPage[0]->intKey */
  50476. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  50477. void *padding1; /* Make object size a multiple of 16 */
  50478. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  50479. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  50480. };
  50481. /*
  50482. ** Legal values for BtCursor.curFlags
  50483. */
  50484. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  50485. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  50486. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  50487. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  50488. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  50489. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  50490. /*
  50491. ** Potential values for BtCursor.eState.
  50492. **
  50493. ** CURSOR_INVALID:
  50494. ** Cursor does not point to a valid entry. This can happen (for example)
  50495. ** because the table is empty or because BtreeCursorFirst() has not been
  50496. ** called.
  50497. **
  50498. ** CURSOR_VALID:
  50499. ** Cursor points to a valid entry. getPayload() etc. may be called.
  50500. **
  50501. ** CURSOR_SKIPNEXT:
  50502. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  50503. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  50504. ** operation should be a no-op.
  50505. **
  50506. ** CURSOR_REQUIRESEEK:
  50507. ** The table that this cursor was opened on still exists, but has been
  50508. ** modified since the cursor was last used. The cursor position is saved
  50509. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  50510. ** this state, restoreCursorPosition() can be called to attempt to
  50511. ** seek the cursor to the saved position.
  50512. **
  50513. ** CURSOR_FAULT:
  50514. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  50515. ** on a different connection that shares the BtShared cache with this
  50516. ** cursor. The error has left the cache in an inconsistent state.
  50517. ** Do nothing else with this cursor. Any attempt to use the cursor
  50518. ** should return the error code stored in BtCursor.skipNext
  50519. */
  50520. #define CURSOR_INVALID 0
  50521. #define CURSOR_VALID 1
  50522. #define CURSOR_SKIPNEXT 2
  50523. #define CURSOR_REQUIRESEEK 3
  50524. #define CURSOR_FAULT 4
  50525. /*
  50526. ** The database page the PENDING_BYTE occupies. This page is never used.
  50527. */
  50528. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  50529. /*
  50530. ** These macros define the location of the pointer-map entry for a
  50531. ** database page. The first argument to each is the number of usable
  50532. ** bytes on each page of the database (often 1024). The second is the
  50533. ** page number to look up in the pointer map.
  50534. **
  50535. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  50536. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  50537. ** the offset of the requested map entry.
  50538. **
  50539. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  50540. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  50541. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  50542. ** this test.
  50543. */
  50544. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  50545. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  50546. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  50547. /*
  50548. ** The pointer map is a lookup table that identifies the parent page for
  50549. ** each child page in the database file. The parent page is the page that
  50550. ** contains a pointer to the child. Every page in the database contains
  50551. ** 0 or 1 parent pages. (In this context 'database page' refers
  50552. ** to any page that is not part of the pointer map itself.) Each pointer map
  50553. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  50554. ** The PTRMAP_XXX identifiers below are the valid types.
  50555. **
  50556. ** The purpose of the pointer map is to facility moving pages from one
  50557. ** position in the file to another as part of autovacuum. When a page
  50558. ** is moved, the pointer in its parent must be updated to point to the
  50559. ** new location. The pointer map is used to locate the parent page quickly.
  50560. **
  50561. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  50562. ** used in this case.
  50563. **
  50564. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  50565. ** is not used in this case.
  50566. **
  50567. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  50568. ** overflow pages. The page number identifies the page that
  50569. ** contains the cell with a pointer to this overflow page.
  50570. **
  50571. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  50572. ** overflow pages. The page-number identifies the previous
  50573. ** page in the overflow page list.
  50574. **
  50575. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  50576. ** identifies the parent page in the btree.
  50577. */
  50578. #define PTRMAP_ROOTPAGE 1
  50579. #define PTRMAP_FREEPAGE 2
  50580. #define PTRMAP_OVERFLOW1 3
  50581. #define PTRMAP_OVERFLOW2 4
  50582. #define PTRMAP_BTREE 5
  50583. /* A bunch of assert() statements to check the transaction state variables
  50584. ** of handle p (type Btree*) are internally consistent.
  50585. */
  50586. #define btreeIntegrity(p) \
  50587. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  50588. assert( p->pBt->inTransaction>=p->inTrans );
  50589. /*
  50590. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  50591. ** if the database supports auto-vacuum or not. Because it is used
  50592. ** within an expression that is an argument to another macro
  50593. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  50594. ** So, this macro is defined instead.
  50595. */
  50596. #ifndef SQLITE_OMIT_AUTOVACUUM
  50597. #define ISAUTOVACUUM (pBt->autoVacuum)
  50598. #else
  50599. #define ISAUTOVACUUM 0
  50600. #endif
  50601. /*
  50602. ** This structure is passed around through all the sanity checking routines
  50603. ** in order to keep track of some global state information.
  50604. **
  50605. ** The aRef[] array is allocated so that there is 1 bit for each page in
  50606. ** the database. As the integrity-check proceeds, for each page used in
  50607. ** the database the corresponding bit is set. This allows integrity-check to
  50608. ** detect pages that are used twice and orphaned pages (both of which
  50609. ** indicate corruption).
  50610. */
  50611. typedef struct IntegrityCk IntegrityCk;
  50612. struct IntegrityCk {
  50613. BtShared *pBt; /* The tree being checked out */
  50614. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  50615. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  50616. Pgno nPage; /* Number of pages in the database */
  50617. int mxErr; /* Stop accumulating errors when this reaches zero */
  50618. int nErr; /* Number of messages written to zErrMsg so far */
  50619. int mallocFailed; /* A memory allocation error has occurred */
  50620. const char *zPfx; /* Error message prefix */
  50621. int v1, v2; /* Values for up to two %d fields in zPfx */
  50622. StrAccum errMsg; /* Accumulate the error message text here */
  50623. u32 *heap; /* Min-heap used for analyzing cell coverage */
  50624. };
  50625. /*
  50626. ** Routines to read or write a two- and four-byte big-endian integer values.
  50627. */
  50628. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  50629. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  50630. #define get4byte sqlite3Get4byte
  50631. #define put4byte sqlite3Put4byte
  50632. /*
  50633. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  50634. ** two-byte aligned address. get2bytea() is only used for accessing the
  50635. ** cell addresses in a btree header.
  50636. */
  50637. #if SQLITE_BYTEORDER==4321
  50638. # define get2byteAligned(x) (*(u16*)(x))
  50639. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  50640. && GCC_VERSION>=4008000
  50641. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  50642. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  50643. && defined(_MSC_VER) && _MSC_VER>=1300
  50644. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  50645. #else
  50646. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  50647. #endif
  50648. /************** End of btreeInt.h ********************************************/
  50649. /************** Continuing where we left off in btmutex.c ********************/
  50650. #ifndef SQLITE_OMIT_SHARED_CACHE
  50651. #if SQLITE_THREADSAFE
  50652. /*
  50653. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  50654. ** set BtShared.db to the database handle associated with p and the
  50655. ** p->locked boolean to true.
  50656. */
  50657. static void lockBtreeMutex(Btree *p){
  50658. assert( p->locked==0 );
  50659. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  50660. assert( sqlite3_mutex_held(p->db->mutex) );
  50661. sqlite3_mutex_enter(p->pBt->mutex);
  50662. p->pBt->db = p->db;
  50663. p->locked = 1;
  50664. }
  50665. /*
  50666. ** Release the BtShared mutex associated with B-Tree handle p and
  50667. ** clear the p->locked boolean.
  50668. */
  50669. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  50670. BtShared *pBt = p->pBt;
  50671. assert( p->locked==1 );
  50672. assert( sqlite3_mutex_held(pBt->mutex) );
  50673. assert( sqlite3_mutex_held(p->db->mutex) );
  50674. assert( p->db==pBt->db );
  50675. sqlite3_mutex_leave(pBt->mutex);
  50676. p->locked = 0;
  50677. }
  50678. /* Forward reference */
  50679. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  50680. /*
  50681. ** Enter a mutex on the given BTree object.
  50682. **
  50683. ** If the object is not sharable, then no mutex is ever required
  50684. ** and this routine is a no-op. The underlying mutex is non-recursive.
  50685. ** But we keep a reference count in Btree.wantToLock so the behavior
  50686. ** of this interface is recursive.
  50687. **
  50688. ** To avoid deadlocks, multiple Btrees are locked in the same order
  50689. ** by all database connections. The p->pNext is a list of other
  50690. ** Btrees belonging to the same database connection as the p Btree
  50691. ** which need to be locked after p. If we cannot get a lock on
  50692. ** p, then first unlock all of the others on p->pNext, then wait
  50693. ** for the lock to become available on p, then relock all of the
  50694. ** subsequent Btrees that desire a lock.
  50695. */
  50696. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  50697. /* Some basic sanity checking on the Btree. The list of Btrees
  50698. ** connected by pNext and pPrev should be in sorted order by
  50699. ** Btree.pBt value. All elements of the list should belong to
  50700. ** the same connection. Only shared Btrees are on the list. */
  50701. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  50702. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  50703. assert( p->pNext==0 || p->pNext->db==p->db );
  50704. assert( p->pPrev==0 || p->pPrev->db==p->db );
  50705. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  50706. /* Check for locking consistency */
  50707. assert( !p->locked || p->wantToLock>0 );
  50708. assert( p->sharable || p->wantToLock==0 );
  50709. /* We should already hold a lock on the database connection */
  50710. assert( sqlite3_mutex_held(p->db->mutex) );
  50711. /* Unless the database is sharable and unlocked, then BtShared.db
  50712. ** should already be set correctly. */
  50713. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  50714. if( !p->sharable ) return;
  50715. p->wantToLock++;
  50716. if( p->locked ) return;
  50717. btreeLockCarefully(p);
  50718. }
  50719. /* This is a helper function for sqlite3BtreeLock(). By moving
  50720. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  50721. ** into this routine, we avoid unnecessary stack pointer changes
  50722. ** and thus help the sqlite3BtreeLock() routine to run much faster
  50723. ** in the common case.
  50724. */
  50725. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  50726. Btree *pLater;
  50727. /* In most cases, we should be able to acquire the lock we
  50728. ** want without having to go through the ascending lock
  50729. ** procedure that follows. Just be sure not to block.
  50730. */
  50731. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  50732. p->pBt->db = p->db;
  50733. p->locked = 1;
  50734. return;
  50735. }
  50736. /* To avoid deadlock, first release all locks with a larger
  50737. ** BtShared address. Then acquire our lock. Then reacquire
  50738. ** the other BtShared locks that we used to hold in ascending
  50739. ** order.
  50740. */
  50741. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  50742. assert( pLater->sharable );
  50743. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  50744. assert( !pLater->locked || pLater->wantToLock>0 );
  50745. if( pLater->locked ){
  50746. unlockBtreeMutex(pLater);
  50747. }
  50748. }
  50749. lockBtreeMutex(p);
  50750. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  50751. if( pLater->wantToLock ){
  50752. lockBtreeMutex(pLater);
  50753. }
  50754. }
  50755. }
  50756. /*
  50757. ** Exit the recursive mutex on a Btree.
  50758. */
  50759. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  50760. assert( sqlite3_mutex_held(p->db->mutex) );
  50761. if( p->sharable ){
  50762. assert( p->wantToLock>0 );
  50763. p->wantToLock--;
  50764. if( p->wantToLock==0 ){
  50765. unlockBtreeMutex(p);
  50766. }
  50767. }
  50768. }
  50769. #ifndef NDEBUG
  50770. /*
  50771. ** Return true if the BtShared mutex is held on the btree, or if the
  50772. ** B-Tree is not marked as sharable.
  50773. **
  50774. ** This routine is used only from within assert() statements.
  50775. */
  50776. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  50777. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  50778. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  50779. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  50780. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  50781. return (p->sharable==0 || p->locked);
  50782. }
  50783. #endif
  50784. #ifndef SQLITE_OMIT_INCRBLOB
  50785. /*
  50786. ** Enter and leave a mutex on a Btree given a cursor owned by that
  50787. ** Btree. These entry points are used by incremental I/O and can be
  50788. ** omitted if that module is not used.
  50789. */
  50790. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  50791. sqlite3BtreeEnter(pCur->pBtree);
  50792. }
  50793. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  50794. sqlite3BtreeLeave(pCur->pBtree);
  50795. }
  50796. #endif /* SQLITE_OMIT_INCRBLOB */
  50797. /*
  50798. ** Enter the mutex on every Btree associated with a database
  50799. ** connection. This is needed (for example) prior to parsing
  50800. ** a statement since we will be comparing table and column names
  50801. ** against all schemas and we do not want those schemas being
  50802. ** reset out from under us.
  50803. **
  50804. ** There is a corresponding leave-all procedures.
  50805. **
  50806. ** Enter the mutexes in accending order by BtShared pointer address
  50807. ** to avoid the possibility of deadlock when two threads with
  50808. ** two or more btrees in common both try to lock all their btrees
  50809. ** at the same instant.
  50810. */
  50811. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  50812. int i;
  50813. Btree *p;
  50814. assert( sqlite3_mutex_held(db->mutex) );
  50815. for(i=0; i<db->nDb; i++){
  50816. p = db->aDb[i].pBt;
  50817. if( p ) sqlite3BtreeEnter(p);
  50818. }
  50819. }
  50820. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  50821. int i;
  50822. Btree *p;
  50823. assert( sqlite3_mutex_held(db->mutex) );
  50824. for(i=0; i<db->nDb; i++){
  50825. p = db->aDb[i].pBt;
  50826. if( p ) sqlite3BtreeLeave(p);
  50827. }
  50828. }
  50829. /*
  50830. ** Return true if a particular Btree requires a lock. Return FALSE if
  50831. ** no lock is ever required since it is not sharable.
  50832. */
  50833. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  50834. return p->sharable;
  50835. }
  50836. #ifndef NDEBUG
  50837. /*
  50838. ** Return true if the current thread holds the database connection
  50839. ** mutex and all required BtShared mutexes.
  50840. **
  50841. ** This routine is used inside assert() statements only.
  50842. */
  50843. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  50844. int i;
  50845. if( !sqlite3_mutex_held(db->mutex) ){
  50846. return 0;
  50847. }
  50848. for(i=0; i<db->nDb; i++){
  50849. Btree *p;
  50850. p = db->aDb[i].pBt;
  50851. if( p && p->sharable &&
  50852. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  50853. return 0;
  50854. }
  50855. }
  50856. return 1;
  50857. }
  50858. #endif /* NDEBUG */
  50859. #ifndef NDEBUG
  50860. /*
  50861. ** Return true if the correct mutexes are held for accessing the
  50862. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  50863. ** access are:
  50864. **
  50865. ** (1) The mutex on db
  50866. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  50867. **
  50868. ** If pSchema is not NULL, then iDb is computed from pSchema and
  50869. ** db using sqlite3SchemaToIndex().
  50870. */
  50871. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  50872. Btree *p;
  50873. assert( db!=0 );
  50874. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  50875. assert( iDb>=0 && iDb<db->nDb );
  50876. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  50877. if( iDb==1 ) return 1;
  50878. p = db->aDb[iDb].pBt;
  50879. assert( p!=0 );
  50880. return p->sharable==0 || p->locked==1;
  50881. }
  50882. #endif /* NDEBUG */
  50883. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  50884. /*
  50885. ** The following are special cases for mutex enter routines for use
  50886. ** in single threaded applications that use shared cache. Except for
  50887. ** these two routines, all mutex operations are no-ops in that case and
  50888. ** are null #defines in btree.h.
  50889. **
  50890. ** If shared cache is disabled, then all btree mutex routines, including
  50891. ** the ones below, are no-ops and are null #defines in btree.h.
  50892. */
  50893. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  50894. p->pBt->db = p->db;
  50895. }
  50896. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  50897. int i;
  50898. for(i=0; i<db->nDb; i++){
  50899. Btree *p = db->aDb[i].pBt;
  50900. if( p ){
  50901. p->pBt->db = p->db;
  50902. }
  50903. }
  50904. }
  50905. #endif /* if SQLITE_THREADSAFE */
  50906. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  50907. /************** End of btmutex.c *********************************************/
  50908. /************** Begin file btree.c *******************************************/
  50909. /*
  50910. ** 2004 April 6
  50911. **
  50912. ** The author disclaims copyright to this source code. In place of
  50913. ** a legal notice, here is a blessing:
  50914. **
  50915. ** May you do good and not evil.
  50916. ** May you find forgiveness for yourself and forgive others.
  50917. ** May you share freely, never taking more than you give.
  50918. **
  50919. *************************************************************************
  50920. ** This file implements an external (disk-based) database using BTrees.
  50921. ** See the header comment on "btreeInt.h" for additional information.
  50922. ** Including a description of file format and an overview of operation.
  50923. */
  50924. /* #include "btreeInt.h" */
  50925. /*
  50926. ** The header string that appears at the beginning of every
  50927. ** SQLite database.
  50928. */
  50929. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  50930. /*
  50931. ** Set this global variable to 1 to enable tracing using the TRACE
  50932. ** macro.
  50933. */
  50934. #if 0
  50935. int sqlite3BtreeTrace=1; /* True to enable tracing */
  50936. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  50937. #else
  50938. # define TRACE(X)
  50939. #endif
  50940. /*
  50941. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  50942. ** But if the value is zero, make it 65536.
  50943. **
  50944. ** This routine is used to extract the "offset to cell content area" value
  50945. ** from the header of a btree page. If the page size is 65536 and the page
  50946. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  50947. ** This routine makes the necessary adjustment to 65536.
  50948. */
  50949. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  50950. /*
  50951. ** Values passed as the 5th argument to allocateBtreePage()
  50952. */
  50953. #define BTALLOC_ANY 0 /* Allocate any page */
  50954. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  50955. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  50956. /*
  50957. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  50958. ** defined, or 0 if it is. For example:
  50959. **
  50960. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  50961. */
  50962. #ifndef SQLITE_OMIT_AUTOVACUUM
  50963. #define IfNotOmitAV(expr) (expr)
  50964. #else
  50965. #define IfNotOmitAV(expr) 0
  50966. #endif
  50967. #ifndef SQLITE_OMIT_SHARED_CACHE
  50968. /*
  50969. ** A list of BtShared objects that are eligible for participation
  50970. ** in shared cache. This variable has file scope during normal builds,
  50971. ** but the test harness needs to access it so we make it global for
  50972. ** test builds.
  50973. **
  50974. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  50975. */
  50976. #ifdef SQLITE_TEST
  50977. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  50978. #else
  50979. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  50980. #endif
  50981. #endif /* SQLITE_OMIT_SHARED_CACHE */
  50982. #ifndef SQLITE_OMIT_SHARED_CACHE
  50983. /*
  50984. ** Enable or disable the shared pager and schema features.
  50985. **
  50986. ** This routine has no effect on existing database connections.
  50987. ** The shared cache setting effects only future calls to
  50988. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  50989. */
  50990. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
  50991. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  50992. return SQLITE_OK;
  50993. }
  50994. #endif
  50995. #ifdef SQLITE_OMIT_SHARED_CACHE
  50996. /*
  50997. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  50998. ** and clearAllSharedCacheTableLocks()
  50999. ** manipulate entries in the BtShared.pLock linked list used to store
  51000. ** shared-cache table level locks. If the library is compiled with the
  51001. ** shared-cache feature disabled, then there is only ever one user
  51002. ** of each BtShared structure and so this locking is not necessary.
  51003. ** So define the lock related functions as no-ops.
  51004. */
  51005. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  51006. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  51007. #define clearAllSharedCacheTableLocks(a)
  51008. #define downgradeAllSharedCacheTableLocks(a)
  51009. #define hasSharedCacheTableLock(a,b,c,d) 1
  51010. #define hasReadConflicts(a, b) 0
  51011. #endif
  51012. #ifndef SQLITE_OMIT_SHARED_CACHE
  51013. #ifdef SQLITE_DEBUG
  51014. /*
  51015. **** This function is only used as part of an assert() statement. ***
  51016. **
  51017. ** Check to see if pBtree holds the required locks to read or write to the
  51018. ** table with root page iRoot. Return 1 if it does and 0 if not.
  51019. **
  51020. ** For example, when writing to a table with root-page iRoot via
  51021. ** Btree connection pBtree:
  51022. **
  51023. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  51024. **
  51025. ** When writing to an index that resides in a sharable database, the
  51026. ** caller should have first obtained a lock specifying the root page of
  51027. ** the corresponding table. This makes things a bit more complicated,
  51028. ** as this module treats each table as a separate structure. To determine
  51029. ** the table corresponding to the index being written, this
  51030. ** function has to search through the database schema.
  51031. **
  51032. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  51033. ** hold a write-lock on the schema table (root page 1). This is also
  51034. ** acceptable.
  51035. */
  51036. static int hasSharedCacheTableLock(
  51037. Btree *pBtree, /* Handle that must hold lock */
  51038. Pgno iRoot, /* Root page of b-tree */
  51039. int isIndex, /* True if iRoot is the root of an index b-tree */
  51040. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  51041. ){
  51042. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  51043. Pgno iTab = 0;
  51044. BtLock *pLock;
  51045. /* If this database is not shareable, or if the client is reading
  51046. ** and has the read-uncommitted flag set, then no lock is required.
  51047. ** Return true immediately.
  51048. */
  51049. if( (pBtree->sharable==0)
  51050. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  51051. ){
  51052. return 1;
  51053. }
  51054. /* If the client is reading or writing an index and the schema is
  51055. ** not loaded, then it is too difficult to actually check to see if
  51056. ** the correct locks are held. So do not bother - just return true.
  51057. ** This case does not come up very often anyhow.
  51058. */
  51059. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  51060. return 1;
  51061. }
  51062. /* Figure out the root-page that the lock should be held on. For table
  51063. ** b-trees, this is just the root page of the b-tree being read or
  51064. ** written. For index b-trees, it is the root page of the associated
  51065. ** table. */
  51066. if( isIndex ){
  51067. HashElem *p;
  51068. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  51069. Index *pIdx = (Index *)sqliteHashData(p);
  51070. if( pIdx->tnum==(int)iRoot ){
  51071. if( iTab ){
  51072. /* Two or more indexes share the same root page. There must
  51073. ** be imposter tables. So just return true. The assert is not
  51074. ** useful in that case. */
  51075. return 1;
  51076. }
  51077. iTab = pIdx->pTable->tnum;
  51078. }
  51079. }
  51080. }else{
  51081. iTab = iRoot;
  51082. }
  51083. /* Search for the required lock. Either a write-lock on root-page iTab, a
  51084. ** write-lock on the schema table, or (if the client is reading) a
  51085. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  51086. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  51087. if( pLock->pBtree==pBtree
  51088. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  51089. && pLock->eLock>=eLockType
  51090. ){
  51091. return 1;
  51092. }
  51093. }
  51094. /* Failed to find the required lock. */
  51095. return 0;
  51096. }
  51097. #endif /* SQLITE_DEBUG */
  51098. #ifdef SQLITE_DEBUG
  51099. /*
  51100. **** This function may be used as part of assert() statements only. ****
  51101. **
  51102. ** Return true if it would be illegal for pBtree to write into the
  51103. ** table or index rooted at iRoot because other shared connections are
  51104. ** simultaneously reading that same table or index.
  51105. **
  51106. ** It is illegal for pBtree to write if some other Btree object that
  51107. ** shares the same BtShared object is currently reading or writing
  51108. ** the iRoot table. Except, if the other Btree object has the
  51109. ** read-uncommitted flag set, then it is OK for the other object to
  51110. ** have a read cursor.
  51111. **
  51112. ** For example, before writing to any part of the table or index
  51113. ** rooted at page iRoot, one should call:
  51114. **
  51115. ** assert( !hasReadConflicts(pBtree, iRoot) );
  51116. */
  51117. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  51118. BtCursor *p;
  51119. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  51120. if( p->pgnoRoot==iRoot
  51121. && p->pBtree!=pBtree
  51122. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  51123. ){
  51124. return 1;
  51125. }
  51126. }
  51127. return 0;
  51128. }
  51129. #endif /* #ifdef SQLITE_DEBUG */
  51130. /*
  51131. ** Query to see if Btree handle p may obtain a lock of type eLock
  51132. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  51133. ** SQLITE_OK if the lock may be obtained (by calling
  51134. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  51135. */
  51136. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  51137. BtShared *pBt = p->pBt;
  51138. BtLock *pIter;
  51139. assert( sqlite3BtreeHoldsMutex(p) );
  51140. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  51141. assert( p->db!=0 );
  51142. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  51143. /* If requesting a write-lock, then the Btree must have an open write
  51144. ** transaction on this file. And, obviously, for this to be so there
  51145. ** must be an open write transaction on the file itself.
  51146. */
  51147. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  51148. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  51149. /* This routine is a no-op if the shared-cache is not enabled */
  51150. if( !p->sharable ){
  51151. return SQLITE_OK;
  51152. }
  51153. /* If some other connection is holding an exclusive lock, the
  51154. ** requested lock may not be obtained.
  51155. */
  51156. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  51157. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  51158. return SQLITE_LOCKED_SHAREDCACHE;
  51159. }
  51160. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51161. /* The condition (pIter->eLock!=eLock) in the following if(...)
  51162. ** statement is a simplification of:
  51163. **
  51164. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  51165. **
  51166. ** since we know that if eLock==WRITE_LOCK, then no other connection
  51167. ** may hold a WRITE_LOCK on any table in this file (since there can
  51168. ** only be a single writer).
  51169. */
  51170. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  51171. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  51172. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  51173. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  51174. if( eLock==WRITE_LOCK ){
  51175. assert( p==pBt->pWriter );
  51176. pBt->btsFlags |= BTS_PENDING;
  51177. }
  51178. return SQLITE_LOCKED_SHAREDCACHE;
  51179. }
  51180. }
  51181. return SQLITE_OK;
  51182. }
  51183. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  51184. #ifndef SQLITE_OMIT_SHARED_CACHE
  51185. /*
  51186. ** Add a lock on the table with root-page iTable to the shared-btree used
  51187. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  51188. ** WRITE_LOCK.
  51189. **
  51190. ** This function assumes the following:
  51191. **
  51192. ** (a) The specified Btree object p is connected to a sharable
  51193. ** database (one with the BtShared.sharable flag set), and
  51194. **
  51195. ** (b) No other Btree objects hold a lock that conflicts
  51196. ** with the requested lock (i.e. querySharedCacheTableLock() has
  51197. ** already been called and returned SQLITE_OK).
  51198. **
  51199. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  51200. ** is returned if a malloc attempt fails.
  51201. */
  51202. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  51203. BtShared *pBt = p->pBt;
  51204. BtLock *pLock = 0;
  51205. BtLock *pIter;
  51206. assert( sqlite3BtreeHoldsMutex(p) );
  51207. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  51208. assert( p->db!=0 );
  51209. /* A connection with the read-uncommitted flag set will never try to
  51210. ** obtain a read-lock using this function. The only read-lock obtained
  51211. ** by a connection in read-uncommitted mode is on the sqlite_master
  51212. ** table, and that lock is obtained in BtreeBeginTrans(). */
  51213. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  51214. /* This function should only be called on a sharable b-tree after it
  51215. ** has been determined that no other b-tree holds a conflicting lock. */
  51216. assert( p->sharable );
  51217. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  51218. /* First search the list for an existing lock on this table. */
  51219. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51220. if( pIter->iTable==iTable && pIter->pBtree==p ){
  51221. pLock = pIter;
  51222. break;
  51223. }
  51224. }
  51225. /* If the above search did not find a BtLock struct associating Btree p
  51226. ** with table iTable, allocate one and link it into the list.
  51227. */
  51228. if( !pLock ){
  51229. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  51230. if( !pLock ){
  51231. return SQLITE_NOMEM;
  51232. }
  51233. pLock->iTable = iTable;
  51234. pLock->pBtree = p;
  51235. pLock->pNext = pBt->pLock;
  51236. pBt->pLock = pLock;
  51237. }
  51238. /* Set the BtLock.eLock variable to the maximum of the current lock
  51239. ** and the requested lock. This means if a write-lock was already held
  51240. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  51241. */
  51242. assert( WRITE_LOCK>READ_LOCK );
  51243. if( eLock>pLock->eLock ){
  51244. pLock->eLock = eLock;
  51245. }
  51246. return SQLITE_OK;
  51247. }
  51248. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  51249. #ifndef SQLITE_OMIT_SHARED_CACHE
  51250. /*
  51251. ** Release all the table locks (locks obtained via calls to
  51252. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  51253. **
  51254. ** This function assumes that Btree p has an open read or write
  51255. ** transaction. If it does not, then the BTS_PENDING flag
  51256. ** may be incorrectly cleared.
  51257. */
  51258. static void clearAllSharedCacheTableLocks(Btree *p){
  51259. BtShared *pBt = p->pBt;
  51260. BtLock **ppIter = &pBt->pLock;
  51261. assert( sqlite3BtreeHoldsMutex(p) );
  51262. assert( p->sharable || 0==*ppIter );
  51263. assert( p->inTrans>0 );
  51264. while( *ppIter ){
  51265. BtLock *pLock = *ppIter;
  51266. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  51267. assert( pLock->pBtree->inTrans>=pLock->eLock );
  51268. if( pLock->pBtree==p ){
  51269. *ppIter = pLock->pNext;
  51270. assert( pLock->iTable!=1 || pLock==&p->lock );
  51271. if( pLock->iTable!=1 ){
  51272. sqlite3_free(pLock);
  51273. }
  51274. }else{
  51275. ppIter = &pLock->pNext;
  51276. }
  51277. }
  51278. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  51279. if( pBt->pWriter==p ){
  51280. pBt->pWriter = 0;
  51281. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  51282. }else if( pBt->nTransaction==2 ){
  51283. /* This function is called when Btree p is concluding its
  51284. ** transaction. If there currently exists a writer, and p is not
  51285. ** that writer, then the number of locks held by connections other
  51286. ** than the writer must be about to drop to zero. In this case
  51287. ** set the BTS_PENDING flag to 0.
  51288. **
  51289. ** If there is not currently a writer, then BTS_PENDING must
  51290. ** be zero already. So this next line is harmless in that case.
  51291. */
  51292. pBt->btsFlags &= ~BTS_PENDING;
  51293. }
  51294. }
  51295. /*
  51296. ** This function changes all write-locks held by Btree p into read-locks.
  51297. */
  51298. static void downgradeAllSharedCacheTableLocks(Btree *p){
  51299. BtShared *pBt = p->pBt;
  51300. if( pBt->pWriter==p ){
  51301. BtLock *pLock;
  51302. pBt->pWriter = 0;
  51303. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  51304. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  51305. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  51306. pLock->eLock = READ_LOCK;
  51307. }
  51308. }
  51309. }
  51310. #endif /* SQLITE_OMIT_SHARED_CACHE */
  51311. static void releasePage(MemPage *pPage); /* Forward reference */
  51312. /*
  51313. ***** This routine is used inside of assert() only ****
  51314. **
  51315. ** Verify that the cursor holds the mutex on its BtShared
  51316. */
  51317. #ifdef SQLITE_DEBUG
  51318. static int cursorHoldsMutex(BtCursor *p){
  51319. return sqlite3_mutex_held(p->pBt->mutex);
  51320. }
  51321. #endif
  51322. /*
  51323. ** Invalidate the overflow cache of the cursor passed as the first argument.
  51324. ** on the shared btree structure pBt.
  51325. */
  51326. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  51327. /*
  51328. ** Invalidate the overflow page-list cache for all cursors opened
  51329. ** on the shared btree structure pBt.
  51330. */
  51331. static void invalidateAllOverflowCache(BtShared *pBt){
  51332. BtCursor *p;
  51333. assert( sqlite3_mutex_held(pBt->mutex) );
  51334. for(p=pBt->pCursor; p; p=p->pNext){
  51335. invalidateOverflowCache(p);
  51336. }
  51337. }
  51338. #ifndef SQLITE_OMIT_INCRBLOB
  51339. /*
  51340. ** This function is called before modifying the contents of a table
  51341. ** to invalidate any incrblob cursors that are open on the
  51342. ** row or one of the rows being modified.
  51343. **
  51344. ** If argument isClearTable is true, then the entire contents of the
  51345. ** table is about to be deleted. In this case invalidate all incrblob
  51346. ** cursors open on any row within the table with root-page pgnoRoot.
  51347. **
  51348. ** Otherwise, if argument isClearTable is false, then the row with
  51349. ** rowid iRow is being replaced or deleted. In this case invalidate
  51350. ** only those incrblob cursors open on that specific row.
  51351. */
  51352. static void invalidateIncrblobCursors(
  51353. Btree *pBtree, /* The database file to check */
  51354. i64 iRow, /* The rowid that might be changing */
  51355. int isClearTable /* True if all rows are being deleted */
  51356. ){
  51357. BtCursor *p;
  51358. if( pBtree->hasIncrblobCur==0 ) return;
  51359. assert( sqlite3BtreeHoldsMutex(pBtree) );
  51360. pBtree->hasIncrblobCur = 0;
  51361. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  51362. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  51363. pBtree->hasIncrblobCur = 1;
  51364. if( isClearTable || p->info.nKey==iRow ){
  51365. p->eState = CURSOR_INVALID;
  51366. }
  51367. }
  51368. }
  51369. }
  51370. #else
  51371. /* Stub function when INCRBLOB is omitted */
  51372. #define invalidateIncrblobCursors(x,y,z)
  51373. #endif /* SQLITE_OMIT_INCRBLOB */
  51374. /*
  51375. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  51376. ** when a page that previously contained data becomes a free-list leaf
  51377. ** page.
  51378. **
  51379. ** The BtShared.pHasContent bitvec exists to work around an obscure
  51380. ** bug caused by the interaction of two useful IO optimizations surrounding
  51381. ** free-list leaf pages:
  51382. **
  51383. ** 1) When all data is deleted from a page and the page becomes
  51384. ** a free-list leaf page, the page is not written to the database
  51385. ** (as free-list leaf pages contain no meaningful data). Sometimes
  51386. ** such a page is not even journalled (as it will not be modified,
  51387. ** why bother journalling it?).
  51388. **
  51389. ** 2) When a free-list leaf page is reused, its content is not read
  51390. ** from the database or written to the journal file (why should it
  51391. ** be, if it is not at all meaningful?).
  51392. **
  51393. ** By themselves, these optimizations work fine and provide a handy
  51394. ** performance boost to bulk delete or insert operations. However, if
  51395. ** a page is moved to the free-list and then reused within the same
  51396. ** transaction, a problem comes up. If the page is not journalled when
  51397. ** it is moved to the free-list and it is also not journalled when it
  51398. ** is extracted from the free-list and reused, then the original data
  51399. ** may be lost. In the event of a rollback, it may not be possible
  51400. ** to restore the database to its original configuration.
  51401. **
  51402. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  51403. ** moved to become a free-list leaf page, the corresponding bit is
  51404. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  51405. ** optimization 2 above is omitted if the corresponding bit is already
  51406. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  51407. ** at the end of every transaction.
  51408. */
  51409. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  51410. int rc = SQLITE_OK;
  51411. if( !pBt->pHasContent ){
  51412. assert( pgno<=pBt->nPage );
  51413. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  51414. if( !pBt->pHasContent ){
  51415. rc = SQLITE_NOMEM;
  51416. }
  51417. }
  51418. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  51419. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  51420. }
  51421. return rc;
  51422. }
  51423. /*
  51424. ** Query the BtShared.pHasContent vector.
  51425. **
  51426. ** This function is called when a free-list leaf page is removed from the
  51427. ** free-list for reuse. It returns false if it is safe to retrieve the
  51428. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  51429. */
  51430. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  51431. Bitvec *p = pBt->pHasContent;
  51432. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  51433. }
  51434. /*
  51435. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  51436. ** invoked at the conclusion of each write-transaction.
  51437. */
  51438. static void btreeClearHasContent(BtShared *pBt){
  51439. sqlite3BitvecDestroy(pBt->pHasContent);
  51440. pBt->pHasContent = 0;
  51441. }
  51442. /*
  51443. ** Release all of the apPage[] pages for a cursor.
  51444. */
  51445. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  51446. int i;
  51447. for(i=0; i<=pCur->iPage; i++){
  51448. releasePage(pCur->apPage[i]);
  51449. pCur->apPage[i] = 0;
  51450. }
  51451. pCur->iPage = -1;
  51452. }
  51453. /*
  51454. ** The cursor passed as the only argument must point to a valid entry
  51455. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  51456. ** function saves the current cursor key in variables pCur->nKey and
  51457. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  51458. ** code otherwise.
  51459. **
  51460. ** If the cursor is open on an intkey table, then the integer key
  51461. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  51462. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  51463. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  51464. ** the key.
  51465. */
  51466. static int saveCursorKey(BtCursor *pCur){
  51467. int rc;
  51468. assert( CURSOR_VALID==pCur->eState );
  51469. assert( 0==pCur->pKey );
  51470. assert( cursorHoldsMutex(pCur) );
  51471. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  51472. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  51473. /* If this is an intKey table, then the above call to BtreeKeySize()
  51474. ** stores the integer key in pCur->nKey. In this case this value is
  51475. ** all that is required. Otherwise, if pCur is not open on an intKey
  51476. ** table, then malloc space for and store the pCur->nKey bytes of key
  51477. ** data. */
  51478. if( 0==pCur->curIntKey ){
  51479. void *pKey = sqlite3Malloc( pCur->nKey );
  51480. if( pKey ){
  51481. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  51482. if( rc==SQLITE_OK ){
  51483. pCur->pKey = pKey;
  51484. }else{
  51485. sqlite3_free(pKey);
  51486. }
  51487. }else{
  51488. rc = SQLITE_NOMEM;
  51489. }
  51490. }
  51491. assert( !pCur->curIntKey || !pCur->pKey );
  51492. return rc;
  51493. }
  51494. /*
  51495. ** Save the current cursor position in the variables BtCursor.nKey
  51496. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  51497. **
  51498. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  51499. ** prior to calling this routine.
  51500. */
  51501. static int saveCursorPosition(BtCursor *pCur){
  51502. int rc;
  51503. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  51504. assert( 0==pCur->pKey );
  51505. assert( cursorHoldsMutex(pCur) );
  51506. if( pCur->eState==CURSOR_SKIPNEXT ){
  51507. pCur->eState = CURSOR_VALID;
  51508. }else{
  51509. pCur->skipNext = 0;
  51510. }
  51511. rc = saveCursorKey(pCur);
  51512. if( rc==SQLITE_OK ){
  51513. btreeReleaseAllCursorPages(pCur);
  51514. pCur->eState = CURSOR_REQUIRESEEK;
  51515. }
  51516. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  51517. return rc;
  51518. }
  51519. /* Forward reference */
  51520. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  51521. /*
  51522. ** Save the positions of all cursors (except pExcept) that are open on
  51523. ** the table with root-page iRoot. "Saving the cursor position" means that
  51524. ** the location in the btree is remembered in such a way that it can be
  51525. ** moved back to the same spot after the btree has been modified. This
  51526. ** routine is called just before cursor pExcept is used to modify the
  51527. ** table, for example in BtreeDelete() or BtreeInsert().
  51528. **
  51529. ** If there are two or more cursors on the same btree, then all such
  51530. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  51531. ** routine enforces that rule. This routine only needs to be called in
  51532. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  51533. **
  51534. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  51535. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  51536. ** pointless call to this routine.
  51537. **
  51538. ** Implementation note: This routine merely checks to see if any cursors
  51539. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  51540. ** event that cursors are in need to being saved.
  51541. */
  51542. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  51543. BtCursor *p;
  51544. assert( sqlite3_mutex_held(pBt->mutex) );
  51545. assert( pExcept==0 || pExcept->pBt==pBt );
  51546. for(p=pBt->pCursor; p; p=p->pNext){
  51547. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  51548. }
  51549. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  51550. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  51551. return SQLITE_OK;
  51552. }
  51553. /* This helper routine to saveAllCursors does the actual work of saving
  51554. ** the cursors if and when a cursor is found that actually requires saving.
  51555. ** The common case is that no cursors need to be saved, so this routine is
  51556. ** broken out from its caller to avoid unnecessary stack pointer movement.
  51557. */
  51558. static int SQLITE_NOINLINE saveCursorsOnList(
  51559. BtCursor *p, /* The first cursor that needs saving */
  51560. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  51561. BtCursor *pExcept /* Do not save this cursor */
  51562. ){
  51563. do{
  51564. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  51565. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  51566. int rc = saveCursorPosition(p);
  51567. if( SQLITE_OK!=rc ){
  51568. return rc;
  51569. }
  51570. }else{
  51571. testcase( p->iPage>0 );
  51572. btreeReleaseAllCursorPages(p);
  51573. }
  51574. }
  51575. p = p->pNext;
  51576. }while( p );
  51577. return SQLITE_OK;
  51578. }
  51579. /*
  51580. ** Clear the current cursor position.
  51581. */
  51582. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  51583. assert( cursorHoldsMutex(pCur) );
  51584. sqlite3_free(pCur->pKey);
  51585. pCur->pKey = 0;
  51586. pCur->eState = CURSOR_INVALID;
  51587. }
  51588. /*
  51589. ** In this version of BtreeMoveto, pKey is a packed index record
  51590. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  51591. ** record and then call BtreeMovetoUnpacked() to do the work.
  51592. */
  51593. static int btreeMoveto(
  51594. BtCursor *pCur, /* Cursor open on the btree to be searched */
  51595. const void *pKey, /* Packed key if the btree is an index */
  51596. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  51597. int bias, /* Bias search to the high end */
  51598. int *pRes /* Write search results here */
  51599. ){
  51600. int rc; /* Status code */
  51601. UnpackedRecord *pIdxKey; /* Unpacked index key */
  51602. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  51603. char *pFree = 0;
  51604. if( pKey ){
  51605. assert( nKey==(i64)(int)nKey );
  51606. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  51607. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  51608. );
  51609. if( pIdxKey==0 ) return SQLITE_NOMEM;
  51610. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  51611. if( pIdxKey->nField==0 ){
  51612. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  51613. return SQLITE_CORRUPT_BKPT;
  51614. }
  51615. }else{
  51616. pIdxKey = 0;
  51617. }
  51618. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  51619. if( pFree ){
  51620. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  51621. }
  51622. return rc;
  51623. }
  51624. /*
  51625. ** Restore the cursor to the position it was in (or as close to as possible)
  51626. ** when saveCursorPosition() was called. Note that this call deletes the
  51627. ** saved position info stored by saveCursorPosition(), so there can be
  51628. ** at most one effective restoreCursorPosition() call after each
  51629. ** saveCursorPosition().
  51630. */
  51631. static int btreeRestoreCursorPosition(BtCursor *pCur){
  51632. int rc;
  51633. int skipNext;
  51634. assert( cursorHoldsMutex(pCur) );
  51635. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  51636. if( pCur->eState==CURSOR_FAULT ){
  51637. return pCur->skipNext;
  51638. }
  51639. pCur->eState = CURSOR_INVALID;
  51640. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  51641. if( rc==SQLITE_OK ){
  51642. sqlite3_free(pCur->pKey);
  51643. pCur->pKey = 0;
  51644. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  51645. pCur->skipNext |= skipNext;
  51646. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  51647. pCur->eState = CURSOR_SKIPNEXT;
  51648. }
  51649. }
  51650. return rc;
  51651. }
  51652. #define restoreCursorPosition(p) \
  51653. (p->eState>=CURSOR_REQUIRESEEK ? \
  51654. btreeRestoreCursorPosition(p) : \
  51655. SQLITE_OK)
  51656. /*
  51657. ** Determine whether or not a cursor has moved from the position where
  51658. ** it was last placed, or has been invalidated for any other reason.
  51659. ** Cursors can move when the row they are pointing at is deleted out
  51660. ** from under them, for example. Cursor might also move if a btree
  51661. ** is rebalanced.
  51662. **
  51663. ** Calling this routine with a NULL cursor pointer returns false.
  51664. **
  51665. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  51666. ** back to where it ought to be if this routine returns true.
  51667. */
  51668. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  51669. return pCur->eState!=CURSOR_VALID;
  51670. }
  51671. /*
  51672. ** This routine restores a cursor back to its original position after it
  51673. ** has been moved by some outside activity (such as a btree rebalance or
  51674. ** a row having been deleted out from under the cursor).
  51675. **
  51676. ** On success, the *pDifferentRow parameter is false if the cursor is left
  51677. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  51678. ** was pointing to has been deleted, forcing the cursor to point to some
  51679. ** nearby row.
  51680. **
  51681. ** This routine should only be called for a cursor that just returned
  51682. ** TRUE from sqlite3BtreeCursorHasMoved().
  51683. */
  51684. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  51685. int rc;
  51686. assert( pCur!=0 );
  51687. assert( pCur->eState!=CURSOR_VALID );
  51688. rc = restoreCursorPosition(pCur);
  51689. if( rc ){
  51690. *pDifferentRow = 1;
  51691. return rc;
  51692. }
  51693. if( pCur->eState!=CURSOR_VALID ){
  51694. *pDifferentRow = 1;
  51695. }else{
  51696. assert( pCur->skipNext==0 );
  51697. *pDifferentRow = 0;
  51698. }
  51699. return SQLITE_OK;
  51700. }
  51701. #ifndef SQLITE_OMIT_AUTOVACUUM
  51702. /*
  51703. ** Given a page number of a regular database page, return the page
  51704. ** number for the pointer-map page that contains the entry for the
  51705. ** input page number.
  51706. **
  51707. ** Return 0 (not a valid page) for pgno==1 since there is
  51708. ** no pointer map associated with page 1. The integrity_check logic
  51709. ** requires that ptrmapPageno(*,1)!=1.
  51710. */
  51711. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  51712. int nPagesPerMapPage;
  51713. Pgno iPtrMap, ret;
  51714. assert( sqlite3_mutex_held(pBt->mutex) );
  51715. if( pgno<2 ) return 0;
  51716. nPagesPerMapPage = (pBt->usableSize/5)+1;
  51717. iPtrMap = (pgno-2)/nPagesPerMapPage;
  51718. ret = (iPtrMap*nPagesPerMapPage) + 2;
  51719. if( ret==PENDING_BYTE_PAGE(pBt) ){
  51720. ret++;
  51721. }
  51722. return ret;
  51723. }
  51724. /*
  51725. ** Write an entry into the pointer map.
  51726. **
  51727. ** This routine updates the pointer map entry for page number 'key'
  51728. ** so that it maps to type 'eType' and parent page number 'pgno'.
  51729. **
  51730. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  51731. ** a no-op. If an error occurs, the appropriate error code is written
  51732. ** into *pRC.
  51733. */
  51734. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  51735. DbPage *pDbPage; /* The pointer map page */
  51736. u8 *pPtrmap; /* The pointer map data */
  51737. Pgno iPtrmap; /* The pointer map page number */
  51738. int offset; /* Offset in pointer map page */
  51739. int rc; /* Return code from subfunctions */
  51740. if( *pRC ) return;
  51741. assert( sqlite3_mutex_held(pBt->mutex) );
  51742. /* The master-journal page number must never be used as a pointer map page */
  51743. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  51744. assert( pBt->autoVacuum );
  51745. if( key==0 ){
  51746. *pRC = SQLITE_CORRUPT_BKPT;
  51747. return;
  51748. }
  51749. iPtrmap = PTRMAP_PAGENO(pBt, key);
  51750. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  51751. if( rc!=SQLITE_OK ){
  51752. *pRC = rc;
  51753. return;
  51754. }
  51755. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  51756. if( offset<0 ){
  51757. *pRC = SQLITE_CORRUPT_BKPT;
  51758. goto ptrmap_exit;
  51759. }
  51760. assert( offset <= (int)pBt->usableSize-5 );
  51761. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  51762. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  51763. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  51764. *pRC= rc = sqlite3PagerWrite(pDbPage);
  51765. if( rc==SQLITE_OK ){
  51766. pPtrmap[offset] = eType;
  51767. put4byte(&pPtrmap[offset+1], parent);
  51768. }
  51769. }
  51770. ptrmap_exit:
  51771. sqlite3PagerUnref(pDbPage);
  51772. }
  51773. /*
  51774. ** Read an entry from the pointer map.
  51775. **
  51776. ** This routine retrieves the pointer map entry for page 'key', writing
  51777. ** the type and parent page number to *pEType and *pPgno respectively.
  51778. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  51779. */
  51780. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  51781. DbPage *pDbPage; /* The pointer map page */
  51782. int iPtrmap; /* Pointer map page index */
  51783. u8 *pPtrmap; /* Pointer map page data */
  51784. int offset; /* Offset of entry in pointer map */
  51785. int rc;
  51786. assert( sqlite3_mutex_held(pBt->mutex) );
  51787. iPtrmap = PTRMAP_PAGENO(pBt, key);
  51788. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  51789. if( rc!=0 ){
  51790. return rc;
  51791. }
  51792. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  51793. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  51794. if( offset<0 ){
  51795. sqlite3PagerUnref(pDbPage);
  51796. return SQLITE_CORRUPT_BKPT;
  51797. }
  51798. assert( offset <= (int)pBt->usableSize-5 );
  51799. assert( pEType!=0 );
  51800. *pEType = pPtrmap[offset];
  51801. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  51802. sqlite3PagerUnref(pDbPage);
  51803. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  51804. return SQLITE_OK;
  51805. }
  51806. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  51807. #define ptrmapPut(w,x,y,z,rc)
  51808. #define ptrmapGet(w,x,y,z) SQLITE_OK
  51809. #define ptrmapPutOvflPtr(x, y, rc)
  51810. #endif
  51811. /*
  51812. ** Given a btree page and a cell index (0 means the first cell on
  51813. ** the page, 1 means the second cell, and so forth) return a pointer
  51814. ** to the cell content.
  51815. **
  51816. ** findCellPastPtr() does the same except it skips past the initial
  51817. ** 4-byte child pointer found on interior pages, if there is one.
  51818. **
  51819. ** This routine works only for pages that do not contain overflow cells.
  51820. */
  51821. #define findCell(P,I) \
  51822. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  51823. #define findCellPastPtr(P,I) \
  51824. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  51825. /*
  51826. ** This is common tail processing for btreeParseCellPtr() and
  51827. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  51828. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  51829. ** structure.
  51830. */
  51831. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  51832. MemPage *pPage, /* Page containing the cell */
  51833. u8 *pCell, /* Pointer to the cell text. */
  51834. CellInfo *pInfo /* Fill in this structure */
  51835. ){
  51836. /* If the payload will not fit completely on the local page, we have
  51837. ** to decide how much to store locally and how much to spill onto
  51838. ** overflow pages. The strategy is to minimize the amount of unused
  51839. ** space on overflow pages while keeping the amount of local storage
  51840. ** in between minLocal and maxLocal.
  51841. **
  51842. ** Warning: changing the way overflow payload is distributed in any
  51843. ** way will result in an incompatible file format.
  51844. */
  51845. int minLocal; /* Minimum amount of payload held locally */
  51846. int maxLocal; /* Maximum amount of payload held locally */
  51847. int surplus; /* Overflow payload available for local storage */
  51848. minLocal = pPage->minLocal;
  51849. maxLocal = pPage->maxLocal;
  51850. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  51851. testcase( surplus==maxLocal );
  51852. testcase( surplus==maxLocal+1 );
  51853. if( surplus <= maxLocal ){
  51854. pInfo->nLocal = (u16)surplus;
  51855. }else{
  51856. pInfo->nLocal = (u16)minLocal;
  51857. }
  51858. pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  51859. pInfo->nSize = pInfo->iOverflow + 4;
  51860. }
  51861. /*
  51862. ** The following routines are implementations of the MemPage.xParseCell()
  51863. ** method.
  51864. **
  51865. ** Parse a cell content block and fill in the CellInfo structure.
  51866. **
  51867. ** btreeParseCellPtr() => table btree leaf nodes
  51868. ** btreeParseCellNoPayload() => table btree internal nodes
  51869. ** btreeParseCellPtrIndex() => index btree nodes
  51870. **
  51871. ** There is also a wrapper function btreeParseCell() that works for
  51872. ** all MemPage types and that references the cell by index rather than
  51873. ** by pointer.
  51874. */
  51875. static void btreeParseCellPtrNoPayload(
  51876. MemPage *pPage, /* Page containing the cell */
  51877. u8 *pCell, /* Pointer to the cell text. */
  51878. CellInfo *pInfo /* Fill in this structure */
  51879. ){
  51880. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51881. assert( pPage->leaf==0 );
  51882. assert( pPage->noPayload );
  51883. assert( pPage->childPtrSize==4 );
  51884. #ifndef SQLITE_DEBUG
  51885. UNUSED_PARAMETER(pPage);
  51886. #endif
  51887. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  51888. pInfo->nPayload = 0;
  51889. pInfo->nLocal = 0;
  51890. pInfo->iOverflow = 0;
  51891. pInfo->pPayload = 0;
  51892. return;
  51893. }
  51894. static void btreeParseCellPtr(
  51895. MemPage *pPage, /* Page containing the cell */
  51896. u8 *pCell, /* Pointer to the cell text. */
  51897. CellInfo *pInfo /* Fill in this structure */
  51898. ){
  51899. u8 *pIter; /* For scanning through pCell */
  51900. u32 nPayload; /* Number of bytes of cell payload */
  51901. u64 iKey; /* Extracted Key value */
  51902. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51903. assert( pPage->leaf==0 || pPage->leaf==1 );
  51904. assert( pPage->intKeyLeaf || pPage->noPayload );
  51905. assert( pPage->noPayload==0 );
  51906. assert( pPage->intKeyLeaf );
  51907. assert( pPage->childPtrSize==0 );
  51908. pIter = pCell;
  51909. /* The next block of code is equivalent to:
  51910. **
  51911. ** pIter += getVarint32(pIter, nPayload);
  51912. **
  51913. ** The code is inlined to avoid a function call.
  51914. */
  51915. nPayload = *pIter;
  51916. if( nPayload>=0x80 ){
  51917. u8 *pEnd = &pIter[8];
  51918. nPayload &= 0x7f;
  51919. do{
  51920. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  51921. }while( (*pIter)>=0x80 && pIter<pEnd );
  51922. }
  51923. pIter++;
  51924. /* The next block of code is equivalent to:
  51925. **
  51926. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  51927. **
  51928. ** The code is inlined to avoid a function call.
  51929. */
  51930. iKey = *pIter;
  51931. if( iKey>=0x80 ){
  51932. u8 *pEnd = &pIter[7];
  51933. iKey &= 0x7f;
  51934. while(1){
  51935. iKey = (iKey<<7) | (*++pIter & 0x7f);
  51936. if( (*pIter)<0x80 ) break;
  51937. if( pIter>=pEnd ){
  51938. iKey = (iKey<<8) | *++pIter;
  51939. break;
  51940. }
  51941. }
  51942. }
  51943. pIter++;
  51944. pInfo->nKey = *(i64*)&iKey;
  51945. pInfo->nPayload = nPayload;
  51946. pInfo->pPayload = pIter;
  51947. testcase( nPayload==pPage->maxLocal );
  51948. testcase( nPayload==pPage->maxLocal+1 );
  51949. if( nPayload<=pPage->maxLocal ){
  51950. /* This is the (easy) common case where the entire payload fits
  51951. ** on the local page. No overflow is required.
  51952. */
  51953. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  51954. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  51955. pInfo->nLocal = (u16)nPayload;
  51956. pInfo->iOverflow = 0;
  51957. }else{
  51958. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  51959. }
  51960. }
  51961. static void btreeParseCellPtrIndex(
  51962. MemPage *pPage, /* Page containing the cell */
  51963. u8 *pCell, /* Pointer to the cell text. */
  51964. CellInfo *pInfo /* Fill in this structure */
  51965. ){
  51966. u8 *pIter; /* For scanning through pCell */
  51967. u32 nPayload; /* Number of bytes of cell payload */
  51968. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51969. assert( pPage->leaf==0 || pPage->leaf==1 );
  51970. assert( pPage->intKeyLeaf==0 );
  51971. assert( pPage->noPayload==0 );
  51972. pIter = pCell + pPage->childPtrSize;
  51973. nPayload = *pIter;
  51974. if( nPayload>=0x80 ){
  51975. u8 *pEnd = &pIter[8];
  51976. nPayload &= 0x7f;
  51977. do{
  51978. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  51979. }while( *(pIter)>=0x80 && pIter<pEnd );
  51980. }
  51981. pIter++;
  51982. pInfo->nKey = nPayload;
  51983. pInfo->nPayload = nPayload;
  51984. pInfo->pPayload = pIter;
  51985. testcase( nPayload==pPage->maxLocal );
  51986. testcase( nPayload==pPage->maxLocal+1 );
  51987. if( nPayload<=pPage->maxLocal ){
  51988. /* This is the (easy) common case where the entire payload fits
  51989. ** on the local page. No overflow is required.
  51990. */
  51991. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  51992. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  51993. pInfo->nLocal = (u16)nPayload;
  51994. pInfo->iOverflow = 0;
  51995. }else{
  51996. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  51997. }
  51998. }
  51999. static void btreeParseCell(
  52000. MemPage *pPage, /* Page containing the cell */
  52001. int iCell, /* The cell index. First cell is 0 */
  52002. CellInfo *pInfo /* Fill in this structure */
  52003. ){
  52004. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  52005. }
  52006. /*
  52007. ** The following routines are implementations of the MemPage.xCellSize
  52008. ** method.
  52009. **
  52010. ** Compute the total number of bytes that a Cell needs in the cell
  52011. ** data area of the btree-page. The return number includes the cell
  52012. ** data header and the local payload, but not any overflow page or
  52013. ** the space used by the cell pointer.
  52014. **
  52015. ** cellSizePtrNoPayload() => table internal nodes
  52016. ** cellSizePtr() => all index nodes & table leaf nodes
  52017. */
  52018. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  52019. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  52020. u8 *pEnd; /* End mark for a varint */
  52021. u32 nSize; /* Size value to return */
  52022. #ifdef SQLITE_DEBUG
  52023. /* The value returned by this function should always be the same as
  52024. ** the (CellInfo.nSize) value found by doing a full parse of the
  52025. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  52026. ** this function verifies that this invariant is not violated. */
  52027. CellInfo debuginfo;
  52028. pPage->xParseCell(pPage, pCell, &debuginfo);
  52029. #endif
  52030. assert( pPage->noPayload==0 );
  52031. nSize = *pIter;
  52032. if( nSize>=0x80 ){
  52033. pEnd = &pIter[8];
  52034. nSize &= 0x7f;
  52035. do{
  52036. nSize = (nSize<<7) | (*++pIter & 0x7f);
  52037. }while( *(pIter)>=0x80 && pIter<pEnd );
  52038. }
  52039. pIter++;
  52040. if( pPage->intKey ){
  52041. /* pIter now points at the 64-bit integer key value, a variable length
  52042. ** integer. The following block moves pIter to point at the first byte
  52043. ** past the end of the key value. */
  52044. pEnd = &pIter[9];
  52045. while( (*pIter++)&0x80 && pIter<pEnd );
  52046. }
  52047. testcase( nSize==pPage->maxLocal );
  52048. testcase( nSize==pPage->maxLocal+1 );
  52049. if( nSize<=pPage->maxLocal ){
  52050. nSize += (u32)(pIter - pCell);
  52051. if( nSize<4 ) nSize = 4;
  52052. }else{
  52053. int minLocal = pPage->minLocal;
  52054. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  52055. testcase( nSize==pPage->maxLocal );
  52056. testcase( nSize==pPage->maxLocal+1 );
  52057. if( nSize>pPage->maxLocal ){
  52058. nSize = minLocal;
  52059. }
  52060. nSize += 4 + (u16)(pIter - pCell);
  52061. }
  52062. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  52063. return (u16)nSize;
  52064. }
  52065. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  52066. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  52067. u8 *pEnd; /* End mark for a varint */
  52068. #ifdef SQLITE_DEBUG
  52069. /* The value returned by this function should always be the same as
  52070. ** the (CellInfo.nSize) value found by doing a full parse of the
  52071. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  52072. ** this function verifies that this invariant is not violated. */
  52073. CellInfo debuginfo;
  52074. pPage->xParseCell(pPage, pCell, &debuginfo);
  52075. #else
  52076. UNUSED_PARAMETER(pPage);
  52077. #endif
  52078. assert( pPage->childPtrSize==4 );
  52079. pEnd = pIter + 9;
  52080. while( (*pIter++)&0x80 && pIter<pEnd );
  52081. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  52082. return (u16)(pIter - pCell);
  52083. }
  52084. #ifdef SQLITE_DEBUG
  52085. /* This variation on cellSizePtr() is used inside of assert() statements
  52086. ** only. */
  52087. static u16 cellSize(MemPage *pPage, int iCell){
  52088. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  52089. }
  52090. #endif
  52091. #ifndef SQLITE_OMIT_AUTOVACUUM
  52092. /*
  52093. ** If the cell pCell, part of page pPage contains a pointer
  52094. ** to an overflow page, insert an entry into the pointer-map
  52095. ** for the overflow page.
  52096. */
  52097. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  52098. CellInfo info;
  52099. if( *pRC ) return;
  52100. assert( pCell!=0 );
  52101. pPage->xParseCell(pPage, pCell, &info);
  52102. if( info.iOverflow ){
  52103. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  52104. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  52105. }
  52106. }
  52107. #endif
  52108. /*
  52109. ** Defragment the page given. All Cells are moved to the
  52110. ** end of the page and all free space is collected into one
  52111. ** big FreeBlk that occurs in between the header and cell
  52112. ** pointer array and the cell content area.
  52113. **
  52114. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  52115. ** b-tree page so that there are no freeblocks or fragment bytes, all
  52116. ** unused bytes are contained in the unallocated space region, and all
  52117. ** cells are packed tightly at the end of the page.
  52118. */
  52119. static int defragmentPage(MemPage *pPage){
  52120. int i; /* Loop counter */
  52121. int pc; /* Address of the i-th cell */
  52122. int hdr; /* Offset to the page header */
  52123. int size; /* Size of a cell */
  52124. int usableSize; /* Number of usable bytes on a page */
  52125. int cellOffset; /* Offset to the cell pointer array */
  52126. int cbrk; /* Offset to the cell content area */
  52127. int nCell; /* Number of cells on the page */
  52128. unsigned char *data; /* The page data */
  52129. unsigned char *temp; /* Temp area for cell content */
  52130. unsigned char *src; /* Source of content */
  52131. int iCellFirst; /* First allowable cell index */
  52132. int iCellLast; /* Last possible cell index */
  52133. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52134. assert( pPage->pBt!=0 );
  52135. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  52136. assert( pPage->nOverflow==0 );
  52137. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52138. temp = 0;
  52139. src = data = pPage->aData;
  52140. hdr = pPage->hdrOffset;
  52141. cellOffset = pPage->cellOffset;
  52142. nCell = pPage->nCell;
  52143. assert( nCell==get2byte(&data[hdr+3]) );
  52144. usableSize = pPage->pBt->usableSize;
  52145. cbrk = usableSize;
  52146. iCellFirst = cellOffset + 2*nCell;
  52147. iCellLast = usableSize - 4;
  52148. for(i=0; i<nCell; i++){
  52149. u8 *pAddr; /* The i-th cell pointer */
  52150. pAddr = &data[cellOffset + i*2];
  52151. pc = get2byte(pAddr);
  52152. testcase( pc==iCellFirst );
  52153. testcase( pc==iCellLast );
  52154. /* These conditions have already been verified in btreeInitPage()
  52155. ** if PRAGMA cell_size_check=ON.
  52156. */
  52157. if( pc<iCellFirst || pc>iCellLast ){
  52158. return SQLITE_CORRUPT_BKPT;
  52159. }
  52160. assert( pc>=iCellFirst && pc<=iCellLast );
  52161. size = pPage->xCellSize(pPage, &src[pc]);
  52162. cbrk -= size;
  52163. if( cbrk<iCellFirst || pc+size>usableSize ){
  52164. return SQLITE_CORRUPT_BKPT;
  52165. }
  52166. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  52167. testcase( cbrk+size==usableSize );
  52168. testcase( pc+size==usableSize );
  52169. put2byte(pAddr, cbrk);
  52170. if( temp==0 ){
  52171. int x;
  52172. if( cbrk==pc ) continue;
  52173. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  52174. x = get2byte(&data[hdr+5]);
  52175. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  52176. src = temp;
  52177. }
  52178. memcpy(&data[cbrk], &src[pc], size);
  52179. }
  52180. assert( cbrk>=iCellFirst );
  52181. put2byte(&data[hdr+5], cbrk);
  52182. data[hdr+1] = 0;
  52183. data[hdr+2] = 0;
  52184. data[hdr+7] = 0;
  52185. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  52186. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52187. if( cbrk-iCellFirst!=pPage->nFree ){
  52188. return SQLITE_CORRUPT_BKPT;
  52189. }
  52190. return SQLITE_OK;
  52191. }
  52192. /*
  52193. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  52194. ** size. If one can be found, return a pointer to the space and remove it
  52195. ** from the free-list.
  52196. **
  52197. ** If no suitable space can be found on the free-list, return NULL.
  52198. **
  52199. ** This function may detect corruption within pPg. If corruption is
  52200. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  52201. **
  52202. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  52203. ** will be ignored if adding the extra space to the fragmentation count
  52204. ** causes the fragmentation count to exceed 60.
  52205. */
  52206. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  52207. const int hdr = pPg->hdrOffset;
  52208. u8 * const aData = pPg->aData;
  52209. int iAddr = hdr + 1;
  52210. int pc = get2byte(&aData[iAddr]);
  52211. int x;
  52212. int usableSize = pPg->pBt->usableSize;
  52213. assert( pc>0 );
  52214. do{
  52215. int size; /* Size of the free slot */
  52216. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  52217. ** increasing offset. */
  52218. if( pc>usableSize-4 || pc<iAddr+4 ){
  52219. *pRc = SQLITE_CORRUPT_BKPT;
  52220. return 0;
  52221. }
  52222. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  52223. ** freeblock form a big-endian integer which is the size of the freeblock
  52224. ** in bytes, including the 4-byte header. */
  52225. size = get2byte(&aData[pc+2]);
  52226. if( (x = size - nByte)>=0 ){
  52227. testcase( x==4 );
  52228. testcase( x==3 );
  52229. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  52230. *pRc = SQLITE_CORRUPT_BKPT;
  52231. return 0;
  52232. }else if( x<4 ){
  52233. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  52234. ** number of bytes in fragments may not exceed 60. */
  52235. if( aData[hdr+7]>57 ) return 0;
  52236. /* Remove the slot from the free-list. Update the number of
  52237. ** fragmented bytes within the page. */
  52238. memcpy(&aData[iAddr], &aData[pc], 2);
  52239. aData[hdr+7] += (u8)x;
  52240. }else{
  52241. /* The slot remains on the free-list. Reduce its size to account
  52242. ** for the portion used by the new allocation. */
  52243. put2byte(&aData[pc+2], x);
  52244. }
  52245. return &aData[pc + x];
  52246. }
  52247. iAddr = pc;
  52248. pc = get2byte(&aData[pc]);
  52249. }while( pc );
  52250. return 0;
  52251. }
  52252. /*
  52253. ** Allocate nByte bytes of space from within the B-Tree page passed
  52254. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  52255. ** of the first byte of allocated space. Return either SQLITE_OK or
  52256. ** an error code (usually SQLITE_CORRUPT).
  52257. **
  52258. ** The caller guarantees that there is sufficient space to make the
  52259. ** allocation. This routine might need to defragment in order to bring
  52260. ** all the space together, however. This routine will avoid using
  52261. ** the first two bytes past the cell pointer area since presumably this
  52262. ** allocation is being made in order to insert a new cell, so we will
  52263. ** also end up needing a new cell pointer.
  52264. */
  52265. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  52266. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  52267. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  52268. int top; /* First byte of cell content area */
  52269. int rc = SQLITE_OK; /* Integer return code */
  52270. int gap; /* First byte of gap between cell pointers and cell content */
  52271. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52272. assert( pPage->pBt );
  52273. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52274. assert( nByte>=0 ); /* Minimum cell size is 4 */
  52275. assert( pPage->nFree>=nByte );
  52276. assert( pPage->nOverflow==0 );
  52277. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  52278. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  52279. gap = pPage->cellOffset + 2*pPage->nCell;
  52280. assert( gap<=65536 );
  52281. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  52282. ** and the reserved space is zero (the usual value for reserved space)
  52283. ** then the cell content offset of an empty page wants to be 65536.
  52284. ** However, that integer is too large to be stored in a 2-byte unsigned
  52285. ** integer, so a value of 0 is used in its place. */
  52286. top = get2byte(&data[hdr+5]);
  52287. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  52288. if( gap>top ){
  52289. if( top==0 && pPage->pBt->usableSize==65536 ){
  52290. top = 65536;
  52291. }else{
  52292. return SQLITE_CORRUPT_BKPT;
  52293. }
  52294. }
  52295. /* If there is enough space between gap and top for one more cell pointer
  52296. ** array entry offset, and if the freelist is not empty, then search the
  52297. ** freelist looking for a free slot big enough to satisfy the request.
  52298. */
  52299. testcase( gap+2==top );
  52300. testcase( gap+1==top );
  52301. testcase( gap==top );
  52302. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  52303. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  52304. if( pSpace ){
  52305. assert( pSpace>=data && (pSpace - data)<65536 );
  52306. *pIdx = (int)(pSpace - data);
  52307. return SQLITE_OK;
  52308. }else if( rc ){
  52309. return rc;
  52310. }
  52311. }
  52312. /* The request could not be fulfilled using a freelist slot. Check
  52313. ** to see if defragmentation is necessary.
  52314. */
  52315. testcase( gap+2+nByte==top );
  52316. if( gap+2+nByte>top ){
  52317. assert( pPage->nCell>0 || CORRUPT_DB );
  52318. rc = defragmentPage(pPage);
  52319. if( rc ) return rc;
  52320. top = get2byteNotZero(&data[hdr+5]);
  52321. assert( gap+nByte<=top );
  52322. }
  52323. /* Allocate memory from the gap in between the cell pointer array
  52324. ** and the cell content area. The btreeInitPage() call has already
  52325. ** validated the freelist. Given that the freelist is valid, there
  52326. ** is no way that the allocation can extend off the end of the page.
  52327. ** The assert() below verifies the previous sentence.
  52328. */
  52329. top -= nByte;
  52330. put2byte(&data[hdr+5], top);
  52331. assert( top+nByte <= (int)pPage->pBt->usableSize );
  52332. *pIdx = top;
  52333. return SQLITE_OK;
  52334. }
  52335. /*
  52336. ** Return a section of the pPage->aData to the freelist.
  52337. ** The first byte of the new free block is pPage->aData[iStart]
  52338. ** and the size of the block is iSize bytes.
  52339. **
  52340. ** Adjacent freeblocks are coalesced.
  52341. **
  52342. ** Note that even though the freeblock list was checked by btreeInitPage(),
  52343. ** that routine will not detect overlap between cells or freeblocks. Nor
  52344. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  52345. ** at the end of the page. So do additional corruption checks inside this
  52346. ** routine and return SQLITE_CORRUPT if any problems are found.
  52347. */
  52348. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  52349. u16 iPtr; /* Address of ptr to next freeblock */
  52350. u16 iFreeBlk; /* Address of the next freeblock */
  52351. u8 hdr; /* Page header size. 0 or 100 */
  52352. u8 nFrag = 0; /* Reduction in fragmentation */
  52353. u16 iOrigSize = iSize; /* Original value of iSize */
  52354. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  52355. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  52356. unsigned char *data = pPage->aData; /* Page content */
  52357. assert( pPage->pBt!=0 );
  52358. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52359. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  52360. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  52361. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52362. assert( iSize>=4 ); /* Minimum cell size is 4 */
  52363. assert( iStart<=iLast );
  52364. /* Overwrite deleted information with zeros when the secure_delete
  52365. ** option is enabled */
  52366. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  52367. memset(&data[iStart], 0, iSize);
  52368. }
  52369. /* The list of freeblocks must be in ascending order. Find the
  52370. ** spot on the list where iStart should be inserted.
  52371. */
  52372. hdr = pPage->hdrOffset;
  52373. iPtr = hdr + 1;
  52374. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  52375. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  52376. }else{
  52377. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  52378. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  52379. iPtr = iFreeBlk;
  52380. }
  52381. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  52382. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  52383. /* At this point:
  52384. ** iFreeBlk: First freeblock after iStart, or zero if none
  52385. ** iPtr: The address of a pointer to iFreeBlk
  52386. **
  52387. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  52388. */
  52389. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  52390. nFrag = iFreeBlk - iEnd;
  52391. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  52392. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  52393. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  52394. iSize = iEnd - iStart;
  52395. iFreeBlk = get2byte(&data[iFreeBlk]);
  52396. }
  52397. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  52398. ** pointer in the page header) then check to see if iStart should be
  52399. ** coalesced onto the end of iPtr.
  52400. */
  52401. if( iPtr>hdr+1 ){
  52402. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  52403. if( iPtrEnd+3>=iStart ){
  52404. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  52405. nFrag += iStart - iPtrEnd;
  52406. iSize = iEnd - iPtr;
  52407. iStart = iPtr;
  52408. }
  52409. }
  52410. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  52411. data[hdr+7] -= nFrag;
  52412. }
  52413. if( iStart==get2byte(&data[hdr+5]) ){
  52414. /* The new freeblock is at the beginning of the cell content area,
  52415. ** so just extend the cell content area rather than create another
  52416. ** freelist entry */
  52417. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  52418. put2byte(&data[hdr+1], iFreeBlk);
  52419. put2byte(&data[hdr+5], iEnd);
  52420. }else{
  52421. /* Insert the new freeblock into the freelist */
  52422. put2byte(&data[iPtr], iStart);
  52423. put2byte(&data[iStart], iFreeBlk);
  52424. put2byte(&data[iStart+2], iSize);
  52425. }
  52426. pPage->nFree += iOrigSize;
  52427. return SQLITE_OK;
  52428. }
  52429. /*
  52430. ** Decode the flags byte (the first byte of the header) for a page
  52431. ** and initialize fields of the MemPage structure accordingly.
  52432. **
  52433. ** Only the following combinations are supported. Anything different
  52434. ** indicates a corrupt database files:
  52435. **
  52436. ** PTF_ZERODATA
  52437. ** PTF_ZERODATA | PTF_LEAF
  52438. ** PTF_LEAFDATA | PTF_INTKEY
  52439. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  52440. */
  52441. static int decodeFlags(MemPage *pPage, int flagByte){
  52442. BtShared *pBt; /* A copy of pPage->pBt */
  52443. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  52444. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52445. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  52446. flagByte &= ~PTF_LEAF;
  52447. pPage->childPtrSize = 4-4*pPage->leaf;
  52448. pPage->xCellSize = cellSizePtr;
  52449. pBt = pPage->pBt;
  52450. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  52451. /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
  52452. ** table b-tree page. */
  52453. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  52454. /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
  52455. ** table b-tree page. */
  52456. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  52457. pPage->intKey = 1;
  52458. if( pPage->leaf ){
  52459. pPage->intKeyLeaf = 1;
  52460. pPage->noPayload = 0;
  52461. pPage->xParseCell = btreeParseCellPtr;
  52462. }else{
  52463. pPage->intKeyLeaf = 0;
  52464. pPage->noPayload = 1;
  52465. pPage->xCellSize = cellSizePtrNoPayload;
  52466. pPage->xParseCell = btreeParseCellPtrNoPayload;
  52467. }
  52468. pPage->maxLocal = pBt->maxLeaf;
  52469. pPage->minLocal = pBt->minLeaf;
  52470. }else if( flagByte==PTF_ZERODATA ){
  52471. /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
  52472. ** index b-tree page. */
  52473. assert( (PTF_ZERODATA)==2 );
  52474. /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
  52475. ** index b-tree page. */
  52476. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  52477. pPage->intKey = 0;
  52478. pPage->intKeyLeaf = 0;
  52479. pPage->noPayload = 0;
  52480. pPage->xParseCell = btreeParseCellPtrIndex;
  52481. pPage->maxLocal = pBt->maxLocal;
  52482. pPage->minLocal = pBt->minLocal;
  52483. }else{
  52484. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  52485. ** an error. */
  52486. return SQLITE_CORRUPT_BKPT;
  52487. }
  52488. pPage->max1bytePayload = pBt->max1bytePayload;
  52489. return SQLITE_OK;
  52490. }
  52491. /*
  52492. ** Initialize the auxiliary information for a disk block.
  52493. **
  52494. ** Return SQLITE_OK on success. If we see that the page does
  52495. ** not contain a well-formed database page, then return
  52496. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  52497. ** guarantee that the page is well-formed. It only shows that
  52498. ** we failed to detect any corruption.
  52499. */
  52500. static int btreeInitPage(MemPage *pPage){
  52501. assert( pPage->pBt!=0 );
  52502. assert( pPage->pBt->db!=0 );
  52503. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52504. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  52505. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  52506. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  52507. if( !pPage->isInit ){
  52508. u16 pc; /* Address of a freeblock within pPage->aData[] */
  52509. u8 hdr; /* Offset to beginning of page header */
  52510. u8 *data; /* Equal to pPage->aData */
  52511. BtShared *pBt; /* The main btree structure */
  52512. int usableSize; /* Amount of usable space on each page */
  52513. u16 cellOffset; /* Offset from start of page to first cell pointer */
  52514. int nFree; /* Number of unused bytes on the page */
  52515. int top; /* First byte of the cell content area */
  52516. int iCellFirst; /* First allowable cell or freeblock offset */
  52517. int iCellLast; /* Last possible cell or freeblock offset */
  52518. pBt = pPage->pBt;
  52519. hdr = pPage->hdrOffset;
  52520. data = pPage->aData;
  52521. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  52522. ** the b-tree page type. */
  52523. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  52524. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  52525. pPage->maskPage = (u16)(pBt->pageSize - 1);
  52526. pPage->nOverflow = 0;
  52527. usableSize = pBt->usableSize;
  52528. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  52529. pPage->aDataEnd = &data[usableSize];
  52530. pPage->aCellIdx = &data[cellOffset];
  52531. pPage->aDataOfst = &data[pPage->childPtrSize];
  52532. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  52533. ** the start of the cell content area. A zero value for this integer is
  52534. ** interpreted as 65536. */
  52535. top = get2byteNotZero(&data[hdr+5]);
  52536. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  52537. ** number of cells on the page. */
  52538. pPage->nCell = get2byte(&data[hdr+3]);
  52539. if( pPage->nCell>MX_CELL(pBt) ){
  52540. /* To many cells for a single page. The page must be corrupt */
  52541. return SQLITE_CORRUPT_BKPT;
  52542. }
  52543. testcase( pPage->nCell==MX_CELL(pBt) );
  52544. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  52545. ** possible for a root page of a table that contains no rows) then the
  52546. ** offset to the cell content area will equal the page size minus the
  52547. ** bytes of reserved space. */
  52548. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  52549. /* A malformed database page might cause us to read past the end
  52550. ** of page when parsing a cell.
  52551. **
  52552. ** The following block of code checks early to see if a cell extends
  52553. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  52554. ** returned if it does.
  52555. */
  52556. iCellFirst = cellOffset + 2*pPage->nCell;
  52557. iCellLast = usableSize - 4;
  52558. if( pBt->db->flags & SQLITE_CellSizeCk ){
  52559. int i; /* Index into the cell pointer array */
  52560. int sz; /* Size of a cell */
  52561. if( !pPage->leaf ) iCellLast--;
  52562. for(i=0; i<pPage->nCell; i++){
  52563. pc = get2byteAligned(&data[cellOffset+i*2]);
  52564. testcase( pc==iCellFirst );
  52565. testcase( pc==iCellLast );
  52566. if( pc<iCellFirst || pc>iCellLast ){
  52567. return SQLITE_CORRUPT_BKPT;
  52568. }
  52569. sz = pPage->xCellSize(pPage, &data[pc]);
  52570. testcase( pc+sz==usableSize );
  52571. if( pc+sz>usableSize ){
  52572. return SQLITE_CORRUPT_BKPT;
  52573. }
  52574. }
  52575. if( !pPage->leaf ) iCellLast++;
  52576. }
  52577. /* Compute the total free space on the page
  52578. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  52579. ** start of the first freeblock on the page, or is zero if there are no
  52580. ** freeblocks. */
  52581. pc = get2byte(&data[hdr+1]);
  52582. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  52583. while( pc>0 ){
  52584. u16 next, size;
  52585. if( pc<iCellFirst || pc>iCellLast ){
  52586. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  52587. ** always be at least one cell before the first freeblock.
  52588. **
  52589. ** Or, the freeblock is off the end of the page
  52590. */
  52591. return SQLITE_CORRUPT_BKPT;
  52592. }
  52593. next = get2byte(&data[pc]);
  52594. size = get2byte(&data[pc+2]);
  52595. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  52596. /* Free blocks must be in ascending order. And the last byte of
  52597. ** the free-block must lie on the database page. */
  52598. return SQLITE_CORRUPT_BKPT;
  52599. }
  52600. nFree = nFree + size;
  52601. pc = next;
  52602. }
  52603. /* At this point, nFree contains the sum of the offset to the start
  52604. ** of the cell-content area plus the number of free bytes within
  52605. ** the cell-content area. If this is greater than the usable-size
  52606. ** of the page, then the page must be corrupted. This check also
  52607. ** serves to verify that the offset to the start of the cell-content
  52608. ** area, according to the page header, lies within the page.
  52609. */
  52610. if( nFree>usableSize ){
  52611. return SQLITE_CORRUPT_BKPT;
  52612. }
  52613. pPage->nFree = (u16)(nFree - iCellFirst);
  52614. pPage->isInit = 1;
  52615. }
  52616. return SQLITE_OK;
  52617. }
  52618. /*
  52619. ** Set up a raw page so that it looks like a database page holding
  52620. ** no entries.
  52621. */
  52622. static void zeroPage(MemPage *pPage, int flags){
  52623. unsigned char *data = pPage->aData;
  52624. BtShared *pBt = pPage->pBt;
  52625. u8 hdr = pPage->hdrOffset;
  52626. u16 first;
  52627. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  52628. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  52629. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  52630. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52631. assert( sqlite3_mutex_held(pBt->mutex) );
  52632. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  52633. memset(&data[hdr], 0, pBt->usableSize - hdr);
  52634. }
  52635. data[hdr] = (char)flags;
  52636. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  52637. memset(&data[hdr+1], 0, 4);
  52638. data[hdr+7] = 0;
  52639. put2byte(&data[hdr+5], pBt->usableSize);
  52640. pPage->nFree = (u16)(pBt->usableSize - first);
  52641. decodeFlags(pPage, flags);
  52642. pPage->cellOffset = first;
  52643. pPage->aDataEnd = &data[pBt->usableSize];
  52644. pPage->aCellIdx = &data[first];
  52645. pPage->aDataOfst = &data[pPage->childPtrSize];
  52646. pPage->nOverflow = 0;
  52647. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  52648. pPage->maskPage = (u16)(pBt->pageSize - 1);
  52649. pPage->nCell = 0;
  52650. pPage->isInit = 1;
  52651. }
  52652. /*
  52653. ** Convert a DbPage obtained from the pager into a MemPage used by
  52654. ** the btree layer.
  52655. */
  52656. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  52657. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  52658. pPage->aData = sqlite3PagerGetData(pDbPage);
  52659. pPage->pDbPage = pDbPage;
  52660. pPage->pBt = pBt;
  52661. pPage->pgno = pgno;
  52662. pPage->hdrOffset = pgno==1 ? 100 : 0;
  52663. return pPage;
  52664. }
  52665. /*
  52666. ** Get a page from the pager. Initialize the MemPage.pBt and
  52667. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  52668. **
  52669. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  52670. ** about the content of the page at this time. So do not go to the disk
  52671. ** to fetch the content. Just fill in the content with zeros for now.
  52672. ** If in the future we call sqlite3PagerWrite() on this page, that
  52673. ** means we have started to be concerned about content and the disk
  52674. ** read should occur at that point.
  52675. */
  52676. static int btreeGetPage(
  52677. BtShared *pBt, /* The btree */
  52678. Pgno pgno, /* Number of the page to fetch */
  52679. MemPage **ppPage, /* Return the page in this parameter */
  52680. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  52681. ){
  52682. int rc;
  52683. DbPage *pDbPage;
  52684. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  52685. assert( sqlite3_mutex_held(pBt->mutex) );
  52686. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  52687. if( rc ) return rc;
  52688. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  52689. return SQLITE_OK;
  52690. }
  52691. /*
  52692. ** Retrieve a page from the pager cache. If the requested page is not
  52693. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  52694. ** MemPage.aData elements if needed.
  52695. */
  52696. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  52697. DbPage *pDbPage;
  52698. assert( sqlite3_mutex_held(pBt->mutex) );
  52699. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  52700. if( pDbPage ){
  52701. return btreePageFromDbPage(pDbPage, pgno, pBt);
  52702. }
  52703. return 0;
  52704. }
  52705. /*
  52706. ** Return the size of the database file in pages. If there is any kind of
  52707. ** error, return ((unsigned int)-1).
  52708. */
  52709. static Pgno btreePagecount(BtShared *pBt){
  52710. return pBt->nPage;
  52711. }
  52712. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  52713. assert( sqlite3BtreeHoldsMutex(p) );
  52714. assert( ((p->pBt->nPage)&0x8000000)==0 );
  52715. return btreePagecount(p->pBt);
  52716. }
  52717. /*
  52718. ** Get a page from the pager and initialize it.
  52719. **
  52720. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  52721. ** call. Do additional sanity checking on the page in this case.
  52722. ** And if the fetch fails, this routine must decrement pCur->iPage.
  52723. **
  52724. ** The page is fetched as read-write unless pCur is not NULL and is
  52725. ** a read-only cursor.
  52726. **
  52727. ** If an error occurs, then *ppPage is undefined. It
  52728. ** may remain unchanged, or it may be set to an invalid value.
  52729. */
  52730. static int getAndInitPage(
  52731. BtShared *pBt, /* The database file */
  52732. Pgno pgno, /* Number of the page to get */
  52733. MemPage **ppPage, /* Write the page pointer here */
  52734. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  52735. int bReadOnly /* True for a read-only page */
  52736. ){
  52737. int rc;
  52738. DbPage *pDbPage;
  52739. assert( sqlite3_mutex_held(pBt->mutex) );
  52740. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  52741. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  52742. assert( pCur==0 || pCur->iPage>0 );
  52743. if( pgno>btreePagecount(pBt) ){
  52744. rc = SQLITE_CORRUPT_BKPT;
  52745. goto getAndInitPage_error;
  52746. }
  52747. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  52748. if( rc ){
  52749. goto getAndInitPage_error;
  52750. }
  52751. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  52752. if( (*ppPage)->isInit==0 ){
  52753. rc = btreeInitPage(*ppPage);
  52754. if( rc!=SQLITE_OK ){
  52755. releasePage(*ppPage);
  52756. goto getAndInitPage_error;
  52757. }
  52758. }
  52759. /* If obtaining a child page for a cursor, we must verify that the page is
  52760. ** compatible with the root page. */
  52761. if( pCur
  52762. && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey)
  52763. ){
  52764. rc = SQLITE_CORRUPT_BKPT;
  52765. releasePage(*ppPage);
  52766. goto getAndInitPage_error;
  52767. }
  52768. return SQLITE_OK;
  52769. getAndInitPage_error:
  52770. if( pCur ) pCur->iPage--;
  52771. testcase( pgno==0 );
  52772. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  52773. return rc;
  52774. }
  52775. /*
  52776. ** Release a MemPage. This should be called once for each prior
  52777. ** call to btreeGetPage.
  52778. */
  52779. static void releasePageNotNull(MemPage *pPage){
  52780. assert( pPage->aData );
  52781. assert( pPage->pBt );
  52782. assert( pPage->pDbPage!=0 );
  52783. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  52784. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  52785. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52786. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  52787. }
  52788. static void releasePage(MemPage *pPage){
  52789. if( pPage ) releasePageNotNull(pPage);
  52790. }
  52791. /*
  52792. ** Get an unused page.
  52793. **
  52794. ** This works just like btreeGetPage() with the addition:
  52795. **
  52796. ** * If the page is already in use for some other purpose, immediately
  52797. ** release it and return an SQLITE_CURRUPT error.
  52798. ** * Make sure the isInit flag is clear
  52799. */
  52800. static int btreeGetUnusedPage(
  52801. BtShared *pBt, /* The btree */
  52802. Pgno pgno, /* Number of the page to fetch */
  52803. MemPage **ppPage, /* Return the page in this parameter */
  52804. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  52805. ){
  52806. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  52807. if( rc==SQLITE_OK ){
  52808. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  52809. releasePage(*ppPage);
  52810. *ppPage = 0;
  52811. return SQLITE_CORRUPT_BKPT;
  52812. }
  52813. (*ppPage)->isInit = 0;
  52814. }else{
  52815. *ppPage = 0;
  52816. }
  52817. return rc;
  52818. }
  52819. /*
  52820. ** During a rollback, when the pager reloads information into the cache
  52821. ** so that the cache is restored to its original state at the start of
  52822. ** the transaction, for each page restored this routine is called.
  52823. **
  52824. ** This routine needs to reset the extra data section at the end of the
  52825. ** page to agree with the restored data.
  52826. */
  52827. static void pageReinit(DbPage *pData){
  52828. MemPage *pPage;
  52829. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  52830. assert( sqlite3PagerPageRefcount(pData)>0 );
  52831. if( pPage->isInit ){
  52832. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52833. pPage->isInit = 0;
  52834. if( sqlite3PagerPageRefcount(pData)>1 ){
  52835. /* pPage might not be a btree page; it might be an overflow page
  52836. ** or ptrmap page or a free page. In those cases, the following
  52837. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  52838. ** But no harm is done by this. And it is very important that
  52839. ** btreeInitPage() be called on every btree page so we make
  52840. ** the call for every page that comes in for re-initing. */
  52841. btreeInitPage(pPage);
  52842. }
  52843. }
  52844. }
  52845. /*
  52846. ** Invoke the busy handler for a btree.
  52847. */
  52848. static int btreeInvokeBusyHandler(void *pArg){
  52849. BtShared *pBt = (BtShared*)pArg;
  52850. assert( pBt->db );
  52851. assert( sqlite3_mutex_held(pBt->db->mutex) );
  52852. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  52853. }
  52854. /*
  52855. ** Open a database file.
  52856. **
  52857. ** zFilename is the name of the database file. If zFilename is NULL
  52858. ** then an ephemeral database is created. The ephemeral database might
  52859. ** be exclusively in memory, or it might use a disk-based memory cache.
  52860. ** Either way, the ephemeral database will be automatically deleted
  52861. ** when sqlite3BtreeClose() is called.
  52862. **
  52863. ** If zFilename is ":memory:" then an in-memory database is created
  52864. ** that is automatically destroyed when it is closed.
  52865. **
  52866. ** The "flags" parameter is a bitmask that might contain bits like
  52867. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  52868. **
  52869. ** If the database is already opened in the same database connection
  52870. ** and we are in shared cache mode, then the open will fail with an
  52871. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  52872. ** objects in the same database connection since doing so will lead
  52873. ** to problems with locking.
  52874. */
  52875. SQLITE_PRIVATE int sqlite3BtreeOpen(
  52876. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  52877. const char *zFilename, /* Name of the file containing the BTree database */
  52878. sqlite3 *db, /* Associated database handle */
  52879. Btree **ppBtree, /* Pointer to new Btree object written here */
  52880. int flags, /* Options */
  52881. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  52882. ){
  52883. BtShared *pBt = 0; /* Shared part of btree structure */
  52884. Btree *p; /* Handle to return */
  52885. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  52886. int rc = SQLITE_OK; /* Result code from this function */
  52887. u8 nReserve; /* Byte of unused space on each page */
  52888. unsigned char zDbHeader[100]; /* Database header content */
  52889. /* True if opening an ephemeral, temporary database */
  52890. const int isTempDb = zFilename==0 || zFilename[0]==0;
  52891. /* Set the variable isMemdb to true for an in-memory database, or
  52892. ** false for a file-based database.
  52893. */
  52894. #ifdef SQLITE_OMIT_MEMORYDB
  52895. const int isMemdb = 0;
  52896. #else
  52897. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  52898. || (isTempDb && sqlite3TempInMemory(db))
  52899. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  52900. #endif
  52901. assert( db!=0 );
  52902. assert( pVfs!=0 );
  52903. assert( sqlite3_mutex_held(db->mutex) );
  52904. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  52905. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  52906. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  52907. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  52908. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  52909. if( isMemdb ){
  52910. flags |= BTREE_MEMORY;
  52911. }
  52912. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  52913. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  52914. }
  52915. p = sqlite3MallocZero(sizeof(Btree));
  52916. if( !p ){
  52917. return SQLITE_NOMEM;
  52918. }
  52919. p->inTrans = TRANS_NONE;
  52920. p->db = db;
  52921. #ifndef SQLITE_OMIT_SHARED_CACHE
  52922. p->lock.pBtree = p;
  52923. p->lock.iTable = 1;
  52924. #endif
  52925. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  52926. /*
  52927. ** If this Btree is a candidate for shared cache, try to find an
  52928. ** existing BtShared object that we can share with
  52929. */
  52930. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  52931. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  52932. int nFilename = sqlite3Strlen30(zFilename)+1;
  52933. int nFullPathname = pVfs->mxPathname+1;
  52934. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  52935. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  52936. p->sharable = 1;
  52937. if( !zFullPathname ){
  52938. sqlite3_free(p);
  52939. return SQLITE_NOMEM;
  52940. }
  52941. if( isMemdb ){
  52942. memcpy(zFullPathname, zFilename, nFilename);
  52943. }else{
  52944. rc = sqlite3OsFullPathname(pVfs, zFilename,
  52945. nFullPathname, zFullPathname);
  52946. if( rc ){
  52947. sqlite3_free(zFullPathname);
  52948. sqlite3_free(p);
  52949. return rc;
  52950. }
  52951. }
  52952. #if SQLITE_THREADSAFE
  52953. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  52954. sqlite3_mutex_enter(mutexOpen);
  52955. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  52956. sqlite3_mutex_enter(mutexShared);
  52957. #endif
  52958. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  52959. assert( pBt->nRef>0 );
  52960. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  52961. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  52962. int iDb;
  52963. for(iDb=db->nDb-1; iDb>=0; iDb--){
  52964. Btree *pExisting = db->aDb[iDb].pBt;
  52965. if( pExisting && pExisting->pBt==pBt ){
  52966. sqlite3_mutex_leave(mutexShared);
  52967. sqlite3_mutex_leave(mutexOpen);
  52968. sqlite3_free(zFullPathname);
  52969. sqlite3_free(p);
  52970. return SQLITE_CONSTRAINT;
  52971. }
  52972. }
  52973. p->pBt = pBt;
  52974. pBt->nRef++;
  52975. break;
  52976. }
  52977. }
  52978. sqlite3_mutex_leave(mutexShared);
  52979. sqlite3_free(zFullPathname);
  52980. }
  52981. #ifdef SQLITE_DEBUG
  52982. else{
  52983. /* In debug mode, we mark all persistent databases as sharable
  52984. ** even when they are not. This exercises the locking code and
  52985. ** gives more opportunity for asserts(sqlite3_mutex_held())
  52986. ** statements to find locking problems.
  52987. */
  52988. p->sharable = 1;
  52989. }
  52990. #endif
  52991. }
  52992. #endif
  52993. if( pBt==0 ){
  52994. /*
  52995. ** The following asserts make sure that structures used by the btree are
  52996. ** the right size. This is to guard against size changes that result
  52997. ** when compiling on a different architecture.
  52998. */
  52999. assert( sizeof(i64)==8 );
  53000. assert( sizeof(u64)==8 );
  53001. assert( sizeof(u32)==4 );
  53002. assert( sizeof(u16)==2 );
  53003. assert( sizeof(Pgno)==4 );
  53004. pBt = sqlite3MallocZero( sizeof(*pBt) );
  53005. if( pBt==0 ){
  53006. rc = SQLITE_NOMEM;
  53007. goto btree_open_out;
  53008. }
  53009. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  53010. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  53011. if( rc==SQLITE_OK ){
  53012. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  53013. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  53014. }
  53015. if( rc!=SQLITE_OK ){
  53016. goto btree_open_out;
  53017. }
  53018. pBt->openFlags = (u8)flags;
  53019. pBt->db = db;
  53020. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  53021. p->pBt = pBt;
  53022. pBt->pCursor = 0;
  53023. pBt->pPage1 = 0;
  53024. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  53025. #ifdef SQLITE_SECURE_DELETE
  53026. pBt->btsFlags |= BTS_SECURE_DELETE;
  53027. #endif
  53028. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  53029. ** determined by the 2-byte integer located at an offset of 16 bytes from
  53030. ** the beginning of the database file. */
  53031. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  53032. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  53033. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  53034. pBt->pageSize = 0;
  53035. #ifndef SQLITE_OMIT_AUTOVACUUM
  53036. /* If the magic name ":memory:" will create an in-memory database, then
  53037. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  53038. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  53039. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  53040. ** regular file-name. In this case the auto-vacuum applies as per normal.
  53041. */
  53042. if( zFilename && !isMemdb ){
  53043. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  53044. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  53045. }
  53046. #endif
  53047. nReserve = 0;
  53048. }else{
  53049. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  53050. ** determined by the one-byte unsigned integer found at an offset of 20
  53051. ** into the database file header. */
  53052. nReserve = zDbHeader[20];
  53053. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53054. #ifndef SQLITE_OMIT_AUTOVACUUM
  53055. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  53056. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  53057. #endif
  53058. }
  53059. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  53060. if( rc ) goto btree_open_out;
  53061. pBt->usableSize = pBt->pageSize - nReserve;
  53062. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  53063. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  53064. /* Add the new BtShared object to the linked list sharable BtShareds.
  53065. */
  53066. if( p->sharable ){
  53067. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  53068. pBt->nRef = 1;
  53069. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  53070. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  53071. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  53072. if( pBt->mutex==0 ){
  53073. rc = SQLITE_NOMEM;
  53074. db->mallocFailed = 0;
  53075. goto btree_open_out;
  53076. }
  53077. }
  53078. sqlite3_mutex_enter(mutexShared);
  53079. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  53080. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  53081. sqlite3_mutex_leave(mutexShared);
  53082. }
  53083. #endif
  53084. }
  53085. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  53086. /* If the new Btree uses a sharable pBtShared, then link the new
  53087. ** Btree into the list of all sharable Btrees for the same connection.
  53088. ** The list is kept in ascending order by pBt address.
  53089. */
  53090. if( p->sharable ){
  53091. int i;
  53092. Btree *pSib;
  53093. for(i=0; i<db->nDb; i++){
  53094. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  53095. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  53096. if( p->pBt<pSib->pBt ){
  53097. p->pNext = pSib;
  53098. p->pPrev = 0;
  53099. pSib->pPrev = p;
  53100. }else{
  53101. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  53102. pSib = pSib->pNext;
  53103. }
  53104. p->pNext = pSib->pNext;
  53105. p->pPrev = pSib;
  53106. if( p->pNext ){
  53107. p->pNext->pPrev = p;
  53108. }
  53109. pSib->pNext = p;
  53110. }
  53111. break;
  53112. }
  53113. }
  53114. }
  53115. #endif
  53116. *ppBtree = p;
  53117. btree_open_out:
  53118. if( rc!=SQLITE_OK ){
  53119. if( pBt && pBt->pPager ){
  53120. sqlite3PagerClose(pBt->pPager);
  53121. }
  53122. sqlite3_free(pBt);
  53123. sqlite3_free(p);
  53124. *ppBtree = 0;
  53125. }else{
  53126. /* If the B-Tree was successfully opened, set the pager-cache size to the
  53127. ** default value. Except, when opening on an existing shared pager-cache,
  53128. ** do not change the pager-cache size.
  53129. */
  53130. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  53131. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  53132. }
  53133. }
  53134. if( mutexOpen ){
  53135. assert( sqlite3_mutex_held(mutexOpen) );
  53136. sqlite3_mutex_leave(mutexOpen);
  53137. }
  53138. return rc;
  53139. }
  53140. /*
  53141. ** Decrement the BtShared.nRef counter. When it reaches zero,
  53142. ** remove the BtShared structure from the sharing list. Return
  53143. ** true if the BtShared.nRef counter reaches zero and return
  53144. ** false if it is still positive.
  53145. */
  53146. static int removeFromSharingList(BtShared *pBt){
  53147. #ifndef SQLITE_OMIT_SHARED_CACHE
  53148. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  53149. BtShared *pList;
  53150. int removed = 0;
  53151. assert( sqlite3_mutex_notheld(pBt->mutex) );
  53152. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  53153. sqlite3_mutex_enter(pMaster);
  53154. pBt->nRef--;
  53155. if( pBt->nRef<=0 ){
  53156. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  53157. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  53158. }else{
  53159. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  53160. while( ALWAYS(pList) && pList->pNext!=pBt ){
  53161. pList=pList->pNext;
  53162. }
  53163. if( ALWAYS(pList) ){
  53164. pList->pNext = pBt->pNext;
  53165. }
  53166. }
  53167. if( SQLITE_THREADSAFE ){
  53168. sqlite3_mutex_free(pBt->mutex);
  53169. }
  53170. removed = 1;
  53171. }
  53172. sqlite3_mutex_leave(pMaster);
  53173. return removed;
  53174. #else
  53175. return 1;
  53176. #endif
  53177. }
  53178. /*
  53179. ** Make sure pBt->pTmpSpace points to an allocation of
  53180. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  53181. ** pointer.
  53182. */
  53183. static void allocateTempSpace(BtShared *pBt){
  53184. if( !pBt->pTmpSpace ){
  53185. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  53186. /* One of the uses of pBt->pTmpSpace is to format cells before
  53187. ** inserting them into a leaf page (function fillInCell()). If
  53188. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  53189. ** by the various routines that manipulate binary cells. Which
  53190. ** can mean that fillInCell() only initializes the first 2 or 3
  53191. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  53192. ** it into a database page. This is not actually a problem, but it
  53193. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  53194. ** data is passed to system call write(). So to avoid this error,
  53195. ** zero the first 4 bytes of temp space here.
  53196. **
  53197. ** Also: Provide four bytes of initialized space before the
  53198. ** beginning of pTmpSpace as an area available to prepend the
  53199. ** left-child pointer to the beginning of a cell.
  53200. */
  53201. if( pBt->pTmpSpace ){
  53202. memset(pBt->pTmpSpace, 0, 8);
  53203. pBt->pTmpSpace += 4;
  53204. }
  53205. }
  53206. }
  53207. /*
  53208. ** Free the pBt->pTmpSpace allocation
  53209. */
  53210. static void freeTempSpace(BtShared *pBt){
  53211. if( pBt->pTmpSpace ){
  53212. pBt->pTmpSpace -= 4;
  53213. sqlite3PageFree(pBt->pTmpSpace);
  53214. pBt->pTmpSpace = 0;
  53215. }
  53216. }
  53217. /*
  53218. ** Close an open database and invalidate all cursors.
  53219. */
  53220. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  53221. BtShared *pBt = p->pBt;
  53222. BtCursor *pCur;
  53223. /* Close all cursors opened via this handle. */
  53224. assert( sqlite3_mutex_held(p->db->mutex) );
  53225. sqlite3BtreeEnter(p);
  53226. pCur = pBt->pCursor;
  53227. while( pCur ){
  53228. BtCursor *pTmp = pCur;
  53229. pCur = pCur->pNext;
  53230. if( pTmp->pBtree==p ){
  53231. sqlite3BtreeCloseCursor(pTmp);
  53232. }
  53233. }
  53234. /* Rollback any active transaction and free the handle structure.
  53235. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  53236. ** this handle.
  53237. */
  53238. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  53239. sqlite3BtreeLeave(p);
  53240. /* If there are still other outstanding references to the shared-btree
  53241. ** structure, return now. The remainder of this procedure cleans
  53242. ** up the shared-btree.
  53243. */
  53244. assert( p->wantToLock==0 && p->locked==0 );
  53245. if( !p->sharable || removeFromSharingList(pBt) ){
  53246. /* The pBt is no longer on the sharing list, so we can access
  53247. ** it without having to hold the mutex.
  53248. **
  53249. ** Clean out and delete the BtShared object.
  53250. */
  53251. assert( !pBt->pCursor );
  53252. sqlite3PagerClose(pBt->pPager);
  53253. if( pBt->xFreeSchema && pBt->pSchema ){
  53254. pBt->xFreeSchema(pBt->pSchema);
  53255. }
  53256. sqlite3DbFree(0, pBt->pSchema);
  53257. freeTempSpace(pBt);
  53258. sqlite3_free(pBt);
  53259. }
  53260. #ifndef SQLITE_OMIT_SHARED_CACHE
  53261. assert( p->wantToLock==0 );
  53262. assert( p->locked==0 );
  53263. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  53264. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  53265. #endif
  53266. sqlite3_free(p);
  53267. return SQLITE_OK;
  53268. }
  53269. /*
  53270. ** Change the limit on the number of pages allowed in the cache.
  53271. **
  53272. ** The maximum number of cache pages is set to the absolute
  53273. ** value of mxPage. If mxPage is negative, the pager will
  53274. ** operate asynchronously - it will not stop to do fsync()s
  53275. ** to insure data is written to the disk surface before
  53276. ** continuing. Transactions still work if synchronous is off,
  53277. ** and the database cannot be corrupted if this program
  53278. ** crashes. But if the operating system crashes or there is
  53279. ** an abrupt power failure when synchronous is off, the database
  53280. ** could be left in an inconsistent and unrecoverable state.
  53281. ** Synchronous is on by default so database corruption is not
  53282. ** normally a worry.
  53283. */
  53284. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  53285. BtShared *pBt = p->pBt;
  53286. assert( sqlite3_mutex_held(p->db->mutex) );
  53287. sqlite3BtreeEnter(p);
  53288. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  53289. sqlite3BtreeLeave(p);
  53290. return SQLITE_OK;
  53291. }
  53292. #if SQLITE_MAX_MMAP_SIZE>0
  53293. /*
  53294. ** Change the limit on the amount of the database file that may be
  53295. ** memory mapped.
  53296. */
  53297. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  53298. BtShared *pBt = p->pBt;
  53299. assert( sqlite3_mutex_held(p->db->mutex) );
  53300. sqlite3BtreeEnter(p);
  53301. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  53302. sqlite3BtreeLeave(p);
  53303. return SQLITE_OK;
  53304. }
  53305. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  53306. /*
  53307. ** Change the way data is synced to disk in order to increase or decrease
  53308. ** how well the database resists damage due to OS crashes and power
  53309. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  53310. ** there is a high probability of damage) Level 2 is the default. There
  53311. ** is a very low but non-zero probability of damage. Level 3 reduces the
  53312. ** probability of damage to near zero but with a write performance reduction.
  53313. */
  53314. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  53315. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  53316. Btree *p, /* The btree to set the safety level on */
  53317. unsigned pgFlags /* Various PAGER_* flags */
  53318. ){
  53319. BtShared *pBt = p->pBt;
  53320. assert( sqlite3_mutex_held(p->db->mutex) );
  53321. sqlite3BtreeEnter(p);
  53322. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  53323. sqlite3BtreeLeave(p);
  53324. return SQLITE_OK;
  53325. }
  53326. #endif
  53327. /*
  53328. ** Return TRUE if the given btree is set to safety level 1. In other
  53329. ** words, return TRUE if no sync() occurs on the disk files.
  53330. */
  53331. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  53332. BtShared *pBt = p->pBt;
  53333. int rc;
  53334. assert( sqlite3_mutex_held(p->db->mutex) );
  53335. sqlite3BtreeEnter(p);
  53336. assert( pBt && pBt->pPager );
  53337. rc = sqlite3PagerNosync(pBt->pPager);
  53338. sqlite3BtreeLeave(p);
  53339. return rc;
  53340. }
  53341. /*
  53342. ** Change the default pages size and the number of reserved bytes per page.
  53343. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  53344. ** without changing anything.
  53345. **
  53346. ** The page size must be a power of 2 between 512 and 65536. If the page
  53347. ** size supplied does not meet this constraint then the page size is not
  53348. ** changed.
  53349. **
  53350. ** Page sizes are constrained to be a power of two so that the region
  53351. ** of the database file used for locking (beginning at PENDING_BYTE,
  53352. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  53353. ** at the beginning of a page.
  53354. **
  53355. ** If parameter nReserve is less than zero, then the number of reserved
  53356. ** bytes per page is left unchanged.
  53357. **
  53358. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  53359. ** and autovacuum mode can no longer be changed.
  53360. */
  53361. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  53362. int rc = SQLITE_OK;
  53363. BtShared *pBt = p->pBt;
  53364. assert( nReserve>=-1 && nReserve<=255 );
  53365. sqlite3BtreeEnter(p);
  53366. #if SQLITE_HAS_CODEC
  53367. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  53368. #endif
  53369. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  53370. sqlite3BtreeLeave(p);
  53371. return SQLITE_READONLY;
  53372. }
  53373. if( nReserve<0 ){
  53374. nReserve = pBt->pageSize - pBt->usableSize;
  53375. }
  53376. assert( nReserve>=0 && nReserve<=255 );
  53377. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  53378. ((pageSize-1)&pageSize)==0 ){
  53379. assert( (pageSize & 7)==0 );
  53380. assert( !pBt->pCursor );
  53381. pBt->pageSize = (u32)pageSize;
  53382. freeTempSpace(pBt);
  53383. }
  53384. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  53385. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  53386. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53387. sqlite3BtreeLeave(p);
  53388. return rc;
  53389. }
  53390. /*
  53391. ** Return the currently defined page size
  53392. */
  53393. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  53394. return p->pBt->pageSize;
  53395. }
  53396. /*
  53397. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  53398. ** may only be called if it is guaranteed that the b-tree mutex is already
  53399. ** held.
  53400. **
  53401. ** This is useful in one special case in the backup API code where it is
  53402. ** known that the shared b-tree mutex is held, but the mutex on the
  53403. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  53404. ** were to be called, it might collide with some other operation on the
  53405. ** database handle that owns *p, causing undefined behavior.
  53406. */
  53407. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  53408. int n;
  53409. assert( sqlite3_mutex_held(p->pBt->mutex) );
  53410. n = p->pBt->pageSize - p->pBt->usableSize;
  53411. return n;
  53412. }
  53413. /*
  53414. ** Return the number of bytes of space at the end of every page that
  53415. ** are intentually left unused. This is the "reserved" space that is
  53416. ** sometimes used by extensions.
  53417. **
  53418. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  53419. ** greater of the current reserved space and the maximum requested
  53420. ** reserve space.
  53421. */
  53422. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  53423. int n;
  53424. sqlite3BtreeEnter(p);
  53425. n = sqlite3BtreeGetReserveNoMutex(p);
  53426. #ifdef SQLITE_HAS_CODEC
  53427. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  53428. #endif
  53429. sqlite3BtreeLeave(p);
  53430. return n;
  53431. }
  53432. /*
  53433. ** Set the maximum page count for a database if mxPage is positive.
  53434. ** No changes are made if mxPage is 0 or negative.
  53435. ** Regardless of the value of mxPage, return the maximum page count.
  53436. */
  53437. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  53438. int n;
  53439. sqlite3BtreeEnter(p);
  53440. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  53441. sqlite3BtreeLeave(p);
  53442. return n;
  53443. }
  53444. /*
  53445. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  53446. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  53447. ** setting after the change.
  53448. */
  53449. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  53450. int b;
  53451. if( p==0 ) return 0;
  53452. sqlite3BtreeEnter(p);
  53453. if( newFlag>=0 ){
  53454. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  53455. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  53456. }
  53457. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  53458. sqlite3BtreeLeave(p);
  53459. return b;
  53460. }
  53461. /*
  53462. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  53463. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  53464. ** is disabled. The default value for the auto-vacuum property is
  53465. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  53466. */
  53467. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  53468. #ifdef SQLITE_OMIT_AUTOVACUUM
  53469. return SQLITE_READONLY;
  53470. #else
  53471. BtShared *pBt = p->pBt;
  53472. int rc = SQLITE_OK;
  53473. u8 av = (u8)autoVacuum;
  53474. sqlite3BtreeEnter(p);
  53475. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  53476. rc = SQLITE_READONLY;
  53477. }else{
  53478. pBt->autoVacuum = av ?1:0;
  53479. pBt->incrVacuum = av==2 ?1:0;
  53480. }
  53481. sqlite3BtreeLeave(p);
  53482. return rc;
  53483. #endif
  53484. }
  53485. /*
  53486. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  53487. ** enabled 1 is returned. Otherwise 0.
  53488. */
  53489. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  53490. #ifdef SQLITE_OMIT_AUTOVACUUM
  53491. return BTREE_AUTOVACUUM_NONE;
  53492. #else
  53493. int rc;
  53494. sqlite3BtreeEnter(p);
  53495. rc = (
  53496. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  53497. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  53498. BTREE_AUTOVACUUM_INCR
  53499. );
  53500. sqlite3BtreeLeave(p);
  53501. return rc;
  53502. #endif
  53503. }
  53504. /*
  53505. ** Get a reference to pPage1 of the database file. This will
  53506. ** also acquire a readlock on that file.
  53507. **
  53508. ** SQLITE_OK is returned on success. If the file is not a
  53509. ** well-formed database file, then SQLITE_CORRUPT is returned.
  53510. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  53511. ** is returned if we run out of memory.
  53512. */
  53513. static int lockBtree(BtShared *pBt){
  53514. int rc; /* Result code from subfunctions */
  53515. MemPage *pPage1; /* Page 1 of the database file */
  53516. int nPage; /* Number of pages in the database */
  53517. int nPageFile = 0; /* Number of pages in the database file */
  53518. int nPageHeader; /* Number of pages in the database according to hdr */
  53519. assert( sqlite3_mutex_held(pBt->mutex) );
  53520. assert( pBt->pPage1==0 );
  53521. rc = sqlite3PagerSharedLock(pBt->pPager);
  53522. if( rc!=SQLITE_OK ) return rc;
  53523. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  53524. if( rc!=SQLITE_OK ) return rc;
  53525. /* Do some checking to help insure the file we opened really is
  53526. ** a valid database file.
  53527. */
  53528. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  53529. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  53530. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  53531. nPage = nPageFile;
  53532. }
  53533. if( nPage>0 ){
  53534. u32 pageSize;
  53535. u32 usableSize;
  53536. u8 *page1 = pPage1->aData;
  53537. rc = SQLITE_NOTADB;
  53538. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  53539. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  53540. ** 61 74 20 33 00. */
  53541. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  53542. goto page1_init_failed;
  53543. }
  53544. #ifdef SQLITE_OMIT_WAL
  53545. if( page1[18]>1 ){
  53546. pBt->btsFlags |= BTS_READ_ONLY;
  53547. }
  53548. if( page1[19]>1 ){
  53549. goto page1_init_failed;
  53550. }
  53551. #else
  53552. if( page1[18]>2 ){
  53553. pBt->btsFlags |= BTS_READ_ONLY;
  53554. }
  53555. if( page1[19]>2 ){
  53556. goto page1_init_failed;
  53557. }
  53558. /* If the write version is set to 2, this database should be accessed
  53559. ** in WAL mode. If the log is not already open, open it now. Then
  53560. ** return SQLITE_OK and return without populating BtShared.pPage1.
  53561. ** The caller detects this and calls this function again. This is
  53562. ** required as the version of page 1 currently in the page1 buffer
  53563. ** may not be the latest version - there may be a newer one in the log
  53564. ** file.
  53565. */
  53566. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  53567. int isOpen = 0;
  53568. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  53569. if( rc!=SQLITE_OK ){
  53570. goto page1_init_failed;
  53571. }else if( isOpen==0 ){
  53572. releasePage(pPage1);
  53573. return SQLITE_OK;
  53574. }
  53575. rc = SQLITE_NOTADB;
  53576. }
  53577. #endif
  53578. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  53579. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  53580. **
  53581. ** The original design allowed these amounts to vary, but as of
  53582. ** version 3.6.0, we require them to be fixed.
  53583. */
  53584. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  53585. goto page1_init_failed;
  53586. }
  53587. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  53588. ** determined by the 2-byte integer located at an offset of 16 bytes from
  53589. ** the beginning of the database file. */
  53590. pageSize = (page1[16]<<8) | (page1[17]<<16);
  53591. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  53592. ** between 512 and 65536 inclusive. */
  53593. if( ((pageSize-1)&pageSize)!=0
  53594. || pageSize>SQLITE_MAX_PAGE_SIZE
  53595. || pageSize<=256
  53596. ){
  53597. goto page1_init_failed;
  53598. }
  53599. assert( (pageSize & 7)==0 );
  53600. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  53601. ** integer at offset 20 is the number of bytes of space at the end of
  53602. ** each page to reserve for extensions.
  53603. **
  53604. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  53605. ** determined by the one-byte unsigned integer found at an offset of 20
  53606. ** into the database file header. */
  53607. usableSize = pageSize - page1[20];
  53608. if( (u32)pageSize!=pBt->pageSize ){
  53609. /* After reading the first page of the database assuming a page size
  53610. ** of BtShared.pageSize, we have discovered that the page-size is
  53611. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  53612. ** zero and return SQLITE_OK. The caller will call this function
  53613. ** again with the correct page-size.
  53614. */
  53615. releasePage(pPage1);
  53616. pBt->usableSize = usableSize;
  53617. pBt->pageSize = pageSize;
  53618. freeTempSpace(pBt);
  53619. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  53620. pageSize-usableSize);
  53621. return rc;
  53622. }
  53623. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  53624. rc = SQLITE_CORRUPT_BKPT;
  53625. goto page1_init_failed;
  53626. }
  53627. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  53628. ** be less than 480. In other words, if the page size is 512, then the
  53629. ** reserved space size cannot exceed 32. */
  53630. if( usableSize<480 ){
  53631. goto page1_init_failed;
  53632. }
  53633. pBt->pageSize = pageSize;
  53634. pBt->usableSize = usableSize;
  53635. #ifndef SQLITE_OMIT_AUTOVACUUM
  53636. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  53637. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  53638. #endif
  53639. }
  53640. /* maxLocal is the maximum amount of payload to store locally for
  53641. ** a cell. Make sure it is small enough so that at least minFanout
  53642. ** cells can will fit on one page. We assume a 10-byte page header.
  53643. ** Besides the payload, the cell must store:
  53644. ** 2-byte pointer to the cell
  53645. ** 4-byte child pointer
  53646. ** 9-byte nKey value
  53647. ** 4-byte nData value
  53648. ** 4-byte overflow page pointer
  53649. ** So a cell consists of a 2-byte pointer, a header which is as much as
  53650. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  53651. ** page pointer.
  53652. */
  53653. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  53654. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  53655. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  53656. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  53657. if( pBt->maxLocal>127 ){
  53658. pBt->max1bytePayload = 127;
  53659. }else{
  53660. pBt->max1bytePayload = (u8)pBt->maxLocal;
  53661. }
  53662. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  53663. pBt->pPage1 = pPage1;
  53664. pBt->nPage = nPage;
  53665. return SQLITE_OK;
  53666. page1_init_failed:
  53667. releasePage(pPage1);
  53668. pBt->pPage1 = 0;
  53669. return rc;
  53670. }
  53671. #ifndef NDEBUG
  53672. /*
  53673. ** Return the number of cursors open on pBt. This is for use
  53674. ** in assert() expressions, so it is only compiled if NDEBUG is not
  53675. ** defined.
  53676. **
  53677. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  53678. ** false then all cursors are counted.
  53679. **
  53680. ** For the purposes of this routine, a cursor is any cursor that
  53681. ** is capable of reading or writing to the database. Cursors that
  53682. ** have been tripped into the CURSOR_FAULT state are not counted.
  53683. */
  53684. static int countValidCursors(BtShared *pBt, int wrOnly){
  53685. BtCursor *pCur;
  53686. int r = 0;
  53687. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  53688. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  53689. && pCur->eState!=CURSOR_FAULT ) r++;
  53690. }
  53691. return r;
  53692. }
  53693. #endif
  53694. /*
  53695. ** If there are no outstanding cursors and we are not in the middle
  53696. ** of a transaction but there is a read lock on the database, then
  53697. ** this routine unrefs the first page of the database file which
  53698. ** has the effect of releasing the read lock.
  53699. **
  53700. ** If there is a transaction in progress, this routine is a no-op.
  53701. */
  53702. static void unlockBtreeIfUnused(BtShared *pBt){
  53703. assert( sqlite3_mutex_held(pBt->mutex) );
  53704. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  53705. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  53706. MemPage *pPage1 = pBt->pPage1;
  53707. assert( pPage1->aData );
  53708. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  53709. pBt->pPage1 = 0;
  53710. releasePageNotNull(pPage1);
  53711. }
  53712. }
  53713. /*
  53714. ** If pBt points to an empty file then convert that empty file
  53715. ** into a new empty database by initializing the first page of
  53716. ** the database.
  53717. */
  53718. static int newDatabase(BtShared *pBt){
  53719. MemPage *pP1;
  53720. unsigned char *data;
  53721. int rc;
  53722. assert( sqlite3_mutex_held(pBt->mutex) );
  53723. if( pBt->nPage>0 ){
  53724. return SQLITE_OK;
  53725. }
  53726. pP1 = pBt->pPage1;
  53727. assert( pP1!=0 );
  53728. data = pP1->aData;
  53729. rc = sqlite3PagerWrite(pP1->pDbPage);
  53730. if( rc ) return rc;
  53731. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  53732. assert( sizeof(zMagicHeader)==16 );
  53733. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  53734. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  53735. data[18] = 1;
  53736. data[19] = 1;
  53737. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  53738. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  53739. data[21] = 64;
  53740. data[22] = 32;
  53741. data[23] = 32;
  53742. memset(&data[24], 0, 100-24);
  53743. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  53744. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53745. #ifndef SQLITE_OMIT_AUTOVACUUM
  53746. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  53747. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  53748. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  53749. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  53750. #endif
  53751. pBt->nPage = 1;
  53752. data[31] = 1;
  53753. return SQLITE_OK;
  53754. }
  53755. /*
  53756. ** Initialize the first page of the database file (creating a database
  53757. ** consisting of a single page and no schema objects). Return SQLITE_OK
  53758. ** if successful, or an SQLite error code otherwise.
  53759. */
  53760. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  53761. int rc;
  53762. sqlite3BtreeEnter(p);
  53763. p->pBt->nPage = 0;
  53764. rc = newDatabase(p->pBt);
  53765. sqlite3BtreeLeave(p);
  53766. return rc;
  53767. }
  53768. /*
  53769. ** Attempt to start a new transaction. A write-transaction
  53770. ** is started if the second argument is nonzero, otherwise a read-
  53771. ** transaction. If the second argument is 2 or more and exclusive
  53772. ** transaction is started, meaning that no other process is allowed
  53773. ** to access the database. A preexisting transaction may not be
  53774. ** upgraded to exclusive by calling this routine a second time - the
  53775. ** exclusivity flag only works for a new transaction.
  53776. **
  53777. ** A write-transaction must be started before attempting any
  53778. ** changes to the database. None of the following routines
  53779. ** will work unless a transaction is started first:
  53780. **
  53781. ** sqlite3BtreeCreateTable()
  53782. ** sqlite3BtreeCreateIndex()
  53783. ** sqlite3BtreeClearTable()
  53784. ** sqlite3BtreeDropTable()
  53785. ** sqlite3BtreeInsert()
  53786. ** sqlite3BtreeDelete()
  53787. ** sqlite3BtreeUpdateMeta()
  53788. **
  53789. ** If an initial attempt to acquire the lock fails because of lock contention
  53790. ** and the database was previously unlocked, then invoke the busy handler
  53791. ** if there is one. But if there was previously a read-lock, do not
  53792. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  53793. ** returned when there is already a read-lock in order to avoid a deadlock.
  53794. **
  53795. ** Suppose there are two processes A and B. A has a read lock and B has
  53796. ** a reserved lock. B tries to promote to exclusive but is blocked because
  53797. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  53798. ** One or the other of the two processes must give way or there can be
  53799. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  53800. ** when A already has a read lock, we encourage A to give up and let B
  53801. ** proceed.
  53802. */
  53803. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  53804. sqlite3 *pBlock = 0;
  53805. BtShared *pBt = p->pBt;
  53806. int rc = SQLITE_OK;
  53807. sqlite3BtreeEnter(p);
  53808. btreeIntegrity(p);
  53809. /* If the btree is already in a write-transaction, or it
  53810. ** is already in a read-transaction and a read-transaction
  53811. ** is requested, this is a no-op.
  53812. */
  53813. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  53814. goto trans_begun;
  53815. }
  53816. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  53817. /* Write transactions are not possible on a read-only database */
  53818. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  53819. rc = SQLITE_READONLY;
  53820. goto trans_begun;
  53821. }
  53822. #ifndef SQLITE_OMIT_SHARED_CACHE
  53823. /* If another database handle has already opened a write transaction
  53824. ** on this shared-btree structure and a second write transaction is
  53825. ** requested, return SQLITE_LOCKED.
  53826. */
  53827. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  53828. || (pBt->btsFlags & BTS_PENDING)!=0
  53829. ){
  53830. pBlock = pBt->pWriter->db;
  53831. }else if( wrflag>1 ){
  53832. BtLock *pIter;
  53833. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  53834. if( pIter->pBtree!=p ){
  53835. pBlock = pIter->pBtree->db;
  53836. break;
  53837. }
  53838. }
  53839. }
  53840. if( pBlock ){
  53841. sqlite3ConnectionBlocked(p->db, pBlock);
  53842. rc = SQLITE_LOCKED_SHAREDCACHE;
  53843. goto trans_begun;
  53844. }
  53845. #endif
  53846. /* Any read-only or read-write transaction implies a read-lock on
  53847. ** page 1. So if some other shared-cache client already has a write-lock
  53848. ** on page 1, the transaction cannot be opened. */
  53849. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  53850. if( SQLITE_OK!=rc ) goto trans_begun;
  53851. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  53852. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  53853. do {
  53854. /* Call lockBtree() until either pBt->pPage1 is populated or
  53855. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  53856. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  53857. ** reading page 1 it discovers that the page-size of the database
  53858. ** file is not pBt->pageSize. In this case lockBtree() will update
  53859. ** pBt->pageSize to the page-size of the file on disk.
  53860. */
  53861. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  53862. if( rc==SQLITE_OK && wrflag ){
  53863. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  53864. rc = SQLITE_READONLY;
  53865. }else{
  53866. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  53867. if( rc==SQLITE_OK ){
  53868. rc = newDatabase(pBt);
  53869. }
  53870. }
  53871. }
  53872. if( rc!=SQLITE_OK ){
  53873. unlockBtreeIfUnused(pBt);
  53874. }
  53875. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  53876. btreeInvokeBusyHandler(pBt) );
  53877. if( rc==SQLITE_OK ){
  53878. if( p->inTrans==TRANS_NONE ){
  53879. pBt->nTransaction++;
  53880. #ifndef SQLITE_OMIT_SHARED_CACHE
  53881. if( p->sharable ){
  53882. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  53883. p->lock.eLock = READ_LOCK;
  53884. p->lock.pNext = pBt->pLock;
  53885. pBt->pLock = &p->lock;
  53886. }
  53887. #endif
  53888. }
  53889. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  53890. if( p->inTrans>pBt->inTransaction ){
  53891. pBt->inTransaction = p->inTrans;
  53892. }
  53893. if( wrflag ){
  53894. MemPage *pPage1 = pBt->pPage1;
  53895. #ifndef SQLITE_OMIT_SHARED_CACHE
  53896. assert( !pBt->pWriter );
  53897. pBt->pWriter = p;
  53898. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  53899. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  53900. #endif
  53901. /* If the db-size header field is incorrect (as it may be if an old
  53902. ** client has been writing the database file), update it now. Doing
  53903. ** this sooner rather than later means the database size can safely
  53904. ** re-read the database size from page 1 if a savepoint or transaction
  53905. ** rollback occurs within the transaction.
  53906. */
  53907. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  53908. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53909. if( rc==SQLITE_OK ){
  53910. put4byte(&pPage1->aData[28], pBt->nPage);
  53911. }
  53912. }
  53913. }
  53914. }
  53915. trans_begun:
  53916. if( rc==SQLITE_OK && wrflag ){
  53917. /* This call makes sure that the pager has the correct number of
  53918. ** open savepoints. If the second parameter is greater than 0 and
  53919. ** the sub-journal is not already open, then it will be opened here.
  53920. */
  53921. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  53922. }
  53923. btreeIntegrity(p);
  53924. sqlite3BtreeLeave(p);
  53925. return rc;
  53926. }
  53927. #ifndef SQLITE_OMIT_AUTOVACUUM
  53928. /*
  53929. ** Set the pointer-map entries for all children of page pPage. Also, if
  53930. ** pPage contains cells that point to overflow pages, set the pointer
  53931. ** map entries for the overflow pages as well.
  53932. */
  53933. static int setChildPtrmaps(MemPage *pPage){
  53934. int i; /* Counter variable */
  53935. int nCell; /* Number of cells in page pPage */
  53936. int rc; /* Return code */
  53937. BtShared *pBt = pPage->pBt;
  53938. u8 isInitOrig = pPage->isInit;
  53939. Pgno pgno = pPage->pgno;
  53940. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53941. rc = btreeInitPage(pPage);
  53942. if( rc!=SQLITE_OK ){
  53943. goto set_child_ptrmaps_out;
  53944. }
  53945. nCell = pPage->nCell;
  53946. for(i=0; i<nCell; i++){
  53947. u8 *pCell = findCell(pPage, i);
  53948. ptrmapPutOvflPtr(pPage, pCell, &rc);
  53949. if( !pPage->leaf ){
  53950. Pgno childPgno = get4byte(pCell);
  53951. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  53952. }
  53953. }
  53954. if( !pPage->leaf ){
  53955. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53956. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  53957. }
  53958. set_child_ptrmaps_out:
  53959. pPage->isInit = isInitOrig;
  53960. return rc;
  53961. }
  53962. /*
  53963. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  53964. ** that it points to iTo. Parameter eType describes the type of pointer to
  53965. ** be modified, as follows:
  53966. **
  53967. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  53968. ** page of pPage.
  53969. **
  53970. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  53971. ** page pointed to by one of the cells on pPage.
  53972. **
  53973. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  53974. ** overflow page in the list.
  53975. */
  53976. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  53977. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53978. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53979. if( eType==PTRMAP_OVERFLOW2 ){
  53980. /* The pointer is always the first 4 bytes of the page in this case. */
  53981. if( get4byte(pPage->aData)!=iFrom ){
  53982. return SQLITE_CORRUPT_BKPT;
  53983. }
  53984. put4byte(pPage->aData, iTo);
  53985. }else{
  53986. u8 isInitOrig = pPage->isInit;
  53987. int i;
  53988. int nCell;
  53989. int rc;
  53990. rc = btreeInitPage(pPage);
  53991. if( rc ) return rc;
  53992. nCell = pPage->nCell;
  53993. for(i=0; i<nCell; i++){
  53994. u8 *pCell = findCell(pPage, i);
  53995. if( eType==PTRMAP_OVERFLOW1 ){
  53996. CellInfo info;
  53997. pPage->xParseCell(pPage, pCell, &info);
  53998. if( info.iOverflow
  53999. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  54000. && iFrom==get4byte(&pCell[info.iOverflow])
  54001. ){
  54002. put4byte(&pCell[info.iOverflow], iTo);
  54003. break;
  54004. }
  54005. }else{
  54006. if( get4byte(pCell)==iFrom ){
  54007. put4byte(pCell, iTo);
  54008. break;
  54009. }
  54010. }
  54011. }
  54012. if( i==nCell ){
  54013. if( eType!=PTRMAP_BTREE ||
  54014. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  54015. return SQLITE_CORRUPT_BKPT;
  54016. }
  54017. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  54018. }
  54019. pPage->isInit = isInitOrig;
  54020. }
  54021. return SQLITE_OK;
  54022. }
  54023. /*
  54024. ** Move the open database page pDbPage to location iFreePage in the
  54025. ** database. The pDbPage reference remains valid.
  54026. **
  54027. ** The isCommit flag indicates that there is no need to remember that
  54028. ** the journal needs to be sync()ed before database page pDbPage->pgno
  54029. ** can be written to. The caller has already promised not to write to that
  54030. ** page.
  54031. */
  54032. static int relocatePage(
  54033. BtShared *pBt, /* Btree */
  54034. MemPage *pDbPage, /* Open page to move */
  54035. u8 eType, /* Pointer map 'type' entry for pDbPage */
  54036. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  54037. Pgno iFreePage, /* The location to move pDbPage to */
  54038. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  54039. ){
  54040. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  54041. Pgno iDbPage = pDbPage->pgno;
  54042. Pager *pPager = pBt->pPager;
  54043. int rc;
  54044. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  54045. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  54046. assert( sqlite3_mutex_held(pBt->mutex) );
  54047. assert( pDbPage->pBt==pBt );
  54048. /* Move page iDbPage from its current location to page number iFreePage */
  54049. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  54050. iDbPage, iFreePage, iPtrPage, eType));
  54051. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  54052. if( rc!=SQLITE_OK ){
  54053. return rc;
  54054. }
  54055. pDbPage->pgno = iFreePage;
  54056. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  54057. ** that point to overflow pages. The pointer map entries for all these
  54058. ** pages need to be changed.
  54059. **
  54060. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  54061. ** pointer to a subsequent overflow page. If this is the case, then
  54062. ** the pointer map needs to be updated for the subsequent overflow page.
  54063. */
  54064. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  54065. rc = setChildPtrmaps(pDbPage);
  54066. if( rc!=SQLITE_OK ){
  54067. return rc;
  54068. }
  54069. }else{
  54070. Pgno nextOvfl = get4byte(pDbPage->aData);
  54071. if( nextOvfl!=0 ){
  54072. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  54073. if( rc!=SQLITE_OK ){
  54074. return rc;
  54075. }
  54076. }
  54077. }
  54078. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  54079. ** that it points at iFreePage. Also fix the pointer map entry for
  54080. ** iPtrPage.
  54081. */
  54082. if( eType!=PTRMAP_ROOTPAGE ){
  54083. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  54084. if( rc!=SQLITE_OK ){
  54085. return rc;
  54086. }
  54087. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  54088. if( rc!=SQLITE_OK ){
  54089. releasePage(pPtrPage);
  54090. return rc;
  54091. }
  54092. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  54093. releasePage(pPtrPage);
  54094. if( rc==SQLITE_OK ){
  54095. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  54096. }
  54097. }
  54098. return rc;
  54099. }
  54100. /* Forward declaration required by incrVacuumStep(). */
  54101. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  54102. /*
  54103. ** Perform a single step of an incremental-vacuum. If successful, return
  54104. ** SQLITE_OK. If there is no work to do (and therefore no point in
  54105. ** calling this function again), return SQLITE_DONE. Or, if an error
  54106. ** occurs, return some other error code.
  54107. **
  54108. ** More specifically, this function attempts to re-organize the database so
  54109. ** that the last page of the file currently in use is no longer in use.
  54110. **
  54111. ** Parameter nFin is the number of pages that this database would contain
  54112. ** were this function called until it returns SQLITE_DONE.
  54113. **
  54114. ** If the bCommit parameter is non-zero, this function assumes that the
  54115. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  54116. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  54117. ** operation, or false for an incremental vacuum.
  54118. */
  54119. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  54120. Pgno nFreeList; /* Number of pages still on the free-list */
  54121. int rc;
  54122. assert( sqlite3_mutex_held(pBt->mutex) );
  54123. assert( iLastPg>nFin );
  54124. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  54125. u8 eType;
  54126. Pgno iPtrPage;
  54127. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  54128. if( nFreeList==0 ){
  54129. return SQLITE_DONE;
  54130. }
  54131. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  54132. if( rc!=SQLITE_OK ){
  54133. return rc;
  54134. }
  54135. if( eType==PTRMAP_ROOTPAGE ){
  54136. return SQLITE_CORRUPT_BKPT;
  54137. }
  54138. if( eType==PTRMAP_FREEPAGE ){
  54139. if( bCommit==0 ){
  54140. /* Remove the page from the files free-list. This is not required
  54141. ** if bCommit is non-zero. In that case, the free-list will be
  54142. ** truncated to zero after this function returns, so it doesn't
  54143. ** matter if it still contains some garbage entries.
  54144. */
  54145. Pgno iFreePg;
  54146. MemPage *pFreePg;
  54147. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  54148. if( rc!=SQLITE_OK ){
  54149. return rc;
  54150. }
  54151. assert( iFreePg==iLastPg );
  54152. releasePage(pFreePg);
  54153. }
  54154. } else {
  54155. Pgno iFreePg; /* Index of free page to move pLastPg to */
  54156. MemPage *pLastPg;
  54157. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  54158. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  54159. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  54160. if( rc!=SQLITE_OK ){
  54161. return rc;
  54162. }
  54163. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  54164. ** is swapped with the first free page pulled off the free list.
  54165. **
  54166. ** On the other hand, if bCommit is greater than zero, then keep
  54167. ** looping until a free-page located within the first nFin pages
  54168. ** of the file is found.
  54169. */
  54170. if( bCommit==0 ){
  54171. eMode = BTALLOC_LE;
  54172. iNear = nFin;
  54173. }
  54174. do {
  54175. MemPage *pFreePg;
  54176. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  54177. if( rc!=SQLITE_OK ){
  54178. releasePage(pLastPg);
  54179. return rc;
  54180. }
  54181. releasePage(pFreePg);
  54182. }while( bCommit && iFreePg>nFin );
  54183. assert( iFreePg<iLastPg );
  54184. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  54185. releasePage(pLastPg);
  54186. if( rc!=SQLITE_OK ){
  54187. return rc;
  54188. }
  54189. }
  54190. }
  54191. if( bCommit==0 ){
  54192. do {
  54193. iLastPg--;
  54194. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  54195. pBt->bDoTruncate = 1;
  54196. pBt->nPage = iLastPg;
  54197. }
  54198. return SQLITE_OK;
  54199. }
  54200. /*
  54201. ** The database opened by the first argument is an auto-vacuum database
  54202. ** nOrig pages in size containing nFree free pages. Return the expected
  54203. ** size of the database in pages following an auto-vacuum operation.
  54204. */
  54205. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  54206. int nEntry; /* Number of entries on one ptrmap page */
  54207. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  54208. Pgno nFin; /* Return value */
  54209. nEntry = pBt->usableSize/5;
  54210. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  54211. nFin = nOrig - nFree - nPtrmap;
  54212. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  54213. nFin--;
  54214. }
  54215. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  54216. nFin--;
  54217. }
  54218. return nFin;
  54219. }
  54220. /*
  54221. ** A write-transaction must be opened before calling this function.
  54222. ** It performs a single unit of work towards an incremental vacuum.
  54223. **
  54224. ** If the incremental vacuum is finished after this function has run,
  54225. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  54226. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  54227. */
  54228. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  54229. int rc;
  54230. BtShared *pBt = p->pBt;
  54231. sqlite3BtreeEnter(p);
  54232. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  54233. if( !pBt->autoVacuum ){
  54234. rc = SQLITE_DONE;
  54235. }else{
  54236. Pgno nOrig = btreePagecount(pBt);
  54237. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  54238. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  54239. if( nOrig<nFin ){
  54240. rc = SQLITE_CORRUPT_BKPT;
  54241. }else if( nFree>0 ){
  54242. rc = saveAllCursors(pBt, 0, 0);
  54243. if( rc==SQLITE_OK ){
  54244. invalidateAllOverflowCache(pBt);
  54245. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  54246. }
  54247. if( rc==SQLITE_OK ){
  54248. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54249. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  54250. }
  54251. }else{
  54252. rc = SQLITE_DONE;
  54253. }
  54254. }
  54255. sqlite3BtreeLeave(p);
  54256. return rc;
  54257. }
  54258. /*
  54259. ** This routine is called prior to sqlite3PagerCommit when a transaction
  54260. ** is committed for an auto-vacuum database.
  54261. **
  54262. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  54263. ** the database file should be truncated to during the commit process.
  54264. ** i.e. the database has been reorganized so that only the first *pnTrunc
  54265. ** pages are in use.
  54266. */
  54267. static int autoVacuumCommit(BtShared *pBt){
  54268. int rc = SQLITE_OK;
  54269. Pager *pPager = pBt->pPager;
  54270. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  54271. assert( sqlite3_mutex_held(pBt->mutex) );
  54272. invalidateAllOverflowCache(pBt);
  54273. assert(pBt->autoVacuum);
  54274. if( !pBt->incrVacuum ){
  54275. Pgno nFin; /* Number of pages in database after autovacuuming */
  54276. Pgno nFree; /* Number of pages on the freelist initially */
  54277. Pgno iFree; /* The next page to be freed */
  54278. Pgno nOrig; /* Database size before freeing */
  54279. nOrig = btreePagecount(pBt);
  54280. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  54281. /* It is not possible to create a database for which the final page
  54282. ** is either a pointer-map page or the pending-byte page. If one
  54283. ** is encountered, this indicates corruption.
  54284. */
  54285. return SQLITE_CORRUPT_BKPT;
  54286. }
  54287. nFree = get4byte(&pBt->pPage1->aData[36]);
  54288. nFin = finalDbSize(pBt, nOrig, nFree);
  54289. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  54290. if( nFin<nOrig ){
  54291. rc = saveAllCursors(pBt, 0, 0);
  54292. }
  54293. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  54294. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  54295. }
  54296. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  54297. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54298. put4byte(&pBt->pPage1->aData[32], 0);
  54299. put4byte(&pBt->pPage1->aData[36], 0);
  54300. put4byte(&pBt->pPage1->aData[28], nFin);
  54301. pBt->bDoTruncate = 1;
  54302. pBt->nPage = nFin;
  54303. }
  54304. if( rc!=SQLITE_OK ){
  54305. sqlite3PagerRollback(pPager);
  54306. }
  54307. }
  54308. assert( nRef>=sqlite3PagerRefcount(pPager) );
  54309. return rc;
  54310. }
  54311. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  54312. # define setChildPtrmaps(x) SQLITE_OK
  54313. #endif
  54314. /*
  54315. ** This routine does the first phase of a two-phase commit. This routine
  54316. ** causes a rollback journal to be created (if it does not already exist)
  54317. ** and populated with enough information so that if a power loss occurs
  54318. ** the database can be restored to its original state by playing back
  54319. ** the journal. Then the contents of the journal are flushed out to
  54320. ** the disk. After the journal is safely on oxide, the changes to the
  54321. ** database are written into the database file and flushed to oxide.
  54322. ** At the end of this call, the rollback journal still exists on the
  54323. ** disk and we are still holding all locks, so the transaction has not
  54324. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  54325. ** commit process.
  54326. **
  54327. ** This call is a no-op if no write-transaction is currently active on pBt.
  54328. **
  54329. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  54330. ** the name of a master journal file that should be written into the
  54331. ** individual journal file, or is NULL, indicating no master journal file
  54332. ** (single database transaction).
  54333. **
  54334. ** When this is called, the master journal should already have been
  54335. ** created, populated with this journal pointer and synced to disk.
  54336. **
  54337. ** Once this is routine has returned, the only thing required to commit
  54338. ** the write-transaction for this database file is to delete the journal.
  54339. */
  54340. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  54341. int rc = SQLITE_OK;
  54342. if( p->inTrans==TRANS_WRITE ){
  54343. BtShared *pBt = p->pBt;
  54344. sqlite3BtreeEnter(p);
  54345. #ifndef SQLITE_OMIT_AUTOVACUUM
  54346. if( pBt->autoVacuum ){
  54347. rc = autoVacuumCommit(pBt);
  54348. if( rc!=SQLITE_OK ){
  54349. sqlite3BtreeLeave(p);
  54350. return rc;
  54351. }
  54352. }
  54353. if( pBt->bDoTruncate ){
  54354. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  54355. }
  54356. #endif
  54357. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  54358. sqlite3BtreeLeave(p);
  54359. }
  54360. return rc;
  54361. }
  54362. /*
  54363. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  54364. ** at the conclusion of a transaction.
  54365. */
  54366. static void btreeEndTransaction(Btree *p){
  54367. BtShared *pBt = p->pBt;
  54368. sqlite3 *db = p->db;
  54369. assert( sqlite3BtreeHoldsMutex(p) );
  54370. #ifndef SQLITE_OMIT_AUTOVACUUM
  54371. pBt->bDoTruncate = 0;
  54372. #endif
  54373. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  54374. /* If there are other active statements that belong to this database
  54375. ** handle, downgrade to a read-only transaction. The other statements
  54376. ** may still be reading from the database. */
  54377. downgradeAllSharedCacheTableLocks(p);
  54378. p->inTrans = TRANS_READ;
  54379. }else{
  54380. /* If the handle had any kind of transaction open, decrement the
  54381. ** transaction count of the shared btree. If the transaction count
  54382. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  54383. ** call below will unlock the pager. */
  54384. if( p->inTrans!=TRANS_NONE ){
  54385. clearAllSharedCacheTableLocks(p);
  54386. pBt->nTransaction--;
  54387. if( 0==pBt->nTransaction ){
  54388. pBt->inTransaction = TRANS_NONE;
  54389. }
  54390. }
  54391. /* Set the current transaction state to TRANS_NONE and unlock the
  54392. ** pager if this call closed the only read or write transaction. */
  54393. p->inTrans = TRANS_NONE;
  54394. unlockBtreeIfUnused(pBt);
  54395. }
  54396. btreeIntegrity(p);
  54397. }
  54398. /*
  54399. ** Commit the transaction currently in progress.
  54400. **
  54401. ** This routine implements the second phase of a 2-phase commit. The
  54402. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  54403. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  54404. ** routine did all the work of writing information out to disk and flushing the
  54405. ** contents so that they are written onto the disk platter. All this
  54406. ** routine has to do is delete or truncate or zero the header in the
  54407. ** the rollback journal (which causes the transaction to commit) and
  54408. ** drop locks.
  54409. **
  54410. ** Normally, if an error occurs while the pager layer is attempting to
  54411. ** finalize the underlying journal file, this function returns an error and
  54412. ** the upper layer will attempt a rollback. However, if the second argument
  54413. ** is non-zero then this b-tree transaction is part of a multi-file
  54414. ** transaction. In this case, the transaction has already been committed
  54415. ** (by deleting a master journal file) and the caller will ignore this
  54416. ** functions return code. So, even if an error occurs in the pager layer,
  54417. ** reset the b-tree objects internal state to indicate that the write
  54418. ** transaction has been closed. This is quite safe, as the pager will have
  54419. ** transitioned to the error state.
  54420. **
  54421. ** This will release the write lock on the database file. If there
  54422. ** are no active cursors, it also releases the read lock.
  54423. */
  54424. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  54425. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  54426. sqlite3BtreeEnter(p);
  54427. btreeIntegrity(p);
  54428. /* If the handle has a write-transaction open, commit the shared-btrees
  54429. ** transaction and set the shared state to TRANS_READ.
  54430. */
  54431. if( p->inTrans==TRANS_WRITE ){
  54432. int rc;
  54433. BtShared *pBt = p->pBt;
  54434. assert( pBt->inTransaction==TRANS_WRITE );
  54435. assert( pBt->nTransaction>0 );
  54436. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  54437. if( rc!=SQLITE_OK && bCleanup==0 ){
  54438. sqlite3BtreeLeave(p);
  54439. return rc;
  54440. }
  54441. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  54442. pBt->inTransaction = TRANS_READ;
  54443. btreeClearHasContent(pBt);
  54444. }
  54445. btreeEndTransaction(p);
  54446. sqlite3BtreeLeave(p);
  54447. return SQLITE_OK;
  54448. }
  54449. /*
  54450. ** Do both phases of a commit.
  54451. */
  54452. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  54453. int rc;
  54454. sqlite3BtreeEnter(p);
  54455. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  54456. if( rc==SQLITE_OK ){
  54457. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  54458. }
  54459. sqlite3BtreeLeave(p);
  54460. return rc;
  54461. }
  54462. /*
  54463. ** This routine sets the state to CURSOR_FAULT and the error
  54464. ** code to errCode for every cursor on any BtShared that pBtree
  54465. ** references. Or if the writeOnly flag is set to 1, then only
  54466. ** trip write cursors and leave read cursors unchanged.
  54467. **
  54468. ** Every cursor is a candidate to be tripped, including cursors
  54469. ** that belong to other database connections that happen to be
  54470. ** sharing the cache with pBtree.
  54471. **
  54472. ** This routine gets called when a rollback occurs. If the writeOnly
  54473. ** flag is true, then only write-cursors need be tripped - read-only
  54474. ** cursors save their current positions so that they may continue
  54475. ** following the rollback. Or, if writeOnly is false, all cursors are
  54476. ** tripped. In general, writeOnly is false if the transaction being
  54477. ** rolled back modified the database schema. In this case b-tree root
  54478. ** pages may be moved or deleted from the database altogether, making
  54479. ** it unsafe for read cursors to continue.
  54480. **
  54481. ** If the writeOnly flag is true and an error is encountered while
  54482. ** saving the current position of a read-only cursor, all cursors,
  54483. ** including all read-cursors are tripped.
  54484. **
  54485. ** SQLITE_OK is returned if successful, or if an error occurs while
  54486. ** saving a cursor position, an SQLite error code.
  54487. */
  54488. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  54489. BtCursor *p;
  54490. int rc = SQLITE_OK;
  54491. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  54492. if( pBtree ){
  54493. sqlite3BtreeEnter(pBtree);
  54494. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  54495. int i;
  54496. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  54497. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  54498. rc = saveCursorPosition(p);
  54499. if( rc!=SQLITE_OK ){
  54500. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  54501. break;
  54502. }
  54503. }
  54504. }else{
  54505. sqlite3BtreeClearCursor(p);
  54506. p->eState = CURSOR_FAULT;
  54507. p->skipNext = errCode;
  54508. }
  54509. for(i=0; i<=p->iPage; i++){
  54510. releasePage(p->apPage[i]);
  54511. p->apPage[i] = 0;
  54512. }
  54513. }
  54514. sqlite3BtreeLeave(pBtree);
  54515. }
  54516. return rc;
  54517. }
  54518. /*
  54519. ** Rollback the transaction in progress.
  54520. **
  54521. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  54522. ** Only write cursors are tripped if writeOnly is true but all cursors are
  54523. ** tripped if writeOnly is false. Any attempt to use
  54524. ** a tripped cursor will result in an error.
  54525. **
  54526. ** This will release the write lock on the database file. If there
  54527. ** are no active cursors, it also releases the read lock.
  54528. */
  54529. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  54530. int rc;
  54531. BtShared *pBt = p->pBt;
  54532. MemPage *pPage1;
  54533. assert( writeOnly==1 || writeOnly==0 );
  54534. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  54535. sqlite3BtreeEnter(p);
  54536. if( tripCode==SQLITE_OK ){
  54537. rc = tripCode = saveAllCursors(pBt, 0, 0);
  54538. if( rc ) writeOnly = 0;
  54539. }else{
  54540. rc = SQLITE_OK;
  54541. }
  54542. if( tripCode ){
  54543. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  54544. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  54545. if( rc2!=SQLITE_OK ) rc = rc2;
  54546. }
  54547. btreeIntegrity(p);
  54548. if( p->inTrans==TRANS_WRITE ){
  54549. int rc2;
  54550. assert( TRANS_WRITE==pBt->inTransaction );
  54551. rc2 = sqlite3PagerRollback(pBt->pPager);
  54552. if( rc2!=SQLITE_OK ){
  54553. rc = rc2;
  54554. }
  54555. /* The rollback may have destroyed the pPage1->aData value. So
  54556. ** call btreeGetPage() on page 1 again to make
  54557. ** sure pPage1->aData is set correctly. */
  54558. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  54559. int nPage = get4byte(28+(u8*)pPage1->aData);
  54560. testcase( nPage==0 );
  54561. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  54562. testcase( pBt->nPage!=nPage );
  54563. pBt->nPage = nPage;
  54564. releasePage(pPage1);
  54565. }
  54566. assert( countValidCursors(pBt, 1)==0 );
  54567. pBt->inTransaction = TRANS_READ;
  54568. btreeClearHasContent(pBt);
  54569. }
  54570. btreeEndTransaction(p);
  54571. sqlite3BtreeLeave(p);
  54572. return rc;
  54573. }
  54574. /*
  54575. ** Start a statement subtransaction. The subtransaction can be rolled
  54576. ** back independently of the main transaction. You must start a transaction
  54577. ** before starting a subtransaction. The subtransaction is ended automatically
  54578. ** if the main transaction commits or rolls back.
  54579. **
  54580. ** Statement subtransactions are used around individual SQL statements
  54581. ** that are contained within a BEGIN...COMMIT block. If a constraint
  54582. ** error occurs within the statement, the effect of that one statement
  54583. ** can be rolled back without having to rollback the entire transaction.
  54584. **
  54585. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  54586. ** value passed as the second parameter is the total number of savepoints,
  54587. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  54588. ** are no active savepoints and no other statement-transactions open,
  54589. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  54590. ** using the sqlite3BtreeSavepoint() function.
  54591. */
  54592. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  54593. int rc;
  54594. BtShared *pBt = p->pBt;
  54595. sqlite3BtreeEnter(p);
  54596. assert( p->inTrans==TRANS_WRITE );
  54597. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  54598. assert( iStatement>0 );
  54599. assert( iStatement>p->db->nSavepoint );
  54600. assert( pBt->inTransaction==TRANS_WRITE );
  54601. /* At the pager level, a statement transaction is a savepoint with
  54602. ** an index greater than all savepoints created explicitly using
  54603. ** SQL statements. It is illegal to open, release or rollback any
  54604. ** such savepoints while the statement transaction savepoint is active.
  54605. */
  54606. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  54607. sqlite3BtreeLeave(p);
  54608. return rc;
  54609. }
  54610. /*
  54611. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  54612. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  54613. ** savepoint identified by parameter iSavepoint, depending on the value
  54614. ** of op.
  54615. **
  54616. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  54617. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  54618. ** contents of the entire transaction are rolled back. This is different
  54619. ** from a normal transaction rollback, as no locks are released and the
  54620. ** transaction remains open.
  54621. */
  54622. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  54623. int rc = SQLITE_OK;
  54624. if( p && p->inTrans==TRANS_WRITE ){
  54625. BtShared *pBt = p->pBt;
  54626. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  54627. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  54628. sqlite3BtreeEnter(p);
  54629. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  54630. if( rc==SQLITE_OK ){
  54631. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  54632. pBt->nPage = 0;
  54633. }
  54634. rc = newDatabase(pBt);
  54635. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  54636. /* The database size was written into the offset 28 of the header
  54637. ** when the transaction started, so we know that the value at offset
  54638. ** 28 is nonzero. */
  54639. assert( pBt->nPage>0 );
  54640. }
  54641. sqlite3BtreeLeave(p);
  54642. }
  54643. return rc;
  54644. }
  54645. /*
  54646. ** Create a new cursor for the BTree whose root is on the page
  54647. ** iTable. If a read-only cursor is requested, it is assumed that
  54648. ** the caller already has at least a read-only transaction open
  54649. ** on the database already. If a write-cursor is requested, then
  54650. ** the caller is assumed to have an open write transaction.
  54651. **
  54652. ** If wrFlag==0, then the cursor can only be used for reading.
  54653. ** If wrFlag==1, then the cursor can be used for reading or for
  54654. ** writing if other conditions for writing are also met. These
  54655. ** are the conditions that must be met in order for writing to
  54656. ** be allowed:
  54657. **
  54658. ** 1: The cursor must have been opened with wrFlag==1
  54659. **
  54660. ** 2: Other database connections that share the same pager cache
  54661. ** but which are not in the READ_UNCOMMITTED state may not have
  54662. ** cursors open with wrFlag==0 on the same table. Otherwise
  54663. ** the changes made by this write cursor would be visible to
  54664. ** the read cursors in the other database connection.
  54665. **
  54666. ** 3: The database must be writable (not on read-only media)
  54667. **
  54668. ** 4: There must be an active transaction.
  54669. **
  54670. ** No checking is done to make sure that page iTable really is the
  54671. ** root page of a b-tree. If it is not, then the cursor acquired
  54672. ** will not work correctly.
  54673. **
  54674. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  54675. ** on pCur to initialize the memory space prior to invoking this routine.
  54676. */
  54677. static int btreeCursor(
  54678. Btree *p, /* The btree */
  54679. int iTable, /* Root page of table to open */
  54680. int wrFlag, /* 1 to write. 0 read-only */
  54681. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  54682. BtCursor *pCur /* Space for new cursor */
  54683. ){
  54684. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  54685. BtCursor *pX; /* Looping over other all cursors */
  54686. assert( sqlite3BtreeHoldsMutex(p) );
  54687. assert( wrFlag==0 || wrFlag==1 );
  54688. /* The following assert statements verify that if this is a sharable
  54689. ** b-tree database, the connection is holding the required table locks,
  54690. ** and that no other connection has any open cursor that conflicts with
  54691. ** this lock. */
  54692. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  54693. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  54694. /* Assert that the caller has opened the required transaction. */
  54695. assert( p->inTrans>TRANS_NONE );
  54696. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  54697. assert( pBt->pPage1 && pBt->pPage1->aData );
  54698. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  54699. if( wrFlag ){
  54700. allocateTempSpace(pBt);
  54701. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  54702. }
  54703. if( iTable==1 && btreePagecount(pBt)==0 ){
  54704. assert( wrFlag==0 );
  54705. iTable = 0;
  54706. }
  54707. /* Now that no other errors can occur, finish filling in the BtCursor
  54708. ** variables and link the cursor into the BtShared list. */
  54709. pCur->pgnoRoot = (Pgno)iTable;
  54710. pCur->iPage = -1;
  54711. pCur->pKeyInfo = pKeyInfo;
  54712. pCur->pBtree = p;
  54713. pCur->pBt = pBt;
  54714. assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
  54715. pCur->curFlags = wrFlag;
  54716. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  54717. /* If there are two or more cursors on the same btree, then all such
  54718. ** cursors *must* have the BTCF_Multiple flag set. */
  54719. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  54720. if( pX->pgnoRoot==(Pgno)iTable ){
  54721. pX->curFlags |= BTCF_Multiple;
  54722. pCur->curFlags |= BTCF_Multiple;
  54723. }
  54724. }
  54725. pCur->pNext = pBt->pCursor;
  54726. pBt->pCursor = pCur;
  54727. pCur->eState = CURSOR_INVALID;
  54728. return SQLITE_OK;
  54729. }
  54730. SQLITE_PRIVATE int sqlite3BtreeCursor(
  54731. Btree *p, /* The btree */
  54732. int iTable, /* Root page of table to open */
  54733. int wrFlag, /* 1 to write. 0 read-only */
  54734. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  54735. BtCursor *pCur /* Write new cursor here */
  54736. ){
  54737. int rc;
  54738. if( iTable<1 ){
  54739. rc = SQLITE_CORRUPT_BKPT;
  54740. }else{
  54741. sqlite3BtreeEnter(p);
  54742. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  54743. sqlite3BtreeLeave(p);
  54744. }
  54745. return rc;
  54746. }
  54747. /*
  54748. ** Return the size of a BtCursor object in bytes.
  54749. **
  54750. ** This interfaces is needed so that users of cursors can preallocate
  54751. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  54752. ** to users so they cannot do the sizeof() themselves - they must call
  54753. ** this routine.
  54754. */
  54755. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  54756. return ROUND8(sizeof(BtCursor));
  54757. }
  54758. /*
  54759. ** Initialize memory that will be converted into a BtCursor object.
  54760. **
  54761. ** The simple approach here would be to memset() the entire object
  54762. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  54763. ** do not need to be zeroed and they are large, so we can save a lot
  54764. ** of run-time by skipping the initialization of those elements.
  54765. */
  54766. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  54767. memset(p, 0, offsetof(BtCursor, iPage));
  54768. }
  54769. /*
  54770. ** Close a cursor. The read lock on the database file is released
  54771. ** when the last cursor is closed.
  54772. */
  54773. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  54774. Btree *pBtree = pCur->pBtree;
  54775. if( pBtree ){
  54776. int i;
  54777. BtShared *pBt = pCur->pBt;
  54778. sqlite3BtreeEnter(pBtree);
  54779. sqlite3BtreeClearCursor(pCur);
  54780. assert( pBt->pCursor!=0 );
  54781. if( pBt->pCursor==pCur ){
  54782. pBt->pCursor = pCur->pNext;
  54783. }else{
  54784. BtCursor *pPrev = pBt->pCursor;
  54785. do{
  54786. if( pPrev->pNext==pCur ){
  54787. pPrev->pNext = pCur->pNext;
  54788. break;
  54789. }
  54790. pPrev = pPrev->pNext;
  54791. }while( ALWAYS(pPrev) );
  54792. }
  54793. for(i=0; i<=pCur->iPage; i++){
  54794. releasePage(pCur->apPage[i]);
  54795. }
  54796. unlockBtreeIfUnused(pBt);
  54797. sqlite3_free(pCur->aOverflow);
  54798. /* sqlite3_free(pCur); */
  54799. sqlite3BtreeLeave(pBtree);
  54800. }
  54801. return SQLITE_OK;
  54802. }
  54803. /*
  54804. ** Make sure the BtCursor* given in the argument has a valid
  54805. ** BtCursor.info structure. If it is not already valid, call
  54806. ** btreeParseCell() to fill it in.
  54807. **
  54808. ** BtCursor.info is a cache of the information in the current cell.
  54809. ** Using this cache reduces the number of calls to btreeParseCell().
  54810. */
  54811. #ifndef NDEBUG
  54812. static void assertCellInfo(BtCursor *pCur){
  54813. CellInfo info;
  54814. int iPage = pCur->iPage;
  54815. memset(&info, 0, sizeof(info));
  54816. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  54817. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  54818. }
  54819. #else
  54820. #define assertCellInfo(x)
  54821. #endif
  54822. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  54823. if( pCur->info.nSize==0 ){
  54824. int iPage = pCur->iPage;
  54825. pCur->curFlags |= BTCF_ValidNKey;
  54826. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  54827. }else{
  54828. assertCellInfo(pCur);
  54829. }
  54830. }
  54831. #ifndef NDEBUG /* The next routine used only within assert() statements */
  54832. /*
  54833. ** Return true if the given BtCursor is valid. A valid cursor is one
  54834. ** that is currently pointing to a row in a (non-empty) table.
  54835. ** This is a verification routine is used only within assert() statements.
  54836. */
  54837. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  54838. return pCur && pCur->eState==CURSOR_VALID;
  54839. }
  54840. #endif /* NDEBUG */
  54841. /*
  54842. ** Set *pSize to the size of the buffer needed to hold the value of
  54843. ** the key for the current entry. If the cursor is not pointing
  54844. ** to a valid entry, *pSize is set to 0.
  54845. **
  54846. ** For a table with the INTKEY flag set, this routine returns the key
  54847. ** itself, not the number of bytes in the key.
  54848. **
  54849. ** The caller must position the cursor prior to invoking this routine.
  54850. **
  54851. ** This routine cannot fail. It always returns SQLITE_OK.
  54852. */
  54853. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  54854. assert( cursorHoldsMutex(pCur) );
  54855. assert( pCur->eState==CURSOR_VALID );
  54856. getCellInfo(pCur);
  54857. *pSize = pCur->info.nKey;
  54858. return SQLITE_OK;
  54859. }
  54860. /*
  54861. ** Set *pSize to the number of bytes of data in the entry the
  54862. ** cursor currently points to.
  54863. **
  54864. ** The caller must guarantee that the cursor is pointing to a non-NULL
  54865. ** valid entry. In other words, the calling procedure must guarantee
  54866. ** that the cursor has Cursor.eState==CURSOR_VALID.
  54867. **
  54868. ** Failure is not possible. This function always returns SQLITE_OK.
  54869. ** It might just as well be a procedure (returning void) but we continue
  54870. ** to return an integer result code for historical reasons.
  54871. */
  54872. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  54873. assert( cursorHoldsMutex(pCur) );
  54874. assert( pCur->eState==CURSOR_VALID );
  54875. assert( pCur->iPage>=0 );
  54876. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  54877. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  54878. getCellInfo(pCur);
  54879. *pSize = pCur->info.nPayload;
  54880. return SQLITE_OK;
  54881. }
  54882. /*
  54883. ** Given the page number of an overflow page in the database (parameter
  54884. ** ovfl), this function finds the page number of the next page in the
  54885. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  54886. ** pointer-map data instead of reading the content of page ovfl to do so.
  54887. **
  54888. ** If an error occurs an SQLite error code is returned. Otherwise:
  54889. **
  54890. ** The page number of the next overflow page in the linked list is
  54891. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  54892. ** list, *pPgnoNext is set to zero.
  54893. **
  54894. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  54895. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  54896. ** reference. It is the responsibility of the caller to call releasePage()
  54897. ** on *ppPage to free the reference. In no reference was obtained (because
  54898. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  54899. ** *ppPage is set to zero.
  54900. */
  54901. static int getOverflowPage(
  54902. BtShared *pBt, /* The database file */
  54903. Pgno ovfl, /* Current overflow page number */
  54904. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  54905. Pgno *pPgnoNext /* OUT: Next overflow page number */
  54906. ){
  54907. Pgno next = 0;
  54908. MemPage *pPage = 0;
  54909. int rc = SQLITE_OK;
  54910. assert( sqlite3_mutex_held(pBt->mutex) );
  54911. assert(pPgnoNext);
  54912. #ifndef SQLITE_OMIT_AUTOVACUUM
  54913. /* Try to find the next page in the overflow list using the
  54914. ** autovacuum pointer-map pages. Guess that the next page in
  54915. ** the overflow list is page number (ovfl+1). If that guess turns
  54916. ** out to be wrong, fall back to loading the data of page
  54917. ** number ovfl to determine the next page number.
  54918. */
  54919. if( pBt->autoVacuum ){
  54920. Pgno pgno;
  54921. Pgno iGuess = ovfl+1;
  54922. u8 eType;
  54923. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  54924. iGuess++;
  54925. }
  54926. if( iGuess<=btreePagecount(pBt) ){
  54927. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  54928. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  54929. next = iGuess;
  54930. rc = SQLITE_DONE;
  54931. }
  54932. }
  54933. }
  54934. #endif
  54935. assert( next==0 || rc==SQLITE_DONE );
  54936. if( rc==SQLITE_OK ){
  54937. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  54938. assert( rc==SQLITE_OK || pPage==0 );
  54939. if( rc==SQLITE_OK ){
  54940. next = get4byte(pPage->aData);
  54941. }
  54942. }
  54943. *pPgnoNext = next;
  54944. if( ppPage ){
  54945. *ppPage = pPage;
  54946. }else{
  54947. releasePage(pPage);
  54948. }
  54949. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  54950. }
  54951. /*
  54952. ** Copy data from a buffer to a page, or from a page to a buffer.
  54953. **
  54954. ** pPayload is a pointer to data stored on database page pDbPage.
  54955. ** If argument eOp is false, then nByte bytes of data are copied
  54956. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  54957. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  54958. ** of data are copied from the buffer pBuf to pPayload.
  54959. **
  54960. ** SQLITE_OK is returned on success, otherwise an error code.
  54961. */
  54962. static int copyPayload(
  54963. void *pPayload, /* Pointer to page data */
  54964. void *pBuf, /* Pointer to buffer */
  54965. int nByte, /* Number of bytes to copy */
  54966. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  54967. DbPage *pDbPage /* Page containing pPayload */
  54968. ){
  54969. if( eOp ){
  54970. /* Copy data from buffer to page (a write operation) */
  54971. int rc = sqlite3PagerWrite(pDbPage);
  54972. if( rc!=SQLITE_OK ){
  54973. return rc;
  54974. }
  54975. memcpy(pPayload, pBuf, nByte);
  54976. }else{
  54977. /* Copy data from page to buffer (a read operation) */
  54978. memcpy(pBuf, pPayload, nByte);
  54979. }
  54980. return SQLITE_OK;
  54981. }
  54982. /*
  54983. ** This function is used to read or overwrite payload information
  54984. ** for the entry that the pCur cursor is pointing to. The eOp
  54985. ** argument is interpreted as follows:
  54986. **
  54987. ** 0: The operation is a read. Populate the overflow cache.
  54988. ** 1: The operation is a write. Populate the overflow cache.
  54989. ** 2: The operation is a read. Do not populate the overflow cache.
  54990. **
  54991. ** A total of "amt" bytes are read or written beginning at "offset".
  54992. ** Data is read to or from the buffer pBuf.
  54993. **
  54994. ** The content being read or written might appear on the main page
  54995. ** or be scattered out on multiple overflow pages.
  54996. **
  54997. ** If the current cursor entry uses one or more overflow pages and the
  54998. ** eOp argument is not 2, this function may allocate space for and lazily
  54999. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  55000. ** Subsequent calls use this cache to make seeking to the supplied offset
  55001. ** more efficient.
  55002. **
  55003. ** Once an overflow page-list cache has been allocated, it may be
  55004. ** invalidated if some other cursor writes to the same table, or if
  55005. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  55006. ** mode, the following events may invalidate an overflow page-list cache.
  55007. **
  55008. ** * An incremental vacuum,
  55009. ** * A commit in auto_vacuum="full" mode,
  55010. ** * Creating a table (may require moving an overflow page).
  55011. */
  55012. static int accessPayload(
  55013. BtCursor *pCur, /* Cursor pointing to entry to read from */
  55014. u32 offset, /* Begin reading this far into payload */
  55015. u32 amt, /* Read this many bytes */
  55016. unsigned char *pBuf, /* Write the bytes into this buffer */
  55017. int eOp /* zero to read. non-zero to write. */
  55018. ){
  55019. unsigned char *aPayload;
  55020. int rc = SQLITE_OK;
  55021. int iIdx = 0;
  55022. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  55023. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  55024. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55025. unsigned char * const pBufStart = pBuf;
  55026. int bEnd; /* True if reading to end of data */
  55027. #endif
  55028. assert( pPage );
  55029. assert( pCur->eState==CURSOR_VALID );
  55030. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  55031. assert( cursorHoldsMutex(pCur) );
  55032. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  55033. getCellInfo(pCur);
  55034. aPayload = pCur->info.pPayload;
  55035. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55036. bEnd = offset+amt==pCur->info.nPayload;
  55037. #endif
  55038. assert( offset+amt <= pCur->info.nPayload );
  55039. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  55040. /* Trying to read or write past the end of the data is an error */
  55041. return SQLITE_CORRUPT_BKPT;
  55042. }
  55043. /* Check if data must be read/written to/from the btree page itself. */
  55044. if( offset<pCur->info.nLocal ){
  55045. int a = amt;
  55046. if( a+offset>pCur->info.nLocal ){
  55047. a = pCur->info.nLocal - offset;
  55048. }
  55049. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  55050. offset = 0;
  55051. pBuf += a;
  55052. amt -= a;
  55053. }else{
  55054. offset -= pCur->info.nLocal;
  55055. }
  55056. if( rc==SQLITE_OK && amt>0 ){
  55057. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  55058. Pgno nextPage;
  55059. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  55060. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  55061. ** Except, do not allocate aOverflow[] for eOp==2.
  55062. **
  55063. ** The aOverflow[] array is sized at one entry for each overflow page
  55064. ** in the overflow chain. The page number of the first overflow page is
  55065. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  55066. ** means "not yet known" (the cache is lazily populated).
  55067. */
  55068. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  55069. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  55070. if( nOvfl>pCur->nOvflAlloc ){
  55071. Pgno *aNew = (Pgno*)sqlite3Realloc(
  55072. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  55073. );
  55074. if( aNew==0 ){
  55075. rc = SQLITE_NOMEM;
  55076. }else{
  55077. pCur->nOvflAlloc = nOvfl*2;
  55078. pCur->aOverflow = aNew;
  55079. }
  55080. }
  55081. if( rc==SQLITE_OK ){
  55082. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  55083. pCur->curFlags |= BTCF_ValidOvfl;
  55084. }
  55085. }
  55086. /* If the overflow page-list cache has been allocated and the
  55087. ** entry for the first required overflow page is valid, skip
  55088. ** directly to it.
  55089. */
  55090. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  55091. && pCur->aOverflow[offset/ovflSize]
  55092. ){
  55093. iIdx = (offset/ovflSize);
  55094. nextPage = pCur->aOverflow[iIdx];
  55095. offset = (offset%ovflSize);
  55096. }
  55097. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  55098. /* If required, populate the overflow page-list cache. */
  55099. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  55100. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  55101. pCur->aOverflow[iIdx] = nextPage;
  55102. }
  55103. if( offset>=ovflSize ){
  55104. /* The only reason to read this page is to obtain the page
  55105. ** number for the next page in the overflow chain. The page
  55106. ** data is not required. So first try to lookup the overflow
  55107. ** page-list cache, if any, then fall back to the getOverflowPage()
  55108. ** function.
  55109. **
  55110. ** Note that the aOverflow[] array must be allocated because eOp!=2
  55111. ** here. If eOp==2, then offset==0 and this branch is never taken.
  55112. */
  55113. assert( eOp!=2 );
  55114. assert( pCur->curFlags & BTCF_ValidOvfl );
  55115. assert( pCur->pBtree->db==pBt->db );
  55116. if( pCur->aOverflow[iIdx+1] ){
  55117. nextPage = pCur->aOverflow[iIdx+1];
  55118. }else{
  55119. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  55120. }
  55121. offset -= ovflSize;
  55122. }else{
  55123. /* Need to read this page properly. It contains some of the
  55124. ** range of data that is being read (eOp==0) or written (eOp!=0).
  55125. */
  55126. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55127. sqlite3_file *fd;
  55128. #endif
  55129. int a = amt;
  55130. if( a + offset > ovflSize ){
  55131. a = ovflSize - offset;
  55132. }
  55133. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55134. /* If all the following are true:
  55135. **
  55136. ** 1) this is a read operation, and
  55137. ** 2) data is required from the start of this overflow page, and
  55138. ** 3) the database is file-backed, and
  55139. ** 4) there is no open write-transaction, and
  55140. ** 5) the database is not a WAL database,
  55141. ** 6) all data from the page is being read.
  55142. ** 7) at least 4 bytes have already been read into the output buffer
  55143. **
  55144. ** then data can be read directly from the database file into the
  55145. ** output buffer, bypassing the page-cache altogether. This speeds
  55146. ** up loading large records that span many overflow pages.
  55147. */
  55148. if( (eOp&0x01)==0 /* (1) */
  55149. && offset==0 /* (2) */
  55150. && (bEnd || a==ovflSize) /* (6) */
  55151. && pBt->inTransaction==TRANS_READ /* (4) */
  55152. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  55153. && pBt->pPage1->aData[19]==0x01 /* (5) */
  55154. && &pBuf[-4]>=pBufStart /* (7) */
  55155. ){
  55156. u8 aSave[4];
  55157. u8 *aWrite = &pBuf[-4];
  55158. assert( aWrite>=pBufStart ); /* hence (7) */
  55159. memcpy(aSave, aWrite, 4);
  55160. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  55161. nextPage = get4byte(aWrite);
  55162. memcpy(aWrite, aSave, 4);
  55163. }else
  55164. #endif
  55165. {
  55166. DbPage *pDbPage;
  55167. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  55168. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  55169. );
  55170. if( rc==SQLITE_OK ){
  55171. aPayload = sqlite3PagerGetData(pDbPage);
  55172. nextPage = get4byte(aPayload);
  55173. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  55174. sqlite3PagerUnref(pDbPage);
  55175. offset = 0;
  55176. }
  55177. }
  55178. amt -= a;
  55179. pBuf += a;
  55180. }
  55181. }
  55182. }
  55183. if( rc==SQLITE_OK && amt>0 ){
  55184. return SQLITE_CORRUPT_BKPT;
  55185. }
  55186. return rc;
  55187. }
  55188. /*
  55189. ** Read part of the key associated with cursor pCur. Exactly
  55190. ** "amt" bytes will be transferred into pBuf[]. The transfer
  55191. ** begins at "offset".
  55192. **
  55193. ** The caller must ensure that pCur is pointing to a valid row
  55194. ** in the table.
  55195. **
  55196. ** Return SQLITE_OK on success or an error code if anything goes
  55197. ** wrong. An error is returned if "offset+amt" is larger than
  55198. ** the available payload.
  55199. */
  55200. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  55201. assert( cursorHoldsMutex(pCur) );
  55202. assert( pCur->eState==CURSOR_VALID );
  55203. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  55204. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55205. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  55206. }
  55207. /*
  55208. ** Read part of the data associated with cursor pCur. Exactly
  55209. ** "amt" bytes will be transfered into pBuf[]. The transfer
  55210. ** begins at "offset".
  55211. **
  55212. ** Return SQLITE_OK on success or an error code if anything goes
  55213. ** wrong. An error is returned if "offset+amt" is larger than
  55214. ** the available payload.
  55215. */
  55216. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  55217. int rc;
  55218. #ifndef SQLITE_OMIT_INCRBLOB
  55219. if ( pCur->eState==CURSOR_INVALID ){
  55220. return SQLITE_ABORT;
  55221. }
  55222. #endif
  55223. assert( cursorHoldsMutex(pCur) );
  55224. rc = restoreCursorPosition(pCur);
  55225. if( rc==SQLITE_OK ){
  55226. assert( pCur->eState==CURSOR_VALID );
  55227. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  55228. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55229. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  55230. }
  55231. return rc;
  55232. }
  55233. /*
  55234. ** Return a pointer to payload information from the entry that the
  55235. ** pCur cursor is pointing to. The pointer is to the beginning of
  55236. ** the key if index btrees (pPage->intKey==0) and is the data for
  55237. ** table btrees (pPage->intKey==1). The number of bytes of available
  55238. ** key/data is written into *pAmt. If *pAmt==0, then the value
  55239. ** returned will not be a valid pointer.
  55240. **
  55241. ** This routine is an optimization. It is common for the entire key
  55242. ** and data to fit on the local page and for there to be no overflow
  55243. ** pages. When that is so, this routine can be used to access the
  55244. ** key and data without making a copy. If the key and/or data spills
  55245. ** onto overflow pages, then accessPayload() must be used to reassemble
  55246. ** the key/data and copy it into a preallocated buffer.
  55247. **
  55248. ** The pointer returned by this routine looks directly into the cached
  55249. ** page of the database. The data might change or move the next time
  55250. ** any btree routine is called.
  55251. */
  55252. static const void *fetchPayload(
  55253. BtCursor *pCur, /* Cursor pointing to entry to read from */
  55254. u32 *pAmt /* Write the number of available bytes here */
  55255. ){
  55256. u32 amt;
  55257. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  55258. assert( pCur->eState==CURSOR_VALID );
  55259. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  55260. assert( cursorHoldsMutex(pCur) );
  55261. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55262. assert( pCur->info.nSize>0 );
  55263. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  55264. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  55265. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  55266. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  55267. *pAmt = amt;
  55268. return (void*)pCur->info.pPayload;
  55269. }
  55270. /*
  55271. ** For the entry that cursor pCur is point to, return as
  55272. ** many bytes of the key or data as are available on the local
  55273. ** b-tree page. Write the number of available bytes into *pAmt.
  55274. **
  55275. ** The pointer returned is ephemeral. The key/data may move
  55276. ** or be destroyed on the next call to any Btree routine,
  55277. ** including calls from other threads against the same cache.
  55278. ** Hence, a mutex on the BtShared should be held prior to calling
  55279. ** this routine.
  55280. **
  55281. ** These routines is used to get quick access to key and data
  55282. ** in the common case where no overflow pages are used.
  55283. */
  55284. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  55285. return fetchPayload(pCur, pAmt);
  55286. }
  55287. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  55288. return fetchPayload(pCur, pAmt);
  55289. }
  55290. /*
  55291. ** Move the cursor down to a new child page. The newPgno argument is the
  55292. ** page number of the child page to move to.
  55293. **
  55294. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  55295. ** the new child page does not match the flags field of the parent (i.e.
  55296. ** if an intkey page appears to be the parent of a non-intkey page, or
  55297. ** vice-versa).
  55298. */
  55299. static int moveToChild(BtCursor *pCur, u32 newPgno){
  55300. BtShared *pBt = pCur->pBt;
  55301. assert( cursorHoldsMutex(pCur) );
  55302. assert( pCur->eState==CURSOR_VALID );
  55303. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  55304. assert( pCur->iPage>=0 );
  55305. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  55306. return SQLITE_CORRUPT_BKPT;
  55307. }
  55308. pCur->info.nSize = 0;
  55309. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55310. pCur->iPage++;
  55311. pCur->aiIdx[pCur->iPage] = 0;
  55312. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  55313. pCur, pCur->curPagerFlags);
  55314. }
  55315. #if SQLITE_DEBUG
  55316. /*
  55317. ** Page pParent is an internal (non-leaf) tree page. This function
  55318. ** asserts that page number iChild is the left-child if the iIdx'th
  55319. ** cell in page pParent. Or, if iIdx is equal to the total number of
  55320. ** cells in pParent, that page number iChild is the right-child of
  55321. ** the page.
  55322. */
  55323. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  55324. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  55325. ** in a corrupt database */
  55326. assert( iIdx<=pParent->nCell );
  55327. if( iIdx==pParent->nCell ){
  55328. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  55329. }else{
  55330. assert( get4byte(findCell(pParent, iIdx))==iChild );
  55331. }
  55332. }
  55333. #else
  55334. # define assertParentIndex(x,y,z)
  55335. #endif
  55336. /*
  55337. ** Move the cursor up to the parent page.
  55338. **
  55339. ** pCur->idx is set to the cell index that contains the pointer
  55340. ** to the page we are coming from. If we are coming from the
  55341. ** right-most child page then pCur->idx is set to one more than
  55342. ** the largest cell index.
  55343. */
  55344. static void moveToParent(BtCursor *pCur){
  55345. assert( cursorHoldsMutex(pCur) );
  55346. assert( pCur->eState==CURSOR_VALID );
  55347. assert( pCur->iPage>0 );
  55348. assert( pCur->apPage[pCur->iPage] );
  55349. assertParentIndex(
  55350. pCur->apPage[pCur->iPage-1],
  55351. pCur->aiIdx[pCur->iPage-1],
  55352. pCur->apPage[pCur->iPage]->pgno
  55353. );
  55354. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  55355. pCur->info.nSize = 0;
  55356. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55357. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  55358. }
  55359. /*
  55360. ** Move the cursor to point to the root page of its b-tree structure.
  55361. **
  55362. ** If the table has a virtual root page, then the cursor is moved to point
  55363. ** to the virtual root page instead of the actual root page. A table has a
  55364. ** virtual root page when the actual root page contains no cells and a
  55365. ** single child page. This can only happen with the table rooted at page 1.
  55366. **
  55367. ** If the b-tree structure is empty, the cursor state is set to
  55368. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  55369. ** cell located on the root (or virtual root) page and the cursor state
  55370. ** is set to CURSOR_VALID.
  55371. **
  55372. ** If this function returns successfully, it may be assumed that the
  55373. ** page-header flags indicate that the [virtual] root-page is the expected
  55374. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  55375. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  55376. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  55377. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  55378. ** b-tree).
  55379. */
  55380. static int moveToRoot(BtCursor *pCur){
  55381. MemPage *pRoot;
  55382. int rc = SQLITE_OK;
  55383. assert( cursorHoldsMutex(pCur) );
  55384. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  55385. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  55386. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  55387. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  55388. if( pCur->eState==CURSOR_FAULT ){
  55389. assert( pCur->skipNext!=SQLITE_OK );
  55390. return pCur->skipNext;
  55391. }
  55392. sqlite3BtreeClearCursor(pCur);
  55393. }
  55394. if( pCur->iPage>=0 ){
  55395. while( pCur->iPage ){
  55396. assert( pCur->apPage[pCur->iPage]!=0 );
  55397. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  55398. }
  55399. }else if( pCur->pgnoRoot==0 ){
  55400. pCur->eState = CURSOR_INVALID;
  55401. return SQLITE_OK;
  55402. }else{
  55403. assert( pCur->iPage==(-1) );
  55404. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  55405. 0, pCur->curPagerFlags);
  55406. if( rc!=SQLITE_OK ){
  55407. pCur->eState = CURSOR_INVALID;
  55408. return rc;
  55409. }
  55410. pCur->iPage = 0;
  55411. pCur->curIntKey = pCur->apPage[0]->intKey;
  55412. }
  55413. pRoot = pCur->apPage[0];
  55414. assert( pRoot->pgno==pCur->pgnoRoot );
  55415. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  55416. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  55417. ** NULL, the caller expects a table b-tree. If this is not the case,
  55418. ** return an SQLITE_CORRUPT error.
  55419. **
  55420. ** Earlier versions of SQLite assumed that this test could not fail
  55421. ** if the root page was already loaded when this function was called (i.e.
  55422. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  55423. ** in such a way that page pRoot is linked into a second b-tree table
  55424. ** (or the freelist). */
  55425. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  55426. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  55427. return SQLITE_CORRUPT_BKPT;
  55428. }
  55429. pCur->aiIdx[0] = 0;
  55430. pCur->info.nSize = 0;
  55431. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  55432. if( pRoot->nCell>0 ){
  55433. pCur->eState = CURSOR_VALID;
  55434. }else if( !pRoot->leaf ){
  55435. Pgno subpage;
  55436. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  55437. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  55438. pCur->eState = CURSOR_VALID;
  55439. rc = moveToChild(pCur, subpage);
  55440. }else{
  55441. pCur->eState = CURSOR_INVALID;
  55442. }
  55443. return rc;
  55444. }
  55445. /*
  55446. ** Move the cursor down to the left-most leaf entry beneath the
  55447. ** entry to which it is currently pointing.
  55448. **
  55449. ** The left-most leaf is the one with the smallest key - the first
  55450. ** in ascending order.
  55451. */
  55452. static int moveToLeftmost(BtCursor *pCur){
  55453. Pgno pgno;
  55454. int rc = SQLITE_OK;
  55455. MemPage *pPage;
  55456. assert( cursorHoldsMutex(pCur) );
  55457. assert( pCur->eState==CURSOR_VALID );
  55458. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  55459. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  55460. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  55461. rc = moveToChild(pCur, pgno);
  55462. }
  55463. return rc;
  55464. }
  55465. /*
  55466. ** Move the cursor down to the right-most leaf entry beneath the
  55467. ** page to which it is currently pointing. Notice the difference
  55468. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  55469. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  55470. ** finds the right-most entry beneath the *page*.
  55471. **
  55472. ** The right-most entry is the one with the largest key - the last
  55473. ** key in ascending order.
  55474. */
  55475. static int moveToRightmost(BtCursor *pCur){
  55476. Pgno pgno;
  55477. int rc = SQLITE_OK;
  55478. MemPage *pPage = 0;
  55479. assert( cursorHoldsMutex(pCur) );
  55480. assert( pCur->eState==CURSOR_VALID );
  55481. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  55482. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55483. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  55484. rc = moveToChild(pCur, pgno);
  55485. if( rc ) return rc;
  55486. }
  55487. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  55488. assert( pCur->info.nSize==0 );
  55489. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  55490. return SQLITE_OK;
  55491. }
  55492. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  55493. ** on success. Set *pRes to 0 if the cursor actually points to something
  55494. ** or set *pRes to 1 if the table is empty.
  55495. */
  55496. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  55497. int rc;
  55498. assert( cursorHoldsMutex(pCur) );
  55499. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  55500. rc = moveToRoot(pCur);
  55501. if( rc==SQLITE_OK ){
  55502. if( pCur->eState==CURSOR_INVALID ){
  55503. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  55504. *pRes = 1;
  55505. }else{
  55506. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  55507. *pRes = 0;
  55508. rc = moveToLeftmost(pCur);
  55509. }
  55510. }
  55511. return rc;
  55512. }
  55513. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  55514. ** on success. Set *pRes to 0 if the cursor actually points to something
  55515. ** or set *pRes to 1 if the table is empty.
  55516. */
  55517. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  55518. int rc;
  55519. assert( cursorHoldsMutex(pCur) );
  55520. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  55521. /* If the cursor already points to the last entry, this is a no-op. */
  55522. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  55523. #ifdef SQLITE_DEBUG
  55524. /* This block serves to assert() that the cursor really does point
  55525. ** to the last entry in the b-tree. */
  55526. int ii;
  55527. for(ii=0; ii<pCur->iPage; ii++){
  55528. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  55529. }
  55530. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  55531. assert( pCur->apPage[pCur->iPage]->leaf );
  55532. #endif
  55533. return SQLITE_OK;
  55534. }
  55535. rc = moveToRoot(pCur);
  55536. if( rc==SQLITE_OK ){
  55537. if( CURSOR_INVALID==pCur->eState ){
  55538. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  55539. *pRes = 1;
  55540. }else{
  55541. assert( pCur->eState==CURSOR_VALID );
  55542. *pRes = 0;
  55543. rc = moveToRightmost(pCur);
  55544. if( rc==SQLITE_OK ){
  55545. pCur->curFlags |= BTCF_AtLast;
  55546. }else{
  55547. pCur->curFlags &= ~BTCF_AtLast;
  55548. }
  55549. }
  55550. }
  55551. return rc;
  55552. }
  55553. /* Move the cursor so that it points to an entry near the key
  55554. ** specified by pIdxKey or intKey. Return a success code.
  55555. **
  55556. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  55557. ** must be NULL. For index tables, pIdxKey is used and intKey
  55558. ** is ignored.
  55559. **
  55560. ** If an exact match is not found, then the cursor is always
  55561. ** left pointing at a leaf page which would hold the entry if it
  55562. ** were present. The cursor might point to an entry that comes
  55563. ** before or after the key.
  55564. **
  55565. ** An integer is written into *pRes which is the result of
  55566. ** comparing the key with the entry to which the cursor is
  55567. ** pointing. The meaning of the integer written into
  55568. ** *pRes is as follows:
  55569. **
  55570. ** *pRes<0 The cursor is left pointing at an entry that
  55571. ** is smaller than intKey/pIdxKey or if the table is empty
  55572. ** and the cursor is therefore left point to nothing.
  55573. **
  55574. ** *pRes==0 The cursor is left pointing at an entry that
  55575. ** exactly matches intKey/pIdxKey.
  55576. **
  55577. ** *pRes>0 The cursor is left pointing at an entry that
  55578. ** is larger than intKey/pIdxKey.
  55579. **
  55580. */
  55581. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  55582. BtCursor *pCur, /* The cursor to be moved */
  55583. UnpackedRecord *pIdxKey, /* Unpacked index key */
  55584. i64 intKey, /* The table key */
  55585. int biasRight, /* If true, bias the search to the high end */
  55586. int *pRes /* Write search results here */
  55587. ){
  55588. int rc;
  55589. RecordCompare xRecordCompare;
  55590. assert( cursorHoldsMutex(pCur) );
  55591. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  55592. assert( pRes );
  55593. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  55594. /* If the cursor is already positioned at the point we are trying
  55595. ** to move to, then just return without doing any work */
  55596. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  55597. && pCur->curIntKey
  55598. ){
  55599. if( pCur->info.nKey==intKey ){
  55600. *pRes = 0;
  55601. return SQLITE_OK;
  55602. }
  55603. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  55604. *pRes = -1;
  55605. return SQLITE_OK;
  55606. }
  55607. }
  55608. if( pIdxKey ){
  55609. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  55610. pIdxKey->errCode = 0;
  55611. assert( pIdxKey->default_rc==1
  55612. || pIdxKey->default_rc==0
  55613. || pIdxKey->default_rc==-1
  55614. );
  55615. }else{
  55616. xRecordCompare = 0; /* All keys are integers */
  55617. }
  55618. rc = moveToRoot(pCur);
  55619. if( rc ){
  55620. return rc;
  55621. }
  55622. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  55623. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  55624. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  55625. if( pCur->eState==CURSOR_INVALID ){
  55626. *pRes = -1;
  55627. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  55628. return SQLITE_OK;
  55629. }
  55630. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  55631. assert( pCur->curIntKey || pIdxKey );
  55632. for(;;){
  55633. int lwr, upr, idx, c;
  55634. Pgno chldPg;
  55635. MemPage *pPage = pCur->apPage[pCur->iPage];
  55636. u8 *pCell; /* Pointer to current cell in pPage */
  55637. /* pPage->nCell must be greater than zero. If this is the root-page
  55638. ** the cursor would have been INVALID above and this for(;;) loop
  55639. ** not run. If this is not the root-page, then the moveToChild() routine
  55640. ** would have already detected db corruption. Similarly, pPage must
  55641. ** be the right kind (index or table) of b-tree page. Otherwise
  55642. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  55643. assert( pPage->nCell>0 );
  55644. assert( pPage->intKey==(pIdxKey==0) );
  55645. lwr = 0;
  55646. upr = pPage->nCell-1;
  55647. assert( biasRight==0 || biasRight==1 );
  55648. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  55649. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55650. if( xRecordCompare==0 ){
  55651. for(;;){
  55652. i64 nCellKey;
  55653. pCell = findCellPastPtr(pPage, idx);
  55654. if( pPage->intKeyLeaf ){
  55655. while( 0x80 <= *(pCell++) ){
  55656. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  55657. }
  55658. }
  55659. getVarint(pCell, (u64*)&nCellKey);
  55660. if( nCellKey<intKey ){
  55661. lwr = idx+1;
  55662. if( lwr>upr ){ c = -1; break; }
  55663. }else if( nCellKey>intKey ){
  55664. upr = idx-1;
  55665. if( lwr>upr ){ c = +1; break; }
  55666. }else{
  55667. assert( nCellKey==intKey );
  55668. pCur->curFlags |= BTCF_ValidNKey;
  55669. pCur->info.nKey = nCellKey;
  55670. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55671. if( !pPage->leaf ){
  55672. lwr = idx;
  55673. goto moveto_next_layer;
  55674. }else{
  55675. *pRes = 0;
  55676. rc = SQLITE_OK;
  55677. goto moveto_finish;
  55678. }
  55679. }
  55680. assert( lwr+upr>=0 );
  55681. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  55682. }
  55683. }else{
  55684. for(;;){
  55685. int nCell; /* Size of the pCell cell in bytes */
  55686. pCell = findCellPastPtr(pPage, idx);
  55687. /* The maximum supported page-size is 65536 bytes. This means that
  55688. ** the maximum number of record bytes stored on an index B-Tree
  55689. ** page is less than 16384 bytes and may be stored as a 2-byte
  55690. ** varint. This information is used to attempt to avoid parsing
  55691. ** the entire cell by checking for the cases where the record is
  55692. ** stored entirely within the b-tree page by inspecting the first
  55693. ** 2 bytes of the cell.
  55694. */
  55695. nCell = pCell[0];
  55696. if( nCell<=pPage->max1bytePayload ){
  55697. /* This branch runs if the record-size field of the cell is a
  55698. ** single byte varint and the record fits entirely on the main
  55699. ** b-tree page. */
  55700. testcase( pCell+nCell+1==pPage->aDataEnd );
  55701. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  55702. }else if( !(pCell[1] & 0x80)
  55703. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  55704. ){
  55705. /* The record-size field is a 2 byte varint and the record
  55706. ** fits entirely on the main b-tree page. */
  55707. testcase( pCell+nCell+2==pPage->aDataEnd );
  55708. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  55709. }else{
  55710. /* The record flows over onto one or more overflow pages. In
  55711. ** this case the whole cell needs to be parsed, a buffer allocated
  55712. ** and accessPayload() used to retrieve the record into the
  55713. ** buffer before VdbeRecordCompare() can be called.
  55714. **
  55715. ** If the record is corrupt, the xRecordCompare routine may read
  55716. ** up to two varints past the end of the buffer. An extra 18
  55717. ** bytes of padding is allocated at the end of the buffer in
  55718. ** case this happens. */
  55719. void *pCellKey;
  55720. u8 * const pCellBody = pCell - pPage->childPtrSize;
  55721. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  55722. nCell = (int)pCur->info.nKey;
  55723. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  55724. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  55725. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  55726. testcase( nCell==2 ); /* Minimum legal index key size */
  55727. if( nCell<2 ){
  55728. rc = SQLITE_CORRUPT_BKPT;
  55729. goto moveto_finish;
  55730. }
  55731. pCellKey = sqlite3Malloc( nCell+18 );
  55732. if( pCellKey==0 ){
  55733. rc = SQLITE_NOMEM;
  55734. goto moveto_finish;
  55735. }
  55736. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55737. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  55738. if( rc ){
  55739. sqlite3_free(pCellKey);
  55740. goto moveto_finish;
  55741. }
  55742. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  55743. sqlite3_free(pCellKey);
  55744. }
  55745. assert(
  55746. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  55747. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  55748. );
  55749. if( c<0 ){
  55750. lwr = idx+1;
  55751. }else if( c>0 ){
  55752. upr = idx-1;
  55753. }else{
  55754. assert( c==0 );
  55755. *pRes = 0;
  55756. rc = SQLITE_OK;
  55757. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55758. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  55759. goto moveto_finish;
  55760. }
  55761. if( lwr>upr ) break;
  55762. assert( lwr+upr>=0 );
  55763. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  55764. }
  55765. }
  55766. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  55767. assert( pPage->isInit );
  55768. if( pPage->leaf ){
  55769. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55770. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55771. *pRes = c;
  55772. rc = SQLITE_OK;
  55773. goto moveto_finish;
  55774. }
  55775. moveto_next_layer:
  55776. if( lwr>=pPage->nCell ){
  55777. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55778. }else{
  55779. chldPg = get4byte(findCell(pPage, lwr));
  55780. }
  55781. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  55782. rc = moveToChild(pCur, chldPg);
  55783. if( rc ) break;
  55784. }
  55785. moveto_finish:
  55786. pCur->info.nSize = 0;
  55787. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55788. return rc;
  55789. }
  55790. /*
  55791. ** Return TRUE if the cursor is not pointing at an entry of the table.
  55792. **
  55793. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  55794. ** past the last entry in the table or sqlite3BtreePrev() moves past
  55795. ** the first entry. TRUE is also returned if the table is empty.
  55796. */
  55797. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  55798. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  55799. ** have been deleted? This API will need to change to return an error code
  55800. ** as well as the boolean result value.
  55801. */
  55802. return (CURSOR_VALID!=pCur->eState);
  55803. }
  55804. /*
  55805. ** Advance the cursor to the next entry in the database. If
  55806. ** successful then set *pRes=0. If the cursor
  55807. ** was already pointing to the last entry in the database before
  55808. ** this routine was called, then set *pRes=1.
  55809. **
  55810. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  55811. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  55812. ** to the next cell on the current page. The (slower) btreeNext() helper
  55813. ** routine is called when it is necessary to move to a different page or
  55814. ** to restore the cursor.
  55815. **
  55816. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  55817. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  55818. ** if this routine could have been skipped if that SQL index had been
  55819. ** a unique index. Otherwise the caller will have set *pRes to zero.
  55820. ** Zero is the common case. The btree implementation is free to use the
  55821. ** initial *pRes value as a hint to improve performance, but the current
  55822. ** SQLite btree implementation does not. (Note that the comdb2 btree
  55823. ** implementation does use this hint, however.)
  55824. */
  55825. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  55826. int rc;
  55827. int idx;
  55828. MemPage *pPage;
  55829. assert( cursorHoldsMutex(pCur) );
  55830. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55831. assert( *pRes==0 );
  55832. if( pCur->eState!=CURSOR_VALID ){
  55833. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  55834. rc = restoreCursorPosition(pCur);
  55835. if( rc!=SQLITE_OK ){
  55836. return rc;
  55837. }
  55838. if( CURSOR_INVALID==pCur->eState ){
  55839. *pRes = 1;
  55840. return SQLITE_OK;
  55841. }
  55842. if( pCur->skipNext ){
  55843. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  55844. pCur->eState = CURSOR_VALID;
  55845. if( pCur->skipNext>0 ){
  55846. pCur->skipNext = 0;
  55847. return SQLITE_OK;
  55848. }
  55849. pCur->skipNext = 0;
  55850. }
  55851. }
  55852. pPage = pCur->apPage[pCur->iPage];
  55853. idx = ++pCur->aiIdx[pCur->iPage];
  55854. assert( pPage->isInit );
  55855. /* If the database file is corrupt, it is possible for the value of idx
  55856. ** to be invalid here. This can only occur if a second cursor modifies
  55857. ** the page while cursor pCur is holding a reference to it. Which can
  55858. ** only happen if the database is corrupt in such a way as to link the
  55859. ** page into more than one b-tree structure. */
  55860. testcase( idx>pPage->nCell );
  55861. if( idx>=pPage->nCell ){
  55862. if( !pPage->leaf ){
  55863. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  55864. if( rc ) return rc;
  55865. return moveToLeftmost(pCur);
  55866. }
  55867. do{
  55868. if( pCur->iPage==0 ){
  55869. *pRes = 1;
  55870. pCur->eState = CURSOR_INVALID;
  55871. return SQLITE_OK;
  55872. }
  55873. moveToParent(pCur);
  55874. pPage = pCur->apPage[pCur->iPage];
  55875. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  55876. if( pPage->intKey ){
  55877. return sqlite3BtreeNext(pCur, pRes);
  55878. }else{
  55879. return SQLITE_OK;
  55880. }
  55881. }
  55882. if( pPage->leaf ){
  55883. return SQLITE_OK;
  55884. }else{
  55885. return moveToLeftmost(pCur);
  55886. }
  55887. }
  55888. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  55889. MemPage *pPage;
  55890. assert( cursorHoldsMutex(pCur) );
  55891. assert( pRes!=0 );
  55892. assert( *pRes==0 || *pRes==1 );
  55893. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55894. pCur->info.nSize = 0;
  55895. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55896. *pRes = 0;
  55897. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  55898. pPage = pCur->apPage[pCur->iPage];
  55899. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  55900. pCur->aiIdx[pCur->iPage]--;
  55901. return btreeNext(pCur, pRes);
  55902. }
  55903. if( pPage->leaf ){
  55904. return SQLITE_OK;
  55905. }else{
  55906. return moveToLeftmost(pCur);
  55907. }
  55908. }
  55909. /*
  55910. ** Step the cursor to the back to the previous entry in the database. If
  55911. ** successful then set *pRes=0. If the cursor
  55912. ** was already pointing to the first entry in the database before
  55913. ** this routine was called, then set *pRes=1.
  55914. **
  55915. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  55916. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  55917. ** to the previous cell on the current page. The (slower) btreePrevious()
  55918. ** helper routine is called when it is necessary to move to a different page
  55919. ** or to restore the cursor.
  55920. **
  55921. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  55922. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  55923. ** if this routine could have been skipped if that SQL index had been
  55924. ** a unique index. Otherwise the caller will have set *pRes to zero.
  55925. ** Zero is the common case. The btree implementation is free to use the
  55926. ** initial *pRes value as a hint to improve performance, but the current
  55927. ** SQLite btree implementation does not. (Note that the comdb2 btree
  55928. ** implementation does use this hint, however.)
  55929. */
  55930. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  55931. int rc;
  55932. MemPage *pPage;
  55933. assert( cursorHoldsMutex(pCur) );
  55934. assert( pRes!=0 );
  55935. assert( *pRes==0 );
  55936. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55937. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  55938. assert( pCur->info.nSize==0 );
  55939. if( pCur->eState!=CURSOR_VALID ){
  55940. rc = restoreCursorPosition(pCur);
  55941. if( rc!=SQLITE_OK ){
  55942. return rc;
  55943. }
  55944. if( CURSOR_INVALID==pCur->eState ){
  55945. *pRes = 1;
  55946. return SQLITE_OK;
  55947. }
  55948. if( pCur->skipNext ){
  55949. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  55950. pCur->eState = CURSOR_VALID;
  55951. if( pCur->skipNext<0 ){
  55952. pCur->skipNext = 0;
  55953. return SQLITE_OK;
  55954. }
  55955. pCur->skipNext = 0;
  55956. }
  55957. }
  55958. pPage = pCur->apPage[pCur->iPage];
  55959. assert( pPage->isInit );
  55960. if( !pPage->leaf ){
  55961. int idx = pCur->aiIdx[pCur->iPage];
  55962. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  55963. if( rc ) return rc;
  55964. rc = moveToRightmost(pCur);
  55965. }else{
  55966. while( pCur->aiIdx[pCur->iPage]==0 ){
  55967. if( pCur->iPage==0 ){
  55968. pCur->eState = CURSOR_INVALID;
  55969. *pRes = 1;
  55970. return SQLITE_OK;
  55971. }
  55972. moveToParent(pCur);
  55973. }
  55974. assert( pCur->info.nSize==0 );
  55975. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  55976. pCur->aiIdx[pCur->iPage]--;
  55977. pPage = pCur->apPage[pCur->iPage];
  55978. if( pPage->intKey && !pPage->leaf ){
  55979. rc = sqlite3BtreePrevious(pCur, pRes);
  55980. }else{
  55981. rc = SQLITE_OK;
  55982. }
  55983. }
  55984. return rc;
  55985. }
  55986. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  55987. assert( cursorHoldsMutex(pCur) );
  55988. assert( pRes!=0 );
  55989. assert( *pRes==0 || *pRes==1 );
  55990. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55991. *pRes = 0;
  55992. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  55993. pCur->info.nSize = 0;
  55994. if( pCur->eState!=CURSOR_VALID
  55995. || pCur->aiIdx[pCur->iPage]==0
  55996. || pCur->apPage[pCur->iPage]->leaf==0
  55997. ){
  55998. return btreePrevious(pCur, pRes);
  55999. }
  56000. pCur->aiIdx[pCur->iPage]--;
  56001. return SQLITE_OK;
  56002. }
  56003. /*
  56004. ** Allocate a new page from the database file.
  56005. **
  56006. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  56007. ** has already been called on the new page.) The new page has also
  56008. ** been referenced and the calling routine is responsible for calling
  56009. ** sqlite3PagerUnref() on the new page when it is done.
  56010. **
  56011. ** SQLITE_OK is returned on success. Any other return value indicates
  56012. ** an error. *ppPage is set to NULL in the event of an error.
  56013. **
  56014. ** If the "nearby" parameter is not 0, then an effort is made to
  56015. ** locate a page close to the page number "nearby". This can be used in an
  56016. ** attempt to keep related pages close to each other in the database file,
  56017. ** which in turn can make database access faster.
  56018. **
  56019. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  56020. ** anywhere on the free-list, then it is guaranteed to be returned. If
  56021. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  56022. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  56023. ** are no restrictions on which page is returned.
  56024. */
  56025. static int allocateBtreePage(
  56026. BtShared *pBt, /* The btree */
  56027. MemPage **ppPage, /* Store pointer to the allocated page here */
  56028. Pgno *pPgno, /* Store the page number here */
  56029. Pgno nearby, /* Search for a page near this one */
  56030. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  56031. ){
  56032. MemPage *pPage1;
  56033. int rc;
  56034. u32 n; /* Number of pages on the freelist */
  56035. u32 k; /* Number of leaves on the trunk of the freelist */
  56036. MemPage *pTrunk = 0;
  56037. MemPage *pPrevTrunk = 0;
  56038. Pgno mxPage; /* Total size of the database file */
  56039. assert( sqlite3_mutex_held(pBt->mutex) );
  56040. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  56041. pPage1 = pBt->pPage1;
  56042. mxPage = btreePagecount(pBt);
  56043. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  56044. ** stores stores the total number of pages on the freelist. */
  56045. n = get4byte(&pPage1->aData[36]);
  56046. testcase( n==mxPage-1 );
  56047. if( n>=mxPage ){
  56048. return SQLITE_CORRUPT_BKPT;
  56049. }
  56050. if( n>0 ){
  56051. /* There are pages on the freelist. Reuse one of those pages. */
  56052. Pgno iTrunk;
  56053. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  56054. u32 nSearch = 0; /* Count of the number of search attempts */
  56055. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  56056. ** shows that the page 'nearby' is somewhere on the free-list, then
  56057. ** the entire-list will be searched for that page.
  56058. */
  56059. #ifndef SQLITE_OMIT_AUTOVACUUM
  56060. if( eMode==BTALLOC_EXACT ){
  56061. if( nearby<=mxPage ){
  56062. u8 eType;
  56063. assert( nearby>0 );
  56064. assert( pBt->autoVacuum );
  56065. rc = ptrmapGet(pBt, nearby, &eType, 0);
  56066. if( rc ) return rc;
  56067. if( eType==PTRMAP_FREEPAGE ){
  56068. searchList = 1;
  56069. }
  56070. }
  56071. }else if( eMode==BTALLOC_LE ){
  56072. searchList = 1;
  56073. }
  56074. #endif
  56075. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  56076. ** first free-list trunk page. iPrevTrunk is initially 1.
  56077. */
  56078. rc = sqlite3PagerWrite(pPage1->pDbPage);
  56079. if( rc ) return rc;
  56080. put4byte(&pPage1->aData[36], n-1);
  56081. /* The code within this loop is run only once if the 'searchList' variable
  56082. ** is not true. Otherwise, it runs once for each trunk-page on the
  56083. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  56084. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  56085. */
  56086. do {
  56087. pPrevTrunk = pTrunk;
  56088. if( pPrevTrunk ){
  56089. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  56090. ** is the page number of the next freelist trunk page in the list or
  56091. ** zero if this is the last freelist trunk page. */
  56092. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  56093. }else{
  56094. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  56095. ** stores the page number of the first page of the freelist, or zero if
  56096. ** the freelist is empty. */
  56097. iTrunk = get4byte(&pPage1->aData[32]);
  56098. }
  56099. testcase( iTrunk==mxPage );
  56100. if( iTrunk>mxPage || nSearch++ > n ){
  56101. rc = SQLITE_CORRUPT_BKPT;
  56102. }else{
  56103. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  56104. }
  56105. if( rc ){
  56106. pTrunk = 0;
  56107. goto end_allocate_page;
  56108. }
  56109. assert( pTrunk!=0 );
  56110. assert( pTrunk->aData!=0 );
  56111. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  56112. ** is the number of leaf page pointers to follow. */
  56113. k = get4byte(&pTrunk->aData[4]);
  56114. if( k==0 && !searchList ){
  56115. /* The trunk has no leaves and the list is not being searched.
  56116. ** So extract the trunk page itself and use it as the newly
  56117. ** allocated page */
  56118. assert( pPrevTrunk==0 );
  56119. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56120. if( rc ){
  56121. goto end_allocate_page;
  56122. }
  56123. *pPgno = iTrunk;
  56124. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  56125. *ppPage = pTrunk;
  56126. pTrunk = 0;
  56127. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  56128. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  56129. /* Value of k is out of range. Database corruption */
  56130. rc = SQLITE_CORRUPT_BKPT;
  56131. goto end_allocate_page;
  56132. #ifndef SQLITE_OMIT_AUTOVACUUM
  56133. }else if( searchList
  56134. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  56135. ){
  56136. /* The list is being searched and this trunk page is the page
  56137. ** to allocate, regardless of whether it has leaves.
  56138. */
  56139. *pPgno = iTrunk;
  56140. *ppPage = pTrunk;
  56141. searchList = 0;
  56142. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56143. if( rc ){
  56144. goto end_allocate_page;
  56145. }
  56146. if( k==0 ){
  56147. if( !pPrevTrunk ){
  56148. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  56149. }else{
  56150. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  56151. if( rc!=SQLITE_OK ){
  56152. goto end_allocate_page;
  56153. }
  56154. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  56155. }
  56156. }else{
  56157. /* The trunk page is required by the caller but it contains
  56158. ** pointers to free-list leaves. The first leaf becomes a trunk
  56159. ** page in this case.
  56160. */
  56161. MemPage *pNewTrunk;
  56162. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  56163. if( iNewTrunk>mxPage ){
  56164. rc = SQLITE_CORRUPT_BKPT;
  56165. goto end_allocate_page;
  56166. }
  56167. testcase( iNewTrunk==mxPage );
  56168. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  56169. if( rc!=SQLITE_OK ){
  56170. goto end_allocate_page;
  56171. }
  56172. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  56173. if( rc!=SQLITE_OK ){
  56174. releasePage(pNewTrunk);
  56175. goto end_allocate_page;
  56176. }
  56177. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  56178. put4byte(&pNewTrunk->aData[4], k-1);
  56179. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  56180. releasePage(pNewTrunk);
  56181. if( !pPrevTrunk ){
  56182. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  56183. put4byte(&pPage1->aData[32], iNewTrunk);
  56184. }else{
  56185. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  56186. if( rc ){
  56187. goto end_allocate_page;
  56188. }
  56189. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  56190. }
  56191. }
  56192. pTrunk = 0;
  56193. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  56194. #endif
  56195. }else if( k>0 ){
  56196. /* Extract a leaf from the trunk */
  56197. u32 closest;
  56198. Pgno iPage;
  56199. unsigned char *aData = pTrunk->aData;
  56200. if( nearby>0 ){
  56201. u32 i;
  56202. closest = 0;
  56203. if( eMode==BTALLOC_LE ){
  56204. for(i=0; i<k; i++){
  56205. iPage = get4byte(&aData[8+i*4]);
  56206. if( iPage<=nearby ){
  56207. closest = i;
  56208. break;
  56209. }
  56210. }
  56211. }else{
  56212. int dist;
  56213. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  56214. for(i=1; i<k; i++){
  56215. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  56216. if( d2<dist ){
  56217. closest = i;
  56218. dist = d2;
  56219. }
  56220. }
  56221. }
  56222. }else{
  56223. closest = 0;
  56224. }
  56225. iPage = get4byte(&aData[8+closest*4]);
  56226. testcase( iPage==mxPage );
  56227. if( iPage>mxPage ){
  56228. rc = SQLITE_CORRUPT_BKPT;
  56229. goto end_allocate_page;
  56230. }
  56231. testcase( iPage==mxPage );
  56232. if( !searchList
  56233. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  56234. ){
  56235. int noContent;
  56236. *pPgno = iPage;
  56237. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  56238. ": %d more free pages\n",
  56239. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  56240. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56241. if( rc ) goto end_allocate_page;
  56242. if( closest<k-1 ){
  56243. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  56244. }
  56245. put4byte(&aData[4], k-1);
  56246. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  56247. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  56248. if( rc==SQLITE_OK ){
  56249. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  56250. if( rc!=SQLITE_OK ){
  56251. releasePage(*ppPage);
  56252. *ppPage = 0;
  56253. }
  56254. }
  56255. searchList = 0;
  56256. }
  56257. }
  56258. releasePage(pPrevTrunk);
  56259. pPrevTrunk = 0;
  56260. }while( searchList );
  56261. }else{
  56262. /* There are no pages on the freelist, so append a new page to the
  56263. ** database image.
  56264. **
  56265. ** Normally, new pages allocated by this block can be requested from the
  56266. ** pager layer with the 'no-content' flag set. This prevents the pager
  56267. ** from trying to read the pages content from disk. However, if the
  56268. ** current transaction has already run one or more incremental-vacuum
  56269. ** steps, then the page we are about to allocate may contain content
  56270. ** that is required in the event of a rollback. In this case, do
  56271. ** not set the no-content flag. This causes the pager to load and journal
  56272. ** the current page content before overwriting it.
  56273. **
  56274. ** Note that the pager will not actually attempt to load or journal
  56275. ** content for any page that really does lie past the end of the database
  56276. ** file on disk. So the effects of disabling the no-content optimization
  56277. ** here are confined to those pages that lie between the end of the
  56278. ** database image and the end of the database file.
  56279. */
  56280. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  56281. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56282. if( rc ) return rc;
  56283. pBt->nPage++;
  56284. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  56285. #ifndef SQLITE_OMIT_AUTOVACUUM
  56286. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  56287. /* If *pPgno refers to a pointer-map page, allocate two new pages
  56288. ** at the end of the file instead of one. The first allocated page
  56289. ** becomes a new pointer-map page, the second is used by the caller.
  56290. */
  56291. MemPage *pPg = 0;
  56292. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  56293. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  56294. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  56295. if( rc==SQLITE_OK ){
  56296. rc = sqlite3PagerWrite(pPg->pDbPage);
  56297. releasePage(pPg);
  56298. }
  56299. if( rc ) return rc;
  56300. pBt->nPage++;
  56301. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  56302. }
  56303. #endif
  56304. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  56305. *pPgno = pBt->nPage;
  56306. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  56307. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  56308. if( rc ) return rc;
  56309. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  56310. if( rc!=SQLITE_OK ){
  56311. releasePage(*ppPage);
  56312. *ppPage = 0;
  56313. }
  56314. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  56315. }
  56316. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  56317. end_allocate_page:
  56318. releasePage(pTrunk);
  56319. releasePage(pPrevTrunk);
  56320. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  56321. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  56322. return rc;
  56323. }
  56324. /*
  56325. ** This function is used to add page iPage to the database file free-list.
  56326. ** It is assumed that the page is not already a part of the free-list.
  56327. **
  56328. ** The value passed as the second argument to this function is optional.
  56329. ** If the caller happens to have a pointer to the MemPage object
  56330. ** corresponding to page iPage handy, it may pass it as the second value.
  56331. ** Otherwise, it may pass NULL.
  56332. **
  56333. ** If a pointer to a MemPage object is passed as the second argument,
  56334. ** its reference count is not altered by this function.
  56335. */
  56336. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  56337. MemPage *pTrunk = 0; /* Free-list trunk page */
  56338. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  56339. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  56340. MemPage *pPage; /* Page being freed. May be NULL. */
  56341. int rc; /* Return Code */
  56342. int nFree; /* Initial number of pages on free-list */
  56343. assert( sqlite3_mutex_held(pBt->mutex) );
  56344. assert( CORRUPT_DB || iPage>1 );
  56345. assert( !pMemPage || pMemPage->pgno==iPage );
  56346. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  56347. if( pMemPage ){
  56348. pPage = pMemPage;
  56349. sqlite3PagerRef(pPage->pDbPage);
  56350. }else{
  56351. pPage = btreePageLookup(pBt, iPage);
  56352. }
  56353. /* Increment the free page count on pPage1 */
  56354. rc = sqlite3PagerWrite(pPage1->pDbPage);
  56355. if( rc ) goto freepage_out;
  56356. nFree = get4byte(&pPage1->aData[36]);
  56357. put4byte(&pPage1->aData[36], nFree+1);
  56358. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  56359. /* If the secure_delete option is enabled, then
  56360. ** always fully overwrite deleted information with zeros.
  56361. */
  56362. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  56363. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  56364. ){
  56365. goto freepage_out;
  56366. }
  56367. memset(pPage->aData, 0, pPage->pBt->pageSize);
  56368. }
  56369. /* If the database supports auto-vacuum, write an entry in the pointer-map
  56370. ** to indicate that the page is free.
  56371. */
  56372. if( ISAUTOVACUUM ){
  56373. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  56374. if( rc ) goto freepage_out;
  56375. }
  56376. /* Now manipulate the actual database free-list structure. There are two
  56377. ** possibilities. If the free-list is currently empty, or if the first
  56378. ** trunk page in the free-list is full, then this page will become a
  56379. ** new free-list trunk page. Otherwise, it will become a leaf of the
  56380. ** first trunk page in the current free-list. This block tests if it
  56381. ** is possible to add the page as a new free-list leaf.
  56382. */
  56383. if( nFree!=0 ){
  56384. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  56385. iTrunk = get4byte(&pPage1->aData[32]);
  56386. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  56387. if( rc!=SQLITE_OK ){
  56388. goto freepage_out;
  56389. }
  56390. nLeaf = get4byte(&pTrunk->aData[4]);
  56391. assert( pBt->usableSize>32 );
  56392. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  56393. rc = SQLITE_CORRUPT_BKPT;
  56394. goto freepage_out;
  56395. }
  56396. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  56397. /* In this case there is room on the trunk page to insert the page
  56398. ** being freed as a new leaf.
  56399. **
  56400. ** Note that the trunk page is not really full until it contains
  56401. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  56402. ** coded. But due to a coding error in versions of SQLite prior to
  56403. ** 3.6.0, databases with freelist trunk pages holding more than
  56404. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  56405. ** to maintain backwards compatibility with older versions of SQLite,
  56406. ** we will continue to restrict the number of entries to usableSize/4 - 8
  56407. ** for now. At some point in the future (once everyone has upgraded
  56408. ** to 3.6.0 or later) we should consider fixing the conditional above
  56409. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  56410. **
  56411. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  56412. ** avoid using the last six entries in the freelist trunk page array in
  56413. ** order that database files created by newer versions of SQLite can be
  56414. ** read by older versions of SQLite.
  56415. */
  56416. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56417. if( rc==SQLITE_OK ){
  56418. put4byte(&pTrunk->aData[4], nLeaf+1);
  56419. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  56420. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  56421. sqlite3PagerDontWrite(pPage->pDbPage);
  56422. }
  56423. rc = btreeSetHasContent(pBt, iPage);
  56424. }
  56425. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  56426. goto freepage_out;
  56427. }
  56428. }
  56429. /* If control flows to this point, then it was not possible to add the
  56430. ** the page being freed as a leaf page of the first trunk in the free-list.
  56431. ** Possibly because the free-list is empty, or possibly because the
  56432. ** first trunk in the free-list is full. Either way, the page being freed
  56433. ** will become the new first trunk page in the free-list.
  56434. */
  56435. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  56436. goto freepage_out;
  56437. }
  56438. rc = sqlite3PagerWrite(pPage->pDbPage);
  56439. if( rc!=SQLITE_OK ){
  56440. goto freepage_out;
  56441. }
  56442. put4byte(pPage->aData, iTrunk);
  56443. put4byte(&pPage->aData[4], 0);
  56444. put4byte(&pPage1->aData[32], iPage);
  56445. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  56446. freepage_out:
  56447. if( pPage ){
  56448. pPage->isInit = 0;
  56449. }
  56450. releasePage(pPage);
  56451. releasePage(pTrunk);
  56452. return rc;
  56453. }
  56454. static void freePage(MemPage *pPage, int *pRC){
  56455. if( (*pRC)==SQLITE_OK ){
  56456. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  56457. }
  56458. }
  56459. /*
  56460. ** Free any overflow pages associated with the given Cell. Write the
  56461. ** local Cell size (the number of bytes on the original page, omitting
  56462. ** overflow) into *pnSize.
  56463. */
  56464. static int clearCell(
  56465. MemPage *pPage, /* The page that contains the Cell */
  56466. unsigned char *pCell, /* First byte of the Cell */
  56467. u16 *pnSize /* Write the size of the Cell here */
  56468. ){
  56469. BtShared *pBt = pPage->pBt;
  56470. CellInfo info;
  56471. Pgno ovflPgno;
  56472. int rc;
  56473. int nOvfl;
  56474. u32 ovflPageSize;
  56475. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56476. pPage->xParseCell(pPage, pCell, &info);
  56477. *pnSize = info.nSize;
  56478. if( info.iOverflow==0 ){
  56479. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  56480. }
  56481. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  56482. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  56483. }
  56484. ovflPgno = get4byte(&pCell[info.iOverflow]);
  56485. assert( pBt->usableSize > 4 );
  56486. ovflPageSize = pBt->usableSize - 4;
  56487. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  56488. assert( nOvfl>0 ||
  56489. (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
  56490. );
  56491. while( nOvfl-- ){
  56492. Pgno iNext = 0;
  56493. MemPage *pOvfl = 0;
  56494. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  56495. /* 0 is not a legal page number and page 1 cannot be an
  56496. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  56497. ** file the database must be corrupt. */
  56498. return SQLITE_CORRUPT_BKPT;
  56499. }
  56500. if( nOvfl ){
  56501. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  56502. if( rc ) return rc;
  56503. }
  56504. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  56505. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  56506. ){
  56507. /* There is no reason any cursor should have an outstanding reference
  56508. ** to an overflow page belonging to a cell that is being deleted/updated.
  56509. ** So if there exists more than one reference to this page, then it
  56510. ** must not really be an overflow page and the database must be corrupt.
  56511. ** It is helpful to detect this before calling freePage2(), as
  56512. ** freePage2() may zero the page contents if secure-delete mode is
  56513. ** enabled. If this 'overflow' page happens to be a page that the
  56514. ** caller is iterating through or using in some other way, this
  56515. ** can be problematic.
  56516. */
  56517. rc = SQLITE_CORRUPT_BKPT;
  56518. }else{
  56519. rc = freePage2(pBt, pOvfl, ovflPgno);
  56520. }
  56521. if( pOvfl ){
  56522. sqlite3PagerUnref(pOvfl->pDbPage);
  56523. }
  56524. if( rc ) return rc;
  56525. ovflPgno = iNext;
  56526. }
  56527. return SQLITE_OK;
  56528. }
  56529. /*
  56530. ** Create the byte sequence used to represent a cell on page pPage
  56531. ** and write that byte sequence into pCell[]. Overflow pages are
  56532. ** allocated and filled in as necessary. The calling procedure
  56533. ** is responsible for making sure sufficient space has been allocated
  56534. ** for pCell[].
  56535. **
  56536. ** Note that pCell does not necessary need to point to the pPage->aData
  56537. ** area. pCell might point to some temporary storage. The cell will
  56538. ** be constructed in this temporary area then copied into pPage->aData
  56539. ** later.
  56540. */
  56541. static int fillInCell(
  56542. MemPage *pPage, /* The page that contains the cell */
  56543. unsigned char *pCell, /* Complete text of the cell */
  56544. const void *pKey, i64 nKey, /* The key */
  56545. const void *pData,int nData, /* The data */
  56546. int nZero, /* Extra zero bytes to append to pData */
  56547. int *pnSize /* Write cell size here */
  56548. ){
  56549. int nPayload;
  56550. const u8 *pSrc;
  56551. int nSrc, n, rc;
  56552. int spaceLeft;
  56553. MemPage *pOvfl = 0;
  56554. MemPage *pToRelease = 0;
  56555. unsigned char *pPrior;
  56556. unsigned char *pPayload;
  56557. BtShared *pBt = pPage->pBt;
  56558. Pgno pgnoOvfl = 0;
  56559. int nHeader;
  56560. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56561. /* pPage is not necessarily writeable since pCell might be auxiliary
  56562. ** buffer space that is separate from the pPage buffer area */
  56563. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  56564. || sqlite3PagerIswriteable(pPage->pDbPage) );
  56565. /* Fill in the header. */
  56566. nHeader = pPage->childPtrSize;
  56567. nPayload = nData + nZero;
  56568. if( pPage->intKeyLeaf ){
  56569. nHeader += putVarint32(&pCell[nHeader], nPayload);
  56570. }else{
  56571. assert( nData==0 );
  56572. assert( nZero==0 );
  56573. }
  56574. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  56575. /* Fill in the payload size */
  56576. if( pPage->intKey ){
  56577. pSrc = pData;
  56578. nSrc = nData;
  56579. nData = 0;
  56580. }else{
  56581. assert( nKey<=0x7fffffff && pKey!=0 );
  56582. nPayload = (int)nKey;
  56583. pSrc = pKey;
  56584. nSrc = (int)nKey;
  56585. }
  56586. if( nPayload<=pPage->maxLocal ){
  56587. n = nHeader + nPayload;
  56588. testcase( n==3 );
  56589. testcase( n==4 );
  56590. if( n<4 ) n = 4;
  56591. *pnSize = n;
  56592. spaceLeft = nPayload;
  56593. pPrior = pCell;
  56594. }else{
  56595. int mn = pPage->minLocal;
  56596. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  56597. testcase( n==pPage->maxLocal );
  56598. testcase( n==pPage->maxLocal+1 );
  56599. if( n > pPage->maxLocal ) n = mn;
  56600. spaceLeft = n;
  56601. *pnSize = n + nHeader + 4;
  56602. pPrior = &pCell[nHeader+n];
  56603. }
  56604. pPayload = &pCell[nHeader];
  56605. /* At this point variables should be set as follows:
  56606. **
  56607. ** nPayload Total payload size in bytes
  56608. ** pPayload Begin writing payload here
  56609. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  56610. ** that means content must spill into overflow pages.
  56611. ** *pnSize Size of the local cell (not counting overflow pages)
  56612. ** pPrior Where to write the pgno of the first overflow page
  56613. **
  56614. ** Use a call to btreeParseCellPtr() to verify that the values above
  56615. ** were computed correctly.
  56616. */
  56617. #if SQLITE_DEBUG
  56618. {
  56619. CellInfo info;
  56620. pPage->xParseCell(pPage, pCell, &info);
  56621. assert( nHeader=(int)(info.pPayload - pCell) );
  56622. assert( info.nKey==nKey );
  56623. assert( *pnSize == info.nSize );
  56624. assert( spaceLeft == info.nLocal );
  56625. assert( pPrior == &pCell[info.iOverflow] );
  56626. }
  56627. #endif
  56628. /* Write the payload into the local Cell and any extra into overflow pages */
  56629. while( nPayload>0 ){
  56630. if( spaceLeft==0 ){
  56631. #ifndef SQLITE_OMIT_AUTOVACUUM
  56632. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  56633. if( pBt->autoVacuum ){
  56634. do{
  56635. pgnoOvfl++;
  56636. } while(
  56637. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  56638. );
  56639. }
  56640. #endif
  56641. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  56642. #ifndef SQLITE_OMIT_AUTOVACUUM
  56643. /* If the database supports auto-vacuum, and the second or subsequent
  56644. ** overflow page is being allocated, add an entry to the pointer-map
  56645. ** for that page now.
  56646. **
  56647. ** If this is the first overflow page, then write a partial entry
  56648. ** to the pointer-map. If we write nothing to this pointer-map slot,
  56649. ** then the optimistic overflow chain processing in clearCell()
  56650. ** may misinterpret the uninitialized values and delete the
  56651. ** wrong pages from the database.
  56652. */
  56653. if( pBt->autoVacuum && rc==SQLITE_OK ){
  56654. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  56655. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  56656. if( rc ){
  56657. releasePage(pOvfl);
  56658. }
  56659. }
  56660. #endif
  56661. if( rc ){
  56662. releasePage(pToRelease);
  56663. return rc;
  56664. }
  56665. /* If pToRelease is not zero than pPrior points into the data area
  56666. ** of pToRelease. Make sure pToRelease is still writeable. */
  56667. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  56668. /* If pPrior is part of the data area of pPage, then make sure pPage
  56669. ** is still writeable */
  56670. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  56671. || sqlite3PagerIswriteable(pPage->pDbPage) );
  56672. put4byte(pPrior, pgnoOvfl);
  56673. releasePage(pToRelease);
  56674. pToRelease = pOvfl;
  56675. pPrior = pOvfl->aData;
  56676. put4byte(pPrior, 0);
  56677. pPayload = &pOvfl->aData[4];
  56678. spaceLeft = pBt->usableSize - 4;
  56679. }
  56680. n = nPayload;
  56681. if( n>spaceLeft ) n = spaceLeft;
  56682. /* If pToRelease is not zero than pPayload points into the data area
  56683. ** of pToRelease. Make sure pToRelease is still writeable. */
  56684. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  56685. /* If pPayload is part of the data area of pPage, then make sure pPage
  56686. ** is still writeable */
  56687. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  56688. || sqlite3PagerIswriteable(pPage->pDbPage) );
  56689. if( nSrc>0 ){
  56690. if( n>nSrc ) n = nSrc;
  56691. assert( pSrc );
  56692. memcpy(pPayload, pSrc, n);
  56693. }else{
  56694. memset(pPayload, 0, n);
  56695. }
  56696. nPayload -= n;
  56697. pPayload += n;
  56698. pSrc += n;
  56699. nSrc -= n;
  56700. spaceLeft -= n;
  56701. if( nSrc==0 ){
  56702. nSrc = nData;
  56703. pSrc = pData;
  56704. }
  56705. }
  56706. releasePage(pToRelease);
  56707. return SQLITE_OK;
  56708. }
  56709. /*
  56710. ** Remove the i-th cell from pPage. This routine effects pPage only.
  56711. ** The cell content is not freed or deallocated. It is assumed that
  56712. ** the cell content has been copied someplace else. This routine just
  56713. ** removes the reference to the cell from pPage.
  56714. **
  56715. ** "sz" must be the number of bytes in the cell.
  56716. */
  56717. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  56718. u32 pc; /* Offset to cell content of cell being deleted */
  56719. u8 *data; /* pPage->aData */
  56720. u8 *ptr; /* Used to move bytes around within data[] */
  56721. int rc; /* The return code */
  56722. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  56723. if( *pRC ) return;
  56724. assert( idx>=0 && idx<pPage->nCell );
  56725. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  56726. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56727. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56728. data = pPage->aData;
  56729. ptr = &pPage->aCellIdx[2*idx];
  56730. pc = get2byte(ptr);
  56731. hdr = pPage->hdrOffset;
  56732. testcase( pc==get2byte(&data[hdr+5]) );
  56733. testcase( pc+sz==pPage->pBt->usableSize );
  56734. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  56735. *pRC = SQLITE_CORRUPT_BKPT;
  56736. return;
  56737. }
  56738. rc = freeSpace(pPage, pc, sz);
  56739. if( rc ){
  56740. *pRC = rc;
  56741. return;
  56742. }
  56743. pPage->nCell--;
  56744. if( pPage->nCell==0 ){
  56745. memset(&data[hdr+1], 0, 4);
  56746. data[hdr+7] = 0;
  56747. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  56748. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  56749. - pPage->childPtrSize - 8;
  56750. }else{
  56751. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  56752. put2byte(&data[hdr+3], pPage->nCell);
  56753. pPage->nFree += 2;
  56754. }
  56755. }
  56756. /*
  56757. ** Insert a new cell on pPage at cell index "i". pCell points to the
  56758. ** content of the cell.
  56759. **
  56760. ** If the cell content will fit on the page, then put it there. If it
  56761. ** will not fit, then make a copy of the cell content into pTemp if
  56762. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  56763. ** in pPage->apOvfl[] and make it point to the cell content (either
  56764. ** in pTemp or the original pCell) and also record its index.
  56765. ** Allocating a new entry in pPage->aCell[] implies that
  56766. ** pPage->nOverflow is incremented.
  56767. */
  56768. static void insertCell(
  56769. MemPage *pPage, /* Page into which we are copying */
  56770. int i, /* New cell becomes the i-th cell of the page */
  56771. u8 *pCell, /* Content of the new cell */
  56772. int sz, /* Bytes of content in pCell */
  56773. u8 *pTemp, /* Temp storage space for pCell, if needed */
  56774. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  56775. int *pRC /* Read and write return code from here */
  56776. ){
  56777. int idx = 0; /* Where to write new cell content in data[] */
  56778. int j; /* Loop counter */
  56779. u8 *data; /* The content of the whole page */
  56780. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  56781. if( *pRC ) return;
  56782. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  56783. assert( MX_CELL(pPage->pBt)<=10921 );
  56784. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  56785. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  56786. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  56787. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56788. /* The cell should normally be sized correctly. However, when moving a
  56789. ** malformed cell from a leaf page to an interior page, if the cell size
  56790. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  56791. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  56792. ** the term after the || in the following assert(). */
  56793. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  56794. if( pPage->nOverflow || sz+2>pPage->nFree ){
  56795. if( pTemp ){
  56796. memcpy(pTemp, pCell, sz);
  56797. pCell = pTemp;
  56798. }
  56799. if( iChild ){
  56800. put4byte(pCell, iChild);
  56801. }
  56802. j = pPage->nOverflow++;
  56803. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  56804. pPage->apOvfl[j] = pCell;
  56805. pPage->aiOvfl[j] = (u16)i;
  56806. /* When multiple overflows occur, they are always sequential and in
  56807. ** sorted order. This invariants arise because multiple overflows can
  56808. ** only occur when inserting divider cells into the parent page during
  56809. ** balancing, and the dividers are adjacent and sorted.
  56810. */
  56811. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  56812. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  56813. }else{
  56814. int rc = sqlite3PagerWrite(pPage->pDbPage);
  56815. if( rc!=SQLITE_OK ){
  56816. *pRC = rc;
  56817. return;
  56818. }
  56819. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56820. data = pPage->aData;
  56821. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  56822. rc = allocateSpace(pPage, sz, &idx);
  56823. if( rc ){ *pRC = rc; return; }
  56824. /* The allocateSpace() routine guarantees the following properties
  56825. ** if it returns successfully */
  56826. assert( idx >= 0 );
  56827. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  56828. assert( idx+sz <= (int)pPage->pBt->usableSize );
  56829. pPage->nFree -= (u16)(2 + sz);
  56830. memcpy(&data[idx], pCell, sz);
  56831. if( iChild ){
  56832. put4byte(&data[idx], iChild);
  56833. }
  56834. pIns = pPage->aCellIdx + i*2;
  56835. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  56836. put2byte(pIns, idx);
  56837. pPage->nCell++;
  56838. /* increment the cell count */
  56839. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  56840. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  56841. #ifndef SQLITE_OMIT_AUTOVACUUM
  56842. if( pPage->pBt->autoVacuum ){
  56843. /* The cell may contain a pointer to an overflow page. If so, write
  56844. ** the entry for the overflow page into the pointer map.
  56845. */
  56846. ptrmapPutOvflPtr(pPage, pCell, pRC);
  56847. }
  56848. #endif
  56849. }
  56850. }
  56851. /*
  56852. ** A CellArray object contains a cache of pointers and sizes for a
  56853. ** consecutive sequence of cells that might be held multiple pages.
  56854. */
  56855. typedef struct CellArray CellArray;
  56856. struct CellArray {
  56857. int nCell; /* Number of cells in apCell[] */
  56858. MemPage *pRef; /* Reference page */
  56859. u8 **apCell; /* All cells begin balanced */
  56860. u16 *szCell; /* Local size of all cells in apCell[] */
  56861. };
  56862. /*
  56863. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  56864. ** computed.
  56865. */
  56866. static void populateCellCache(CellArray *p, int idx, int N){
  56867. assert( idx>=0 && idx+N<=p->nCell );
  56868. while( N>0 ){
  56869. assert( p->apCell[idx]!=0 );
  56870. if( p->szCell[idx]==0 ){
  56871. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  56872. }else{
  56873. assert( CORRUPT_DB ||
  56874. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  56875. }
  56876. idx++;
  56877. N--;
  56878. }
  56879. }
  56880. /*
  56881. ** Return the size of the Nth element of the cell array
  56882. */
  56883. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  56884. assert( N>=0 && N<p->nCell );
  56885. assert( p->szCell[N]==0 );
  56886. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  56887. return p->szCell[N];
  56888. }
  56889. static u16 cachedCellSize(CellArray *p, int N){
  56890. assert( N>=0 && N<p->nCell );
  56891. if( p->szCell[N] ) return p->szCell[N];
  56892. return computeCellSize(p, N);
  56893. }
  56894. /*
  56895. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  56896. ** szCell[] array contains the size in bytes of each cell. This function
  56897. ** replaces the current contents of page pPg with the contents of the cell
  56898. ** array.
  56899. **
  56900. ** Some of the cells in apCell[] may currently be stored in pPg. This
  56901. ** function works around problems caused by this by making a copy of any
  56902. ** such cells before overwriting the page data.
  56903. **
  56904. ** The MemPage.nFree field is invalidated by this function. It is the
  56905. ** responsibility of the caller to set it correctly.
  56906. */
  56907. static int rebuildPage(
  56908. MemPage *pPg, /* Edit this page */
  56909. int nCell, /* Final number of cells on page */
  56910. u8 **apCell, /* Array of cells */
  56911. u16 *szCell /* Array of cell sizes */
  56912. ){
  56913. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  56914. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  56915. const int usableSize = pPg->pBt->usableSize;
  56916. u8 * const pEnd = &aData[usableSize];
  56917. int i;
  56918. u8 *pCellptr = pPg->aCellIdx;
  56919. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  56920. u8 *pData;
  56921. i = get2byte(&aData[hdr+5]);
  56922. memcpy(&pTmp[i], &aData[i], usableSize - i);
  56923. pData = pEnd;
  56924. for(i=0; i<nCell; i++){
  56925. u8 *pCell = apCell[i];
  56926. if( pCell>aData && pCell<pEnd ){
  56927. pCell = &pTmp[pCell - aData];
  56928. }
  56929. pData -= szCell[i];
  56930. put2byte(pCellptr, (pData - aData));
  56931. pCellptr += 2;
  56932. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  56933. memcpy(pData, pCell, szCell[i]);
  56934. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  56935. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  56936. }
  56937. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  56938. pPg->nCell = nCell;
  56939. pPg->nOverflow = 0;
  56940. put2byte(&aData[hdr+1], 0);
  56941. put2byte(&aData[hdr+3], pPg->nCell);
  56942. put2byte(&aData[hdr+5], pData - aData);
  56943. aData[hdr+7] = 0x00;
  56944. return SQLITE_OK;
  56945. }
  56946. /*
  56947. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  56948. ** contains the size in bytes of each such cell. This function attempts to
  56949. ** add the cells stored in the array to page pPg. If it cannot (because
  56950. ** the page needs to be defragmented before the cells will fit), non-zero
  56951. ** is returned. Otherwise, if the cells are added successfully, zero is
  56952. ** returned.
  56953. **
  56954. ** Argument pCellptr points to the first entry in the cell-pointer array
  56955. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  56956. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  56957. ** cell in the array. It is the responsibility of the caller to ensure
  56958. ** that it is safe to overwrite this part of the cell-pointer array.
  56959. **
  56960. ** When this function is called, *ppData points to the start of the
  56961. ** content area on page pPg. If the size of the content area is extended,
  56962. ** *ppData is updated to point to the new start of the content area
  56963. ** before returning.
  56964. **
  56965. ** Finally, argument pBegin points to the byte immediately following the
  56966. ** end of the space required by this page for the cell-pointer area (for
  56967. ** all cells - not just those inserted by the current call). If the content
  56968. ** area must be extended to before this point in order to accomodate all
  56969. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  56970. */
  56971. static int pageInsertArray(
  56972. MemPage *pPg, /* Page to add cells to */
  56973. u8 *pBegin, /* End of cell-pointer array */
  56974. u8 **ppData, /* IN/OUT: Page content -area pointer */
  56975. u8 *pCellptr, /* Pointer to cell-pointer area */
  56976. int iFirst, /* Index of first cell to add */
  56977. int nCell, /* Number of cells to add to pPg */
  56978. CellArray *pCArray /* Array of cells */
  56979. ){
  56980. int i;
  56981. u8 *aData = pPg->aData;
  56982. u8 *pData = *ppData;
  56983. int iEnd = iFirst + nCell;
  56984. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  56985. for(i=iFirst; i<iEnd; i++){
  56986. int sz, rc;
  56987. u8 *pSlot;
  56988. sz = cachedCellSize(pCArray, i);
  56989. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  56990. pData -= sz;
  56991. if( pData<pBegin ) return 1;
  56992. pSlot = pData;
  56993. }
  56994. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  56995. ** database. But they might for a corrupt database. Hence use memmove()
  56996. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  56997. assert( (pSlot+sz)<=pCArray->apCell[i]
  56998. || pSlot>=(pCArray->apCell[i]+sz)
  56999. || CORRUPT_DB );
  57000. memmove(pSlot, pCArray->apCell[i], sz);
  57001. put2byte(pCellptr, (pSlot - aData));
  57002. pCellptr += 2;
  57003. }
  57004. *ppData = pData;
  57005. return 0;
  57006. }
  57007. /*
  57008. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  57009. ** contains the size in bytes of each such cell. This function adds the
  57010. ** space associated with each cell in the array that is currently stored
  57011. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  57012. ** fields of the page are not updated.
  57013. **
  57014. ** This function returns the total number of cells added to the free-list.
  57015. */
  57016. static int pageFreeArray(
  57017. MemPage *pPg, /* Page to edit */
  57018. int iFirst, /* First cell to delete */
  57019. int nCell, /* Cells to delete */
  57020. CellArray *pCArray /* Array of cells */
  57021. ){
  57022. u8 * const aData = pPg->aData;
  57023. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  57024. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  57025. int nRet = 0;
  57026. int i;
  57027. int iEnd = iFirst + nCell;
  57028. u8 *pFree = 0;
  57029. int szFree = 0;
  57030. for(i=iFirst; i<iEnd; i++){
  57031. u8 *pCell = pCArray->apCell[i];
  57032. if( pCell>=pStart && pCell<pEnd ){
  57033. int sz;
  57034. /* No need to use cachedCellSize() here. The sizes of all cells that
  57035. ** are to be freed have already been computing while deciding which
  57036. ** cells need freeing */
  57037. sz = pCArray->szCell[i]; assert( sz>0 );
  57038. if( pFree!=(pCell + sz) ){
  57039. if( pFree ){
  57040. assert( pFree>aData && (pFree - aData)<65536 );
  57041. freeSpace(pPg, (u16)(pFree - aData), szFree);
  57042. }
  57043. pFree = pCell;
  57044. szFree = sz;
  57045. if( pFree+sz>pEnd ) return 0;
  57046. }else{
  57047. pFree = pCell;
  57048. szFree += sz;
  57049. }
  57050. nRet++;
  57051. }
  57052. }
  57053. if( pFree ){
  57054. assert( pFree>aData && (pFree - aData)<65536 );
  57055. freeSpace(pPg, (u16)(pFree - aData), szFree);
  57056. }
  57057. return nRet;
  57058. }
  57059. /*
  57060. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  57061. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  57062. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  57063. ** starting at apCell[iNew].
  57064. **
  57065. ** This routine makes the necessary adjustments to pPg so that it contains
  57066. ** the correct cells after being balanced.
  57067. **
  57068. ** The pPg->nFree field is invalid when this function returns. It is the
  57069. ** responsibility of the caller to set it correctly.
  57070. */
  57071. static int editPage(
  57072. MemPage *pPg, /* Edit this page */
  57073. int iOld, /* Index of first cell currently on page */
  57074. int iNew, /* Index of new first cell on page */
  57075. int nNew, /* Final number of cells on page */
  57076. CellArray *pCArray /* Array of cells and sizes */
  57077. ){
  57078. u8 * const aData = pPg->aData;
  57079. const int hdr = pPg->hdrOffset;
  57080. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  57081. int nCell = pPg->nCell; /* Cells stored on pPg */
  57082. u8 *pData;
  57083. u8 *pCellptr;
  57084. int i;
  57085. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  57086. int iNewEnd = iNew + nNew;
  57087. #ifdef SQLITE_DEBUG
  57088. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  57089. memcpy(pTmp, aData, pPg->pBt->usableSize);
  57090. #endif
  57091. /* Remove cells from the start and end of the page */
  57092. if( iOld<iNew ){
  57093. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  57094. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  57095. nCell -= nShift;
  57096. }
  57097. if( iNewEnd < iOldEnd ){
  57098. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  57099. }
  57100. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  57101. if( pData<pBegin ) goto editpage_fail;
  57102. /* Add cells to the start of the page */
  57103. if( iNew<iOld ){
  57104. int nAdd = MIN(nNew,iOld-iNew);
  57105. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  57106. pCellptr = pPg->aCellIdx;
  57107. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  57108. if( pageInsertArray(
  57109. pPg, pBegin, &pData, pCellptr,
  57110. iNew, nAdd, pCArray
  57111. ) ) goto editpage_fail;
  57112. nCell += nAdd;
  57113. }
  57114. /* Add any overflow cells */
  57115. for(i=0; i<pPg->nOverflow; i++){
  57116. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  57117. if( iCell>=0 && iCell<nNew ){
  57118. pCellptr = &pPg->aCellIdx[iCell * 2];
  57119. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  57120. nCell++;
  57121. if( pageInsertArray(
  57122. pPg, pBegin, &pData, pCellptr,
  57123. iCell+iNew, 1, pCArray
  57124. ) ) goto editpage_fail;
  57125. }
  57126. }
  57127. /* Append cells to the end of the page */
  57128. pCellptr = &pPg->aCellIdx[nCell*2];
  57129. if( pageInsertArray(
  57130. pPg, pBegin, &pData, pCellptr,
  57131. iNew+nCell, nNew-nCell, pCArray
  57132. ) ) goto editpage_fail;
  57133. pPg->nCell = nNew;
  57134. pPg->nOverflow = 0;
  57135. put2byte(&aData[hdr+3], pPg->nCell);
  57136. put2byte(&aData[hdr+5], pData - aData);
  57137. #ifdef SQLITE_DEBUG
  57138. for(i=0; i<nNew && !CORRUPT_DB; i++){
  57139. u8 *pCell = pCArray->apCell[i+iNew];
  57140. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  57141. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  57142. pCell = &pTmp[pCell - aData];
  57143. }
  57144. assert( 0==memcmp(pCell, &aData[iOff],
  57145. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  57146. }
  57147. #endif
  57148. return SQLITE_OK;
  57149. editpage_fail:
  57150. /* Unable to edit this page. Rebuild it from scratch instead. */
  57151. populateCellCache(pCArray, iNew, nNew);
  57152. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  57153. }
  57154. /*
  57155. ** The following parameters determine how many adjacent pages get involved
  57156. ** in a balancing operation. NN is the number of neighbors on either side
  57157. ** of the page that participate in the balancing operation. NB is the
  57158. ** total number of pages that participate, including the target page and
  57159. ** NN neighbors on either side.
  57160. **
  57161. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  57162. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  57163. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  57164. ** The value of NN appears to give the best results overall.
  57165. */
  57166. #define NN 1 /* Number of neighbors on either side of pPage */
  57167. #define NB (NN*2+1) /* Total pages involved in the balance */
  57168. #ifndef SQLITE_OMIT_QUICKBALANCE
  57169. /*
  57170. ** This version of balance() handles the common special case where
  57171. ** a new entry is being inserted on the extreme right-end of the
  57172. ** tree, in other words, when the new entry will become the largest
  57173. ** entry in the tree.
  57174. **
  57175. ** Instead of trying to balance the 3 right-most leaf pages, just add
  57176. ** a new page to the right-hand side and put the one new entry in
  57177. ** that page. This leaves the right side of the tree somewhat
  57178. ** unbalanced. But odds are that we will be inserting new entries
  57179. ** at the end soon afterwards so the nearly empty page will quickly
  57180. ** fill up. On average.
  57181. **
  57182. ** pPage is the leaf page which is the right-most page in the tree.
  57183. ** pParent is its parent. pPage must have a single overflow entry
  57184. ** which is also the right-most entry on the page.
  57185. **
  57186. ** The pSpace buffer is used to store a temporary copy of the divider
  57187. ** cell that will be inserted into pParent. Such a cell consists of a 4
  57188. ** byte page number followed by a variable length integer. In other
  57189. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  57190. ** least 13 bytes in size.
  57191. */
  57192. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  57193. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  57194. MemPage *pNew; /* Newly allocated page */
  57195. int rc; /* Return Code */
  57196. Pgno pgnoNew; /* Page number of pNew */
  57197. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57198. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57199. assert( pPage->nOverflow==1 );
  57200. /* This error condition is now caught prior to reaching this function */
  57201. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  57202. /* Allocate a new page. This page will become the right-sibling of
  57203. ** pPage. Make the parent page writable, so that the new divider cell
  57204. ** may be inserted. If both these operations are successful, proceed.
  57205. */
  57206. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  57207. if( rc==SQLITE_OK ){
  57208. u8 *pOut = &pSpace[4];
  57209. u8 *pCell = pPage->apOvfl[0];
  57210. u16 szCell = pPage->xCellSize(pPage, pCell);
  57211. u8 *pStop;
  57212. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  57213. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  57214. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  57215. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  57216. if( NEVER(rc) ) return rc;
  57217. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  57218. /* If this is an auto-vacuum database, update the pointer map
  57219. ** with entries for the new page, and any pointer from the
  57220. ** cell on the page to an overflow page. If either of these
  57221. ** operations fails, the return code is set, but the contents
  57222. ** of the parent page are still manipulated by thh code below.
  57223. ** That is Ok, at this point the parent page is guaranteed to
  57224. ** be marked as dirty. Returning an error code will cause a
  57225. ** rollback, undoing any changes made to the parent page.
  57226. */
  57227. if( ISAUTOVACUUM ){
  57228. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  57229. if( szCell>pNew->minLocal ){
  57230. ptrmapPutOvflPtr(pNew, pCell, &rc);
  57231. }
  57232. }
  57233. /* Create a divider cell to insert into pParent. The divider cell
  57234. ** consists of a 4-byte page number (the page number of pPage) and
  57235. ** a variable length key value (which must be the same value as the
  57236. ** largest key on pPage).
  57237. **
  57238. ** To find the largest key value on pPage, first find the right-most
  57239. ** cell on pPage. The first two fields of this cell are the
  57240. ** record-length (a variable length integer at most 32-bits in size)
  57241. ** and the key value (a variable length integer, may have any value).
  57242. ** The first of the while(...) loops below skips over the record-length
  57243. ** field. The second while(...) loop copies the key value from the
  57244. ** cell on pPage into the pSpace buffer.
  57245. */
  57246. pCell = findCell(pPage, pPage->nCell-1);
  57247. pStop = &pCell[9];
  57248. while( (*(pCell++)&0x80) && pCell<pStop );
  57249. pStop = &pCell[9];
  57250. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  57251. /* Insert the new divider cell into pParent. */
  57252. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  57253. 0, pPage->pgno, &rc);
  57254. /* Set the right-child pointer of pParent to point to the new page. */
  57255. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  57256. /* Release the reference to the new page. */
  57257. releasePage(pNew);
  57258. }
  57259. return rc;
  57260. }
  57261. #endif /* SQLITE_OMIT_QUICKBALANCE */
  57262. #if 0
  57263. /*
  57264. ** This function does not contribute anything to the operation of SQLite.
  57265. ** it is sometimes activated temporarily while debugging code responsible
  57266. ** for setting pointer-map entries.
  57267. */
  57268. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  57269. int i, j;
  57270. for(i=0; i<nPage; i++){
  57271. Pgno n;
  57272. u8 e;
  57273. MemPage *pPage = apPage[i];
  57274. BtShared *pBt = pPage->pBt;
  57275. assert( pPage->isInit );
  57276. for(j=0; j<pPage->nCell; j++){
  57277. CellInfo info;
  57278. u8 *z;
  57279. z = findCell(pPage, j);
  57280. pPage->xParseCell(pPage, z, &info);
  57281. if( info.iOverflow ){
  57282. Pgno ovfl = get4byte(&z[info.iOverflow]);
  57283. ptrmapGet(pBt, ovfl, &e, &n);
  57284. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  57285. }
  57286. if( !pPage->leaf ){
  57287. Pgno child = get4byte(z);
  57288. ptrmapGet(pBt, child, &e, &n);
  57289. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  57290. }
  57291. }
  57292. if( !pPage->leaf ){
  57293. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57294. ptrmapGet(pBt, child, &e, &n);
  57295. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  57296. }
  57297. }
  57298. return 1;
  57299. }
  57300. #endif
  57301. /*
  57302. ** This function is used to copy the contents of the b-tree node stored
  57303. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  57304. ** the pointer-map entries for each child page are updated so that the
  57305. ** parent page stored in the pointer map is page pTo. If pFrom contained
  57306. ** any cells with overflow page pointers, then the corresponding pointer
  57307. ** map entries are also updated so that the parent page is page pTo.
  57308. **
  57309. ** If pFrom is currently carrying any overflow cells (entries in the
  57310. ** MemPage.apOvfl[] array), they are not copied to pTo.
  57311. **
  57312. ** Before returning, page pTo is reinitialized using btreeInitPage().
  57313. **
  57314. ** The performance of this function is not critical. It is only used by
  57315. ** the balance_shallower() and balance_deeper() procedures, neither of
  57316. ** which are called often under normal circumstances.
  57317. */
  57318. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  57319. if( (*pRC)==SQLITE_OK ){
  57320. BtShared * const pBt = pFrom->pBt;
  57321. u8 * const aFrom = pFrom->aData;
  57322. u8 * const aTo = pTo->aData;
  57323. int const iFromHdr = pFrom->hdrOffset;
  57324. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  57325. int rc;
  57326. int iData;
  57327. assert( pFrom->isInit );
  57328. assert( pFrom->nFree>=iToHdr );
  57329. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  57330. /* Copy the b-tree node content from page pFrom to page pTo. */
  57331. iData = get2byte(&aFrom[iFromHdr+5]);
  57332. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  57333. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  57334. /* Reinitialize page pTo so that the contents of the MemPage structure
  57335. ** match the new data. The initialization of pTo can actually fail under
  57336. ** fairly obscure circumstances, even though it is a copy of initialized
  57337. ** page pFrom.
  57338. */
  57339. pTo->isInit = 0;
  57340. rc = btreeInitPage(pTo);
  57341. if( rc!=SQLITE_OK ){
  57342. *pRC = rc;
  57343. return;
  57344. }
  57345. /* If this is an auto-vacuum database, update the pointer-map entries
  57346. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  57347. */
  57348. if( ISAUTOVACUUM ){
  57349. *pRC = setChildPtrmaps(pTo);
  57350. }
  57351. }
  57352. }
  57353. /*
  57354. ** This routine redistributes cells on the iParentIdx'th child of pParent
  57355. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  57356. ** same amount of free space. Usually a single sibling on either side of the
  57357. ** page are used in the balancing, though both siblings might come from one
  57358. ** side if the page is the first or last child of its parent. If the page
  57359. ** has fewer than 2 siblings (something which can only happen if the page
  57360. ** is a root page or a child of a root page) then all available siblings
  57361. ** participate in the balancing.
  57362. **
  57363. ** The number of siblings of the page might be increased or decreased by
  57364. ** one or two in an effort to keep pages nearly full but not over full.
  57365. **
  57366. ** Note that when this routine is called, some of the cells on the page
  57367. ** might not actually be stored in MemPage.aData[]. This can happen
  57368. ** if the page is overfull. This routine ensures that all cells allocated
  57369. ** to the page and its siblings fit into MemPage.aData[] before returning.
  57370. **
  57371. ** In the course of balancing the page and its siblings, cells may be
  57372. ** inserted into or removed from the parent page (pParent). Doing so
  57373. ** may cause the parent page to become overfull or underfull. If this
  57374. ** happens, it is the responsibility of the caller to invoke the correct
  57375. ** balancing routine to fix this problem (see the balance() routine).
  57376. **
  57377. ** If this routine fails for any reason, it might leave the database
  57378. ** in a corrupted state. So if this routine fails, the database should
  57379. ** be rolled back.
  57380. **
  57381. ** The third argument to this function, aOvflSpace, is a pointer to a
  57382. ** buffer big enough to hold one page. If while inserting cells into the parent
  57383. ** page (pParent) the parent page becomes overfull, this buffer is
  57384. ** used to store the parent's overflow cells. Because this function inserts
  57385. ** a maximum of four divider cells into the parent page, and the maximum
  57386. ** size of a cell stored within an internal node is always less than 1/4
  57387. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  57388. ** enough for all overflow cells.
  57389. **
  57390. ** If aOvflSpace is set to a null pointer, this function returns
  57391. ** SQLITE_NOMEM.
  57392. */
  57393. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  57394. #pragma optimize("", off)
  57395. #endif
  57396. static int balance_nonroot(
  57397. MemPage *pParent, /* Parent page of siblings being balanced */
  57398. int iParentIdx, /* Index of "the page" in pParent */
  57399. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  57400. int isRoot, /* True if pParent is a root-page */
  57401. int bBulk /* True if this call is part of a bulk load */
  57402. ){
  57403. BtShared *pBt; /* The whole database */
  57404. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  57405. int nNew = 0; /* Number of pages in apNew[] */
  57406. int nOld; /* Number of pages in apOld[] */
  57407. int i, j, k; /* Loop counters */
  57408. int nxDiv; /* Next divider slot in pParent->aCell[] */
  57409. int rc = SQLITE_OK; /* The return code */
  57410. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  57411. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  57412. int usableSpace; /* Bytes in pPage beyond the header */
  57413. int pageFlags; /* Value of pPage->aData[0] */
  57414. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  57415. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  57416. int szScratch; /* Size of scratch memory requested */
  57417. MemPage *apOld[NB]; /* pPage and up to two siblings */
  57418. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  57419. u8 *pRight; /* Location in parent of right-sibling pointer */
  57420. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  57421. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  57422. int cntOld[NB+2]; /* Old index in b.apCell[] */
  57423. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  57424. u8 *aSpace1; /* Space for copies of dividers cells */
  57425. Pgno pgno; /* Temp var to store a page number in */
  57426. u8 abDone[NB+2]; /* True after i'th new page is populated */
  57427. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  57428. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  57429. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  57430. CellArray b; /* Parsed information on cells being balanced */
  57431. memset(abDone, 0, sizeof(abDone));
  57432. b.nCell = 0;
  57433. b.apCell = 0;
  57434. pBt = pParent->pBt;
  57435. assert( sqlite3_mutex_held(pBt->mutex) );
  57436. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57437. #if 0
  57438. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  57439. #endif
  57440. /* At this point pParent may have at most one overflow cell. And if
  57441. ** this overflow cell is present, it must be the cell with
  57442. ** index iParentIdx. This scenario comes about when this function
  57443. ** is called (indirectly) from sqlite3BtreeDelete().
  57444. */
  57445. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  57446. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  57447. if( !aOvflSpace ){
  57448. return SQLITE_NOMEM;
  57449. }
  57450. /* Find the sibling pages to balance. Also locate the cells in pParent
  57451. ** that divide the siblings. An attempt is made to find NN siblings on
  57452. ** either side of pPage. More siblings are taken from one side, however,
  57453. ** if there are fewer than NN siblings on the other side. If pParent
  57454. ** has NB or fewer children then all children of pParent are taken.
  57455. **
  57456. ** This loop also drops the divider cells from the parent page. This
  57457. ** way, the remainder of the function does not have to deal with any
  57458. ** overflow cells in the parent page, since if any existed they will
  57459. ** have already been removed.
  57460. */
  57461. i = pParent->nOverflow + pParent->nCell;
  57462. if( i<2 ){
  57463. nxDiv = 0;
  57464. }else{
  57465. assert( bBulk==0 || bBulk==1 );
  57466. if( iParentIdx==0 ){
  57467. nxDiv = 0;
  57468. }else if( iParentIdx==i ){
  57469. nxDiv = i-2+bBulk;
  57470. }else{
  57471. nxDiv = iParentIdx-1;
  57472. }
  57473. i = 2-bBulk;
  57474. }
  57475. nOld = i+1;
  57476. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  57477. pRight = &pParent->aData[pParent->hdrOffset+8];
  57478. }else{
  57479. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  57480. }
  57481. pgno = get4byte(pRight);
  57482. while( 1 ){
  57483. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  57484. if( rc ){
  57485. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  57486. goto balance_cleanup;
  57487. }
  57488. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  57489. if( (i--)==0 ) break;
  57490. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  57491. apDiv[i] = pParent->apOvfl[0];
  57492. pgno = get4byte(apDiv[i]);
  57493. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  57494. pParent->nOverflow = 0;
  57495. }else{
  57496. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  57497. pgno = get4byte(apDiv[i]);
  57498. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  57499. /* Drop the cell from the parent page. apDiv[i] still points to
  57500. ** the cell within the parent, even though it has been dropped.
  57501. ** This is safe because dropping a cell only overwrites the first
  57502. ** four bytes of it, and this function does not need the first
  57503. ** four bytes of the divider cell. So the pointer is safe to use
  57504. ** later on.
  57505. **
  57506. ** But not if we are in secure-delete mode. In secure-delete mode,
  57507. ** the dropCell() routine will overwrite the entire cell with zeroes.
  57508. ** In this case, temporarily copy the cell into the aOvflSpace[]
  57509. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  57510. ** is allocated. */
  57511. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  57512. int iOff;
  57513. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  57514. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  57515. rc = SQLITE_CORRUPT_BKPT;
  57516. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  57517. goto balance_cleanup;
  57518. }else{
  57519. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  57520. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  57521. }
  57522. }
  57523. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  57524. }
  57525. }
  57526. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  57527. ** alignment */
  57528. nMaxCells = (nMaxCells + 3)&~3;
  57529. /*
  57530. ** Allocate space for memory structures
  57531. */
  57532. szScratch =
  57533. nMaxCells*sizeof(u8*) /* b.apCell */
  57534. + nMaxCells*sizeof(u16) /* b.szCell */
  57535. + pBt->pageSize; /* aSpace1 */
  57536. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  57537. ** that is more than 6 times the database page size. */
  57538. assert( szScratch<=6*(int)pBt->pageSize );
  57539. b.apCell = sqlite3ScratchMalloc( szScratch );
  57540. if( b.apCell==0 ){
  57541. rc = SQLITE_NOMEM;
  57542. goto balance_cleanup;
  57543. }
  57544. b.szCell = (u16*)&b.apCell[nMaxCells];
  57545. aSpace1 = (u8*)&b.szCell[nMaxCells];
  57546. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  57547. /*
  57548. ** Load pointers to all cells on sibling pages and the divider cells
  57549. ** into the local b.apCell[] array. Make copies of the divider cells
  57550. ** into space obtained from aSpace1[]. The divider cells have already
  57551. ** been removed from pParent.
  57552. **
  57553. ** If the siblings are on leaf pages, then the child pointers of the
  57554. ** divider cells are stripped from the cells before they are copied
  57555. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  57556. ** child pointers. If siblings are not leaves, then all cell in
  57557. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  57558. ** are alike.
  57559. **
  57560. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  57561. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  57562. */
  57563. b.pRef = apOld[0];
  57564. leafCorrection = b.pRef->leaf*4;
  57565. leafData = b.pRef->intKeyLeaf;
  57566. for(i=0; i<nOld; i++){
  57567. MemPage *pOld = apOld[i];
  57568. int limit = pOld->nCell;
  57569. u8 *aData = pOld->aData;
  57570. u16 maskPage = pOld->maskPage;
  57571. u8 *piCell = aData + pOld->cellOffset;
  57572. u8 *piEnd;
  57573. /* Verify that all sibling pages are of the same "type" (table-leaf,
  57574. ** table-interior, index-leaf, or index-interior).
  57575. */
  57576. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  57577. rc = SQLITE_CORRUPT_BKPT;
  57578. goto balance_cleanup;
  57579. }
  57580. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  57581. ** constains overflow cells, include them in the b.apCell[] array
  57582. ** in the correct spot.
  57583. **
  57584. ** Note that when there are multiple overflow cells, it is always the
  57585. ** case that they are sequential and adjacent. This invariant arises
  57586. ** because multiple overflows can only occurs when inserting divider
  57587. ** cells into a parent on a prior balance, and divider cells are always
  57588. ** adjacent and are inserted in order. There is an assert() tagged
  57589. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  57590. ** invariant.
  57591. **
  57592. ** This must be done in advance. Once the balance starts, the cell
  57593. ** offset section of the btree page will be overwritten and we will no
  57594. ** long be able to find the cells if a pointer to each cell is not saved
  57595. ** first.
  57596. */
  57597. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit);
  57598. if( pOld->nOverflow>0 ){
  57599. memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow);
  57600. limit = pOld->aiOvfl[0];
  57601. for(j=0; j<limit; j++){
  57602. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  57603. piCell += 2;
  57604. b.nCell++;
  57605. }
  57606. for(k=0; k<pOld->nOverflow; k++){
  57607. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  57608. b.apCell[b.nCell] = pOld->apOvfl[k];
  57609. b.nCell++;
  57610. }
  57611. }
  57612. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  57613. while( piCell<piEnd ){
  57614. assert( b.nCell<nMaxCells );
  57615. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  57616. piCell += 2;
  57617. b.nCell++;
  57618. }
  57619. cntOld[i] = b.nCell;
  57620. if( i<nOld-1 && !leafData){
  57621. u16 sz = (u16)szNew[i];
  57622. u8 *pTemp;
  57623. assert( b.nCell<nMaxCells );
  57624. b.szCell[b.nCell] = sz;
  57625. pTemp = &aSpace1[iSpace1];
  57626. iSpace1 += sz;
  57627. assert( sz<=pBt->maxLocal+23 );
  57628. assert( iSpace1 <= (int)pBt->pageSize );
  57629. memcpy(pTemp, apDiv[i], sz);
  57630. b.apCell[b.nCell] = pTemp+leafCorrection;
  57631. assert( leafCorrection==0 || leafCorrection==4 );
  57632. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  57633. if( !pOld->leaf ){
  57634. assert( leafCorrection==0 );
  57635. assert( pOld->hdrOffset==0 );
  57636. /* The right pointer of the child page pOld becomes the left
  57637. ** pointer of the divider cell */
  57638. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  57639. }else{
  57640. assert( leafCorrection==4 );
  57641. while( b.szCell[b.nCell]<4 ){
  57642. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  57643. ** does exist, pad it with 0x00 bytes. */
  57644. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  57645. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  57646. aSpace1[iSpace1++] = 0x00;
  57647. b.szCell[b.nCell]++;
  57648. }
  57649. }
  57650. b.nCell++;
  57651. }
  57652. }
  57653. /*
  57654. ** Figure out the number of pages needed to hold all b.nCell cells.
  57655. ** Store this number in "k". Also compute szNew[] which is the total
  57656. ** size of all cells on the i-th page and cntNew[] which is the index
  57657. ** in b.apCell[] of the cell that divides page i from page i+1.
  57658. ** cntNew[k] should equal b.nCell.
  57659. **
  57660. ** Values computed by this block:
  57661. **
  57662. ** k: The total number of sibling pages
  57663. ** szNew[i]: Spaced used on the i-th sibling page.
  57664. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  57665. ** the right of the i-th sibling page.
  57666. ** usableSpace: Number of bytes of space available on each sibling.
  57667. **
  57668. */
  57669. usableSpace = pBt->usableSize - 12 + leafCorrection;
  57670. for(i=0; i<nOld; i++){
  57671. MemPage *p = apOld[i];
  57672. szNew[i] = usableSpace - p->nFree;
  57673. if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  57674. for(j=0; j<p->nOverflow; j++){
  57675. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  57676. }
  57677. cntNew[i] = cntOld[i];
  57678. }
  57679. k = nOld;
  57680. for(i=0; i<k; i++){
  57681. int sz;
  57682. while( szNew[i]>usableSpace ){
  57683. if( i+1>=k ){
  57684. k = i+2;
  57685. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  57686. szNew[k-1] = 0;
  57687. cntNew[k-1] = b.nCell;
  57688. }
  57689. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  57690. szNew[i] -= sz;
  57691. if( !leafData ){
  57692. if( cntNew[i]<b.nCell ){
  57693. sz = 2 + cachedCellSize(&b, cntNew[i]);
  57694. }else{
  57695. sz = 0;
  57696. }
  57697. }
  57698. szNew[i+1] += sz;
  57699. cntNew[i]--;
  57700. }
  57701. while( cntNew[i]<b.nCell ){
  57702. sz = 2 + cachedCellSize(&b, cntNew[i]);
  57703. if( szNew[i]+sz>usableSpace ) break;
  57704. szNew[i] += sz;
  57705. cntNew[i]++;
  57706. if( !leafData ){
  57707. if( cntNew[i]<b.nCell ){
  57708. sz = 2 + cachedCellSize(&b, cntNew[i]);
  57709. }else{
  57710. sz = 0;
  57711. }
  57712. }
  57713. szNew[i+1] -= sz;
  57714. }
  57715. if( cntNew[i]>=b.nCell ){
  57716. k = i+1;
  57717. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  57718. rc = SQLITE_CORRUPT_BKPT;
  57719. goto balance_cleanup;
  57720. }
  57721. }
  57722. /*
  57723. ** The packing computed by the previous block is biased toward the siblings
  57724. ** on the left side (siblings with smaller keys). The left siblings are
  57725. ** always nearly full, while the right-most sibling might be nearly empty.
  57726. ** The next block of code attempts to adjust the packing of siblings to
  57727. ** get a better balance.
  57728. **
  57729. ** This adjustment is more than an optimization. The packing above might
  57730. ** be so out of balance as to be illegal. For example, the right-most
  57731. ** sibling might be completely empty. This adjustment is not optional.
  57732. */
  57733. for(i=k-1; i>0; i--){
  57734. int szRight = szNew[i]; /* Size of sibling on the right */
  57735. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  57736. int r; /* Index of right-most cell in left sibling */
  57737. int d; /* Index of first cell to the left of right sibling */
  57738. r = cntNew[i-1] - 1;
  57739. d = r + 1 - leafData;
  57740. (void)cachedCellSize(&b, d);
  57741. do{
  57742. assert( d<nMaxCells );
  57743. assert( r<nMaxCells );
  57744. (void)cachedCellSize(&b, r);
  57745. if( szRight!=0
  57746. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
  57747. break;
  57748. }
  57749. szRight += b.szCell[d] + 2;
  57750. szLeft -= b.szCell[r] + 2;
  57751. cntNew[i-1] = r;
  57752. r--;
  57753. d--;
  57754. }while( r>=0 );
  57755. szNew[i] = szRight;
  57756. szNew[i-1] = szLeft;
  57757. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  57758. rc = SQLITE_CORRUPT_BKPT;
  57759. goto balance_cleanup;
  57760. }
  57761. }
  57762. /* Sanity check: For a non-corrupt database file one of the follwing
  57763. ** must be true:
  57764. ** (1) We found one or more cells (cntNew[0])>0), or
  57765. ** (2) pPage is a virtual root page. A virtual root page is when
  57766. ** the real root page is page 1 and we are the only child of
  57767. ** that page.
  57768. */
  57769. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  57770. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  57771. apOld[0]->pgno, apOld[0]->nCell,
  57772. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  57773. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  57774. ));
  57775. /*
  57776. ** Allocate k new pages. Reuse old pages where possible.
  57777. */
  57778. pageFlags = apOld[0]->aData[0];
  57779. for(i=0; i<k; i++){
  57780. MemPage *pNew;
  57781. if( i<nOld ){
  57782. pNew = apNew[i] = apOld[i];
  57783. apOld[i] = 0;
  57784. rc = sqlite3PagerWrite(pNew->pDbPage);
  57785. nNew++;
  57786. if( rc ) goto balance_cleanup;
  57787. }else{
  57788. assert( i>0 );
  57789. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  57790. if( rc ) goto balance_cleanup;
  57791. zeroPage(pNew, pageFlags);
  57792. apNew[i] = pNew;
  57793. nNew++;
  57794. cntOld[i] = b.nCell;
  57795. /* Set the pointer-map entry for the new sibling page. */
  57796. if( ISAUTOVACUUM ){
  57797. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  57798. if( rc!=SQLITE_OK ){
  57799. goto balance_cleanup;
  57800. }
  57801. }
  57802. }
  57803. }
  57804. /*
  57805. ** Reassign page numbers so that the new pages are in ascending order.
  57806. ** This helps to keep entries in the disk file in order so that a scan
  57807. ** of the table is closer to a linear scan through the file. That in turn
  57808. ** helps the operating system to deliver pages from the disk more rapidly.
  57809. **
  57810. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  57811. ** than (NB+2) (a small constant), that should not be a problem.
  57812. **
  57813. ** When NB==3, this one optimization makes the database about 25% faster
  57814. ** for large insertions and deletions.
  57815. */
  57816. for(i=0; i<nNew; i++){
  57817. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  57818. aPgFlags[i] = apNew[i]->pDbPage->flags;
  57819. for(j=0; j<i; j++){
  57820. if( aPgno[j]==aPgno[i] ){
  57821. /* This branch is taken if the set of sibling pages somehow contains
  57822. ** duplicate entries. This can happen if the database is corrupt.
  57823. ** It would be simpler to detect this as part of the loop below, but
  57824. ** we do the detection here in order to avoid populating the pager
  57825. ** cache with two separate objects associated with the same
  57826. ** page number. */
  57827. assert( CORRUPT_DB );
  57828. rc = SQLITE_CORRUPT_BKPT;
  57829. goto balance_cleanup;
  57830. }
  57831. }
  57832. }
  57833. for(i=0; i<nNew; i++){
  57834. int iBest = 0; /* aPgno[] index of page number to use */
  57835. for(j=1; j<nNew; j++){
  57836. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  57837. }
  57838. pgno = aPgOrder[iBest];
  57839. aPgOrder[iBest] = 0xffffffff;
  57840. if( iBest!=i ){
  57841. if( iBest>i ){
  57842. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  57843. }
  57844. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  57845. apNew[i]->pgno = pgno;
  57846. }
  57847. }
  57848. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  57849. "%d(%d nc=%d) %d(%d nc=%d)\n",
  57850. apNew[0]->pgno, szNew[0], cntNew[0],
  57851. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  57852. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  57853. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  57854. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  57855. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  57856. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  57857. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  57858. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  57859. ));
  57860. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57861. put4byte(pRight, apNew[nNew-1]->pgno);
  57862. /* If the sibling pages are not leaves, ensure that the right-child pointer
  57863. ** of the right-most new sibling page is set to the value that was
  57864. ** originally in the same field of the right-most old sibling page. */
  57865. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  57866. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  57867. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  57868. }
  57869. /* Make any required updates to pointer map entries associated with
  57870. ** cells stored on sibling pages following the balance operation. Pointer
  57871. ** map entries associated with divider cells are set by the insertCell()
  57872. ** routine. The associated pointer map entries are:
  57873. **
  57874. ** a) if the cell contains a reference to an overflow chain, the
  57875. ** entry associated with the first page in the overflow chain, and
  57876. **
  57877. ** b) if the sibling pages are not leaves, the child page associated
  57878. ** with the cell.
  57879. **
  57880. ** If the sibling pages are not leaves, then the pointer map entry
  57881. ** associated with the right-child of each sibling may also need to be
  57882. ** updated. This happens below, after the sibling pages have been
  57883. ** populated, not here.
  57884. */
  57885. if( ISAUTOVACUUM ){
  57886. MemPage *pNew = apNew[0];
  57887. u8 *aOld = pNew->aData;
  57888. int cntOldNext = pNew->nCell + pNew->nOverflow;
  57889. int usableSize = pBt->usableSize;
  57890. int iNew = 0;
  57891. int iOld = 0;
  57892. for(i=0; i<b.nCell; i++){
  57893. u8 *pCell = b.apCell[i];
  57894. if( i==cntOldNext ){
  57895. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  57896. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  57897. aOld = pOld->aData;
  57898. }
  57899. if( i==cntNew[iNew] ){
  57900. pNew = apNew[++iNew];
  57901. if( !leafData ) continue;
  57902. }
  57903. /* Cell pCell is destined for new sibling page pNew. Originally, it
  57904. ** was either part of sibling page iOld (possibly an overflow cell),
  57905. ** or else the divider cell to the left of sibling page iOld. So,
  57906. ** if sibling page iOld had the same page number as pNew, and if
  57907. ** pCell really was a part of sibling page iOld (not a divider or
  57908. ** overflow cell), we can skip updating the pointer map entries. */
  57909. if( iOld>=nNew
  57910. || pNew->pgno!=aPgno[iOld]
  57911. || pCell<aOld
  57912. || pCell>=&aOld[usableSize]
  57913. ){
  57914. if( !leafCorrection ){
  57915. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  57916. }
  57917. if( cachedCellSize(&b,i)>pNew->minLocal ){
  57918. ptrmapPutOvflPtr(pNew, pCell, &rc);
  57919. }
  57920. if( rc ) goto balance_cleanup;
  57921. }
  57922. }
  57923. }
  57924. /* Insert new divider cells into pParent. */
  57925. for(i=0; i<nNew-1; i++){
  57926. u8 *pCell;
  57927. u8 *pTemp;
  57928. int sz;
  57929. MemPage *pNew = apNew[i];
  57930. j = cntNew[i];
  57931. assert( j<nMaxCells );
  57932. assert( b.apCell[j]!=0 );
  57933. pCell = b.apCell[j];
  57934. sz = b.szCell[j] + leafCorrection;
  57935. pTemp = &aOvflSpace[iOvflSpace];
  57936. if( !pNew->leaf ){
  57937. memcpy(&pNew->aData[8], pCell, 4);
  57938. }else if( leafData ){
  57939. /* If the tree is a leaf-data tree, and the siblings are leaves,
  57940. ** then there is no divider cell in b.apCell[]. Instead, the divider
  57941. ** cell consists of the integer key for the right-most cell of
  57942. ** the sibling-page assembled above only.
  57943. */
  57944. CellInfo info;
  57945. j--;
  57946. pNew->xParseCell(pNew, b.apCell[j], &info);
  57947. pCell = pTemp;
  57948. sz = 4 + putVarint(&pCell[4], info.nKey);
  57949. pTemp = 0;
  57950. }else{
  57951. pCell -= 4;
  57952. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  57953. ** previously stored on a leaf node, and its reported size was 4
  57954. ** bytes, then it may actually be smaller than this
  57955. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  57956. ** any cell). But it is important to pass the correct size to
  57957. ** insertCell(), so reparse the cell now.
  57958. **
  57959. ** Note that this can never happen in an SQLite data file, as all
  57960. ** cells are at least 4 bytes. It only happens in b-trees used
  57961. ** to evaluate "IN (SELECT ...)" and similar clauses.
  57962. */
  57963. if( b.szCell[j]==4 ){
  57964. assert(leafCorrection==4);
  57965. sz = pParent->xCellSize(pParent, pCell);
  57966. }
  57967. }
  57968. iOvflSpace += sz;
  57969. assert( sz<=pBt->maxLocal+23 );
  57970. assert( iOvflSpace <= (int)pBt->pageSize );
  57971. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  57972. if( rc!=SQLITE_OK ) goto balance_cleanup;
  57973. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57974. }
  57975. /* Now update the actual sibling pages. The order in which they are updated
  57976. ** is important, as this code needs to avoid disrupting any page from which
  57977. ** cells may still to be read. In practice, this means:
  57978. **
  57979. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  57980. ** then it is not safe to update page apNew[iPg] until after
  57981. ** the left-hand sibling apNew[iPg-1] has been updated.
  57982. **
  57983. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  57984. ** then it is not safe to update page apNew[iPg] until after
  57985. ** the right-hand sibling apNew[iPg+1] has been updated.
  57986. **
  57987. ** If neither of the above apply, the page is safe to update.
  57988. **
  57989. ** The iPg value in the following loop starts at nNew-1 goes down
  57990. ** to 0, then back up to nNew-1 again, thus making two passes over
  57991. ** the pages. On the initial downward pass, only condition (1) above
  57992. ** needs to be tested because (2) will always be true from the previous
  57993. ** step. On the upward pass, both conditions are always true, so the
  57994. ** upwards pass simply processes pages that were missed on the downward
  57995. ** pass.
  57996. */
  57997. for(i=1-nNew; i<nNew; i++){
  57998. int iPg = i<0 ? -i : i;
  57999. assert( iPg>=0 && iPg<nNew );
  58000. if( abDone[iPg] ) continue; /* Skip pages already processed */
  58001. if( i>=0 /* On the upwards pass, or... */
  58002. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  58003. ){
  58004. int iNew;
  58005. int iOld;
  58006. int nNewCell;
  58007. /* Verify condition (1): If cells are moving left, update iPg
  58008. ** only after iPg-1 has already been updated. */
  58009. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  58010. /* Verify condition (2): If cells are moving right, update iPg
  58011. ** only after iPg+1 has already been updated. */
  58012. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  58013. if( iPg==0 ){
  58014. iNew = iOld = 0;
  58015. nNewCell = cntNew[0];
  58016. }else{
  58017. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  58018. iNew = cntNew[iPg-1] + !leafData;
  58019. nNewCell = cntNew[iPg] - iNew;
  58020. }
  58021. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  58022. if( rc ) goto balance_cleanup;
  58023. abDone[iPg]++;
  58024. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  58025. assert( apNew[iPg]->nOverflow==0 );
  58026. assert( apNew[iPg]->nCell==nNewCell );
  58027. }
  58028. }
  58029. /* All pages have been processed exactly once */
  58030. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  58031. assert( nOld>0 );
  58032. assert( nNew>0 );
  58033. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  58034. /* The root page of the b-tree now contains no cells. The only sibling
  58035. ** page is the right-child of the parent. Copy the contents of the
  58036. ** child page into the parent, decreasing the overall height of the
  58037. ** b-tree structure by one. This is described as the "balance-shallower"
  58038. ** sub-algorithm in some documentation.
  58039. **
  58040. ** If this is an auto-vacuum database, the call to copyNodeContent()
  58041. ** sets all pointer-map entries corresponding to database image pages
  58042. ** for which the pointer is stored within the content being copied.
  58043. **
  58044. ** It is critical that the child page be defragmented before being
  58045. ** copied into the parent, because if the parent is page 1 then it will
  58046. ** by smaller than the child due to the database header, and so all the
  58047. ** free space needs to be up front.
  58048. */
  58049. assert( nNew==1 || CORRUPT_DB );
  58050. rc = defragmentPage(apNew[0]);
  58051. testcase( rc!=SQLITE_OK );
  58052. assert( apNew[0]->nFree ==
  58053. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  58054. || rc!=SQLITE_OK
  58055. );
  58056. copyNodeContent(apNew[0], pParent, &rc);
  58057. freePage(apNew[0], &rc);
  58058. }else if( ISAUTOVACUUM && !leafCorrection ){
  58059. /* Fix the pointer map entries associated with the right-child of each
  58060. ** sibling page. All other pointer map entries have already been taken
  58061. ** care of. */
  58062. for(i=0; i<nNew; i++){
  58063. u32 key = get4byte(&apNew[i]->aData[8]);
  58064. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  58065. }
  58066. }
  58067. assert( pParent->isInit );
  58068. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  58069. nOld, nNew, b.nCell));
  58070. /* Free any old pages that were not reused as new pages.
  58071. */
  58072. for(i=nNew; i<nOld; i++){
  58073. freePage(apOld[i], &rc);
  58074. }
  58075. #if 0
  58076. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  58077. /* The ptrmapCheckPages() contains assert() statements that verify that
  58078. ** all pointer map pages are set correctly. This is helpful while
  58079. ** debugging. This is usually disabled because a corrupt database may
  58080. ** cause an assert() statement to fail. */
  58081. ptrmapCheckPages(apNew, nNew);
  58082. ptrmapCheckPages(&pParent, 1);
  58083. }
  58084. #endif
  58085. /*
  58086. ** Cleanup before returning.
  58087. */
  58088. balance_cleanup:
  58089. sqlite3ScratchFree(b.apCell);
  58090. for(i=0; i<nOld; i++){
  58091. releasePage(apOld[i]);
  58092. }
  58093. for(i=0; i<nNew; i++){
  58094. releasePage(apNew[i]);
  58095. }
  58096. return rc;
  58097. }
  58098. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  58099. #pragma optimize("", on)
  58100. #endif
  58101. /*
  58102. ** This function is called when the root page of a b-tree structure is
  58103. ** overfull (has one or more overflow pages).
  58104. **
  58105. ** A new child page is allocated and the contents of the current root
  58106. ** page, including overflow cells, are copied into the child. The root
  58107. ** page is then overwritten to make it an empty page with the right-child
  58108. ** pointer pointing to the new page.
  58109. **
  58110. ** Before returning, all pointer-map entries corresponding to pages
  58111. ** that the new child-page now contains pointers to are updated. The
  58112. ** entry corresponding to the new right-child pointer of the root
  58113. ** page is also updated.
  58114. **
  58115. ** If successful, *ppChild is set to contain a reference to the child
  58116. ** page and SQLITE_OK is returned. In this case the caller is required
  58117. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  58118. ** an error code is returned and *ppChild is set to 0.
  58119. */
  58120. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  58121. int rc; /* Return value from subprocedures */
  58122. MemPage *pChild = 0; /* Pointer to a new child page */
  58123. Pgno pgnoChild = 0; /* Page number of the new child page */
  58124. BtShared *pBt = pRoot->pBt; /* The BTree */
  58125. assert( pRoot->nOverflow>0 );
  58126. assert( sqlite3_mutex_held(pBt->mutex) );
  58127. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  58128. ** page that will become the new right-child of pPage. Copy the contents
  58129. ** of the node stored on pRoot into the new child page.
  58130. */
  58131. rc = sqlite3PagerWrite(pRoot->pDbPage);
  58132. if( rc==SQLITE_OK ){
  58133. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  58134. copyNodeContent(pRoot, pChild, &rc);
  58135. if( ISAUTOVACUUM ){
  58136. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  58137. }
  58138. }
  58139. if( rc ){
  58140. *ppChild = 0;
  58141. releasePage(pChild);
  58142. return rc;
  58143. }
  58144. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  58145. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  58146. assert( pChild->nCell==pRoot->nCell );
  58147. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  58148. /* Copy the overflow cells from pRoot to pChild */
  58149. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  58150. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  58151. memcpy(pChild->apOvfl, pRoot->apOvfl,
  58152. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  58153. pChild->nOverflow = pRoot->nOverflow;
  58154. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  58155. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  58156. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  58157. *ppChild = pChild;
  58158. return SQLITE_OK;
  58159. }
  58160. /*
  58161. ** The page that pCur currently points to has just been modified in
  58162. ** some way. This function figures out if this modification means the
  58163. ** tree needs to be balanced, and if so calls the appropriate balancing
  58164. ** routine. Balancing routines are:
  58165. **
  58166. ** balance_quick()
  58167. ** balance_deeper()
  58168. ** balance_nonroot()
  58169. */
  58170. static int balance(BtCursor *pCur){
  58171. int rc = SQLITE_OK;
  58172. const int nMin = pCur->pBt->usableSize * 2 / 3;
  58173. u8 aBalanceQuickSpace[13];
  58174. u8 *pFree = 0;
  58175. TESTONLY( int balance_quick_called = 0 );
  58176. TESTONLY( int balance_deeper_called = 0 );
  58177. do {
  58178. int iPage = pCur->iPage;
  58179. MemPage *pPage = pCur->apPage[iPage];
  58180. if( iPage==0 ){
  58181. if( pPage->nOverflow ){
  58182. /* The root page of the b-tree is overfull. In this case call the
  58183. ** balance_deeper() function to create a new child for the root-page
  58184. ** and copy the current contents of the root-page to it. The
  58185. ** next iteration of the do-loop will balance the child page.
  58186. */
  58187. assert( (balance_deeper_called++)==0 );
  58188. rc = balance_deeper(pPage, &pCur->apPage[1]);
  58189. if( rc==SQLITE_OK ){
  58190. pCur->iPage = 1;
  58191. pCur->aiIdx[0] = 0;
  58192. pCur->aiIdx[1] = 0;
  58193. assert( pCur->apPage[1]->nOverflow );
  58194. }
  58195. }else{
  58196. break;
  58197. }
  58198. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  58199. break;
  58200. }else{
  58201. MemPage * const pParent = pCur->apPage[iPage-1];
  58202. int const iIdx = pCur->aiIdx[iPage-1];
  58203. rc = sqlite3PagerWrite(pParent->pDbPage);
  58204. if( rc==SQLITE_OK ){
  58205. #ifndef SQLITE_OMIT_QUICKBALANCE
  58206. if( pPage->intKeyLeaf
  58207. && pPage->nOverflow==1
  58208. && pPage->aiOvfl[0]==pPage->nCell
  58209. && pParent->pgno!=1
  58210. && pParent->nCell==iIdx
  58211. ){
  58212. /* Call balance_quick() to create a new sibling of pPage on which
  58213. ** to store the overflow cell. balance_quick() inserts a new cell
  58214. ** into pParent, which may cause pParent overflow. If this
  58215. ** happens, the next iteration of the do-loop will balance pParent
  58216. ** use either balance_nonroot() or balance_deeper(). Until this
  58217. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  58218. ** buffer.
  58219. **
  58220. ** The purpose of the following assert() is to check that only a
  58221. ** single call to balance_quick() is made for each call to this
  58222. ** function. If this were not verified, a subtle bug involving reuse
  58223. ** of the aBalanceQuickSpace[] might sneak in.
  58224. */
  58225. assert( (balance_quick_called++)==0 );
  58226. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  58227. }else
  58228. #endif
  58229. {
  58230. /* In this case, call balance_nonroot() to redistribute cells
  58231. ** between pPage and up to 2 of its sibling pages. This involves
  58232. ** modifying the contents of pParent, which may cause pParent to
  58233. ** become overfull or underfull. The next iteration of the do-loop
  58234. ** will balance the parent page to correct this.
  58235. **
  58236. ** If the parent page becomes overfull, the overflow cell or cells
  58237. ** are stored in the pSpace buffer allocated immediately below.
  58238. ** A subsequent iteration of the do-loop will deal with this by
  58239. ** calling balance_nonroot() (balance_deeper() may be called first,
  58240. ** but it doesn't deal with overflow cells - just moves them to a
  58241. ** different page). Once this subsequent call to balance_nonroot()
  58242. ** has completed, it is safe to release the pSpace buffer used by
  58243. ** the previous call, as the overflow cell data will have been
  58244. ** copied either into the body of a database page or into the new
  58245. ** pSpace buffer passed to the latter call to balance_nonroot().
  58246. */
  58247. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  58248. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  58249. pCur->hints&BTREE_BULKLOAD);
  58250. if( pFree ){
  58251. /* If pFree is not NULL, it points to the pSpace buffer used
  58252. ** by a previous call to balance_nonroot(). Its contents are
  58253. ** now stored either on real database pages or within the
  58254. ** new pSpace buffer, so it may be safely freed here. */
  58255. sqlite3PageFree(pFree);
  58256. }
  58257. /* The pSpace buffer will be freed after the next call to
  58258. ** balance_nonroot(), or just before this function returns, whichever
  58259. ** comes first. */
  58260. pFree = pSpace;
  58261. }
  58262. }
  58263. pPage->nOverflow = 0;
  58264. /* The next iteration of the do-loop balances the parent page. */
  58265. releasePage(pPage);
  58266. pCur->iPage--;
  58267. assert( pCur->iPage>=0 );
  58268. }
  58269. }while( rc==SQLITE_OK );
  58270. if( pFree ){
  58271. sqlite3PageFree(pFree);
  58272. }
  58273. return rc;
  58274. }
  58275. /*
  58276. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  58277. ** and the data is given by (pData,nData). The cursor is used only to
  58278. ** define what table the record should be inserted into. The cursor
  58279. ** is left pointing at a random location.
  58280. **
  58281. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  58282. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  58283. **
  58284. ** If the seekResult parameter is non-zero, then a successful call to
  58285. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  58286. ** been performed. seekResult is the search result returned (a negative
  58287. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  58288. ** a positive value if pCur points at an entry that is larger than
  58289. ** (pKey, nKey)).
  58290. **
  58291. ** If the seekResult parameter is non-zero, then the caller guarantees that
  58292. ** cursor pCur is pointing at the existing copy of a row that is to be
  58293. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  58294. ** point to any entry or to no entry at all and so this function has to seek
  58295. ** the cursor before the new key can be inserted.
  58296. */
  58297. SQLITE_PRIVATE int sqlite3BtreeInsert(
  58298. BtCursor *pCur, /* Insert data into the table of this cursor */
  58299. const void *pKey, i64 nKey, /* The key of the new record */
  58300. const void *pData, int nData, /* The data of the new record */
  58301. int nZero, /* Number of extra 0 bytes to append to data */
  58302. int appendBias, /* True if this is likely an append */
  58303. int seekResult /* Result of prior MovetoUnpacked() call */
  58304. ){
  58305. int rc;
  58306. int loc = seekResult; /* -1: before desired location +1: after */
  58307. int szNew = 0;
  58308. int idx;
  58309. MemPage *pPage;
  58310. Btree *p = pCur->pBtree;
  58311. BtShared *pBt = p->pBt;
  58312. unsigned char *oldCell;
  58313. unsigned char *newCell = 0;
  58314. if( pCur->eState==CURSOR_FAULT ){
  58315. assert( pCur->skipNext!=SQLITE_OK );
  58316. return pCur->skipNext;
  58317. }
  58318. assert( cursorHoldsMutex(pCur) );
  58319. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  58320. && pBt->inTransaction==TRANS_WRITE
  58321. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  58322. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  58323. /* Assert that the caller has been consistent. If this cursor was opened
  58324. ** expecting an index b-tree, then the caller should be inserting blob
  58325. ** keys with no associated data. If the cursor was opened expecting an
  58326. ** intkey table, the caller should be inserting integer keys with a
  58327. ** blob of associated data. */
  58328. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  58329. /* Save the positions of any other cursors open on this table.
  58330. **
  58331. ** In some cases, the call to btreeMoveto() below is a no-op. For
  58332. ** example, when inserting data into a table with auto-generated integer
  58333. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  58334. ** integer key to use. It then calls this function to actually insert the
  58335. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  58336. ** that the cursor is already where it needs to be and returns without
  58337. ** doing any work. To avoid thwarting these optimizations, it is important
  58338. ** not to clear the cursor here.
  58339. */
  58340. if( pCur->curFlags & BTCF_Multiple ){
  58341. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  58342. if( rc ) return rc;
  58343. }
  58344. if( pCur->pKeyInfo==0 ){
  58345. assert( pKey==0 );
  58346. /* If this is an insert into a table b-tree, invalidate any incrblob
  58347. ** cursors open on the row being replaced */
  58348. invalidateIncrblobCursors(p, nKey, 0);
  58349. /* If the cursor is currently on the last row and we are appending a
  58350. ** new row onto the end, set the "loc" to avoid an unnecessary
  58351. ** btreeMoveto() call */
  58352. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  58353. && pCur->info.nKey==nKey-1 ){
  58354. loc = -1;
  58355. }else if( loc==0 ){
  58356. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
  58357. if( rc ) return rc;
  58358. }
  58359. }else if( loc==0 ){
  58360. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  58361. if( rc ) return rc;
  58362. }
  58363. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  58364. pPage = pCur->apPage[pCur->iPage];
  58365. assert( pPage->intKey || nKey>=0 );
  58366. assert( pPage->leaf || !pPage->intKey );
  58367. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  58368. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  58369. loc==0 ? "overwrite" : "new entry"));
  58370. assert( pPage->isInit );
  58371. newCell = pBt->pTmpSpace;
  58372. assert( newCell!=0 );
  58373. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  58374. if( rc ) goto end_insert;
  58375. assert( szNew==pPage->xCellSize(pPage, newCell) );
  58376. assert( szNew <= MX_CELL_SIZE(pBt) );
  58377. idx = pCur->aiIdx[pCur->iPage];
  58378. if( loc==0 ){
  58379. u16 szOld;
  58380. assert( idx<pPage->nCell );
  58381. rc = sqlite3PagerWrite(pPage->pDbPage);
  58382. if( rc ){
  58383. goto end_insert;
  58384. }
  58385. oldCell = findCell(pPage, idx);
  58386. if( !pPage->leaf ){
  58387. memcpy(newCell, oldCell, 4);
  58388. }
  58389. rc = clearCell(pPage, oldCell, &szOld);
  58390. dropCell(pPage, idx, szOld, &rc);
  58391. if( rc ) goto end_insert;
  58392. }else if( loc<0 && pPage->nCell>0 ){
  58393. assert( pPage->leaf );
  58394. idx = ++pCur->aiIdx[pCur->iPage];
  58395. }else{
  58396. assert( pPage->leaf );
  58397. }
  58398. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  58399. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  58400. /* If no error has occurred and pPage has an overflow cell, call balance()
  58401. ** to redistribute the cells within the tree. Since balance() may move
  58402. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  58403. ** variables.
  58404. **
  58405. ** Previous versions of SQLite called moveToRoot() to move the cursor
  58406. ** back to the root page as balance() used to invalidate the contents
  58407. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  58408. ** set the cursor state to "invalid". This makes common insert operations
  58409. ** slightly faster.
  58410. **
  58411. ** There is a subtle but important optimization here too. When inserting
  58412. ** multiple records into an intkey b-tree using a single cursor (as can
  58413. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  58414. ** is advantageous to leave the cursor pointing to the last entry in
  58415. ** the b-tree if possible. If the cursor is left pointing to the last
  58416. ** entry in the table, and the next row inserted has an integer key
  58417. ** larger than the largest existing key, it is possible to insert the
  58418. ** row without seeking the cursor. This can be a big performance boost.
  58419. */
  58420. pCur->info.nSize = 0;
  58421. if( rc==SQLITE_OK && pPage->nOverflow ){
  58422. pCur->curFlags &= ~(BTCF_ValidNKey);
  58423. rc = balance(pCur);
  58424. /* Must make sure nOverflow is reset to zero even if the balance()
  58425. ** fails. Internal data structure corruption will result otherwise.
  58426. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  58427. ** from trying to save the current position of the cursor. */
  58428. pCur->apPage[pCur->iPage]->nOverflow = 0;
  58429. pCur->eState = CURSOR_INVALID;
  58430. }
  58431. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  58432. end_insert:
  58433. return rc;
  58434. }
  58435. /*
  58436. ** Delete the entry that the cursor is pointing to.
  58437. **
  58438. ** If the second parameter is zero, then the cursor is left pointing at an
  58439. ** arbitrary location after the delete. If it is non-zero, then the cursor
  58440. ** is left in a state such that the next call to BtreeNext() or BtreePrev()
  58441. ** moves it to the same row as it would if the call to BtreeDelete() had
  58442. ** been omitted.
  58443. */
  58444. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, int bPreserve){
  58445. Btree *p = pCur->pBtree;
  58446. BtShared *pBt = p->pBt;
  58447. int rc; /* Return code */
  58448. MemPage *pPage; /* Page to delete cell from */
  58449. unsigned char *pCell; /* Pointer to cell to delete */
  58450. int iCellIdx; /* Index of cell to delete */
  58451. int iCellDepth; /* Depth of node containing pCell */
  58452. u16 szCell; /* Size of the cell being deleted */
  58453. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  58454. assert( cursorHoldsMutex(pCur) );
  58455. assert( pBt->inTransaction==TRANS_WRITE );
  58456. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  58457. assert( pCur->curFlags & BTCF_WriteFlag );
  58458. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  58459. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  58460. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  58461. assert( pCur->eState==CURSOR_VALID );
  58462. iCellDepth = pCur->iPage;
  58463. iCellIdx = pCur->aiIdx[iCellDepth];
  58464. pPage = pCur->apPage[iCellDepth];
  58465. pCell = findCell(pPage, iCellIdx);
  58466. /* If the page containing the entry to delete is not a leaf page, move
  58467. ** the cursor to the largest entry in the tree that is smaller than
  58468. ** the entry being deleted. This cell will replace the cell being deleted
  58469. ** from the internal node. The 'previous' entry is used for this instead
  58470. ** of the 'next' entry, as the previous entry is always a part of the
  58471. ** sub-tree headed by the child page of the cell being deleted. This makes
  58472. ** balancing the tree following the delete operation easier. */
  58473. if( !pPage->leaf ){
  58474. int notUsed = 0;
  58475. rc = sqlite3BtreePrevious(pCur, &notUsed);
  58476. if( rc ) return rc;
  58477. }
  58478. /* Save the positions of any other cursors open on this table before
  58479. ** making any modifications. */
  58480. if( pCur->curFlags & BTCF_Multiple ){
  58481. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  58482. if( rc ) return rc;
  58483. }
  58484. /* If this is a delete operation to remove a row from a table b-tree,
  58485. ** invalidate any incrblob cursors open on the row being deleted. */
  58486. if( pCur->pKeyInfo==0 ){
  58487. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  58488. }
  58489. /* If the bPreserve flag is set to true, then the cursor position must
  58490. ** be preserved following this delete operation. If the current delete
  58491. ** will cause a b-tree rebalance, then this is done by saving the cursor
  58492. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  58493. ** returning.
  58494. **
  58495. ** Or, if the current delete will not cause a rebalance, then the cursor
  58496. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  58497. ** before or after the deleted entry. In this case set bSkipnext to true. */
  58498. if( bPreserve ){
  58499. if( !pPage->leaf
  58500. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  58501. ){
  58502. /* A b-tree rebalance will be required after deleting this entry.
  58503. ** Save the cursor key. */
  58504. rc = saveCursorKey(pCur);
  58505. if( rc ) return rc;
  58506. }else{
  58507. bSkipnext = 1;
  58508. }
  58509. }
  58510. /* Make the page containing the entry to be deleted writable. Then free any
  58511. ** overflow pages associated with the entry and finally remove the cell
  58512. ** itself from within the page. */
  58513. rc = sqlite3PagerWrite(pPage->pDbPage);
  58514. if( rc ) return rc;
  58515. rc = clearCell(pPage, pCell, &szCell);
  58516. dropCell(pPage, iCellIdx, szCell, &rc);
  58517. if( rc ) return rc;
  58518. /* If the cell deleted was not located on a leaf page, then the cursor
  58519. ** is currently pointing to the largest entry in the sub-tree headed
  58520. ** by the child-page of the cell that was just deleted from an internal
  58521. ** node. The cell from the leaf node needs to be moved to the internal
  58522. ** node to replace the deleted cell. */
  58523. if( !pPage->leaf ){
  58524. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  58525. int nCell;
  58526. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  58527. unsigned char *pTmp;
  58528. pCell = findCell(pLeaf, pLeaf->nCell-1);
  58529. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  58530. nCell = pLeaf->xCellSize(pLeaf, pCell);
  58531. assert( MX_CELL_SIZE(pBt) >= nCell );
  58532. pTmp = pBt->pTmpSpace;
  58533. assert( pTmp!=0 );
  58534. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  58535. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  58536. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  58537. if( rc ) return rc;
  58538. }
  58539. /* Balance the tree. If the entry deleted was located on a leaf page,
  58540. ** then the cursor still points to that page. In this case the first
  58541. ** call to balance() repairs the tree, and the if(...) condition is
  58542. ** never true.
  58543. **
  58544. ** Otherwise, if the entry deleted was on an internal node page, then
  58545. ** pCur is pointing to the leaf page from which a cell was removed to
  58546. ** replace the cell deleted from the internal node. This is slightly
  58547. ** tricky as the leaf node may be underfull, and the internal node may
  58548. ** be either under or overfull. In this case run the balancing algorithm
  58549. ** on the leaf node first. If the balance proceeds far enough up the
  58550. ** tree that we can be sure that any problem in the internal node has
  58551. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  58552. ** walk the cursor up the tree to the internal node and balance it as
  58553. ** well. */
  58554. rc = balance(pCur);
  58555. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  58556. while( pCur->iPage>iCellDepth ){
  58557. releasePage(pCur->apPage[pCur->iPage--]);
  58558. }
  58559. rc = balance(pCur);
  58560. }
  58561. if( rc==SQLITE_OK ){
  58562. if( bSkipnext ){
  58563. assert( bPreserve && pCur->iPage==iCellDepth );
  58564. assert( pPage==pCur->apPage[pCur->iPage] );
  58565. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  58566. pCur->eState = CURSOR_SKIPNEXT;
  58567. if( iCellIdx>=pPage->nCell ){
  58568. pCur->skipNext = -1;
  58569. pCur->aiIdx[iCellDepth] = pPage->nCell-1;
  58570. }else{
  58571. pCur->skipNext = 1;
  58572. }
  58573. }else{
  58574. rc = moveToRoot(pCur);
  58575. if( bPreserve ){
  58576. pCur->eState = CURSOR_REQUIRESEEK;
  58577. }
  58578. }
  58579. }
  58580. return rc;
  58581. }
  58582. /*
  58583. ** Create a new BTree table. Write into *piTable the page
  58584. ** number for the root page of the new table.
  58585. **
  58586. ** The type of type is determined by the flags parameter. Only the
  58587. ** following values of flags are currently in use. Other values for
  58588. ** flags might not work:
  58589. **
  58590. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  58591. ** BTREE_ZERODATA Used for SQL indices
  58592. */
  58593. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  58594. BtShared *pBt = p->pBt;
  58595. MemPage *pRoot;
  58596. Pgno pgnoRoot;
  58597. int rc;
  58598. int ptfFlags; /* Page-type flage for the root page of new table */
  58599. assert( sqlite3BtreeHoldsMutex(p) );
  58600. assert( pBt->inTransaction==TRANS_WRITE );
  58601. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  58602. #ifdef SQLITE_OMIT_AUTOVACUUM
  58603. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  58604. if( rc ){
  58605. return rc;
  58606. }
  58607. #else
  58608. if( pBt->autoVacuum ){
  58609. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  58610. MemPage *pPageMove; /* The page to move to. */
  58611. /* Creating a new table may probably require moving an existing database
  58612. ** to make room for the new tables root page. In case this page turns
  58613. ** out to be an overflow page, delete all overflow page-map caches
  58614. ** held by open cursors.
  58615. */
  58616. invalidateAllOverflowCache(pBt);
  58617. /* Read the value of meta[3] from the database to determine where the
  58618. ** root page of the new table should go. meta[3] is the largest root-page
  58619. ** created so far, so the new root-page is (meta[3]+1).
  58620. */
  58621. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  58622. pgnoRoot++;
  58623. /* The new root-page may not be allocated on a pointer-map page, or the
  58624. ** PENDING_BYTE page.
  58625. */
  58626. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  58627. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  58628. pgnoRoot++;
  58629. }
  58630. assert( pgnoRoot>=3 || CORRUPT_DB );
  58631. testcase( pgnoRoot<3 );
  58632. /* Allocate a page. The page that currently resides at pgnoRoot will
  58633. ** be moved to the allocated page (unless the allocated page happens
  58634. ** to reside at pgnoRoot).
  58635. */
  58636. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  58637. if( rc!=SQLITE_OK ){
  58638. return rc;
  58639. }
  58640. if( pgnoMove!=pgnoRoot ){
  58641. /* pgnoRoot is the page that will be used for the root-page of
  58642. ** the new table (assuming an error did not occur). But we were
  58643. ** allocated pgnoMove. If required (i.e. if it was not allocated
  58644. ** by extending the file), the current page at position pgnoMove
  58645. ** is already journaled.
  58646. */
  58647. u8 eType = 0;
  58648. Pgno iPtrPage = 0;
  58649. /* Save the positions of any open cursors. This is required in
  58650. ** case they are holding a reference to an xFetch reference
  58651. ** corresponding to page pgnoRoot. */
  58652. rc = saveAllCursors(pBt, 0, 0);
  58653. releasePage(pPageMove);
  58654. if( rc!=SQLITE_OK ){
  58655. return rc;
  58656. }
  58657. /* Move the page currently at pgnoRoot to pgnoMove. */
  58658. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  58659. if( rc!=SQLITE_OK ){
  58660. return rc;
  58661. }
  58662. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  58663. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  58664. rc = SQLITE_CORRUPT_BKPT;
  58665. }
  58666. if( rc!=SQLITE_OK ){
  58667. releasePage(pRoot);
  58668. return rc;
  58669. }
  58670. assert( eType!=PTRMAP_ROOTPAGE );
  58671. assert( eType!=PTRMAP_FREEPAGE );
  58672. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  58673. releasePage(pRoot);
  58674. /* Obtain the page at pgnoRoot */
  58675. if( rc!=SQLITE_OK ){
  58676. return rc;
  58677. }
  58678. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  58679. if( rc!=SQLITE_OK ){
  58680. return rc;
  58681. }
  58682. rc = sqlite3PagerWrite(pRoot->pDbPage);
  58683. if( rc!=SQLITE_OK ){
  58684. releasePage(pRoot);
  58685. return rc;
  58686. }
  58687. }else{
  58688. pRoot = pPageMove;
  58689. }
  58690. /* Update the pointer-map and meta-data with the new root-page number. */
  58691. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  58692. if( rc ){
  58693. releasePage(pRoot);
  58694. return rc;
  58695. }
  58696. /* When the new root page was allocated, page 1 was made writable in
  58697. ** order either to increase the database filesize, or to decrement the
  58698. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  58699. */
  58700. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  58701. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  58702. if( NEVER(rc) ){
  58703. releasePage(pRoot);
  58704. return rc;
  58705. }
  58706. }else{
  58707. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  58708. if( rc ) return rc;
  58709. }
  58710. #endif
  58711. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  58712. if( createTabFlags & BTREE_INTKEY ){
  58713. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  58714. }else{
  58715. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  58716. }
  58717. zeroPage(pRoot, ptfFlags);
  58718. sqlite3PagerUnref(pRoot->pDbPage);
  58719. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  58720. *piTable = (int)pgnoRoot;
  58721. return SQLITE_OK;
  58722. }
  58723. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  58724. int rc;
  58725. sqlite3BtreeEnter(p);
  58726. rc = btreeCreateTable(p, piTable, flags);
  58727. sqlite3BtreeLeave(p);
  58728. return rc;
  58729. }
  58730. /*
  58731. ** Erase the given database page and all its children. Return
  58732. ** the page to the freelist.
  58733. */
  58734. static int clearDatabasePage(
  58735. BtShared *pBt, /* The BTree that contains the table */
  58736. Pgno pgno, /* Page number to clear */
  58737. int freePageFlag, /* Deallocate page if true */
  58738. int *pnChange /* Add number of Cells freed to this counter */
  58739. ){
  58740. MemPage *pPage;
  58741. int rc;
  58742. unsigned char *pCell;
  58743. int i;
  58744. int hdr;
  58745. u16 szCell;
  58746. assert( sqlite3_mutex_held(pBt->mutex) );
  58747. if( pgno>btreePagecount(pBt) ){
  58748. return SQLITE_CORRUPT_BKPT;
  58749. }
  58750. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  58751. if( rc ) return rc;
  58752. if( pPage->bBusy ){
  58753. rc = SQLITE_CORRUPT_BKPT;
  58754. goto cleardatabasepage_out;
  58755. }
  58756. pPage->bBusy = 1;
  58757. hdr = pPage->hdrOffset;
  58758. for(i=0; i<pPage->nCell; i++){
  58759. pCell = findCell(pPage, i);
  58760. if( !pPage->leaf ){
  58761. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  58762. if( rc ) goto cleardatabasepage_out;
  58763. }
  58764. rc = clearCell(pPage, pCell, &szCell);
  58765. if( rc ) goto cleardatabasepage_out;
  58766. }
  58767. if( !pPage->leaf ){
  58768. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  58769. if( rc ) goto cleardatabasepage_out;
  58770. }else if( pnChange ){
  58771. assert( pPage->intKey || CORRUPT_DB );
  58772. testcase( !pPage->intKey );
  58773. *pnChange += pPage->nCell;
  58774. }
  58775. if( freePageFlag ){
  58776. freePage(pPage, &rc);
  58777. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  58778. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  58779. }
  58780. cleardatabasepage_out:
  58781. pPage->bBusy = 0;
  58782. releasePage(pPage);
  58783. return rc;
  58784. }
  58785. /*
  58786. ** Delete all information from a single table in the database. iTable is
  58787. ** the page number of the root of the table. After this routine returns,
  58788. ** the root page is empty, but still exists.
  58789. **
  58790. ** This routine will fail with SQLITE_LOCKED if there are any open
  58791. ** read cursors on the table. Open write cursors are moved to the
  58792. ** root of the table.
  58793. **
  58794. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  58795. ** integer value pointed to by pnChange is incremented by the number of
  58796. ** entries in the table.
  58797. */
  58798. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  58799. int rc;
  58800. BtShared *pBt = p->pBt;
  58801. sqlite3BtreeEnter(p);
  58802. assert( p->inTrans==TRANS_WRITE );
  58803. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  58804. if( SQLITE_OK==rc ){
  58805. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  58806. ** is the root of a table b-tree - if it is not, the following call is
  58807. ** a no-op). */
  58808. invalidateIncrblobCursors(p, 0, 1);
  58809. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  58810. }
  58811. sqlite3BtreeLeave(p);
  58812. return rc;
  58813. }
  58814. /*
  58815. ** Delete all information from the single table that pCur is open on.
  58816. **
  58817. ** This routine only work for pCur on an ephemeral table.
  58818. */
  58819. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  58820. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  58821. }
  58822. /*
  58823. ** Erase all information in a table and add the root of the table to
  58824. ** the freelist. Except, the root of the principle table (the one on
  58825. ** page 1) is never added to the freelist.
  58826. **
  58827. ** This routine will fail with SQLITE_LOCKED if there are any open
  58828. ** cursors on the table.
  58829. **
  58830. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  58831. ** root page in the database file, then the last root page
  58832. ** in the database file is moved into the slot formerly occupied by
  58833. ** iTable and that last slot formerly occupied by the last root page
  58834. ** is added to the freelist instead of iTable. In this say, all
  58835. ** root pages are kept at the beginning of the database file, which
  58836. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  58837. ** page number that used to be the last root page in the file before
  58838. ** the move. If no page gets moved, *piMoved is set to 0.
  58839. ** The last root page is recorded in meta[3] and the value of
  58840. ** meta[3] is updated by this procedure.
  58841. */
  58842. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  58843. int rc;
  58844. MemPage *pPage = 0;
  58845. BtShared *pBt = p->pBt;
  58846. assert( sqlite3BtreeHoldsMutex(p) );
  58847. assert( p->inTrans==TRANS_WRITE );
  58848. /* It is illegal to drop a table if any cursors are open on the
  58849. ** database. This is because in auto-vacuum mode the backend may
  58850. ** need to move another root-page to fill a gap left by the deleted
  58851. ** root page. If an open cursor was using this page a problem would
  58852. ** occur.
  58853. **
  58854. ** This error is caught long before control reaches this point.
  58855. */
  58856. if( NEVER(pBt->pCursor) ){
  58857. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  58858. return SQLITE_LOCKED_SHAREDCACHE;
  58859. }
  58860. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  58861. if( rc ) return rc;
  58862. rc = sqlite3BtreeClearTable(p, iTable, 0);
  58863. if( rc ){
  58864. releasePage(pPage);
  58865. return rc;
  58866. }
  58867. *piMoved = 0;
  58868. if( iTable>1 ){
  58869. #ifdef SQLITE_OMIT_AUTOVACUUM
  58870. freePage(pPage, &rc);
  58871. releasePage(pPage);
  58872. #else
  58873. if( pBt->autoVacuum ){
  58874. Pgno maxRootPgno;
  58875. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  58876. if( iTable==maxRootPgno ){
  58877. /* If the table being dropped is the table with the largest root-page
  58878. ** number in the database, put the root page on the free list.
  58879. */
  58880. freePage(pPage, &rc);
  58881. releasePage(pPage);
  58882. if( rc!=SQLITE_OK ){
  58883. return rc;
  58884. }
  58885. }else{
  58886. /* The table being dropped does not have the largest root-page
  58887. ** number in the database. So move the page that does into the
  58888. ** gap left by the deleted root-page.
  58889. */
  58890. MemPage *pMove;
  58891. releasePage(pPage);
  58892. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  58893. if( rc!=SQLITE_OK ){
  58894. return rc;
  58895. }
  58896. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  58897. releasePage(pMove);
  58898. if( rc!=SQLITE_OK ){
  58899. return rc;
  58900. }
  58901. pMove = 0;
  58902. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  58903. freePage(pMove, &rc);
  58904. releasePage(pMove);
  58905. if( rc!=SQLITE_OK ){
  58906. return rc;
  58907. }
  58908. *piMoved = maxRootPgno;
  58909. }
  58910. /* Set the new 'max-root-page' value in the database header. This
  58911. ** is the old value less one, less one more if that happens to
  58912. ** be a root-page number, less one again if that is the
  58913. ** PENDING_BYTE_PAGE.
  58914. */
  58915. maxRootPgno--;
  58916. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  58917. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  58918. maxRootPgno--;
  58919. }
  58920. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  58921. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  58922. }else{
  58923. freePage(pPage, &rc);
  58924. releasePage(pPage);
  58925. }
  58926. #endif
  58927. }else{
  58928. /* If sqlite3BtreeDropTable was called on page 1.
  58929. ** This really never should happen except in a corrupt
  58930. ** database.
  58931. */
  58932. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  58933. releasePage(pPage);
  58934. }
  58935. return rc;
  58936. }
  58937. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  58938. int rc;
  58939. sqlite3BtreeEnter(p);
  58940. rc = btreeDropTable(p, iTable, piMoved);
  58941. sqlite3BtreeLeave(p);
  58942. return rc;
  58943. }
  58944. /*
  58945. ** This function may only be called if the b-tree connection already
  58946. ** has a read or write transaction open on the database.
  58947. **
  58948. ** Read the meta-information out of a database file. Meta[0]
  58949. ** is the number of free pages currently in the database. Meta[1]
  58950. ** through meta[15] are available for use by higher layers. Meta[0]
  58951. ** is read-only, the others are read/write.
  58952. **
  58953. ** The schema layer numbers meta values differently. At the schema
  58954. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  58955. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  58956. **
  58957. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  58958. ** of reading the value out of the header, it instead loads the "DataVersion"
  58959. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  58960. ** database file. It is a number computed by the pager. But its access
  58961. ** pattern is the same as header meta values, and so it is convenient to
  58962. ** read it from this routine.
  58963. */
  58964. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  58965. BtShared *pBt = p->pBt;
  58966. sqlite3BtreeEnter(p);
  58967. assert( p->inTrans>TRANS_NONE );
  58968. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  58969. assert( pBt->pPage1 );
  58970. assert( idx>=0 && idx<=15 );
  58971. if( idx==BTREE_DATA_VERSION ){
  58972. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  58973. }else{
  58974. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  58975. }
  58976. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  58977. ** database, mark the database as read-only. */
  58978. #ifdef SQLITE_OMIT_AUTOVACUUM
  58979. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  58980. pBt->btsFlags |= BTS_READ_ONLY;
  58981. }
  58982. #endif
  58983. sqlite3BtreeLeave(p);
  58984. }
  58985. /*
  58986. ** Write meta-information back into the database. Meta[0] is
  58987. ** read-only and may not be written.
  58988. */
  58989. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  58990. BtShared *pBt = p->pBt;
  58991. unsigned char *pP1;
  58992. int rc;
  58993. assert( idx>=1 && idx<=15 );
  58994. sqlite3BtreeEnter(p);
  58995. assert( p->inTrans==TRANS_WRITE );
  58996. assert( pBt->pPage1!=0 );
  58997. pP1 = pBt->pPage1->aData;
  58998. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58999. if( rc==SQLITE_OK ){
  59000. put4byte(&pP1[36 + idx*4], iMeta);
  59001. #ifndef SQLITE_OMIT_AUTOVACUUM
  59002. if( idx==BTREE_INCR_VACUUM ){
  59003. assert( pBt->autoVacuum || iMeta==0 );
  59004. assert( iMeta==0 || iMeta==1 );
  59005. pBt->incrVacuum = (u8)iMeta;
  59006. }
  59007. #endif
  59008. }
  59009. sqlite3BtreeLeave(p);
  59010. return rc;
  59011. }
  59012. #ifndef SQLITE_OMIT_BTREECOUNT
  59013. /*
  59014. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  59015. ** number of entries in the b-tree and write the result to *pnEntry.
  59016. **
  59017. ** SQLITE_OK is returned if the operation is successfully executed.
  59018. ** Otherwise, if an error is encountered (i.e. an IO error or database
  59019. ** corruption) an SQLite error code is returned.
  59020. */
  59021. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  59022. i64 nEntry = 0; /* Value to return in *pnEntry */
  59023. int rc; /* Return code */
  59024. if( pCur->pgnoRoot==0 ){
  59025. *pnEntry = 0;
  59026. return SQLITE_OK;
  59027. }
  59028. rc = moveToRoot(pCur);
  59029. /* Unless an error occurs, the following loop runs one iteration for each
  59030. ** page in the B-Tree structure (not including overflow pages).
  59031. */
  59032. while( rc==SQLITE_OK ){
  59033. int iIdx; /* Index of child node in parent */
  59034. MemPage *pPage; /* Current page of the b-tree */
  59035. /* If this is a leaf page or the tree is not an int-key tree, then
  59036. ** this page contains countable entries. Increment the entry counter
  59037. ** accordingly.
  59038. */
  59039. pPage = pCur->apPage[pCur->iPage];
  59040. if( pPage->leaf || !pPage->intKey ){
  59041. nEntry += pPage->nCell;
  59042. }
  59043. /* pPage is a leaf node. This loop navigates the cursor so that it
  59044. ** points to the first interior cell that it points to the parent of
  59045. ** the next page in the tree that has not yet been visited. The
  59046. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  59047. ** of the page, or to the number of cells in the page if the next page
  59048. ** to visit is the right-child of its parent.
  59049. **
  59050. ** If all pages in the tree have been visited, return SQLITE_OK to the
  59051. ** caller.
  59052. */
  59053. if( pPage->leaf ){
  59054. do {
  59055. if( pCur->iPage==0 ){
  59056. /* All pages of the b-tree have been visited. Return successfully. */
  59057. *pnEntry = nEntry;
  59058. return moveToRoot(pCur);
  59059. }
  59060. moveToParent(pCur);
  59061. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  59062. pCur->aiIdx[pCur->iPage]++;
  59063. pPage = pCur->apPage[pCur->iPage];
  59064. }
  59065. /* Descend to the child node of the cell that the cursor currently
  59066. ** points at. This is the right-child if (iIdx==pPage->nCell).
  59067. */
  59068. iIdx = pCur->aiIdx[pCur->iPage];
  59069. if( iIdx==pPage->nCell ){
  59070. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  59071. }else{
  59072. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  59073. }
  59074. }
  59075. /* An error has occurred. Return an error code. */
  59076. return rc;
  59077. }
  59078. #endif
  59079. /*
  59080. ** Return the pager associated with a BTree. This routine is used for
  59081. ** testing and debugging only.
  59082. */
  59083. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  59084. return p->pBt->pPager;
  59085. }
  59086. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59087. /*
  59088. ** Append a message to the error message string.
  59089. */
  59090. static void checkAppendMsg(
  59091. IntegrityCk *pCheck,
  59092. const char *zFormat,
  59093. ...
  59094. ){
  59095. va_list ap;
  59096. if( !pCheck->mxErr ) return;
  59097. pCheck->mxErr--;
  59098. pCheck->nErr++;
  59099. va_start(ap, zFormat);
  59100. if( pCheck->errMsg.nChar ){
  59101. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  59102. }
  59103. if( pCheck->zPfx ){
  59104. sqlite3XPrintf(&pCheck->errMsg, 0, pCheck->zPfx, pCheck->v1, pCheck->v2);
  59105. }
  59106. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  59107. va_end(ap);
  59108. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  59109. pCheck->mallocFailed = 1;
  59110. }
  59111. }
  59112. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59113. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59114. /*
  59115. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  59116. ** corresponds to page iPg is already set.
  59117. */
  59118. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  59119. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  59120. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  59121. }
  59122. /*
  59123. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  59124. */
  59125. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  59126. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  59127. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  59128. }
  59129. /*
  59130. ** Add 1 to the reference count for page iPage. If this is the second
  59131. ** reference to the page, add an error message to pCheck->zErrMsg.
  59132. ** Return 1 if there are 2 or more references to the page and 0 if
  59133. ** if this is the first reference to the page.
  59134. **
  59135. ** Also check that the page number is in bounds.
  59136. */
  59137. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  59138. if( iPage==0 ) return 1;
  59139. if( iPage>pCheck->nPage ){
  59140. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  59141. return 1;
  59142. }
  59143. if( getPageReferenced(pCheck, iPage) ){
  59144. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  59145. return 1;
  59146. }
  59147. setPageReferenced(pCheck, iPage);
  59148. return 0;
  59149. }
  59150. #ifndef SQLITE_OMIT_AUTOVACUUM
  59151. /*
  59152. ** Check that the entry in the pointer-map for page iChild maps to
  59153. ** page iParent, pointer type ptrType. If not, append an error message
  59154. ** to pCheck.
  59155. */
  59156. static void checkPtrmap(
  59157. IntegrityCk *pCheck, /* Integrity check context */
  59158. Pgno iChild, /* Child page number */
  59159. u8 eType, /* Expected pointer map type */
  59160. Pgno iParent /* Expected pointer map parent page number */
  59161. ){
  59162. int rc;
  59163. u8 ePtrmapType;
  59164. Pgno iPtrmapParent;
  59165. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  59166. if( rc!=SQLITE_OK ){
  59167. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  59168. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  59169. return;
  59170. }
  59171. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  59172. checkAppendMsg(pCheck,
  59173. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  59174. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  59175. }
  59176. }
  59177. #endif
  59178. /*
  59179. ** Check the integrity of the freelist or of an overflow page list.
  59180. ** Verify that the number of pages on the list is N.
  59181. */
  59182. static void checkList(
  59183. IntegrityCk *pCheck, /* Integrity checking context */
  59184. int isFreeList, /* True for a freelist. False for overflow page list */
  59185. int iPage, /* Page number for first page in the list */
  59186. int N /* Expected number of pages in the list */
  59187. ){
  59188. int i;
  59189. int expected = N;
  59190. int iFirst = iPage;
  59191. while( N-- > 0 && pCheck->mxErr ){
  59192. DbPage *pOvflPage;
  59193. unsigned char *pOvflData;
  59194. if( iPage<1 ){
  59195. checkAppendMsg(pCheck,
  59196. "%d of %d pages missing from overflow list starting at %d",
  59197. N+1, expected, iFirst);
  59198. break;
  59199. }
  59200. if( checkRef(pCheck, iPage) ) break;
  59201. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  59202. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  59203. break;
  59204. }
  59205. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  59206. if( isFreeList ){
  59207. int n = get4byte(&pOvflData[4]);
  59208. #ifndef SQLITE_OMIT_AUTOVACUUM
  59209. if( pCheck->pBt->autoVacuum ){
  59210. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  59211. }
  59212. #endif
  59213. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  59214. checkAppendMsg(pCheck,
  59215. "freelist leaf count too big on page %d", iPage);
  59216. N--;
  59217. }else{
  59218. for(i=0; i<n; i++){
  59219. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  59220. #ifndef SQLITE_OMIT_AUTOVACUUM
  59221. if( pCheck->pBt->autoVacuum ){
  59222. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  59223. }
  59224. #endif
  59225. checkRef(pCheck, iFreePage);
  59226. }
  59227. N -= n;
  59228. }
  59229. }
  59230. #ifndef SQLITE_OMIT_AUTOVACUUM
  59231. else{
  59232. /* If this database supports auto-vacuum and iPage is not the last
  59233. ** page in this overflow list, check that the pointer-map entry for
  59234. ** the following page matches iPage.
  59235. */
  59236. if( pCheck->pBt->autoVacuum && N>0 ){
  59237. i = get4byte(pOvflData);
  59238. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  59239. }
  59240. }
  59241. #endif
  59242. iPage = get4byte(pOvflData);
  59243. sqlite3PagerUnref(pOvflPage);
  59244. if( isFreeList && N<(iPage!=0) ){
  59245. checkAppendMsg(pCheck, "free-page count in header is too small");
  59246. }
  59247. }
  59248. }
  59249. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59250. /*
  59251. ** An implementation of a min-heap.
  59252. **
  59253. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  59254. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  59255. ** and aHeap[N*2+1].
  59256. **
  59257. ** The heap property is this: Every node is less than or equal to both
  59258. ** of its daughter nodes. A consequence of the heap property is that the
  59259. ** root node aHeap[1] is always the minimum value currently in the heap.
  59260. **
  59261. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  59262. ** the heap, preserving the heap property. The btreeHeapPull() routine
  59263. ** removes the root element from the heap (the minimum value in the heap)
  59264. ** and then moves other nodes around as necessary to preserve the heap
  59265. ** property.
  59266. **
  59267. ** This heap is used for cell overlap and coverage testing. Each u32
  59268. ** entry represents the span of a cell or freeblock on a btree page.
  59269. ** The upper 16 bits are the index of the first byte of a range and the
  59270. ** lower 16 bits are the index of the last byte of that range.
  59271. */
  59272. static void btreeHeapInsert(u32 *aHeap, u32 x){
  59273. u32 j, i = ++aHeap[0];
  59274. aHeap[i] = x;
  59275. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  59276. x = aHeap[j];
  59277. aHeap[j] = aHeap[i];
  59278. aHeap[i] = x;
  59279. i = j;
  59280. }
  59281. }
  59282. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  59283. u32 j, i, x;
  59284. if( (x = aHeap[0])==0 ) return 0;
  59285. *pOut = aHeap[1];
  59286. aHeap[1] = aHeap[x];
  59287. aHeap[x] = 0xffffffff;
  59288. aHeap[0]--;
  59289. i = 1;
  59290. while( (j = i*2)<=aHeap[0] ){
  59291. if( aHeap[j]>aHeap[j+1] ) j++;
  59292. if( aHeap[i]<aHeap[j] ) break;
  59293. x = aHeap[i];
  59294. aHeap[i] = aHeap[j];
  59295. aHeap[j] = x;
  59296. i = j;
  59297. }
  59298. return 1;
  59299. }
  59300. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59301. /*
  59302. ** Do various sanity checks on a single page of a tree. Return
  59303. ** the tree depth. Root pages return 0. Parents of root pages
  59304. ** return 1, and so forth.
  59305. **
  59306. ** These checks are done:
  59307. **
  59308. ** 1. Make sure that cells and freeblocks do not overlap
  59309. ** but combine to completely cover the page.
  59310. ** 2. Make sure integer cell keys are in order.
  59311. ** 3. Check the integrity of overflow pages.
  59312. ** 4. Recursively call checkTreePage on all children.
  59313. ** 5. Verify that the depth of all children is the same.
  59314. */
  59315. static int checkTreePage(
  59316. IntegrityCk *pCheck, /* Context for the sanity check */
  59317. int iPage, /* Page number of the page to check */
  59318. i64 *piMinKey, /* Write minimum integer primary key here */
  59319. i64 maxKey /* Error if integer primary key greater than this */
  59320. ){
  59321. MemPage *pPage = 0; /* The page being analyzed */
  59322. int i; /* Loop counter */
  59323. int rc; /* Result code from subroutine call */
  59324. int depth = -1, d2; /* Depth of a subtree */
  59325. int pgno; /* Page number */
  59326. int nFrag; /* Number of fragmented bytes on the page */
  59327. int hdr; /* Offset to the page header */
  59328. int cellStart; /* Offset to the start of the cell pointer array */
  59329. int nCell; /* Number of cells */
  59330. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  59331. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  59332. ** False if IPK must be strictly less than maxKey */
  59333. u8 *data; /* Page content */
  59334. u8 *pCell; /* Cell content */
  59335. u8 *pCellIdx; /* Next element of the cell pointer array */
  59336. BtShared *pBt; /* The BtShared object that owns pPage */
  59337. u32 pc; /* Address of a cell */
  59338. u32 usableSize; /* Usable size of the page */
  59339. u32 contentOffset; /* Offset to the start of the cell content area */
  59340. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  59341. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  59342. const char *saved_zPfx = pCheck->zPfx;
  59343. int saved_v1 = pCheck->v1;
  59344. int saved_v2 = pCheck->v2;
  59345. u8 savedIsInit = 0;
  59346. /* Check that the page exists
  59347. */
  59348. pBt = pCheck->pBt;
  59349. usableSize = pBt->usableSize;
  59350. if( iPage==0 ) return 0;
  59351. if( checkRef(pCheck, iPage) ) return 0;
  59352. pCheck->zPfx = "Page %d: ";
  59353. pCheck->v1 = iPage;
  59354. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  59355. checkAppendMsg(pCheck,
  59356. "unable to get the page. error code=%d", rc);
  59357. goto end_of_check;
  59358. }
  59359. /* Clear MemPage.isInit to make sure the corruption detection code in
  59360. ** btreeInitPage() is executed. */
  59361. savedIsInit = pPage->isInit;
  59362. pPage->isInit = 0;
  59363. if( (rc = btreeInitPage(pPage))!=0 ){
  59364. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  59365. checkAppendMsg(pCheck,
  59366. "btreeInitPage() returns error code %d", rc);
  59367. goto end_of_check;
  59368. }
  59369. data = pPage->aData;
  59370. hdr = pPage->hdrOffset;
  59371. /* Set up for cell analysis */
  59372. pCheck->zPfx = "On tree page %d cell %d: ";
  59373. contentOffset = get2byteNotZero(&data[hdr+5]);
  59374. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  59375. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  59376. ** number of cells on the page. */
  59377. nCell = get2byte(&data[hdr+3]);
  59378. assert( pPage->nCell==nCell );
  59379. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  59380. ** immediately follows the b-tree page header. */
  59381. cellStart = hdr + 12 - 4*pPage->leaf;
  59382. assert( pPage->aCellIdx==&data[cellStart] );
  59383. pCellIdx = &data[cellStart + 2*(nCell-1)];
  59384. if( !pPage->leaf ){
  59385. /* Analyze the right-child page of internal pages */
  59386. pgno = get4byte(&data[hdr+8]);
  59387. #ifndef SQLITE_OMIT_AUTOVACUUM
  59388. if( pBt->autoVacuum ){
  59389. pCheck->zPfx = "On page %d at right child: ";
  59390. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  59391. }
  59392. #endif
  59393. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  59394. keyCanBeEqual = 0;
  59395. }else{
  59396. /* For leaf pages, the coverage check will occur in the same loop
  59397. ** as the other cell checks, so initialize the heap. */
  59398. heap = pCheck->heap;
  59399. heap[0] = 0;
  59400. }
  59401. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  59402. ** integer offsets to the cell contents. */
  59403. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  59404. CellInfo info;
  59405. /* Check cell size */
  59406. pCheck->v2 = i;
  59407. assert( pCellIdx==&data[cellStart + i*2] );
  59408. pc = get2byteAligned(pCellIdx);
  59409. pCellIdx -= 2;
  59410. if( pc<contentOffset || pc>usableSize-4 ){
  59411. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  59412. pc, contentOffset, usableSize-4);
  59413. doCoverageCheck = 0;
  59414. continue;
  59415. }
  59416. pCell = &data[pc];
  59417. pPage->xParseCell(pPage, pCell, &info);
  59418. if( pc+info.nSize>usableSize ){
  59419. checkAppendMsg(pCheck, "Extends off end of page");
  59420. doCoverageCheck = 0;
  59421. continue;
  59422. }
  59423. /* Check for integer primary key out of range */
  59424. if( pPage->intKey ){
  59425. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  59426. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  59427. }
  59428. maxKey = info.nKey;
  59429. }
  59430. /* Check the content overflow list */
  59431. if( info.nPayload>info.nLocal ){
  59432. int nPage; /* Number of pages on the overflow chain */
  59433. Pgno pgnoOvfl; /* First page of the overflow chain */
  59434. assert( pc + info.iOverflow <= usableSize );
  59435. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  59436. pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  59437. #ifndef SQLITE_OMIT_AUTOVACUUM
  59438. if( pBt->autoVacuum ){
  59439. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  59440. }
  59441. #endif
  59442. checkList(pCheck, 0, pgnoOvfl, nPage);
  59443. }
  59444. if( !pPage->leaf ){
  59445. /* Check sanity of left child page for internal pages */
  59446. pgno = get4byte(pCell);
  59447. #ifndef SQLITE_OMIT_AUTOVACUUM
  59448. if( pBt->autoVacuum ){
  59449. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  59450. }
  59451. #endif
  59452. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  59453. keyCanBeEqual = 0;
  59454. if( d2!=depth ){
  59455. checkAppendMsg(pCheck, "Child page depth differs");
  59456. depth = d2;
  59457. }
  59458. }else{
  59459. /* Populate the coverage-checking heap for leaf pages */
  59460. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  59461. }
  59462. }
  59463. *piMinKey = maxKey;
  59464. /* Check for complete coverage of the page
  59465. */
  59466. pCheck->zPfx = 0;
  59467. if( doCoverageCheck && pCheck->mxErr>0 ){
  59468. /* For leaf pages, the min-heap has already been initialized and the
  59469. ** cells have already been inserted. But for internal pages, that has
  59470. ** not yet been done, so do it now */
  59471. if( !pPage->leaf ){
  59472. heap = pCheck->heap;
  59473. heap[0] = 0;
  59474. for(i=nCell-1; i>=0; i--){
  59475. u32 size;
  59476. pc = get2byteAligned(&data[cellStart+i*2]);
  59477. size = pPage->xCellSize(pPage, &data[pc]);
  59478. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  59479. }
  59480. }
  59481. /* Add the freeblocks to the min-heap
  59482. **
  59483. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  59484. ** is the offset of the first freeblock, or zero if there are no
  59485. ** freeblocks on the page.
  59486. */
  59487. i = get2byte(&data[hdr+1]);
  59488. while( i>0 ){
  59489. int size, j;
  59490. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  59491. size = get2byte(&data[i+2]);
  59492. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  59493. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  59494. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  59495. ** big-endian integer which is the offset in the b-tree page of the next
  59496. ** freeblock in the chain, or zero if the freeblock is the last on the
  59497. ** chain. */
  59498. j = get2byte(&data[i]);
  59499. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  59500. ** increasing offset. */
  59501. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  59502. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  59503. i = j;
  59504. }
  59505. /* Analyze the min-heap looking for overlap between cells and/or
  59506. ** freeblocks, and counting the number of untracked bytes in nFrag.
  59507. **
  59508. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  59509. ** There is an implied first entry the covers the page header, the cell
  59510. ** pointer index, and the gap between the cell pointer index and the start
  59511. ** of cell content.
  59512. **
  59513. ** The loop below pulls entries from the min-heap in order and compares
  59514. ** the start_address against the previous end_address. If there is an
  59515. ** overlap, that means bytes are used multiple times. If there is a gap,
  59516. ** that gap is added to the fragmentation count.
  59517. */
  59518. nFrag = 0;
  59519. prev = contentOffset - 1; /* Implied first min-heap entry */
  59520. while( btreeHeapPull(heap,&x) ){
  59521. if( (prev&0xffff)>=(x>>16) ){
  59522. checkAppendMsg(pCheck,
  59523. "Multiple uses for byte %u of page %d", x>>16, iPage);
  59524. break;
  59525. }else{
  59526. nFrag += (x>>16) - (prev&0xffff) - 1;
  59527. prev = x;
  59528. }
  59529. }
  59530. nFrag += usableSize - (prev&0xffff) - 1;
  59531. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  59532. ** is stored in the fifth field of the b-tree page header.
  59533. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  59534. ** number of fragmented free bytes within the cell content area.
  59535. */
  59536. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  59537. checkAppendMsg(pCheck,
  59538. "Fragmentation of %d bytes reported as %d on page %d",
  59539. nFrag, data[hdr+7], iPage);
  59540. }
  59541. }
  59542. end_of_check:
  59543. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  59544. releasePage(pPage);
  59545. pCheck->zPfx = saved_zPfx;
  59546. pCheck->v1 = saved_v1;
  59547. pCheck->v2 = saved_v2;
  59548. return depth+1;
  59549. }
  59550. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59551. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59552. /*
  59553. ** This routine does a complete check of the given BTree file. aRoot[] is
  59554. ** an array of pages numbers were each page number is the root page of
  59555. ** a table. nRoot is the number of entries in aRoot.
  59556. **
  59557. ** A read-only or read-write transaction must be opened before calling
  59558. ** this function.
  59559. **
  59560. ** Write the number of error seen in *pnErr. Except for some memory
  59561. ** allocation errors, an error message held in memory obtained from
  59562. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  59563. ** returned. If a memory allocation error occurs, NULL is returned.
  59564. */
  59565. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  59566. Btree *p, /* The btree to be checked */
  59567. int *aRoot, /* An array of root pages numbers for individual trees */
  59568. int nRoot, /* Number of entries in aRoot[] */
  59569. int mxErr, /* Stop reporting errors after this many */
  59570. int *pnErr /* Write number of errors seen to this variable */
  59571. ){
  59572. Pgno i;
  59573. IntegrityCk sCheck;
  59574. BtShared *pBt = p->pBt;
  59575. int savedDbFlags = pBt->db->flags;
  59576. char zErr[100];
  59577. VVA_ONLY( int nRef );
  59578. sqlite3BtreeEnter(p);
  59579. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  59580. assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 );
  59581. sCheck.pBt = pBt;
  59582. sCheck.pPager = pBt->pPager;
  59583. sCheck.nPage = btreePagecount(sCheck.pBt);
  59584. sCheck.mxErr = mxErr;
  59585. sCheck.nErr = 0;
  59586. sCheck.mallocFailed = 0;
  59587. sCheck.zPfx = 0;
  59588. sCheck.v1 = 0;
  59589. sCheck.v2 = 0;
  59590. sCheck.aPgRef = 0;
  59591. sCheck.heap = 0;
  59592. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  59593. if( sCheck.nPage==0 ){
  59594. goto integrity_ck_cleanup;
  59595. }
  59596. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  59597. if( !sCheck.aPgRef ){
  59598. sCheck.mallocFailed = 1;
  59599. goto integrity_ck_cleanup;
  59600. }
  59601. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  59602. if( sCheck.heap==0 ){
  59603. sCheck.mallocFailed = 1;
  59604. goto integrity_ck_cleanup;
  59605. }
  59606. i = PENDING_BYTE_PAGE(pBt);
  59607. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  59608. /* Check the integrity of the freelist
  59609. */
  59610. sCheck.zPfx = "Main freelist: ";
  59611. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  59612. get4byte(&pBt->pPage1->aData[36]));
  59613. sCheck.zPfx = 0;
  59614. /* Check all the tables.
  59615. */
  59616. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  59617. pBt->db->flags &= ~SQLITE_CellSizeCk;
  59618. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  59619. i64 notUsed;
  59620. if( aRoot[i]==0 ) continue;
  59621. #ifndef SQLITE_OMIT_AUTOVACUUM
  59622. if( pBt->autoVacuum && aRoot[i]>1 ){
  59623. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  59624. }
  59625. #endif
  59626. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  59627. }
  59628. pBt->db->flags = savedDbFlags;
  59629. /* Make sure every page in the file is referenced
  59630. */
  59631. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  59632. #ifdef SQLITE_OMIT_AUTOVACUUM
  59633. if( getPageReferenced(&sCheck, i)==0 ){
  59634. checkAppendMsg(&sCheck, "Page %d is never used", i);
  59635. }
  59636. #else
  59637. /* If the database supports auto-vacuum, make sure no tables contain
  59638. ** references to pointer-map pages.
  59639. */
  59640. if( getPageReferenced(&sCheck, i)==0 &&
  59641. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  59642. checkAppendMsg(&sCheck, "Page %d is never used", i);
  59643. }
  59644. if( getPageReferenced(&sCheck, i)!=0 &&
  59645. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  59646. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  59647. }
  59648. #endif
  59649. }
  59650. /* Clean up and report errors.
  59651. */
  59652. integrity_ck_cleanup:
  59653. sqlite3PageFree(sCheck.heap);
  59654. sqlite3_free(sCheck.aPgRef);
  59655. if( sCheck.mallocFailed ){
  59656. sqlite3StrAccumReset(&sCheck.errMsg);
  59657. sCheck.nErr++;
  59658. }
  59659. *pnErr = sCheck.nErr;
  59660. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  59661. /* Make sure this analysis did not leave any unref() pages. */
  59662. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  59663. sqlite3BtreeLeave(p);
  59664. return sqlite3StrAccumFinish(&sCheck.errMsg);
  59665. }
  59666. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59667. /*
  59668. ** Return the full pathname of the underlying database file. Return
  59669. ** an empty string if the database is in-memory or a TEMP database.
  59670. **
  59671. ** The pager filename is invariant as long as the pager is
  59672. ** open so it is safe to access without the BtShared mutex.
  59673. */
  59674. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  59675. assert( p->pBt->pPager!=0 );
  59676. return sqlite3PagerFilename(p->pBt->pPager, 1);
  59677. }
  59678. /*
  59679. ** Return the pathname of the journal file for this database. The return
  59680. ** value of this routine is the same regardless of whether the journal file
  59681. ** has been created or not.
  59682. **
  59683. ** The pager journal filename is invariant as long as the pager is
  59684. ** open so it is safe to access without the BtShared mutex.
  59685. */
  59686. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  59687. assert( p->pBt->pPager!=0 );
  59688. return sqlite3PagerJournalname(p->pBt->pPager);
  59689. }
  59690. /*
  59691. ** Return non-zero if a transaction is active.
  59692. */
  59693. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  59694. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  59695. return (p && (p->inTrans==TRANS_WRITE));
  59696. }
  59697. #ifndef SQLITE_OMIT_WAL
  59698. /*
  59699. ** Run a checkpoint on the Btree passed as the first argument.
  59700. **
  59701. ** Return SQLITE_LOCKED if this or any other connection has an open
  59702. ** transaction on the shared-cache the argument Btree is connected to.
  59703. **
  59704. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  59705. */
  59706. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  59707. int rc = SQLITE_OK;
  59708. if( p ){
  59709. BtShared *pBt = p->pBt;
  59710. sqlite3BtreeEnter(p);
  59711. if( pBt->inTransaction!=TRANS_NONE ){
  59712. rc = SQLITE_LOCKED;
  59713. }else{
  59714. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  59715. }
  59716. sqlite3BtreeLeave(p);
  59717. }
  59718. return rc;
  59719. }
  59720. #endif
  59721. /*
  59722. ** Return non-zero if a read (or write) transaction is active.
  59723. */
  59724. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  59725. assert( p );
  59726. assert( sqlite3_mutex_held(p->db->mutex) );
  59727. return p->inTrans!=TRANS_NONE;
  59728. }
  59729. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  59730. assert( p );
  59731. assert( sqlite3_mutex_held(p->db->mutex) );
  59732. return p->nBackup!=0;
  59733. }
  59734. /*
  59735. ** This function returns a pointer to a blob of memory associated with
  59736. ** a single shared-btree. The memory is used by client code for its own
  59737. ** purposes (for example, to store a high-level schema associated with
  59738. ** the shared-btree). The btree layer manages reference counting issues.
  59739. **
  59740. ** The first time this is called on a shared-btree, nBytes bytes of memory
  59741. ** are allocated, zeroed, and returned to the caller. For each subsequent
  59742. ** call the nBytes parameter is ignored and a pointer to the same blob
  59743. ** of memory returned.
  59744. **
  59745. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  59746. ** allocated, a null pointer is returned. If the blob has already been
  59747. ** allocated, it is returned as normal.
  59748. **
  59749. ** Just before the shared-btree is closed, the function passed as the
  59750. ** xFree argument when the memory allocation was made is invoked on the
  59751. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  59752. ** on the memory, the btree layer does that.
  59753. */
  59754. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  59755. BtShared *pBt = p->pBt;
  59756. sqlite3BtreeEnter(p);
  59757. if( !pBt->pSchema && nBytes ){
  59758. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  59759. pBt->xFreeSchema = xFree;
  59760. }
  59761. sqlite3BtreeLeave(p);
  59762. return pBt->pSchema;
  59763. }
  59764. /*
  59765. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  59766. ** btree as the argument handle holds an exclusive lock on the
  59767. ** sqlite_master table. Otherwise SQLITE_OK.
  59768. */
  59769. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  59770. int rc;
  59771. assert( sqlite3_mutex_held(p->db->mutex) );
  59772. sqlite3BtreeEnter(p);
  59773. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  59774. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  59775. sqlite3BtreeLeave(p);
  59776. return rc;
  59777. }
  59778. #ifndef SQLITE_OMIT_SHARED_CACHE
  59779. /*
  59780. ** Obtain a lock on the table whose root page is iTab. The
  59781. ** lock is a write lock if isWritelock is true or a read lock
  59782. ** if it is false.
  59783. */
  59784. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  59785. int rc = SQLITE_OK;
  59786. assert( p->inTrans!=TRANS_NONE );
  59787. if( p->sharable ){
  59788. u8 lockType = READ_LOCK + isWriteLock;
  59789. assert( READ_LOCK+1==WRITE_LOCK );
  59790. assert( isWriteLock==0 || isWriteLock==1 );
  59791. sqlite3BtreeEnter(p);
  59792. rc = querySharedCacheTableLock(p, iTab, lockType);
  59793. if( rc==SQLITE_OK ){
  59794. rc = setSharedCacheTableLock(p, iTab, lockType);
  59795. }
  59796. sqlite3BtreeLeave(p);
  59797. }
  59798. return rc;
  59799. }
  59800. #endif
  59801. #ifndef SQLITE_OMIT_INCRBLOB
  59802. /*
  59803. ** Argument pCsr must be a cursor opened for writing on an
  59804. ** INTKEY table currently pointing at a valid table entry.
  59805. ** This function modifies the data stored as part of that entry.
  59806. **
  59807. ** Only the data content may only be modified, it is not possible to
  59808. ** change the length of the data stored. If this function is called with
  59809. ** parameters that attempt to write past the end of the existing data,
  59810. ** no modifications are made and SQLITE_CORRUPT is returned.
  59811. */
  59812. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  59813. int rc;
  59814. assert( cursorHoldsMutex(pCsr) );
  59815. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  59816. assert( pCsr->curFlags & BTCF_Incrblob );
  59817. rc = restoreCursorPosition(pCsr);
  59818. if( rc!=SQLITE_OK ){
  59819. return rc;
  59820. }
  59821. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  59822. if( pCsr->eState!=CURSOR_VALID ){
  59823. return SQLITE_ABORT;
  59824. }
  59825. /* Save the positions of all other cursors open on this table. This is
  59826. ** required in case any of them are holding references to an xFetch
  59827. ** version of the b-tree page modified by the accessPayload call below.
  59828. **
  59829. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  59830. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  59831. ** saveAllCursors can only return SQLITE_OK.
  59832. */
  59833. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  59834. assert( rc==SQLITE_OK );
  59835. /* Check some assumptions:
  59836. ** (a) the cursor is open for writing,
  59837. ** (b) there is a read/write transaction open,
  59838. ** (c) the connection holds a write-lock on the table (if required),
  59839. ** (d) there are no conflicting read-locks, and
  59840. ** (e) the cursor points at a valid row of an intKey table.
  59841. */
  59842. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  59843. return SQLITE_READONLY;
  59844. }
  59845. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  59846. && pCsr->pBt->inTransaction==TRANS_WRITE );
  59847. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  59848. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  59849. assert( pCsr->apPage[pCsr->iPage]->intKey );
  59850. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  59851. }
  59852. /*
  59853. ** Mark this cursor as an incremental blob cursor.
  59854. */
  59855. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  59856. pCur->curFlags |= BTCF_Incrblob;
  59857. pCur->pBtree->hasIncrblobCur = 1;
  59858. }
  59859. #endif
  59860. /*
  59861. ** Set both the "read version" (single byte at byte offset 18) and
  59862. ** "write version" (single byte at byte offset 19) fields in the database
  59863. ** header to iVersion.
  59864. */
  59865. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  59866. BtShared *pBt = pBtree->pBt;
  59867. int rc; /* Return code */
  59868. assert( iVersion==1 || iVersion==2 );
  59869. /* If setting the version fields to 1, do not automatically open the
  59870. ** WAL connection, even if the version fields are currently set to 2.
  59871. */
  59872. pBt->btsFlags &= ~BTS_NO_WAL;
  59873. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  59874. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  59875. if( rc==SQLITE_OK ){
  59876. u8 *aData = pBt->pPage1->aData;
  59877. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  59878. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  59879. if( rc==SQLITE_OK ){
  59880. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  59881. if( rc==SQLITE_OK ){
  59882. aData[18] = (u8)iVersion;
  59883. aData[19] = (u8)iVersion;
  59884. }
  59885. }
  59886. }
  59887. }
  59888. pBt->btsFlags &= ~BTS_NO_WAL;
  59889. return rc;
  59890. }
  59891. /*
  59892. ** set the mask of hint flags for cursor pCsr.
  59893. */
  59894. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  59895. assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
  59896. pCsr->hints = mask;
  59897. }
  59898. #ifdef SQLITE_DEBUG
  59899. /*
  59900. ** Return true if the cursor has a hint specified. This routine is
  59901. ** only used from within assert() statements
  59902. */
  59903. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  59904. return (pCsr->hints & mask)!=0;
  59905. }
  59906. #endif
  59907. /*
  59908. ** Return true if the given Btree is read-only.
  59909. */
  59910. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  59911. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  59912. }
  59913. /*
  59914. ** Return the size of the header added to each page by this module.
  59915. */
  59916. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  59917. /************** End of btree.c ***********************************************/
  59918. /************** Begin file backup.c ******************************************/
  59919. /*
  59920. ** 2009 January 28
  59921. **
  59922. ** The author disclaims copyright to this source code. In place of
  59923. ** a legal notice, here is a blessing:
  59924. **
  59925. ** May you do good and not evil.
  59926. ** May you find forgiveness for yourself and forgive others.
  59927. ** May you share freely, never taking more than you give.
  59928. **
  59929. *************************************************************************
  59930. ** This file contains the implementation of the sqlite3_backup_XXX()
  59931. ** API functions and the related features.
  59932. */
  59933. /* #include "sqliteInt.h" */
  59934. /* #include "btreeInt.h" */
  59935. /*
  59936. ** Structure allocated for each backup operation.
  59937. */
  59938. struct sqlite3_backup {
  59939. sqlite3* pDestDb; /* Destination database handle */
  59940. Btree *pDest; /* Destination b-tree file */
  59941. u32 iDestSchema; /* Original schema cookie in destination */
  59942. int bDestLocked; /* True once a write-transaction is open on pDest */
  59943. Pgno iNext; /* Page number of the next source page to copy */
  59944. sqlite3* pSrcDb; /* Source database handle */
  59945. Btree *pSrc; /* Source b-tree file */
  59946. int rc; /* Backup process error code */
  59947. /* These two variables are set by every call to backup_step(). They are
  59948. ** read by calls to backup_remaining() and backup_pagecount().
  59949. */
  59950. Pgno nRemaining; /* Number of pages left to copy */
  59951. Pgno nPagecount; /* Total number of pages to copy */
  59952. int isAttached; /* True once backup has been registered with pager */
  59953. sqlite3_backup *pNext; /* Next backup associated with source pager */
  59954. };
  59955. /*
  59956. ** THREAD SAFETY NOTES:
  59957. **
  59958. ** Once it has been created using backup_init(), a single sqlite3_backup
  59959. ** structure may be accessed via two groups of thread-safe entry points:
  59960. **
  59961. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  59962. ** backup_finish(). Both these functions obtain the source database
  59963. ** handle mutex and the mutex associated with the source BtShared
  59964. ** structure, in that order.
  59965. **
  59966. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  59967. ** invoked by the pager layer to report various state changes in
  59968. ** the page cache associated with the source database. The mutex
  59969. ** associated with the source database BtShared structure will always
  59970. ** be held when either of these functions are invoked.
  59971. **
  59972. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  59973. ** backup_pagecount() are not thread-safe functions. If they are called
  59974. ** while some other thread is calling backup_step() or backup_finish(),
  59975. ** the values returned may be invalid. There is no way for a call to
  59976. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  59977. ** or backup_pagecount().
  59978. **
  59979. ** Depending on the SQLite configuration, the database handles and/or
  59980. ** the Btree objects may have their own mutexes that require locking.
  59981. ** Non-sharable Btrees (in-memory databases for example), do not have
  59982. ** associated mutexes.
  59983. */
  59984. /*
  59985. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  59986. ** in connection handle pDb. If such a database cannot be found, return
  59987. ** a NULL pointer and write an error message to pErrorDb.
  59988. **
  59989. ** If the "temp" database is requested, it may need to be opened by this
  59990. ** function. If an error occurs while doing so, return 0 and write an
  59991. ** error message to pErrorDb.
  59992. */
  59993. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  59994. int i = sqlite3FindDbName(pDb, zDb);
  59995. if( i==1 ){
  59996. Parse *pParse;
  59997. int rc = 0;
  59998. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  59999. if( pParse==0 ){
  60000. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  60001. rc = SQLITE_NOMEM;
  60002. }else{
  60003. pParse->db = pDb;
  60004. if( sqlite3OpenTempDatabase(pParse) ){
  60005. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  60006. rc = SQLITE_ERROR;
  60007. }
  60008. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  60009. sqlite3ParserReset(pParse);
  60010. sqlite3StackFree(pErrorDb, pParse);
  60011. }
  60012. if( rc ){
  60013. return 0;
  60014. }
  60015. }
  60016. if( i<0 ){
  60017. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  60018. return 0;
  60019. }
  60020. return pDb->aDb[i].pBt;
  60021. }
  60022. /*
  60023. ** Attempt to set the page size of the destination to match the page size
  60024. ** of the source.
  60025. */
  60026. static int setDestPgsz(sqlite3_backup *p){
  60027. int rc;
  60028. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  60029. return rc;
  60030. }
  60031. /*
  60032. ** Check that there is no open read-transaction on the b-tree passed as the
  60033. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  60034. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  60035. ** message in database handle db.
  60036. */
  60037. static int checkReadTransaction(sqlite3 *db, Btree *p){
  60038. if( sqlite3BtreeIsInReadTrans(p) ){
  60039. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  60040. return SQLITE_ERROR;
  60041. }
  60042. return SQLITE_OK;
  60043. }
  60044. /*
  60045. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  60046. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  60047. ** a pointer to the new sqlite3_backup object.
  60048. **
  60049. ** If an error occurs, NULL is returned and an error code and error message
  60050. ** stored in database handle pDestDb.
  60051. */
  60052. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  60053. sqlite3* pDestDb, /* Database to write to */
  60054. const char *zDestDb, /* Name of database within pDestDb */
  60055. sqlite3* pSrcDb, /* Database connection to read from */
  60056. const char *zSrcDb /* Name of database within pSrcDb */
  60057. ){
  60058. sqlite3_backup *p; /* Value to return */
  60059. #ifdef SQLITE_ENABLE_API_ARMOR
  60060. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  60061. (void)SQLITE_MISUSE_BKPT;
  60062. return 0;
  60063. }
  60064. #endif
  60065. /* Lock the source database handle. The destination database
  60066. ** handle is not locked in this routine, but it is locked in
  60067. ** sqlite3_backup_step(). The user is required to ensure that no
  60068. ** other thread accesses the destination handle for the duration
  60069. ** of the backup operation. Any attempt to use the destination
  60070. ** database connection while a backup is in progress may cause
  60071. ** a malfunction or a deadlock.
  60072. */
  60073. sqlite3_mutex_enter(pSrcDb->mutex);
  60074. sqlite3_mutex_enter(pDestDb->mutex);
  60075. if( pSrcDb==pDestDb ){
  60076. sqlite3ErrorWithMsg(
  60077. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  60078. );
  60079. p = 0;
  60080. }else {
  60081. /* Allocate space for a new sqlite3_backup object...
  60082. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  60083. ** call to sqlite3_backup_init() and is destroyed by a call to
  60084. ** sqlite3_backup_finish(). */
  60085. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  60086. if( !p ){
  60087. sqlite3Error(pDestDb, SQLITE_NOMEM);
  60088. }
  60089. }
  60090. /* If the allocation succeeded, populate the new object. */
  60091. if( p ){
  60092. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  60093. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  60094. p->pDestDb = pDestDb;
  60095. p->pSrcDb = pSrcDb;
  60096. p->iNext = 1;
  60097. p->isAttached = 0;
  60098. if( 0==p->pSrc || 0==p->pDest
  60099. || setDestPgsz(p)==SQLITE_NOMEM
  60100. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  60101. ){
  60102. /* One (or both) of the named databases did not exist or an OOM
  60103. ** error was hit. Or there is a transaction open on the destination
  60104. ** database. The error has already been written into the pDestDb
  60105. ** handle. All that is left to do here is free the sqlite3_backup
  60106. ** structure. */
  60107. sqlite3_free(p);
  60108. p = 0;
  60109. }
  60110. }
  60111. if( p ){
  60112. p->pSrc->nBackup++;
  60113. }
  60114. sqlite3_mutex_leave(pDestDb->mutex);
  60115. sqlite3_mutex_leave(pSrcDb->mutex);
  60116. return p;
  60117. }
  60118. /*
  60119. ** Argument rc is an SQLite error code. Return true if this error is
  60120. ** considered fatal if encountered during a backup operation. All errors
  60121. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  60122. */
  60123. static int isFatalError(int rc){
  60124. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  60125. }
  60126. /*
  60127. ** Parameter zSrcData points to a buffer containing the data for
  60128. ** page iSrcPg from the source database. Copy this data into the
  60129. ** destination database.
  60130. */
  60131. static int backupOnePage(
  60132. sqlite3_backup *p, /* Backup handle */
  60133. Pgno iSrcPg, /* Source database page to backup */
  60134. const u8 *zSrcData, /* Source database page data */
  60135. int bUpdate /* True for an update, false otherwise */
  60136. ){
  60137. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  60138. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  60139. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  60140. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  60141. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  60142. #ifdef SQLITE_HAS_CODEC
  60143. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  60144. ** guaranteed that the shared-mutex is held by this thread, handle
  60145. ** p->pSrc may not actually be the owner. */
  60146. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  60147. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  60148. #endif
  60149. int rc = SQLITE_OK;
  60150. i64 iOff;
  60151. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  60152. assert( p->bDestLocked );
  60153. assert( !isFatalError(p->rc) );
  60154. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  60155. assert( zSrcData );
  60156. /* Catch the case where the destination is an in-memory database and the
  60157. ** page sizes of the source and destination differ.
  60158. */
  60159. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  60160. rc = SQLITE_READONLY;
  60161. }
  60162. #ifdef SQLITE_HAS_CODEC
  60163. /* Backup is not possible if the page size of the destination is changing
  60164. ** and a codec is in use.
  60165. */
  60166. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  60167. rc = SQLITE_READONLY;
  60168. }
  60169. /* Backup is not possible if the number of bytes of reserve space differ
  60170. ** between source and destination. If there is a difference, try to
  60171. ** fix the destination to agree with the source. If that is not possible,
  60172. ** then the backup cannot proceed.
  60173. */
  60174. if( nSrcReserve!=nDestReserve ){
  60175. u32 newPgsz = nSrcPgsz;
  60176. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  60177. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  60178. }
  60179. #endif
  60180. /* This loop runs once for each destination page spanned by the source
  60181. ** page. For each iteration, variable iOff is set to the byte offset
  60182. ** of the destination page.
  60183. */
  60184. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  60185. DbPage *pDestPg = 0;
  60186. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  60187. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  60188. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  60189. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  60190. ){
  60191. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  60192. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  60193. u8 *zOut = &zDestData[iOff%nDestPgsz];
  60194. /* Copy the data from the source page into the destination page.
  60195. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  60196. ** and the pager code use this trick (clearing the first byte
  60197. ** of the page 'extra' space to invalidate the Btree layers
  60198. ** cached parse of the page). MemPage.isInit is marked
  60199. ** "MUST BE FIRST" for this purpose.
  60200. */
  60201. memcpy(zOut, zIn, nCopy);
  60202. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  60203. if( iOff==0 && bUpdate==0 ){
  60204. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  60205. }
  60206. }
  60207. sqlite3PagerUnref(pDestPg);
  60208. }
  60209. return rc;
  60210. }
  60211. /*
  60212. ** If pFile is currently larger than iSize bytes, then truncate it to
  60213. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  60214. ** this function is a no-op.
  60215. **
  60216. ** Return SQLITE_OK if everything is successful, or an SQLite error
  60217. ** code if an error occurs.
  60218. */
  60219. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  60220. i64 iCurrent;
  60221. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  60222. if( rc==SQLITE_OK && iCurrent>iSize ){
  60223. rc = sqlite3OsTruncate(pFile, iSize);
  60224. }
  60225. return rc;
  60226. }
  60227. /*
  60228. ** Register this backup object with the associated source pager for
  60229. ** callbacks when pages are changed or the cache invalidated.
  60230. */
  60231. static void attachBackupObject(sqlite3_backup *p){
  60232. sqlite3_backup **pp;
  60233. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  60234. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  60235. p->pNext = *pp;
  60236. *pp = p;
  60237. p->isAttached = 1;
  60238. }
  60239. /*
  60240. ** Copy nPage pages from the source b-tree to the destination.
  60241. */
  60242. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
  60243. int rc;
  60244. int destMode; /* Destination journal mode */
  60245. int pgszSrc = 0; /* Source page size */
  60246. int pgszDest = 0; /* Destination page size */
  60247. #ifdef SQLITE_ENABLE_API_ARMOR
  60248. if( p==0 ) return SQLITE_MISUSE_BKPT;
  60249. #endif
  60250. sqlite3_mutex_enter(p->pSrcDb->mutex);
  60251. sqlite3BtreeEnter(p->pSrc);
  60252. if( p->pDestDb ){
  60253. sqlite3_mutex_enter(p->pDestDb->mutex);
  60254. }
  60255. rc = p->rc;
  60256. if( !isFatalError(rc) ){
  60257. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  60258. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  60259. int ii; /* Iterator variable */
  60260. int nSrcPage = -1; /* Size of source db in pages */
  60261. int bCloseTrans = 0; /* True if src db requires unlocking */
  60262. /* If the source pager is currently in a write-transaction, return
  60263. ** SQLITE_BUSY immediately.
  60264. */
  60265. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  60266. rc = SQLITE_BUSY;
  60267. }else{
  60268. rc = SQLITE_OK;
  60269. }
  60270. /* Lock the destination database, if it is not locked already. */
  60271. if( SQLITE_OK==rc && p->bDestLocked==0
  60272. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  60273. ){
  60274. p->bDestLocked = 1;
  60275. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  60276. }
  60277. /* If there is no open read-transaction on the source database, open
  60278. ** one now. If a transaction is opened here, then it will be closed
  60279. ** before this function exits.
  60280. */
  60281. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  60282. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  60283. bCloseTrans = 1;
  60284. }
  60285. /* Do not allow backup if the destination database is in WAL mode
  60286. ** and the page sizes are different between source and destination */
  60287. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  60288. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  60289. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  60290. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  60291. rc = SQLITE_READONLY;
  60292. }
  60293. /* Now that there is a read-lock on the source database, query the
  60294. ** source pager for the number of pages in the database.
  60295. */
  60296. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  60297. assert( nSrcPage>=0 );
  60298. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  60299. const Pgno iSrcPg = p->iNext; /* Source page number */
  60300. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  60301. DbPage *pSrcPg; /* Source page object */
  60302. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  60303. PAGER_GET_READONLY);
  60304. if( rc==SQLITE_OK ){
  60305. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  60306. sqlite3PagerUnref(pSrcPg);
  60307. }
  60308. }
  60309. p->iNext++;
  60310. }
  60311. if( rc==SQLITE_OK ){
  60312. p->nPagecount = nSrcPage;
  60313. p->nRemaining = nSrcPage+1-p->iNext;
  60314. if( p->iNext>(Pgno)nSrcPage ){
  60315. rc = SQLITE_DONE;
  60316. }else if( !p->isAttached ){
  60317. attachBackupObject(p);
  60318. }
  60319. }
  60320. /* Update the schema version field in the destination database. This
  60321. ** is to make sure that the schema-version really does change in
  60322. ** the case where the source and destination databases have the
  60323. ** same schema version.
  60324. */
  60325. if( rc==SQLITE_DONE ){
  60326. if( nSrcPage==0 ){
  60327. rc = sqlite3BtreeNewDb(p->pDest);
  60328. nSrcPage = 1;
  60329. }
  60330. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  60331. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  60332. }
  60333. if( rc==SQLITE_OK ){
  60334. if( p->pDestDb ){
  60335. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  60336. }
  60337. if( destMode==PAGER_JOURNALMODE_WAL ){
  60338. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  60339. }
  60340. }
  60341. if( rc==SQLITE_OK ){
  60342. int nDestTruncate;
  60343. /* Set nDestTruncate to the final number of pages in the destination
  60344. ** database. The complication here is that the destination page
  60345. ** size may be different to the source page size.
  60346. **
  60347. ** If the source page size is smaller than the destination page size,
  60348. ** round up. In this case the call to sqlite3OsTruncate() below will
  60349. ** fix the size of the file. However it is important to call
  60350. ** sqlite3PagerTruncateImage() here so that any pages in the
  60351. ** destination file that lie beyond the nDestTruncate page mark are
  60352. ** journalled by PagerCommitPhaseOne() before they are destroyed
  60353. ** by the file truncation.
  60354. */
  60355. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  60356. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  60357. if( pgszSrc<pgszDest ){
  60358. int ratio = pgszDest/pgszSrc;
  60359. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  60360. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  60361. nDestTruncate--;
  60362. }
  60363. }else{
  60364. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  60365. }
  60366. assert( nDestTruncate>0 );
  60367. if( pgszSrc<pgszDest ){
  60368. /* If the source page-size is smaller than the destination page-size,
  60369. ** two extra things may need to happen:
  60370. **
  60371. ** * The destination may need to be truncated, and
  60372. **
  60373. ** * Data stored on the pages immediately following the
  60374. ** pending-byte page in the source database may need to be
  60375. ** copied into the destination database.
  60376. */
  60377. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  60378. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  60379. Pgno iPg;
  60380. int nDstPage;
  60381. i64 iOff;
  60382. i64 iEnd;
  60383. assert( pFile );
  60384. assert( nDestTruncate==0
  60385. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  60386. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  60387. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  60388. ));
  60389. /* This block ensures that all data required to recreate the original
  60390. ** database has been stored in the journal for pDestPager and the
  60391. ** journal synced to disk. So at this point we may safely modify
  60392. ** the database file in any way, knowing that if a power failure
  60393. ** occurs, the original database will be reconstructed from the
  60394. ** journal file. */
  60395. sqlite3PagerPagecount(pDestPager, &nDstPage);
  60396. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  60397. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  60398. DbPage *pPg;
  60399. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  60400. if( rc==SQLITE_OK ){
  60401. rc = sqlite3PagerWrite(pPg);
  60402. sqlite3PagerUnref(pPg);
  60403. }
  60404. }
  60405. }
  60406. if( rc==SQLITE_OK ){
  60407. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  60408. }
  60409. /* Write the extra pages and truncate the database file as required */
  60410. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  60411. for(
  60412. iOff=PENDING_BYTE+pgszSrc;
  60413. rc==SQLITE_OK && iOff<iEnd;
  60414. iOff+=pgszSrc
  60415. ){
  60416. PgHdr *pSrcPg = 0;
  60417. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  60418. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  60419. if( rc==SQLITE_OK ){
  60420. u8 *zData = sqlite3PagerGetData(pSrcPg);
  60421. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  60422. }
  60423. sqlite3PagerUnref(pSrcPg);
  60424. }
  60425. if( rc==SQLITE_OK ){
  60426. rc = backupTruncateFile(pFile, iSize);
  60427. }
  60428. /* Sync the database file to disk. */
  60429. if( rc==SQLITE_OK ){
  60430. rc = sqlite3PagerSync(pDestPager, 0);
  60431. }
  60432. }else{
  60433. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  60434. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  60435. }
  60436. /* Finish committing the transaction to the destination database. */
  60437. if( SQLITE_OK==rc
  60438. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  60439. ){
  60440. rc = SQLITE_DONE;
  60441. }
  60442. }
  60443. }
  60444. /* If bCloseTrans is true, then this function opened a read transaction
  60445. ** on the source database. Close the read transaction here. There is
  60446. ** no need to check the return values of the btree methods here, as
  60447. ** "committing" a read-only transaction cannot fail.
  60448. */
  60449. if( bCloseTrans ){
  60450. TESTONLY( int rc2 );
  60451. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  60452. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  60453. assert( rc2==SQLITE_OK );
  60454. }
  60455. if( rc==SQLITE_IOERR_NOMEM ){
  60456. rc = SQLITE_NOMEM;
  60457. }
  60458. p->rc = rc;
  60459. }
  60460. if( p->pDestDb ){
  60461. sqlite3_mutex_leave(p->pDestDb->mutex);
  60462. }
  60463. sqlite3BtreeLeave(p->pSrc);
  60464. sqlite3_mutex_leave(p->pSrcDb->mutex);
  60465. return rc;
  60466. }
  60467. /*
  60468. ** Release all resources associated with an sqlite3_backup* handle.
  60469. */
  60470. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
  60471. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  60472. sqlite3 *pSrcDb; /* Source database connection */
  60473. int rc; /* Value to return */
  60474. /* Enter the mutexes */
  60475. if( p==0 ) return SQLITE_OK;
  60476. pSrcDb = p->pSrcDb;
  60477. sqlite3_mutex_enter(pSrcDb->mutex);
  60478. sqlite3BtreeEnter(p->pSrc);
  60479. if( p->pDestDb ){
  60480. sqlite3_mutex_enter(p->pDestDb->mutex);
  60481. }
  60482. /* Detach this backup from the source pager. */
  60483. if( p->pDestDb ){
  60484. p->pSrc->nBackup--;
  60485. }
  60486. if( p->isAttached ){
  60487. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  60488. while( *pp!=p ){
  60489. pp = &(*pp)->pNext;
  60490. }
  60491. *pp = p->pNext;
  60492. }
  60493. /* If a transaction is still open on the Btree, roll it back. */
  60494. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  60495. /* Set the error code of the destination database handle. */
  60496. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  60497. if( p->pDestDb ){
  60498. sqlite3Error(p->pDestDb, rc);
  60499. /* Exit the mutexes and free the backup context structure. */
  60500. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  60501. }
  60502. sqlite3BtreeLeave(p->pSrc);
  60503. if( p->pDestDb ){
  60504. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  60505. ** call to sqlite3_backup_init() and is destroyed by a call to
  60506. ** sqlite3_backup_finish(). */
  60507. sqlite3_free(p);
  60508. }
  60509. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  60510. return rc;
  60511. }
  60512. /*
  60513. ** Return the number of pages still to be backed up as of the most recent
  60514. ** call to sqlite3_backup_step().
  60515. */
  60516. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
  60517. #ifdef SQLITE_ENABLE_API_ARMOR
  60518. if( p==0 ){
  60519. (void)SQLITE_MISUSE_BKPT;
  60520. return 0;
  60521. }
  60522. #endif
  60523. return p->nRemaining;
  60524. }
  60525. /*
  60526. ** Return the total number of pages in the source database as of the most
  60527. ** recent call to sqlite3_backup_step().
  60528. */
  60529. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
  60530. #ifdef SQLITE_ENABLE_API_ARMOR
  60531. if( p==0 ){
  60532. (void)SQLITE_MISUSE_BKPT;
  60533. return 0;
  60534. }
  60535. #endif
  60536. return p->nPagecount;
  60537. }
  60538. /*
  60539. ** This function is called after the contents of page iPage of the
  60540. ** source database have been modified. If page iPage has already been
  60541. ** copied into the destination database, then the data written to the
  60542. ** destination is now invalidated. The destination copy of iPage needs
  60543. ** to be updated with the new data before the backup operation is
  60544. ** complete.
  60545. **
  60546. ** It is assumed that the mutex associated with the BtShared object
  60547. ** corresponding to the source database is held when this function is
  60548. ** called.
  60549. */
  60550. static SQLITE_NOINLINE void backupUpdate(
  60551. sqlite3_backup *p,
  60552. Pgno iPage,
  60553. const u8 *aData
  60554. ){
  60555. assert( p!=0 );
  60556. do{
  60557. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  60558. if( !isFatalError(p->rc) && iPage<p->iNext ){
  60559. /* The backup process p has already copied page iPage. But now it
  60560. ** has been modified by a transaction on the source pager. Copy
  60561. ** the new data into the backup.
  60562. */
  60563. int rc;
  60564. assert( p->pDestDb );
  60565. sqlite3_mutex_enter(p->pDestDb->mutex);
  60566. rc = backupOnePage(p, iPage, aData, 1);
  60567. sqlite3_mutex_leave(p->pDestDb->mutex);
  60568. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  60569. if( rc!=SQLITE_OK ){
  60570. p->rc = rc;
  60571. }
  60572. }
  60573. }while( (p = p->pNext)!=0 );
  60574. }
  60575. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  60576. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  60577. }
  60578. /*
  60579. ** Restart the backup process. This is called when the pager layer
  60580. ** detects that the database has been modified by an external database
  60581. ** connection. In this case there is no way of knowing which of the
  60582. ** pages that have been copied into the destination database are still
  60583. ** valid and which are not, so the entire process needs to be restarted.
  60584. **
  60585. ** It is assumed that the mutex associated with the BtShared object
  60586. ** corresponding to the source database is held when this function is
  60587. ** called.
  60588. */
  60589. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  60590. sqlite3_backup *p; /* Iterator variable */
  60591. for(p=pBackup; p; p=p->pNext){
  60592. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  60593. p->iNext = 1;
  60594. }
  60595. }
  60596. #ifndef SQLITE_OMIT_VACUUM
  60597. /*
  60598. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  60599. ** must be active for both files.
  60600. **
  60601. ** The size of file pTo may be reduced by this operation. If anything
  60602. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  60603. ** transaction is committed before returning.
  60604. */
  60605. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  60606. int rc;
  60607. sqlite3_file *pFd; /* File descriptor for database pTo */
  60608. sqlite3_backup b;
  60609. sqlite3BtreeEnter(pTo);
  60610. sqlite3BtreeEnter(pFrom);
  60611. assert( sqlite3BtreeIsInTrans(pTo) );
  60612. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  60613. if( pFd->pMethods ){
  60614. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  60615. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  60616. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  60617. if( rc ) goto copy_finished;
  60618. }
  60619. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  60620. ** to 0. This is used by the implementations of sqlite3_backup_step()
  60621. ** and sqlite3_backup_finish() to detect that they are being called
  60622. ** from this function, not directly by the user.
  60623. */
  60624. memset(&b, 0, sizeof(b));
  60625. b.pSrcDb = pFrom->db;
  60626. b.pSrc = pFrom;
  60627. b.pDest = pTo;
  60628. b.iNext = 1;
  60629. #ifdef SQLITE_HAS_CODEC
  60630. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  60631. #endif
  60632. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  60633. ** file. By passing this as the number of pages to copy to
  60634. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  60635. ** within a single call (unless an error occurs). The assert() statement
  60636. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  60637. ** or an error code.
  60638. */
  60639. sqlite3_backup_step(&b, 0x7FFFFFFF);
  60640. assert( b.rc!=SQLITE_OK );
  60641. rc = sqlite3_backup_finish(&b);
  60642. if( rc==SQLITE_OK ){
  60643. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  60644. }else{
  60645. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  60646. }
  60647. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  60648. copy_finished:
  60649. sqlite3BtreeLeave(pFrom);
  60650. sqlite3BtreeLeave(pTo);
  60651. return rc;
  60652. }
  60653. #endif /* SQLITE_OMIT_VACUUM */
  60654. /************** End of backup.c **********************************************/
  60655. /************** Begin file vdbemem.c *****************************************/
  60656. /*
  60657. ** 2004 May 26
  60658. **
  60659. ** The author disclaims copyright to this source code. In place of
  60660. ** a legal notice, here is a blessing:
  60661. **
  60662. ** May you do good and not evil.
  60663. ** May you find forgiveness for yourself and forgive others.
  60664. ** May you share freely, never taking more than you give.
  60665. **
  60666. *************************************************************************
  60667. **
  60668. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  60669. ** stores a single value in the VDBE. Mem is an opaque structure visible
  60670. ** only within the VDBE. Interface routines refer to a Mem using the
  60671. ** name sqlite_value
  60672. */
  60673. /* #include "sqliteInt.h" */
  60674. /* #include "vdbeInt.h" */
  60675. #ifdef SQLITE_DEBUG
  60676. /*
  60677. ** Check invariants on a Mem object.
  60678. **
  60679. ** This routine is intended for use inside of assert() statements, like
  60680. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  60681. */
  60682. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  60683. /* If MEM_Dyn is set then Mem.xDel!=0.
  60684. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  60685. */
  60686. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  60687. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  60688. ** ensure that if Mem.szMalloc>0 then it is safe to do
  60689. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  60690. ** That saves a few cycles in inner loops. */
  60691. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  60692. /* Cannot be both MEM_Int and MEM_Real at the same time */
  60693. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  60694. /* The szMalloc field holds the correct memory allocation size */
  60695. assert( p->szMalloc==0
  60696. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  60697. /* If p holds a string or blob, the Mem.z must point to exactly
  60698. ** one of the following:
  60699. **
  60700. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  60701. ** (2) Memory to be freed using Mem.xDel
  60702. ** (3) An ephemeral string or blob
  60703. ** (4) A static string or blob
  60704. */
  60705. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  60706. assert(
  60707. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  60708. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  60709. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  60710. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  60711. );
  60712. }
  60713. return 1;
  60714. }
  60715. #endif
  60716. /*
  60717. ** If pMem is an object with a valid string representation, this routine
  60718. ** ensures the internal encoding for the string representation is
  60719. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  60720. **
  60721. ** If pMem is not a string object, or the encoding of the string
  60722. ** representation is already stored using the requested encoding, then this
  60723. ** routine is a no-op.
  60724. **
  60725. ** SQLITE_OK is returned if the conversion is successful (or not required).
  60726. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  60727. ** between formats.
  60728. */
  60729. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  60730. #ifndef SQLITE_OMIT_UTF16
  60731. int rc;
  60732. #endif
  60733. assert( (pMem->flags&MEM_RowSet)==0 );
  60734. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  60735. || desiredEnc==SQLITE_UTF16BE );
  60736. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  60737. return SQLITE_OK;
  60738. }
  60739. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60740. #ifdef SQLITE_OMIT_UTF16
  60741. return SQLITE_ERROR;
  60742. #else
  60743. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  60744. ** then the encoding of the value may not have changed.
  60745. */
  60746. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  60747. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  60748. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  60749. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  60750. return rc;
  60751. #endif
  60752. }
  60753. /*
  60754. ** Make sure pMem->z points to a writable allocation of at least
  60755. ** min(n,32) bytes.
  60756. **
  60757. ** If the bPreserve argument is true, then copy of the content of
  60758. ** pMem->z into the new allocation. pMem must be either a string or
  60759. ** blob if bPreserve is true. If bPreserve is false, any prior content
  60760. ** in pMem->z is discarded.
  60761. */
  60762. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  60763. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  60764. assert( (pMem->flags&MEM_RowSet)==0 );
  60765. /* If the bPreserve flag is set to true, then the memory cell must already
  60766. ** contain a valid string or blob value. */
  60767. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  60768. testcase( bPreserve && pMem->z==0 );
  60769. assert( pMem->szMalloc==0
  60770. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  60771. if( pMem->szMalloc<n ){
  60772. if( n<32 ) n = 32;
  60773. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  60774. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  60775. bPreserve = 0;
  60776. }else{
  60777. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  60778. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  60779. }
  60780. if( pMem->zMalloc==0 ){
  60781. sqlite3VdbeMemSetNull(pMem);
  60782. pMem->z = 0;
  60783. pMem->szMalloc = 0;
  60784. return SQLITE_NOMEM;
  60785. }else{
  60786. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  60787. }
  60788. }
  60789. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  60790. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  60791. }
  60792. if( (pMem->flags&MEM_Dyn)!=0 ){
  60793. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  60794. pMem->xDel((void *)(pMem->z));
  60795. }
  60796. pMem->z = pMem->zMalloc;
  60797. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  60798. return SQLITE_OK;
  60799. }
  60800. /*
  60801. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  60802. ** If pMem->zMalloc already meets or exceeds the requested size, this
  60803. ** routine is a no-op.
  60804. **
  60805. ** Any prior string or blob content in the pMem object may be discarded.
  60806. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  60807. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  60808. ** values are preserved.
  60809. **
  60810. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  60811. ** if unable to complete the resizing.
  60812. */
  60813. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  60814. assert( szNew>0 );
  60815. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  60816. if( pMem->szMalloc<szNew ){
  60817. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  60818. }
  60819. assert( (pMem->flags & MEM_Dyn)==0 );
  60820. pMem->z = pMem->zMalloc;
  60821. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  60822. return SQLITE_OK;
  60823. }
  60824. /*
  60825. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  60826. ** MEM.zMalloc, where it can be safely written.
  60827. **
  60828. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  60829. */
  60830. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  60831. int f;
  60832. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60833. assert( (pMem->flags&MEM_RowSet)==0 );
  60834. ExpandBlob(pMem);
  60835. f = pMem->flags;
  60836. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  60837. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  60838. return SQLITE_NOMEM;
  60839. }
  60840. pMem->z[pMem->n] = 0;
  60841. pMem->z[pMem->n+1] = 0;
  60842. pMem->flags |= MEM_Term;
  60843. }
  60844. pMem->flags &= ~MEM_Ephem;
  60845. #ifdef SQLITE_DEBUG
  60846. pMem->pScopyFrom = 0;
  60847. #endif
  60848. return SQLITE_OK;
  60849. }
  60850. /*
  60851. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  60852. ** blob stored in dynamically allocated space.
  60853. */
  60854. #ifndef SQLITE_OMIT_INCRBLOB
  60855. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  60856. if( pMem->flags & MEM_Zero ){
  60857. int nByte;
  60858. assert( pMem->flags&MEM_Blob );
  60859. assert( (pMem->flags&MEM_RowSet)==0 );
  60860. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60861. /* Set nByte to the number of bytes required to store the expanded blob. */
  60862. nByte = pMem->n + pMem->u.nZero;
  60863. if( nByte<=0 ){
  60864. nByte = 1;
  60865. }
  60866. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  60867. return SQLITE_NOMEM;
  60868. }
  60869. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  60870. pMem->n += pMem->u.nZero;
  60871. pMem->flags &= ~(MEM_Zero|MEM_Term);
  60872. }
  60873. return SQLITE_OK;
  60874. }
  60875. #endif
  60876. /*
  60877. ** It is already known that pMem contains an unterminated string.
  60878. ** Add the zero terminator.
  60879. */
  60880. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  60881. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  60882. return SQLITE_NOMEM;
  60883. }
  60884. pMem->z[pMem->n] = 0;
  60885. pMem->z[pMem->n+1] = 0;
  60886. pMem->flags |= MEM_Term;
  60887. return SQLITE_OK;
  60888. }
  60889. /*
  60890. ** Make sure the given Mem is \u0000 terminated.
  60891. */
  60892. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  60893. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60894. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  60895. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  60896. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  60897. return SQLITE_OK; /* Nothing to do */
  60898. }else{
  60899. return vdbeMemAddTerminator(pMem);
  60900. }
  60901. }
  60902. /*
  60903. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  60904. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  60905. ** is a no-op.
  60906. **
  60907. ** Existing representations MEM_Int and MEM_Real are invalidated if
  60908. ** bForce is true but are retained if bForce is false.
  60909. **
  60910. ** A MEM_Null value will never be passed to this function. This function is
  60911. ** used for converting values to text for returning to the user (i.e. via
  60912. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  60913. ** keys are strings. In the former case a NULL pointer is returned the
  60914. ** user and the latter is an internal programming error.
  60915. */
  60916. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  60917. int fg = pMem->flags;
  60918. const int nByte = 32;
  60919. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60920. assert( !(fg&MEM_Zero) );
  60921. assert( !(fg&(MEM_Str|MEM_Blob)) );
  60922. assert( fg&(MEM_Int|MEM_Real) );
  60923. assert( (pMem->flags&MEM_RowSet)==0 );
  60924. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60925. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  60926. return SQLITE_NOMEM;
  60927. }
  60928. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  60929. ** string representation of the value. Then, if the required encoding
  60930. ** is UTF-16le or UTF-16be do a translation.
  60931. **
  60932. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  60933. */
  60934. if( fg & MEM_Int ){
  60935. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  60936. }else{
  60937. assert( fg & MEM_Real );
  60938. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  60939. }
  60940. pMem->n = sqlite3Strlen30(pMem->z);
  60941. pMem->enc = SQLITE_UTF8;
  60942. pMem->flags |= MEM_Str|MEM_Term;
  60943. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  60944. sqlite3VdbeChangeEncoding(pMem, enc);
  60945. return SQLITE_OK;
  60946. }
  60947. /*
  60948. ** Memory cell pMem contains the context of an aggregate function.
  60949. ** This routine calls the finalize method for that function. The
  60950. ** result of the aggregate is stored back into pMem.
  60951. **
  60952. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  60953. ** otherwise.
  60954. */
  60955. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  60956. int rc = SQLITE_OK;
  60957. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  60958. sqlite3_context ctx;
  60959. Mem t;
  60960. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  60961. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60962. memset(&ctx, 0, sizeof(ctx));
  60963. memset(&t, 0, sizeof(t));
  60964. t.flags = MEM_Null;
  60965. t.db = pMem->db;
  60966. ctx.pOut = &t;
  60967. ctx.pMem = pMem;
  60968. ctx.pFunc = pFunc;
  60969. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  60970. assert( (pMem->flags & MEM_Dyn)==0 );
  60971. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  60972. memcpy(pMem, &t, sizeof(t));
  60973. rc = ctx.isError;
  60974. }
  60975. return rc;
  60976. }
  60977. /*
  60978. ** If the memory cell contains a value that must be freed by
  60979. ** invoking the external callback in Mem.xDel, then this routine
  60980. ** will free that value. It also sets Mem.flags to MEM_Null.
  60981. **
  60982. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  60983. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  60984. ** entry point for releasing Mem resources.
  60985. */
  60986. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  60987. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  60988. assert( VdbeMemDynamic(p) );
  60989. if( p->flags&MEM_Agg ){
  60990. sqlite3VdbeMemFinalize(p, p->u.pDef);
  60991. assert( (p->flags & MEM_Agg)==0 );
  60992. testcase( p->flags & MEM_Dyn );
  60993. }
  60994. if( p->flags&MEM_Dyn ){
  60995. assert( (p->flags&MEM_RowSet)==0 );
  60996. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  60997. p->xDel((void *)p->z);
  60998. }else if( p->flags&MEM_RowSet ){
  60999. sqlite3RowSetClear(p->u.pRowSet);
  61000. }else if( p->flags&MEM_Frame ){
  61001. VdbeFrame *pFrame = p->u.pFrame;
  61002. pFrame->pParent = pFrame->v->pDelFrame;
  61003. pFrame->v->pDelFrame = pFrame;
  61004. }
  61005. p->flags = MEM_Null;
  61006. }
  61007. /*
  61008. ** Release memory held by the Mem p, both external memory cleared
  61009. ** by p->xDel and memory in p->zMalloc.
  61010. **
  61011. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  61012. ** the unusual case where there really is memory in p that needs
  61013. ** to be freed.
  61014. */
  61015. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  61016. if( VdbeMemDynamic(p) ){
  61017. vdbeMemClearExternAndSetNull(p);
  61018. }
  61019. if( p->szMalloc ){
  61020. sqlite3DbFree(p->db, p->zMalloc);
  61021. p->szMalloc = 0;
  61022. }
  61023. p->z = 0;
  61024. }
  61025. /*
  61026. ** Release any memory resources held by the Mem. Both the memory that is
  61027. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  61028. **
  61029. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  61030. ** reset a Mem back to its minimum memory utilization.
  61031. **
  61032. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  61033. ** prior to inserting new content into the Mem.
  61034. */
  61035. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  61036. assert( sqlite3VdbeCheckMemInvariants(p) );
  61037. if( VdbeMemDynamic(p) || p->szMalloc ){
  61038. vdbeMemClear(p);
  61039. }
  61040. }
  61041. /*
  61042. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  61043. ** If the double is out of range of a 64-bit signed integer then
  61044. ** return the closest available 64-bit signed integer.
  61045. */
  61046. static i64 doubleToInt64(double r){
  61047. #ifdef SQLITE_OMIT_FLOATING_POINT
  61048. /* When floating-point is omitted, double and int64 are the same thing */
  61049. return r;
  61050. #else
  61051. /*
  61052. ** Many compilers we encounter do not define constants for the
  61053. ** minimum and maximum 64-bit integers, or they define them
  61054. ** inconsistently. And many do not understand the "LL" notation.
  61055. ** So we define our own static constants here using nothing
  61056. ** larger than a 32-bit integer constant.
  61057. */
  61058. static const i64 maxInt = LARGEST_INT64;
  61059. static const i64 minInt = SMALLEST_INT64;
  61060. if( r<=(double)minInt ){
  61061. return minInt;
  61062. }else if( r>=(double)maxInt ){
  61063. return maxInt;
  61064. }else{
  61065. return (i64)r;
  61066. }
  61067. #endif
  61068. }
  61069. /*
  61070. ** Return some kind of integer value which is the best we can do
  61071. ** at representing the value that *pMem describes as an integer.
  61072. ** If pMem is an integer, then the value is exact. If pMem is
  61073. ** a floating-point then the value returned is the integer part.
  61074. ** If pMem is a string or blob, then we make an attempt to convert
  61075. ** it into an integer and return that. If pMem represents an
  61076. ** an SQL-NULL value, return 0.
  61077. **
  61078. ** If pMem represents a string value, its encoding might be changed.
  61079. */
  61080. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  61081. int flags;
  61082. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61083. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61084. flags = pMem->flags;
  61085. if( flags & MEM_Int ){
  61086. return pMem->u.i;
  61087. }else if( flags & MEM_Real ){
  61088. return doubleToInt64(pMem->u.r);
  61089. }else if( flags & (MEM_Str|MEM_Blob) ){
  61090. i64 value = 0;
  61091. assert( pMem->z || pMem->n==0 );
  61092. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  61093. return value;
  61094. }else{
  61095. return 0;
  61096. }
  61097. }
  61098. /*
  61099. ** Return the best representation of pMem that we can get into a
  61100. ** double. If pMem is already a double or an integer, return its
  61101. ** value. If it is a string or blob, try to convert it to a double.
  61102. ** If it is a NULL, return 0.0.
  61103. */
  61104. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  61105. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61106. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61107. if( pMem->flags & MEM_Real ){
  61108. return pMem->u.r;
  61109. }else if( pMem->flags & MEM_Int ){
  61110. return (double)pMem->u.i;
  61111. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  61112. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  61113. double val = (double)0;
  61114. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  61115. return val;
  61116. }else{
  61117. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  61118. return (double)0;
  61119. }
  61120. }
  61121. /*
  61122. ** The MEM structure is already a MEM_Real. Try to also make it a
  61123. ** MEM_Int if we can.
  61124. */
  61125. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  61126. i64 ix;
  61127. assert( pMem->flags & MEM_Real );
  61128. assert( (pMem->flags & MEM_RowSet)==0 );
  61129. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61130. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61131. ix = doubleToInt64(pMem->u.r);
  61132. /* Only mark the value as an integer if
  61133. **
  61134. ** (1) the round-trip conversion real->int->real is a no-op, and
  61135. ** (2) The integer is neither the largest nor the smallest
  61136. ** possible integer (ticket #3922)
  61137. **
  61138. ** The second and third terms in the following conditional enforces
  61139. ** the second condition under the assumption that addition overflow causes
  61140. ** values to wrap around.
  61141. */
  61142. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  61143. pMem->u.i = ix;
  61144. MemSetTypeFlag(pMem, MEM_Int);
  61145. }
  61146. }
  61147. /*
  61148. ** Convert pMem to type integer. Invalidate any prior representations.
  61149. */
  61150. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  61151. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61152. assert( (pMem->flags & MEM_RowSet)==0 );
  61153. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61154. pMem->u.i = sqlite3VdbeIntValue(pMem);
  61155. MemSetTypeFlag(pMem, MEM_Int);
  61156. return SQLITE_OK;
  61157. }
  61158. /*
  61159. ** Convert pMem so that it is of type MEM_Real.
  61160. ** Invalidate any prior representations.
  61161. */
  61162. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  61163. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61164. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61165. pMem->u.r = sqlite3VdbeRealValue(pMem);
  61166. MemSetTypeFlag(pMem, MEM_Real);
  61167. return SQLITE_OK;
  61168. }
  61169. /*
  61170. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  61171. ** Invalidate any prior representations.
  61172. **
  61173. ** Every effort is made to force the conversion, even if the input
  61174. ** is a string that does not look completely like a number. Convert
  61175. ** as much of the string as we can and ignore the rest.
  61176. */
  61177. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  61178. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  61179. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  61180. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61181. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  61182. MemSetTypeFlag(pMem, MEM_Int);
  61183. }else{
  61184. pMem->u.r = sqlite3VdbeRealValue(pMem);
  61185. MemSetTypeFlag(pMem, MEM_Real);
  61186. sqlite3VdbeIntegerAffinity(pMem);
  61187. }
  61188. }
  61189. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  61190. pMem->flags &= ~(MEM_Str|MEM_Blob);
  61191. return SQLITE_OK;
  61192. }
  61193. /*
  61194. ** Cast the datatype of the value in pMem according to the affinity
  61195. ** "aff". Casting is different from applying affinity in that a cast
  61196. ** is forced. In other words, the value is converted into the desired
  61197. ** affinity even if that results in loss of data. This routine is
  61198. ** used (for example) to implement the SQL "cast()" operator.
  61199. */
  61200. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  61201. if( pMem->flags & MEM_Null ) return;
  61202. switch( aff ){
  61203. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  61204. if( (pMem->flags & MEM_Blob)==0 ){
  61205. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  61206. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  61207. MemSetTypeFlag(pMem, MEM_Blob);
  61208. }else{
  61209. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  61210. }
  61211. break;
  61212. }
  61213. case SQLITE_AFF_NUMERIC: {
  61214. sqlite3VdbeMemNumerify(pMem);
  61215. break;
  61216. }
  61217. case SQLITE_AFF_INTEGER: {
  61218. sqlite3VdbeMemIntegerify(pMem);
  61219. break;
  61220. }
  61221. case SQLITE_AFF_REAL: {
  61222. sqlite3VdbeMemRealify(pMem);
  61223. break;
  61224. }
  61225. default: {
  61226. assert( aff==SQLITE_AFF_TEXT );
  61227. assert( MEM_Str==(MEM_Blob>>3) );
  61228. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  61229. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  61230. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  61231. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  61232. break;
  61233. }
  61234. }
  61235. }
  61236. /*
  61237. ** Initialize bulk memory to be a consistent Mem object.
  61238. **
  61239. ** The minimum amount of initialization feasible is performed.
  61240. */
  61241. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  61242. assert( (flags & ~MEM_TypeMask)==0 );
  61243. pMem->flags = flags;
  61244. pMem->db = db;
  61245. pMem->szMalloc = 0;
  61246. }
  61247. /*
  61248. ** Delete any previous value and set the value stored in *pMem to NULL.
  61249. **
  61250. ** This routine calls the Mem.xDel destructor to dispose of values that
  61251. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  61252. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  61253. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  61254. **
  61255. ** Use this routine to reset the Mem prior to insert a new value.
  61256. **
  61257. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  61258. */
  61259. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  61260. if( VdbeMemDynamic(pMem) ){
  61261. vdbeMemClearExternAndSetNull(pMem);
  61262. }else{
  61263. pMem->flags = MEM_Null;
  61264. }
  61265. }
  61266. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  61267. sqlite3VdbeMemSetNull((Mem*)p);
  61268. }
  61269. /*
  61270. ** Delete any previous value and set the value to be a BLOB of length
  61271. ** n containing all zeros.
  61272. */
  61273. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  61274. sqlite3VdbeMemRelease(pMem);
  61275. pMem->flags = MEM_Blob|MEM_Zero;
  61276. pMem->n = 0;
  61277. if( n<0 ) n = 0;
  61278. pMem->u.nZero = n;
  61279. pMem->enc = SQLITE_UTF8;
  61280. pMem->z = 0;
  61281. }
  61282. /*
  61283. ** The pMem is known to contain content that needs to be destroyed prior
  61284. ** to a value change. So invoke the destructor, then set the value to
  61285. ** a 64-bit integer.
  61286. */
  61287. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  61288. sqlite3VdbeMemSetNull(pMem);
  61289. pMem->u.i = val;
  61290. pMem->flags = MEM_Int;
  61291. }
  61292. /*
  61293. ** Delete any previous value and set the value stored in *pMem to val,
  61294. ** manifest type INTEGER.
  61295. */
  61296. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  61297. if( VdbeMemDynamic(pMem) ){
  61298. vdbeReleaseAndSetInt64(pMem, val);
  61299. }else{
  61300. pMem->u.i = val;
  61301. pMem->flags = MEM_Int;
  61302. }
  61303. }
  61304. #ifndef SQLITE_OMIT_FLOATING_POINT
  61305. /*
  61306. ** Delete any previous value and set the value stored in *pMem to val,
  61307. ** manifest type REAL.
  61308. */
  61309. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  61310. sqlite3VdbeMemSetNull(pMem);
  61311. if( !sqlite3IsNaN(val) ){
  61312. pMem->u.r = val;
  61313. pMem->flags = MEM_Real;
  61314. }
  61315. }
  61316. #endif
  61317. /*
  61318. ** Delete any previous value and set the value of pMem to be an
  61319. ** empty boolean index.
  61320. */
  61321. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  61322. sqlite3 *db = pMem->db;
  61323. assert( db!=0 );
  61324. assert( (pMem->flags & MEM_RowSet)==0 );
  61325. sqlite3VdbeMemRelease(pMem);
  61326. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  61327. if( db->mallocFailed ){
  61328. pMem->flags = MEM_Null;
  61329. pMem->szMalloc = 0;
  61330. }else{
  61331. assert( pMem->zMalloc );
  61332. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  61333. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  61334. assert( pMem->u.pRowSet!=0 );
  61335. pMem->flags = MEM_RowSet;
  61336. }
  61337. }
  61338. /*
  61339. ** Return true if the Mem object contains a TEXT or BLOB that is
  61340. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  61341. */
  61342. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  61343. assert( p->db!=0 );
  61344. if( p->flags & (MEM_Str|MEM_Blob) ){
  61345. int n = p->n;
  61346. if( p->flags & MEM_Zero ){
  61347. n += p->u.nZero;
  61348. }
  61349. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  61350. }
  61351. return 0;
  61352. }
  61353. #ifdef SQLITE_DEBUG
  61354. /*
  61355. ** This routine prepares a memory cell for modification by breaking
  61356. ** its link to a shallow copy and by marking any current shallow
  61357. ** copies of this cell as invalid.
  61358. **
  61359. ** This is used for testing and debugging only - to make sure shallow
  61360. ** copies are not misused.
  61361. */
  61362. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  61363. int i;
  61364. Mem *pX;
  61365. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  61366. if( pX->pScopyFrom==pMem ){
  61367. pX->flags |= MEM_Undefined;
  61368. pX->pScopyFrom = 0;
  61369. }
  61370. }
  61371. pMem->pScopyFrom = 0;
  61372. }
  61373. #endif /* SQLITE_DEBUG */
  61374. /*
  61375. ** Make an shallow copy of pFrom into pTo. Prior contents of
  61376. ** pTo are freed. The pFrom->z field is not duplicated. If
  61377. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  61378. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  61379. */
  61380. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  61381. vdbeMemClearExternAndSetNull(pTo);
  61382. assert( !VdbeMemDynamic(pTo) );
  61383. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  61384. }
  61385. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  61386. assert( (pFrom->flags & MEM_RowSet)==0 );
  61387. assert( pTo->db==pFrom->db );
  61388. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  61389. memcpy(pTo, pFrom, MEMCELLSIZE);
  61390. if( (pFrom->flags&MEM_Static)==0 ){
  61391. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  61392. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  61393. pTo->flags |= srcType;
  61394. }
  61395. }
  61396. /*
  61397. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  61398. ** freed before the copy is made.
  61399. */
  61400. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  61401. int rc = SQLITE_OK;
  61402. /* The pFrom==0 case in the following assert() is when an sqlite3_value
  61403. ** from sqlite3_value_dup() is used as the argument
  61404. ** to sqlite3_result_value(). */
  61405. assert( pTo->db==pFrom->db || pFrom->db==0 );
  61406. assert( (pFrom->flags & MEM_RowSet)==0 );
  61407. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  61408. memcpy(pTo, pFrom, MEMCELLSIZE);
  61409. pTo->flags &= ~MEM_Dyn;
  61410. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  61411. if( 0==(pFrom->flags&MEM_Static) ){
  61412. pTo->flags |= MEM_Ephem;
  61413. rc = sqlite3VdbeMemMakeWriteable(pTo);
  61414. }
  61415. }
  61416. return rc;
  61417. }
  61418. /*
  61419. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  61420. ** freed. If pFrom contains ephemeral data, a copy is made.
  61421. **
  61422. ** pFrom contains an SQL NULL when this routine returns.
  61423. */
  61424. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  61425. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  61426. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  61427. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  61428. sqlite3VdbeMemRelease(pTo);
  61429. memcpy(pTo, pFrom, sizeof(Mem));
  61430. pFrom->flags = MEM_Null;
  61431. pFrom->szMalloc = 0;
  61432. }
  61433. /*
  61434. ** Change the value of a Mem to be a string or a BLOB.
  61435. **
  61436. ** The memory management strategy depends on the value of the xDel
  61437. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  61438. ** string is copied into a (possibly existing) buffer managed by the
  61439. ** Mem structure. Otherwise, any existing buffer is freed and the
  61440. ** pointer copied.
  61441. **
  61442. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  61443. ** size limit) then no memory allocation occurs. If the string can be
  61444. ** stored without allocating memory, then it is. If a memory allocation
  61445. ** is required to store the string, then value of pMem is unchanged. In
  61446. ** either case, SQLITE_TOOBIG is returned.
  61447. */
  61448. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  61449. Mem *pMem, /* Memory cell to set to string value */
  61450. const char *z, /* String pointer */
  61451. int n, /* Bytes in string, or negative */
  61452. u8 enc, /* Encoding of z. 0 for BLOBs */
  61453. void (*xDel)(void*) /* Destructor function */
  61454. ){
  61455. int nByte = n; /* New value for pMem->n */
  61456. int iLimit; /* Maximum allowed string or blob size */
  61457. u16 flags = 0; /* New value for pMem->flags */
  61458. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61459. assert( (pMem->flags & MEM_RowSet)==0 );
  61460. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  61461. if( !z ){
  61462. sqlite3VdbeMemSetNull(pMem);
  61463. return SQLITE_OK;
  61464. }
  61465. if( pMem->db ){
  61466. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  61467. }else{
  61468. iLimit = SQLITE_MAX_LENGTH;
  61469. }
  61470. flags = (enc==0?MEM_Blob:MEM_Str);
  61471. if( nByte<0 ){
  61472. assert( enc!=0 );
  61473. if( enc==SQLITE_UTF8 ){
  61474. nByte = sqlite3Strlen30(z);
  61475. if( nByte>iLimit ) nByte = iLimit+1;
  61476. }else{
  61477. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  61478. }
  61479. flags |= MEM_Term;
  61480. }
  61481. /* The following block sets the new values of Mem.z and Mem.xDel. It
  61482. ** also sets a flag in local variable "flags" to indicate the memory
  61483. ** management (one of MEM_Dyn or MEM_Static).
  61484. */
  61485. if( xDel==SQLITE_TRANSIENT ){
  61486. int nAlloc = nByte;
  61487. if( flags&MEM_Term ){
  61488. nAlloc += (enc==SQLITE_UTF8?1:2);
  61489. }
  61490. if( nByte>iLimit ){
  61491. return SQLITE_TOOBIG;
  61492. }
  61493. testcase( nAlloc==0 );
  61494. testcase( nAlloc==31 );
  61495. testcase( nAlloc==32 );
  61496. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  61497. return SQLITE_NOMEM;
  61498. }
  61499. memcpy(pMem->z, z, nAlloc);
  61500. }else if( xDel==SQLITE_DYNAMIC ){
  61501. sqlite3VdbeMemRelease(pMem);
  61502. pMem->zMalloc = pMem->z = (char *)z;
  61503. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  61504. }else{
  61505. sqlite3VdbeMemRelease(pMem);
  61506. pMem->z = (char *)z;
  61507. pMem->xDel = xDel;
  61508. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  61509. }
  61510. pMem->n = nByte;
  61511. pMem->flags = flags;
  61512. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  61513. #ifndef SQLITE_OMIT_UTF16
  61514. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  61515. return SQLITE_NOMEM;
  61516. }
  61517. #endif
  61518. if( nByte>iLimit ){
  61519. return SQLITE_TOOBIG;
  61520. }
  61521. return SQLITE_OK;
  61522. }
  61523. /*
  61524. ** Move data out of a btree key or data field and into a Mem structure.
  61525. ** The data or key is taken from the entry that pCur is currently pointing
  61526. ** to. offset and amt determine what portion of the data or key to retrieve.
  61527. ** key is true to get the key or false to get data. The result is written
  61528. ** into the pMem element.
  61529. **
  61530. ** The pMem object must have been initialized. This routine will use
  61531. ** pMem->zMalloc to hold the content from the btree, if possible. New
  61532. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  61533. ** is responsible for making sure that the pMem object is eventually
  61534. ** destroyed.
  61535. **
  61536. ** If this routine fails for any reason (malloc returns NULL or unable
  61537. ** to read from the disk) then the pMem is left in an inconsistent state.
  61538. */
  61539. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  61540. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  61541. u32 offset, /* Offset from the start of data to return bytes from. */
  61542. u32 amt, /* Number of bytes to return. */
  61543. int key, /* If true, retrieve from the btree key, not data. */
  61544. Mem *pMem /* OUT: Return data in this Mem structure. */
  61545. ){
  61546. int rc;
  61547. pMem->flags = MEM_Null;
  61548. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  61549. if( key ){
  61550. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  61551. }else{
  61552. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  61553. }
  61554. if( rc==SQLITE_OK ){
  61555. pMem->z[amt] = 0;
  61556. pMem->z[amt+1] = 0;
  61557. pMem->flags = MEM_Blob|MEM_Term;
  61558. pMem->n = (int)amt;
  61559. }else{
  61560. sqlite3VdbeMemRelease(pMem);
  61561. }
  61562. }
  61563. return rc;
  61564. }
  61565. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  61566. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  61567. u32 offset, /* Offset from the start of data to return bytes from. */
  61568. u32 amt, /* Number of bytes to return. */
  61569. int key, /* If true, retrieve from the btree key, not data. */
  61570. Mem *pMem /* OUT: Return data in this Mem structure. */
  61571. ){
  61572. char *zData; /* Data from the btree layer */
  61573. u32 available = 0; /* Number of bytes available on the local btree page */
  61574. int rc = SQLITE_OK; /* Return code */
  61575. assert( sqlite3BtreeCursorIsValid(pCur) );
  61576. assert( !VdbeMemDynamic(pMem) );
  61577. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  61578. ** that both the BtShared and database handle mutexes are held. */
  61579. assert( (pMem->flags & MEM_RowSet)==0 );
  61580. if( key ){
  61581. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  61582. }else{
  61583. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  61584. }
  61585. assert( zData!=0 );
  61586. if( offset+amt<=available ){
  61587. pMem->z = &zData[offset];
  61588. pMem->flags = MEM_Blob|MEM_Ephem;
  61589. pMem->n = (int)amt;
  61590. }else{
  61591. rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
  61592. }
  61593. return rc;
  61594. }
  61595. /*
  61596. ** The pVal argument is known to be a value other than NULL.
  61597. ** Convert it into a string with encoding enc and return a pointer
  61598. ** to a zero-terminated version of that string.
  61599. */
  61600. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  61601. assert( pVal!=0 );
  61602. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  61603. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  61604. assert( (pVal->flags & MEM_RowSet)==0 );
  61605. assert( (pVal->flags & (MEM_Null))==0 );
  61606. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  61607. pVal->flags |= MEM_Str;
  61608. if( pVal->flags & MEM_Zero ){
  61609. sqlite3VdbeMemExpandBlob(pVal);
  61610. }
  61611. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  61612. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  61613. }
  61614. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  61615. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  61616. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  61617. return 0;
  61618. }
  61619. }
  61620. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  61621. }else{
  61622. sqlite3VdbeMemStringify(pVal, enc, 0);
  61623. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  61624. }
  61625. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  61626. || pVal->db->mallocFailed );
  61627. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  61628. return pVal->z;
  61629. }else{
  61630. return 0;
  61631. }
  61632. }
  61633. /* This function is only available internally, it is not part of the
  61634. ** external API. It works in a similar way to sqlite3_value_text(),
  61635. ** except the data returned is in the encoding specified by the second
  61636. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  61637. ** SQLITE_UTF8.
  61638. **
  61639. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  61640. ** If that is the case, then the result must be aligned on an even byte
  61641. ** boundary.
  61642. */
  61643. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  61644. if( !pVal ) return 0;
  61645. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  61646. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  61647. assert( (pVal->flags & MEM_RowSet)==0 );
  61648. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  61649. return pVal->z;
  61650. }
  61651. if( pVal->flags&MEM_Null ){
  61652. return 0;
  61653. }
  61654. return valueToText(pVal, enc);
  61655. }
  61656. /*
  61657. ** Create a new sqlite3_value object.
  61658. */
  61659. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  61660. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  61661. if( p ){
  61662. p->flags = MEM_Null;
  61663. p->db = db;
  61664. }
  61665. return p;
  61666. }
  61667. /*
  61668. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  61669. ** valueNew(). See comments above valueNew() for details.
  61670. */
  61671. struct ValueNewStat4Ctx {
  61672. Parse *pParse;
  61673. Index *pIdx;
  61674. UnpackedRecord **ppRec;
  61675. int iVal;
  61676. };
  61677. /*
  61678. ** Allocate and return a pointer to a new sqlite3_value object. If
  61679. ** the second argument to this function is NULL, the object is allocated
  61680. ** by calling sqlite3ValueNew().
  61681. **
  61682. ** Otherwise, if the second argument is non-zero, then this function is
  61683. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  61684. ** already been allocated, allocate the UnpackedRecord structure that
  61685. ** that function will return to its caller here. Then return a pointer to
  61686. ** an sqlite3_value within the UnpackedRecord.a[] array.
  61687. */
  61688. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  61689. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61690. if( p ){
  61691. UnpackedRecord *pRec = p->ppRec[0];
  61692. if( pRec==0 ){
  61693. Index *pIdx = p->pIdx; /* Index being probed */
  61694. int nByte; /* Bytes of space to allocate */
  61695. int i; /* Counter variable */
  61696. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  61697. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  61698. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  61699. if( pRec ){
  61700. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  61701. if( pRec->pKeyInfo ){
  61702. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  61703. assert( pRec->pKeyInfo->enc==ENC(db) );
  61704. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  61705. for(i=0; i<nCol; i++){
  61706. pRec->aMem[i].flags = MEM_Null;
  61707. pRec->aMem[i].db = db;
  61708. }
  61709. }else{
  61710. sqlite3DbFree(db, pRec);
  61711. pRec = 0;
  61712. }
  61713. }
  61714. if( pRec==0 ) return 0;
  61715. p->ppRec[0] = pRec;
  61716. }
  61717. pRec->nField = p->iVal+1;
  61718. return &pRec->aMem[p->iVal];
  61719. }
  61720. #else
  61721. UNUSED_PARAMETER(p);
  61722. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  61723. return sqlite3ValueNew(db);
  61724. }
  61725. /*
  61726. ** The expression object indicated by the second argument is guaranteed
  61727. ** to be a scalar SQL function. If
  61728. **
  61729. ** * all function arguments are SQL literals,
  61730. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  61731. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  61732. **
  61733. ** then this routine attempts to invoke the SQL function. Assuming no
  61734. ** error occurs, output parameter (*ppVal) is set to point to a value
  61735. ** object containing the result before returning SQLITE_OK.
  61736. **
  61737. ** Affinity aff is applied to the result of the function before returning.
  61738. ** If the result is a text value, the sqlite3_value object uses encoding
  61739. ** enc.
  61740. **
  61741. ** If the conditions above are not met, this function returns SQLITE_OK
  61742. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  61743. ** NULL and an SQLite error code returned.
  61744. */
  61745. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61746. static int valueFromFunction(
  61747. sqlite3 *db, /* The database connection */
  61748. Expr *p, /* The expression to evaluate */
  61749. u8 enc, /* Encoding to use */
  61750. u8 aff, /* Affinity to use */
  61751. sqlite3_value **ppVal, /* Write the new value here */
  61752. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  61753. ){
  61754. sqlite3_context ctx; /* Context object for function invocation */
  61755. sqlite3_value **apVal = 0; /* Function arguments */
  61756. int nVal = 0; /* Size of apVal[] array */
  61757. FuncDef *pFunc = 0; /* Function definition */
  61758. sqlite3_value *pVal = 0; /* New value */
  61759. int rc = SQLITE_OK; /* Return code */
  61760. int nName; /* Size of function name in bytes */
  61761. ExprList *pList = 0; /* Function arguments */
  61762. int i; /* Iterator variable */
  61763. assert( pCtx!=0 );
  61764. assert( (p->flags & EP_TokenOnly)==0 );
  61765. pList = p->x.pList;
  61766. if( pList ) nVal = pList->nExpr;
  61767. nName = sqlite3Strlen30(p->u.zToken);
  61768. pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
  61769. assert( pFunc );
  61770. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  61771. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  61772. ){
  61773. return SQLITE_OK;
  61774. }
  61775. if( pList ){
  61776. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  61777. if( apVal==0 ){
  61778. rc = SQLITE_NOMEM;
  61779. goto value_from_function_out;
  61780. }
  61781. for(i=0; i<nVal; i++){
  61782. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  61783. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  61784. }
  61785. }
  61786. pVal = valueNew(db, pCtx);
  61787. if( pVal==0 ){
  61788. rc = SQLITE_NOMEM;
  61789. goto value_from_function_out;
  61790. }
  61791. assert( pCtx->pParse->rc==SQLITE_OK );
  61792. memset(&ctx, 0, sizeof(ctx));
  61793. ctx.pOut = pVal;
  61794. ctx.pFunc = pFunc;
  61795. pFunc->xFunc(&ctx, nVal, apVal);
  61796. if( ctx.isError ){
  61797. rc = ctx.isError;
  61798. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  61799. }else{
  61800. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  61801. assert( rc==SQLITE_OK );
  61802. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  61803. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  61804. rc = SQLITE_TOOBIG;
  61805. pCtx->pParse->nErr++;
  61806. }
  61807. }
  61808. pCtx->pParse->rc = rc;
  61809. value_from_function_out:
  61810. if( rc!=SQLITE_OK ){
  61811. pVal = 0;
  61812. }
  61813. if( apVal ){
  61814. for(i=0; i<nVal; i++){
  61815. sqlite3ValueFree(apVal[i]);
  61816. }
  61817. sqlite3DbFree(db, apVal);
  61818. }
  61819. *ppVal = pVal;
  61820. return rc;
  61821. }
  61822. #else
  61823. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  61824. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  61825. /*
  61826. ** Extract a value from the supplied expression in the manner described
  61827. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  61828. ** using valueNew().
  61829. **
  61830. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  61831. ** has been allocated, it is freed before returning. Or, if pCtx is not
  61832. ** NULL, it is assumed that the caller will free any allocated object
  61833. ** in all cases.
  61834. */
  61835. static int valueFromExpr(
  61836. sqlite3 *db, /* The database connection */
  61837. Expr *pExpr, /* The expression to evaluate */
  61838. u8 enc, /* Encoding to use */
  61839. u8 affinity, /* Affinity to use */
  61840. sqlite3_value **ppVal, /* Write the new value here */
  61841. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  61842. ){
  61843. int op;
  61844. char *zVal = 0;
  61845. sqlite3_value *pVal = 0;
  61846. int negInt = 1;
  61847. const char *zNeg = "";
  61848. int rc = SQLITE_OK;
  61849. if( !pExpr ){
  61850. *ppVal = 0;
  61851. return SQLITE_OK;
  61852. }
  61853. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  61854. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  61855. /* Compressed expressions only appear when parsing the DEFAULT clause
  61856. ** on a table column definition, and hence only when pCtx==0. This
  61857. ** check ensures that an EP_TokenOnly expression is never passed down
  61858. ** into valueFromFunction(). */
  61859. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  61860. if( op==TK_CAST ){
  61861. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  61862. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  61863. testcase( rc!=SQLITE_OK );
  61864. if( *ppVal ){
  61865. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  61866. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  61867. }
  61868. return rc;
  61869. }
  61870. /* Handle negative integers in a single step. This is needed in the
  61871. ** case when the value is -9223372036854775808.
  61872. */
  61873. if( op==TK_UMINUS
  61874. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  61875. pExpr = pExpr->pLeft;
  61876. op = pExpr->op;
  61877. negInt = -1;
  61878. zNeg = "-";
  61879. }
  61880. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  61881. pVal = valueNew(db, pCtx);
  61882. if( pVal==0 ) goto no_mem;
  61883. if( ExprHasProperty(pExpr, EP_IntValue) ){
  61884. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  61885. }else{
  61886. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  61887. if( zVal==0 ) goto no_mem;
  61888. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  61889. }
  61890. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  61891. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  61892. }else{
  61893. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  61894. }
  61895. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  61896. if( enc!=SQLITE_UTF8 ){
  61897. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  61898. }
  61899. }else if( op==TK_UMINUS ) {
  61900. /* This branch happens for multiple negative signs. Ex: -(-5) */
  61901. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  61902. && pVal!=0
  61903. ){
  61904. sqlite3VdbeMemNumerify(pVal);
  61905. if( pVal->flags & MEM_Real ){
  61906. pVal->u.r = -pVal->u.r;
  61907. }else if( pVal->u.i==SMALLEST_INT64 ){
  61908. pVal->u.r = -(double)SMALLEST_INT64;
  61909. MemSetTypeFlag(pVal, MEM_Real);
  61910. }else{
  61911. pVal->u.i = -pVal->u.i;
  61912. }
  61913. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  61914. }
  61915. }else if( op==TK_NULL ){
  61916. pVal = valueNew(db, pCtx);
  61917. if( pVal==0 ) goto no_mem;
  61918. }
  61919. #ifndef SQLITE_OMIT_BLOB_LITERAL
  61920. else if( op==TK_BLOB ){
  61921. int nVal;
  61922. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  61923. assert( pExpr->u.zToken[1]=='\'' );
  61924. pVal = valueNew(db, pCtx);
  61925. if( !pVal ) goto no_mem;
  61926. zVal = &pExpr->u.zToken[2];
  61927. nVal = sqlite3Strlen30(zVal)-1;
  61928. assert( zVal[nVal]=='\'' );
  61929. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  61930. 0, SQLITE_DYNAMIC);
  61931. }
  61932. #endif
  61933. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61934. else if( op==TK_FUNCTION && pCtx!=0 ){
  61935. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  61936. }
  61937. #endif
  61938. *ppVal = pVal;
  61939. return rc;
  61940. no_mem:
  61941. db->mallocFailed = 1;
  61942. sqlite3DbFree(db, zVal);
  61943. assert( *ppVal==0 );
  61944. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61945. if( pCtx==0 ) sqlite3ValueFree(pVal);
  61946. #else
  61947. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  61948. #endif
  61949. return SQLITE_NOMEM;
  61950. }
  61951. /*
  61952. ** Create a new sqlite3_value object, containing the value of pExpr.
  61953. **
  61954. ** This only works for very simple expressions that consist of one constant
  61955. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  61956. ** be converted directly into a value, then the value is allocated and
  61957. ** a pointer written to *ppVal. The caller is responsible for deallocating
  61958. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  61959. ** cannot be converted to a value, then *ppVal is set to NULL.
  61960. */
  61961. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  61962. sqlite3 *db, /* The database connection */
  61963. Expr *pExpr, /* The expression to evaluate */
  61964. u8 enc, /* Encoding to use */
  61965. u8 affinity, /* Affinity to use */
  61966. sqlite3_value **ppVal /* Write the new value here */
  61967. ){
  61968. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  61969. }
  61970. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61971. /*
  61972. ** The implementation of the sqlite_record() function. This function accepts
  61973. ** a single argument of any type. The return value is a formatted database
  61974. ** record (a blob) containing the argument value.
  61975. **
  61976. ** This is used to convert the value stored in the 'sample' column of the
  61977. ** sqlite_stat3 table to the record format SQLite uses internally.
  61978. */
  61979. static void recordFunc(
  61980. sqlite3_context *context,
  61981. int argc,
  61982. sqlite3_value **argv
  61983. ){
  61984. const int file_format = 1;
  61985. int iSerial; /* Serial type */
  61986. int nSerial; /* Bytes of space for iSerial as varint */
  61987. int nVal; /* Bytes of space required for argv[0] */
  61988. int nRet;
  61989. sqlite3 *db;
  61990. u8 *aRet;
  61991. UNUSED_PARAMETER( argc );
  61992. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  61993. nSerial = sqlite3VarintLen(iSerial);
  61994. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  61995. db = sqlite3_context_db_handle(context);
  61996. nRet = 1 + nSerial + nVal;
  61997. aRet = sqlite3DbMallocRaw(db, nRet);
  61998. if( aRet==0 ){
  61999. sqlite3_result_error_nomem(context);
  62000. }else{
  62001. aRet[0] = nSerial+1;
  62002. putVarint32(&aRet[1], iSerial);
  62003. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  62004. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  62005. sqlite3DbFree(db, aRet);
  62006. }
  62007. }
  62008. /*
  62009. ** Register built-in functions used to help read ANALYZE data.
  62010. */
  62011. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  62012. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  62013. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  62014. };
  62015. int i;
  62016. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  62017. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  62018. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  62019. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  62020. }
  62021. }
  62022. /*
  62023. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  62024. **
  62025. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  62026. ** pAlloc if one does not exist and the new value is added to the
  62027. ** UnpackedRecord object.
  62028. **
  62029. ** A value is extracted in the following cases:
  62030. **
  62031. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  62032. **
  62033. ** * The expression is a bound variable, and this is a reprepare, or
  62034. **
  62035. ** * The expression is a literal value.
  62036. **
  62037. ** On success, *ppVal is made to point to the extracted value. The caller
  62038. ** is responsible for ensuring that the value is eventually freed.
  62039. */
  62040. static int stat4ValueFromExpr(
  62041. Parse *pParse, /* Parse context */
  62042. Expr *pExpr, /* The expression to extract a value from */
  62043. u8 affinity, /* Affinity to use */
  62044. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  62045. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  62046. ){
  62047. int rc = SQLITE_OK;
  62048. sqlite3_value *pVal = 0;
  62049. sqlite3 *db = pParse->db;
  62050. /* Skip over any TK_COLLATE nodes */
  62051. pExpr = sqlite3ExprSkipCollate(pExpr);
  62052. if( !pExpr ){
  62053. pVal = valueNew(db, pAlloc);
  62054. if( pVal ){
  62055. sqlite3VdbeMemSetNull((Mem*)pVal);
  62056. }
  62057. }else if( pExpr->op==TK_VARIABLE
  62058. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  62059. ){
  62060. Vdbe *v;
  62061. int iBindVar = pExpr->iColumn;
  62062. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  62063. if( (v = pParse->pReprepare)!=0 ){
  62064. pVal = valueNew(db, pAlloc);
  62065. if( pVal ){
  62066. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  62067. if( rc==SQLITE_OK ){
  62068. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  62069. }
  62070. pVal->db = pParse->db;
  62071. }
  62072. }
  62073. }else{
  62074. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  62075. }
  62076. assert( pVal==0 || pVal->db==db );
  62077. *ppVal = pVal;
  62078. return rc;
  62079. }
  62080. /*
  62081. ** This function is used to allocate and populate UnpackedRecord
  62082. ** structures intended to be compared against sample index keys stored
  62083. ** in the sqlite_stat4 table.
  62084. **
  62085. ** A single call to this function attempts to populates field iVal (leftmost
  62086. ** is 0 etc.) of the unpacked record with a value extracted from expression
  62087. ** pExpr. Extraction of values is possible if:
  62088. **
  62089. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  62090. **
  62091. ** * The expression is a bound variable, and this is a reprepare, or
  62092. **
  62093. ** * The sqlite3ValueFromExpr() function is able to extract a value
  62094. ** from the expression (i.e. the expression is a literal value).
  62095. **
  62096. ** If a value can be extracted, the affinity passed as the 5th argument
  62097. ** is applied to it before it is copied into the UnpackedRecord. Output
  62098. ** parameter *pbOk is set to true if a value is extracted, or false
  62099. ** otherwise.
  62100. **
  62101. ** When this function is called, *ppRec must either point to an object
  62102. ** allocated by an earlier call to this function, or must be NULL. If it
  62103. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  62104. ** is allocated (and *ppRec set to point to it) before returning.
  62105. **
  62106. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  62107. ** error if a value cannot be extracted from pExpr. If an error does
  62108. ** occur, an SQLite error code is returned.
  62109. */
  62110. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  62111. Parse *pParse, /* Parse context */
  62112. Index *pIdx, /* Index being probed */
  62113. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  62114. Expr *pExpr, /* The expression to extract a value from */
  62115. u8 affinity, /* Affinity to use */
  62116. int iVal, /* Array element to populate */
  62117. int *pbOk /* OUT: True if value was extracted */
  62118. ){
  62119. int rc;
  62120. sqlite3_value *pVal = 0;
  62121. struct ValueNewStat4Ctx alloc;
  62122. alloc.pParse = pParse;
  62123. alloc.pIdx = pIdx;
  62124. alloc.ppRec = ppRec;
  62125. alloc.iVal = iVal;
  62126. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  62127. assert( pVal==0 || pVal->db==pParse->db );
  62128. *pbOk = (pVal!=0);
  62129. return rc;
  62130. }
  62131. /*
  62132. ** Attempt to extract a value from expression pExpr using the methods
  62133. ** as described for sqlite3Stat4ProbeSetValue() above.
  62134. **
  62135. ** If successful, set *ppVal to point to a new value object and return
  62136. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  62137. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  62138. ** does occur, return an SQLite error code. The final value of *ppVal
  62139. ** is undefined in this case.
  62140. */
  62141. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  62142. Parse *pParse, /* Parse context */
  62143. Expr *pExpr, /* The expression to extract a value from */
  62144. u8 affinity, /* Affinity to use */
  62145. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  62146. ){
  62147. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  62148. }
  62149. /*
  62150. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  62151. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  62152. ** sqlite3_value object is allocated.
  62153. **
  62154. ** If *ppVal is initially NULL then the caller is responsible for
  62155. ** ensuring that the value written into *ppVal is eventually freed.
  62156. */
  62157. SQLITE_PRIVATE int sqlite3Stat4Column(
  62158. sqlite3 *db, /* Database handle */
  62159. const void *pRec, /* Pointer to buffer containing record */
  62160. int nRec, /* Size of buffer pRec in bytes */
  62161. int iCol, /* Column to extract */
  62162. sqlite3_value **ppVal /* OUT: Extracted value */
  62163. ){
  62164. u32 t; /* a column type code */
  62165. int nHdr; /* Size of the header in the record */
  62166. int iHdr; /* Next unread header byte */
  62167. int iField; /* Next unread data byte */
  62168. int szField; /* Size of the current data field */
  62169. int i; /* Column index */
  62170. u8 *a = (u8*)pRec; /* Typecast byte array */
  62171. Mem *pMem = *ppVal; /* Write result into this Mem object */
  62172. assert( iCol>0 );
  62173. iHdr = getVarint32(a, nHdr);
  62174. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  62175. iField = nHdr;
  62176. for(i=0; i<=iCol; i++){
  62177. iHdr += getVarint32(&a[iHdr], t);
  62178. testcase( iHdr==nHdr );
  62179. testcase( iHdr==nHdr+1 );
  62180. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  62181. szField = sqlite3VdbeSerialTypeLen(t);
  62182. iField += szField;
  62183. }
  62184. testcase( iField==nRec );
  62185. testcase( iField==nRec+1 );
  62186. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  62187. if( pMem==0 ){
  62188. pMem = *ppVal = sqlite3ValueNew(db);
  62189. if( pMem==0 ) return SQLITE_NOMEM;
  62190. }
  62191. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  62192. pMem->enc = ENC(db);
  62193. return SQLITE_OK;
  62194. }
  62195. /*
  62196. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  62197. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  62198. ** the object.
  62199. */
  62200. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  62201. if( pRec ){
  62202. int i;
  62203. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  62204. Mem *aMem = pRec->aMem;
  62205. sqlite3 *db = aMem[0].db;
  62206. for(i=0; i<nCol; i++){
  62207. sqlite3VdbeMemRelease(&aMem[i]);
  62208. }
  62209. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  62210. sqlite3DbFree(db, pRec);
  62211. }
  62212. }
  62213. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  62214. /*
  62215. ** Change the string value of an sqlite3_value object
  62216. */
  62217. SQLITE_PRIVATE void sqlite3ValueSetStr(
  62218. sqlite3_value *v, /* Value to be set */
  62219. int n, /* Length of string z */
  62220. const void *z, /* Text of the new string */
  62221. u8 enc, /* Encoding to use */
  62222. void (*xDel)(void*) /* Destructor for the string */
  62223. ){
  62224. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  62225. }
  62226. /*
  62227. ** Free an sqlite3_value object
  62228. */
  62229. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  62230. if( !v ) return;
  62231. sqlite3VdbeMemRelease((Mem *)v);
  62232. sqlite3DbFree(((Mem*)v)->db, v);
  62233. }
  62234. /*
  62235. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  62236. ** sqlite3_value object assuming that it uses the encoding "enc".
  62237. ** The valueBytes() routine is a helper function.
  62238. */
  62239. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  62240. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  62241. }
  62242. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  62243. Mem *p = (Mem*)pVal;
  62244. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  62245. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  62246. return p->n;
  62247. }
  62248. if( (p->flags & MEM_Blob)!=0 ){
  62249. if( p->flags & MEM_Zero ){
  62250. return p->n + p->u.nZero;
  62251. }else{
  62252. return p->n;
  62253. }
  62254. }
  62255. if( p->flags & MEM_Null ) return 0;
  62256. return valueBytes(pVal, enc);
  62257. }
  62258. /************** End of vdbemem.c *********************************************/
  62259. /************** Begin file vdbeaux.c *****************************************/
  62260. /*
  62261. ** 2003 September 6
  62262. **
  62263. ** The author disclaims copyright to this source code. In place of
  62264. ** a legal notice, here is a blessing:
  62265. **
  62266. ** May you do good and not evil.
  62267. ** May you find forgiveness for yourself and forgive others.
  62268. ** May you share freely, never taking more than you give.
  62269. **
  62270. *************************************************************************
  62271. ** This file contains code used for creating, destroying, and populating
  62272. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  62273. */
  62274. /* #include "sqliteInt.h" */
  62275. /* #include "vdbeInt.h" */
  62276. /*
  62277. ** Create a new virtual database engine.
  62278. */
  62279. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  62280. sqlite3 *db = pParse->db;
  62281. Vdbe *p;
  62282. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  62283. if( p==0 ) return 0;
  62284. p->db = db;
  62285. if( db->pVdbe ){
  62286. db->pVdbe->pPrev = p;
  62287. }
  62288. p->pNext = db->pVdbe;
  62289. p->pPrev = 0;
  62290. db->pVdbe = p;
  62291. p->magic = VDBE_MAGIC_INIT;
  62292. p->pParse = pParse;
  62293. assert( pParse->aLabel==0 );
  62294. assert( pParse->nLabel==0 );
  62295. assert( pParse->nOpAlloc==0 );
  62296. return p;
  62297. }
  62298. /*
  62299. ** Change the error string stored in Vdbe.zErrMsg
  62300. */
  62301. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  62302. va_list ap;
  62303. sqlite3DbFree(p->db, p->zErrMsg);
  62304. va_start(ap, zFormat);
  62305. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  62306. va_end(ap);
  62307. }
  62308. /*
  62309. ** Remember the SQL string for a prepared statement.
  62310. */
  62311. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  62312. assert( isPrepareV2==1 || isPrepareV2==0 );
  62313. if( p==0 ) return;
  62314. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  62315. if( !isPrepareV2 ) return;
  62316. #endif
  62317. assert( p->zSql==0 );
  62318. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  62319. p->isPrepareV2 = (u8)isPrepareV2;
  62320. }
  62321. /*
  62322. ** Return the SQL associated with a prepared statement
  62323. */
  62324. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
  62325. Vdbe *p = (Vdbe *)pStmt;
  62326. return p ? p->zSql : 0;
  62327. }
  62328. /*
  62329. ** Swap all content between two VDBE structures.
  62330. */
  62331. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  62332. Vdbe tmp, *pTmp;
  62333. char *zTmp;
  62334. tmp = *pA;
  62335. *pA = *pB;
  62336. *pB = tmp;
  62337. pTmp = pA->pNext;
  62338. pA->pNext = pB->pNext;
  62339. pB->pNext = pTmp;
  62340. pTmp = pA->pPrev;
  62341. pA->pPrev = pB->pPrev;
  62342. pB->pPrev = pTmp;
  62343. zTmp = pA->zSql;
  62344. pA->zSql = pB->zSql;
  62345. pB->zSql = zTmp;
  62346. pB->isPrepareV2 = pA->isPrepareV2;
  62347. }
  62348. /*
  62349. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  62350. ** than its current size. nOp is guaranteed to be less than or equal
  62351. ** to 1024/sizeof(Op).
  62352. **
  62353. ** If an out-of-memory error occurs while resizing the array, return
  62354. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  62355. ** unchanged (this is so that any opcodes already allocated can be
  62356. ** correctly deallocated along with the rest of the Vdbe).
  62357. */
  62358. static int growOpArray(Vdbe *v, int nOp){
  62359. VdbeOp *pNew;
  62360. Parse *p = v->pParse;
  62361. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  62362. ** more frequent reallocs and hence provide more opportunities for
  62363. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  62364. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  62365. ** by the minimum* amount required until the size reaches 512. Normal
  62366. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  62367. ** size of the op array or add 1KB of space, whichever is smaller. */
  62368. #ifdef SQLITE_TEST_REALLOC_STRESS
  62369. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  62370. #else
  62371. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  62372. UNUSED_PARAMETER(nOp);
  62373. #endif
  62374. assert( nOp<=(1024/sizeof(Op)) );
  62375. assert( nNew>=(p->nOpAlloc+nOp) );
  62376. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  62377. if( pNew ){
  62378. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  62379. v->aOp = pNew;
  62380. }
  62381. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  62382. }
  62383. #ifdef SQLITE_DEBUG
  62384. /* This routine is just a convenient place to set a breakpoint that will
  62385. ** fire after each opcode is inserted and displayed using
  62386. ** "PRAGMA vdbe_addoptrace=on".
  62387. */
  62388. static void test_addop_breakpoint(void){
  62389. static int n = 0;
  62390. n++;
  62391. }
  62392. #endif
  62393. /*
  62394. ** Add a new instruction to the list of instructions current in the
  62395. ** VDBE. Return the address of the new instruction.
  62396. **
  62397. ** Parameters:
  62398. **
  62399. ** p Pointer to the VDBE
  62400. **
  62401. ** op The opcode for this instruction
  62402. **
  62403. ** p1, p2, p3 Operands
  62404. **
  62405. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  62406. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  62407. ** operand.
  62408. */
  62409. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  62410. int i;
  62411. VdbeOp *pOp;
  62412. i = p->nOp;
  62413. assert( p->magic==VDBE_MAGIC_INIT );
  62414. assert( op>0 && op<0xff );
  62415. if( p->pParse->nOpAlloc<=i ){
  62416. if( growOpArray(p, 1) ){
  62417. return 1;
  62418. }
  62419. }
  62420. p->nOp++;
  62421. pOp = &p->aOp[i];
  62422. pOp->opcode = (u8)op;
  62423. pOp->p5 = 0;
  62424. pOp->p1 = p1;
  62425. pOp->p2 = p2;
  62426. pOp->p3 = p3;
  62427. pOp->p4.p = 0;
  62428. pOp->p4type = P4_NOTUSED;
  62429. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62430. pOp->zComment = 0;
  62431. #endif
  62432. #ifdef SQLITE_DEBUG
  62433. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  62434. int jj, kk;
  62435. Parse *pParse = p->pParse;
  62436. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  62437. struct yColCache *x = pParse->aColCache + jj;
  62438. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  62439. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  62440. kk++;
  62441. }
  62442. if( kk ) printf("\n");
  62443. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  62444. test_addop_breakpoint();
  62445. }
  62446. #endif
  62447. #ifdef VDBE_PROFILE
  62448. pOp->cycles = 0;
  62449. pOp->cnt = 0;
  62450. #endif
  62451. #ifdef SQLITE_VDBE_COVERAGE
  62452. pOp->iSrcLine = 0;
  62453. #endif
  62454. return i;
  62455. }
  62456. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  62457. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  62458. }
  62459. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  62460. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  62461. }
  62462. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  62463. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  62464. }
  62465. /* Generate code for an unconditional jump to instruction iDest
  62466. */
  62467. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  62468. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  62469. }
  62470. /* Generate code to cause the string zStr to be loaded into
  62471. ** register iDest
  62472. */
  62473. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  62474. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  62475. }
  62476. /*
  62477. ** Generate code that initializes multiple registers to string or integer
  62478. ** constants. The registers begin with iDest and increase consecutively.
  62479. ** One register is initialized for each characgter in zTypes[]. For each
  62480. ** "s" character in zTypes[], the register is a string if the argument is
  62481. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  62482. ** in zTypes[], the register is initialized to an integer.
  62483. */
  62484. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  62485. va_list ap;
  62486. int i;
  62487. char c;
  62488. va_start(ap, zTypes);
  62489. for(i=0; (c = zTypes[i])!=0; i++){
  62490. if( c=='s' ){
  62491. const char *z = va_arg(ap, const char*);
  62492. int addr = sqlite3VdbeAddOp2(p, z==0 ? OP_Null : OP_String8, 0, iDest++);
  62493. if( z ) sqlite3VdbeChangeP4(p, addr, z, 0);
  62494. }else{
  62495. assert( c=='i' );
  62496. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
  62497. }
  62498. }
  62499. va_end(ap);
  62500. }
  62501. /*
  62502. ** Add an opcode that includes the p4 value as a pointer.
  62503. */
  62504. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  62505. Vdbe *p, /* Add the opcode to this VM */
  62506. int op, /* The new opcode */
  62507. int p1, /* The P1 operand */
  62508. int p2, /* The P2 operand */
  62509. int p3, /* The P3 operand */
  62510. const char *zP4, /* The P4 operand */
  62511. int p4type /* P4 operand type */
  62512. ){
  62513. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  62514. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  62515. return addr;
  62516. }
  62517. /*
  62518. ** Add an opcode that includes the p4 value with a P4_INT64 or
  62519. ** P4_REAL type.
  62520. */
  62521. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  62522. Vdbe *p, /* Add the opcode to this VM */
  62523. int op, /* The new opcode */
  62524. int p1, /* The P1 operand */
  62525. int p2, /* The P2 operand */
  62526. int p3, /* The P3 operand */
  62527. const u8 *zP4, /* The P4 operand */
  62528. int p4type /* P4 operand type */
  62529. ){
  62530. char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
  62531. if( p4copy ) memcpy(p4copy, zP4, 8);
  62532. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  62533. }
  62534. /*
  62535. ** Add an OP_ParseSchema opcode. This routine is broken out from
  62536. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  62537. ** as having been used.
  62538. **
  62539. ** The zWhere string must have been obtained from sqlite3_malloc().
  62540. ** This routine will take ownership of the allocated memory.
  62541. */
  62542. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  62543. int j;
  62544. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  62545. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  62546. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  62547. }
  62548. /*
  62549. ** Add an opcode that includes the p4 value as an integer.
  62550. */
  62551. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  62552. Vdbe *p, /* Add the opcode to this VM */
  62553. int op, /* The new opcode */
  62554. int p1, /* The P1 operand */
  62555. int p2, /* The P2 operand */
  62556. int p3, /* The P3 operand */
  62557. int p4 /* The P4 operand as an integer */
  62558. ){
  62559. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  62560. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  62561. return addr;
  62562. }
  62563. /*
  62564. ** Create a new symbolic label for an instruction that has yet to be
  62565. ** coded. The symbolic label is really just a negative number. The
  62566. ** label can be used as the P2 value of an operation. Later, when
  62567. ** the label is resolved to a specific address, the VDBE will scan
  62568. ** through its operation list and change all values of P2 which match
  62569. ** the label into the resolved address.
  62570. **
  62571. ** The VDBE knows that a P2 value is a label because labels are
  62572. ** always negative and P2 values are suppose to be non-negative.
  62573. ** Hence, a negative P2 value is a label that has yet to be resolved.
  62574. **
  62575. ** Zero is returned if a malloc() fails.
  62576. */
  62577. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  62578. Parse *p = v->pParse;
  62579. int i = p->nLabel++;
  62580. assert( v->magic==VDBE_MAGIC_INIT );
  62581. if( (i & (i-1))==0 ){
  62582. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  62583. (i*2+1)*sizeof(p->aLabel[0]));
  62584. }
  62585. if( p->aLabel ){
  62586. p->aLabel[i] = -1;
  62587. }
  62588. return -1-i;
  62589. }
  62590. /*
  62591. ** Resolve label "x" to be the address of the next instruction to
  62592. ** be inserted. The parameter "x" must have been obtained from
  62593. ** a prior call to sqlite3VdbeMakeLabel().
  62594. */
  62595. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  62596. Parse *p = v->pParse;
  62597. int j = -1-x;
  62598. assert( v->magic==VDBE_MAGIC_INIT );
  62599. assert( j<p->nLabel );
  62600. assert( j>=0 );
  62601. if( p->aLabel ){
  62602. p->aLabel[j] = v->nOp;
  62603. }
  62604. p->iFixedOp = v->nOp - 1;
  62605. }
  62606. /*
  62607. ** Mark the VDBE as one that can only be run one time.
  62608. */
  62609. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  62610. p->runOnlyOnce = 1;
  62611. }
  62612. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  62613. /*
  62614. ** The following type and function are used to iterate through all opcodes
  62615. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  62616. ** invoke directly or indirectly. It should be used as follows:
  62617. **
  62618. ** Op *pOp;
  62619. ** VdbeOpIter sIter;
  62620. **
  62621. ** memset(&sIter, 0, sizeof(sIter));
  62622. ** sIter.v = v; // v is of type Vdbe*
  62623. ** while( (pOp = opIterNext(&sIter)) ){
  62624. ** // Do something with pOp
  62625. ** }
  62626. ** sqlite3DbFree(v->db, sIter.apSub);
  62627. **
  62628. */
  62629. typedef struct VdbeOpIter VdbeOpIter;
  62630. struct VdbeOpIter {
  62631. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  62632. SubProgram **apSub; /* Array of subprograms */
  62633. int nSub; /* Number of entries in apSub */
  62634. int iAddr; /* Address of next instruction to return */
  62635. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  62636. };
  62637. static Op *opIterNext(VdbeOpIter *p){
  62638. Vdbe *v = p->v;
  62639. Op *pRet = 0;
  62640. Op *aOp;
  62641. int nOp;
  62642. if( p->iSub<=p->nSub ){
  62643. if( p->iSub==0 ){
  62644. aOp = v->aOp;
  62645. nOp = v->nOp;
  62646. }else{
  62647. aOp = p->apSub[p->iSub-1]->aOp;
  62648. nOp = p->apSub[p->iSub-1]->nOp;
  62649. }
  62650. assert( p->iAddr<nOp );
  62651. pRet = &aOp[p->iAddr];
  62652. p->iAddr++;
  62653. if( p->iAddr==nOp ){
  62654. p->iSub++;
  62655. p->iAddr = 0;
  62656. }
  62657. if( pRet->p4type==P4_SUBPROGRAM ){
  62658. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  62659. int j;
  62660. for(j=0; j<p->nSub; j++){
  62661. if( p->apSub[j]==pRet->p4.pProgram ) break;
  62662. }
  62663. if( j==p->nSub ){
  62664. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  62665. if( !p->apSub ){
  62666. pRet = 0;
  62667. }else{
  62668. p->apSub[p->nSub++] = pRet->p4.pProgram;
  62669. }
  62670. }
  62671. }
  62672. }
  62673. return pRet;
  62674. }
  62675. /*
  62676. ** Check if the program stored in the VM associated with pParse may
  62677. ** throw an ABORT exception (causing the statement, but not entire transaction
  62678. ** to be rolled back). This condition is true if the main program or any
  62679. ** sub-programs contains any of the following:
  62680. **
  62681. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  62682. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  62683. ** * OP_Destroy
  62684. ** * OP_VUpdate
  62685. ** * OP_VRename
  62686. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  62687. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  62688. **
  62689. ** Then check that the value of Parse.mayAbort is true if an
  62690. ** ABORT may be thrown, or false otherwise. Return true if it does
  62691. ** match, or false otherwise. This function is intended to be used as
  62692. ** part of an assert statement in the compiler. Similar to:
  62693. **
  62694. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  62695. */
  62696. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  62697. int hasAbort = 0;
  62698. int hasFkCounter = 0;
  62699. int hasCreateTable = 0;
  62700. int hasInitCoroutine = 0;
  62701. Op *pOp;
  62702. VdbeOpIter sIter;
  62703. memset(&sIter, 0, sizeof(sIter));
  62704. sIter.v = v;
  62705. while( (pOp = opIterNext(&sIter))!=0 ){
  62706. int opcode = pOp->opcode;
  62707. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  62708. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  62709. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  62710. ){
  62711. hasAbort = 1;
  62712. break;
  62713. }
  62714. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  62715. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  62716. #ifndef SQLITE_OMIT_FOREIGN_KEY
  62717. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  62718. hasFkCounter = 1;
  62719. }
  62720. #endif
  62721. }
  62722. sqlite3DbFree(v->db, sIter.apSub);
  62723. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  62724. ** If malloc failed, then the while() loop above may not have iterated
  62725. ** through all opcodes and hasAbort may be set incorrectly. Return
  62726. ** true for this case to prevent the assert() in the callers frame
  62727. ** from failing. */
  62728. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  62729. || (hasCreateTable && hasInitCoroutine) );
  62730. }
  62731. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  62732. /*
  62733. ** This routine is called after all opcodes have been inserted. It loops
  62734. ** through all the opcodes and fixes up some details.
  62735. **
  62736. ** (1) For each jump instruction with a negative P2 value (a label)
  62737. ** resolve the P2 value to an actual address.
  62738. **
  62739. ** (2) Compute the maximum number of arguments used by any SQL function
  62740. ** and store that value in *pMaxFuncArgs.
  62741. **
  62742. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  62743. ** indicate what the prepared statement actually does.
  62744. **
  62745. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  62746. **
  62747. ** (5) Reclaim the memory allocated for storing labels.
  62748. */
  62749. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  62750. int i;
  62751. int nMaxArgs = *pMaxFuncArgs;
  62752. Op *pOp;
  62753. Parse *pParse = p->pParse;
  62754. int *aLabel = pParse->aLabel;
  62755. p->readOnly = 1;
  62756. p->bIsReader = 0;
  62757. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  62758. u8 opcode = pOp->opcode;
  62759. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  62760. ** cases from this switch! */
  62761. switch( opcode ){
  62762. case OP_Transaction: {
  62763. if( pOp->p2!=0 ) p->readOnly = 0;
  62764. /* fall thru */
  62765. }
  62766. case OP_AutoCommit:
  62767. case OP_Savepoint: {
  62768. p->bIsReader = 1;
  62769. break;
  62770. }
  62771. #ifndef SQLITE_OMIT_WAL
  62772. case OP_Checkpoint:
  62773. #endif
  62774. case OP_Vacuum:
  62775. case OP_JournalMode: {
  62776. p->readOnly = 0;
  62777. p->bIsReader = 1;
  62778. break;
  62779. }
  62780. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62781. case OP_VUpdate: {
  62782. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  62783. break;
  62784. }
  62785. case OP_VFilter: {
  62786. int n;
  62787. assert( p->nOp - i >= 3 );
  62788. assert( pOp[-1].opcode==OP_Integer );
  62789. n = pOp[-1].p1;
  62790. if( n>nMaxArgs ) nMaxArgs = n;
  62791. break;
  62792. }
  62793. #endif
  62794. case OP_Next:
  62795. case OP_NextIfOpen:
  62796. case OP_SorterNext: {
  62797. pOp->p4.xAdvance = sqlite3BtreeNext;
  62798. pOp->p4type = P4_ADVANCE;
  62799. break;
  62800. }
  62801. case OP_Prev:
  62802. case OP_PrevIfOpen: {
  62803. pOp->p4.xAdvance = sqlite3BtreePrevious;
  62804. pOp->p4type = P4_ADVANCE;
  62805. break;
  62806. }
  62807. }
  62808. pOp->opflags = sqlite3OpcodeProperty[opcode];
  62809. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  62810. assert( -1-pOp->p2<pParse->nLabel );
  62811. pOp->p2 = aLabel[-1-pOp->p2];
  62812. }
  62813. }
  62814. sqlite3DbFree(p->db, pParse->aLabel);
  62815. pParse->aLabel = 0;
  62816. pParse->nLabel = 0;
  62817. *pMaxFuncArgs = nMaxArgs;
  62818. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  62819. }
  62820. /*
  62821. ** Return the address of the next instruction to be inserted.
  62822. */
  62823. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  62824. assert( p->magic==VDBE_MAGIC_INIT );
  62825. return p->nOp;
  62826. }
  62827. /*
  62828. ** This function returns a pointer to the array of opcodes associated with
  62829. ** the Vdbe passed as the first argument. It is the callers responsibility
  62830. ** to arrange for the returned array to be eventually freed using the
  62831. ** vdbeFreeOpArray() function.
  62832. **
  62833. ** Before returning, *pnOp is set to the number of entries in the returned
  62834. ** array. Also, *pnMaxArg is set to the larger of its current value and
  62835. ** the number of entries in the Vdbe.apArg[] array required to execute the
  62836. ** returned program.
  62837. */
  62838. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  62839. VdbeOp *aOp = p->aOp;
  62840. assert( aOp && !p->db->mallocFailed );
  62841. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  62842. assert( DbMaskAllZero(p->btreeMask) );
  62843. resolveP2Values(p, pnMaxArg);
  62844. *pnOp = p->nOp;
  62845. p->aOp = 0;
  62846. return aOp;
  62847. }
  62848. /*
  62849. ** Add a whole list of operations to the operation stack. Return the
  62850. ** address of the first operation added.
  62851. */
  62852. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  62853. int addr, i;
  62854. VdbeOp *pOut;
  62855. assert( nOp>0 );
  62856. assert( p->magic==VDBE_MAGIC_INIT );
  62857. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  62858. return 0;
  62859. }
  62860. addr = p->nOp;
  62861. pOut = &p->aOp[addr];
  62862. for(i=0; i<nOp; i++, aOp++, pOut++){
  62863. int p2 = aOp->p2;
  62864. pOut->opcode = aOp->opcode;
  62865. pOut->p1 = aOp->p1;
  62866. if( p2<0 ){
  62867. assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
  62868. pOut->p2 = addr + ADDR(p2);
  62869. }else{
  62870. pOut->p2 = p2;
  62871. }
  62872. pOut->p3 = aOp->p3;
  62873. pOut->p4type = P4_NOTUSED;
  62874. pOut->p4.p = 0;
  62875. pOut->p5 = 0;
  62876. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62877. pOut->zComment = 0;
  62878. #endif
  62879. #ifdef SQLITE_VDBE_COVERAGE
  62880. pOut->iSrcLine = iLineno+i;
  62881. #else
  62882. (void)iLineno;
  62883. #endif
  62884. #ifdef SQLITE_DEBUG
  62885. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  62886. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  62887. }
  62888. #endif
  62889. }
  62890. p->nOp += nOp;
  62891. return addr;
  62892. }
  62893. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  62894. /*
  62895. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  62896. */
  62897. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  62898. Vdbe *p, /* VM to add scanstatus() to */
  62899. int addrExplain, /* Address of OP_Explain (or 0) */
  62900. int addrLoop, /* Address of loop counter */
  62901. int addrVisit, /* Address of rows visited counter */
  62902. LogEst nEst, /* Estimated number of output rows */
  62903. const char *zName /* Name of table or index being scanned */
  62904. ){
  62905. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  62906. ScanStatus *aNew;
  62907. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  62908. if( aNew ){
  62909. ScanStatus *pNew = &aNew[p->nScan++];
  62910. pNew->addrExplain = addrExplain;
  62911. pNew->addrLoop = addrLoop;
  62912. pNew->addrVisit = addrVisit;
  62913. pNew->nEst = nEst;
  62914. pNew->zName = sqlite3DbStrDup(p->db, zName);
  62915. p->aScan = aNew;
  62916. }
  62917. }
  62918. #endif
  62919. /*
  62920. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  62921. ** for a specific instruction.
  62922. */
  62923. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  62924. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  62925. }
  62926. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  62927. sqlite3VdbeGetOp(p,addr)->p1 = val;
  62928. }
  62929. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  62930. sqlite3VdbeGetOp(p,addr)->p2 = val;
  62931. }
  62932. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  62933. sqlite3VdbeGetOp(p,addr)->p3 = val;
  62934. }
  62935. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
  62936. sqlite3VdbeGetOp(p,-1)->p5 = p5;
  62937. }
  62938. /*
  62939. ** Change the P2 operand of instruction addr so that it points to
  62940. ** the address of the next instruction to be coded.
  62941. */
  62942. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  62943. p->pParse->iFixedOp = p->nOp - 1;
  62944. sqlite3VdbeChangeP2(p, addr, p->nOp);
  62945. }
  62946. /*
  62947. ** If the input FuncDef structure is ephemeral, then free it. If
  62948. ** the FuncDef is not ephermal, then do nothing.
  62949. */
  62950. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  62951. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  62952. sqlite3DbFree(db, pDef);
  62953. }
  62954. }
  62955. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  62956. /*
  62957. ** Delete a P4 value if necessary.
  62958. */
  62959. static void freeP4(sqlite3 *db, int p4type, void *p4){
  62960. if( p4 ){
  62961. assert( db );
  62962. switch( p4type ){
  62963. case P4_FUNCCTX: {
  62964. freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
  62965. /* Fall through into the next case */
  62966. }
  62967. case P4_REAL:
  62968. case P4_INT64:
  62969. case P4_DYNAMIC:
  62970. case P4_INTARRAY: {
  62971. sqlite3DbFree(db, p4);
  62972. break;
  62973. }
  62974. case P4_KEYINFO: {
  62975. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  62976. break;
  62977. }
  62978. case P4_MPRINTF: {
  62979. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  62980. break;
  62981. }
  62982. case P4_FUNCDEF: {
  62983. freeEphemeralFunction(db, (FuncDef*)p4);
  62984. break;
  62985. }
  62986. case P4_MEM: {
  62987. if( db->pnBytesFreed==0 ){
  62988. sqlite3ValueFree((sqlite3_value*)p4);
  62989. }else{
  62990. Mem *p = (Mem*)p4;
  62991. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  62992. sqlite3DbFree(db, p);
  62993. }
  62994. break;
  62995. }
  62996. case P4_VTAB : {
  62997. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  62998. break;
  62999. }
  63000. }
  63001. }
  63002. }
  63003. /*
  63004. ** Free the space allocated for aOp and any p4 values allocated for the
  63005. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  63006. ** nOp entries.
  63007. */
  63008. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  63009. if( aOp ){
  63010. Op *pOp;
  63011. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  63012. freeP4(db, pOp->p4type, pOp->p4.p);
  63013. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63014. sqlite3DbFree(db, pOp->zComment);
  63015. #endif
  63016. }
  63017. }
  63018. sqlite3DbFree(db, aOp);
  63019. }
  63020. /*
  63021. ** Link the SubProgram object passed as the second argument into the linked
  63022. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  63023. ** objects when the VM is no longer required.
  63024. */
  63025. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  63026. p->pNext = pVdbe->pProgram;
  63027. pVdbe->pProgram = p;
  63028. }
  63029. /*
  63030. ** Change the opcode at addr into OP_Noop
  63031. */
  63032. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  63033. if( addr<p->nOp ){
  63034. VdbeOp *pOp = &p->aOp[addr];
  63035. sqlite3 *db = p->db;
  63036. freeP4(db, pOp->p4type, pOp->p4.p);
  63037. memset(pOp, 0, sizeof(pOp[0]));
  63038. pOp->opcode = OP_Noop;
  63039. if( addr==p->nOp-1 ) p->nOp--;
  63040. }
  63041. }
  63042. /*
  63043. ** If the last opcode is "op" and it is not a jump destination,
  63044. ** then remove it. Return true if and only if an opcode was removed.
  63045. */
  63046. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  63047. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  63048. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  63049. return 1;
  63050. }else{
  63051. return 0;
  63052. }
  63053. }
  63054. /*
  63055. ** Change the value of the P4 operand for a specific instruction.
  63056. ** This routine is useful when a large program is loaded from a
  63057. ** static array using sqlite3VdbeAddOpList but we want to make a
  63058. ** few minor changes to the program.
  63059. **
  63060. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  63061. ** the string is made into memory obtained from sqlite3_malloc().
  63062. ** A value of n==0 means copy bytes of zP4 up to and including the
  63063. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  63064. **
  63065. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  63066. ** to a string or structure that is guaranteed to exist for the lifetime of
  63067. ** the Vdbe. In these cases we can just copy the pointer.
  63068. **
  63069. ** If addr<0 then change P4 on the most recently inserted instruction.
  63070. */
  63071. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  63072. Op *pOp;
  63073. sqlite3 *db;
  63074. assert( p!=0 );
  63075. db = p->db;
  63076. assert( p->magic==VDBE_MAGIC_INIT );
  63077. if( p->aOp==0 || db->mallocFailed ){
  63078. if( n!=P4_VTAB ){
  63079. freeP4(db, n, (void*)*(char**)&zP4);
  63080. }
  63081. return;
  63082. }
  63083. assert( p->nOp>0 );
  63084. assert( addr<p->nOp );
  63085. if( addr<0 ){
  63086. addr = p->nOp - 1;
  63087. }
  63088. pOp = &p->aOp[addr];
  63089. assert( pOp->p4type==P4_NOTUSED
  63090. || pOp->p4type==P4_INT32
  63091. || pOp->p4type==P4_KEYINFO );
  63092. freeP4(db, pOp->p4type, pOp->p4.p);
  63093. pOp->p4.p = 0;
  63094. if( n==P4_INT32 ){
  63095. /* Note: this cast is safe, because the origin data point was an int
  63096. ** that was cast to a (const char *). */
  63097. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  63098. pOp->p4type = P4_INT32;
  63099. }else if( zP4==0 ){
  63100. pOp->p4.p = 0;
  63101. pOp->p4type = P4_NOTUSED;
  63102. }else if( n==P4_KEYINFO ){
  63103. pOp->p4.p = (void*)zP4;
  63104. pOp->p4type = P4_KEYINFO;
  63105. }else if( n==P4_VTAB ){
  63106. pOp->p4.p = (void*)zP4;
  63107. pOp->p4type = P4_VTAB;
  63108. sqlite3VtabLock((VTable *)zP4);
  63109. assert( ((VTable *)zP4)->db==p->db );
  63110. }else if( n<0 ){
  63111. pOp->p4.p = (void*)zP4;
  63112. pOp->p4type = (signed char)n;
  63113. }else{
  63114. if( n==0 ) n = sqlite3Strlen30(zP4);
  63115. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  63116. pOp->p4type = P4_DYNAMIC;
  63117. }
  63118. }
  63119. /*
  63120. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  63121. ** index given.
  63122. */
  63123. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  63124. Vdbe *v = pParse->pVdbe;
  63125. assert( v!=0 );
  63126. assert( pIdx!=0 );
  63127. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  63128. P4_KEYINFO);
  63129. }
  63130. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63131. /*
  63132. ** Change the comment on the most recently coded instruction. Or
  63133. ** insert a No-op and add the comment to that new instruction. This
  63134. ** makes the code easier to read during debugging. None of this happens
  63135. ** in a production build.
  63136. */
  63137. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  63138. assert( p->nOp>0 || p->aOp==0 );
  63139. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  63140. if( p->nOp ){
  63141. assert( p->aOp );
  63142. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  63143. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  63144. }
  63145. }
  63146. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  63147. va_list ap;
  63148. if( p ){
  63149. va_start(ap, zFormat);
  63150. vdbeVComment(p, zFormat, ap);
  63151. va_end(ap);
  63152. }
  63153. }
  63154. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  63155. va_list ap;
  63156. if( p ){
  63157. sqlite3VdbeAddOp0(p, OP_Noop);
  63158. va_start(ap, zFormat);
  63159. vdbeVComment(p, zFormat, ap);
  63160. va_end(ap);
  63161. }
  63162. }
  63163. #endif /* NDEBUG */
  63164. #ifdef SQLITE_VDBE_COVERAGE
  63165. /*
  63166. ** Set the value if the iSrcLine field for the previously coded instruction.
  63167. */
  63168. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  63169. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  63170. }
  63171. #endif /* SQLITE_VDBE_COVERAGE */
  63172. /*
  63173. ** Return the opcode for a given address. If the address is -1, then
  63174. ** return the most recently inserted opcode.
  63175. **
  63176. ** If a memory allocation error has occurred prior to the calling of this
  63177. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  63178. ** is readable but not writable, though it is cast to a writable value.
  63179. ** The return of a dummy opcode allows the call to continue functioning
  63180. ** after an OOM fault without having to check to see if the return from
  63181. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  63182. ** dummy will never be written to. This is verified by code inspection and
  63183. ** by running with Valgrind.
  63184. */
  63185. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  63186. /* C89 specifies that the constant "dummy" will be initialized to all
  63187. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  63188. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  63189. assert( p->magic==VDBE_MAGIC_INIT );
  63190. if( addr<0 ){
  63191. addr = p->nOp - 1;
  63192. }
  63193. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  63194. if( p->db->mallocFailed ){
  63195. return (VdbeOp*)&dummy;
  63196. }else{
  63197. return &p->aOp[addr];
  63198. }
  63199. }
  63200. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  63201. /*
  63202. ** Return an integer value for one of the parameters to the opcode pOp
  63203. ** determined by character c.
  63204. */
  63205. static int translateP(char c, const Op *pOp){
  63206. if( c=='1' ) return pOp->p1;
  63207. if( c=='2' ) return pOp->p2;
  63208. if( c=='3' ) return pOp->p3;
  63209. if( c=='4' ) return pOp->p4.i;
  63210. return pOp->p5;
  63211. }
  63212. /*
  63213. ** Compute a string for the "comment" field of a VDBE opcode listing.
  63214. **
  63215. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  63216. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  63217. ** absence of other comments, this synopsis becomes the comment on the opcode.
  63218. ** Some translation occurs:
  63219. **
  63220. ** "PX" -> "r[X]"
  63221. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  63222. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  63223. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  63224. */
  63225. static int displayComment(
  63226. const Op *pOp, /* The opcode to be commented */
  63227. const char *zP4, /* Previously obtained value for P4 */
  63228. char *zTemp, /* Write result here */
  63229. int nTemp /* Space available in zTemp[] */
  63230. ){
  63231. const char *zOpName;
  63232. const char *zSynopsis;
  63233. int nOpName;
  63234. int ii, jj;
  63235. zOpName = sqlite3OpcodeName(pOp->opcode);
  63236. nOpName = sqlite3Strlen30(zOpName);
  63237. if( zOpName[nOpName+1] ){
  63238. int seenCom = 0;
  63239. char c;
  63240. zSynopsis = zOpName += nOpName + 1;
  63241. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  63242. if( c=='P' ){
  63243. c = zSynopsis[++ii];
  63244. if( c=='4' ){
  63245. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  63246. }else if( c=='X' ){
  63247. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  63248. seenCom = 1;
  63249. }else{
  63250. int v1 = translateP(c, pOp);
  63251. int v2;
  63252. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  63253. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  63254. ii += 3;
  63255. jj += sqlite3Strlen30(zTemp+jj);
  63256. v2 = translateP(zSynopsis[ii], pOp);
  63257. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  63258. ii += 2;
  63259. v2++;
  63260. }
  63261. if( v2>1 ){
  63262. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  63263. }
  63264. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  63265. ii += 4;
  63266. }
  63267. }
  63268. jj += sqlite3Strlen30(zTemp+jj);
  63269. }else{
  63270. zTemp[jj++] = c;
  63271. }
  63272. }
  63273. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  63274. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  63275. jj += sqlite3Strlen30(zTemp+jj);
  63276. }
  63277. if( jj<nTemp ) zTemp[jj] = 0;
  63278. }else if( pOp->zComment ){
  63279. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  63280. jj = sqlite3Strlen30(zTemp);
  63281. }else{
  63282. zTemp[0] = 0;
  63283. jj = 0;
  63284. }
  63285. return jj;
  63286. }
  63287. #endif /* SQLITE_DEBUG */
  63288. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  63289. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  63290. /*
  63291. ** Compute a string that describes the P4 parameter for an opcode.
  63292. ** Use zTemp for any required temporary buffer space.
  63293. */
  63294. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  63295. char *zP4 = zTemp;
  63296. assert( nTemp>=20 );
  63297. switch( pOp->p4type ){
  63298. case P4_KEYINFO: {
  63299. int i, j;
  63300. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  63301. assert( pKeyInfo->aSortOrder!=0 );
  63302. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  63303. i = sqlite3Strlen30(zTemp);
  63304. for(j=0; j<pKeyInfo->nField; j++){
  63305. CollSeq *pColl = pKeyInfo->aColl[j];
  63306. const char *zColl = pColl ? pColl->zName : "nil";
  63307. int n = sqlite3Strlen30(zColl);
  63308. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  63309. zColl = "B";
  63310. n = 1;
  63311. }
  63312. if( i+n>nTemp-7 ){
  63313. memcpy(&zTemp[i],",...",4);
  63314. i += 4;
  63315. break;
  63316. }
  63317. zTemp[i++] = ',';
  63318. if( pKeyInfo->aSortOrder[j] ){
  63319. zTemp[i++] = '-';
  63320. }
  63321. memcpy(&zTemp[i], zColl, n+1);
  63322. i += n;
  63323. }
  63324. zTemp[i++] = ')';
  63325. zTemp[i] = 0;
  63326. assert( i<nTemp );
  63327. break;
  63328. }
  63329. case P4_COLLSEQ: {
  63330. CollSeq *pColl = pOp->p4.pColl;
  63331. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  63332. break;
  63333. }
  63334. case P4_FUNCDEF: {
  63335. FuncDef *pDef = pOp->p4.pFunc;
  63336. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  63337. break;
  63338. }
  63339. #ifdef SQLITE_DEBUG
  63340. case P4_FUNCCTX: {
  63341. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  63342. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  63343. break;
  63344. }
  63345. #endif
  63346. case P4_INT64: {
  63347. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  63348. break;
  63349. }
  63350. case P4_INT32: {
  63351. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  63352. break;
  63353. }
  63354. case P4_REAL: {
  63355. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  63356. break;
  63357. }
  63358. case P4_MEM: {
  63359. Mem *pMem = pOp->p4.pMem;
  63360. if( pMem->flags & MEM_Str ){
  63361. zP4 = pMem->z;
  63362. }else if( pMem->flags & MEM_Int ){
  63363. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  63364. }else if( pMem->flags & MEM_Real ){
  63365. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  63366. }else if( pMem->flags & MEM_Null ){
  63367. sqlite3_snprintf(nTemp, zTemp, "NULL");
  63368. }else{
  63369. assert( pMem->flags & MEM_Blob );
  63370. zP4 = "(blob)";
  63371. }
  63372. break;
  63373. }
  63374. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63375. case P4_VTAB: {
  63376. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  63377. sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
  63378. break;
  63379. }
  63380. #endif
  63381. case P4_INTARRAY: {
  63382. sqlite3_snprintf(nTemp, zTemp, "intarray");
  63383. break;
  63384. }
  63385. case P4_SUBPROGRAM: {
  63386. sqlite3_snprintf(nTemp, zTemp, "program");
  63387. break;
  63388. }
  63389. case P4_ADVANCE: {
  63390. zTemp[0] = 0;
  63391. break;
  63392. }
  63393. default: {
  63394. zP4 = pOp->p4.z;
  63395. if( zP4==0 ){
  63396. zP4 = zTemp;
  63397. zTemp[0] = 0;
  63398. }
  63399. }
  63400. }
  63401. assert( zP4!=0 );
  63402. return zP4;
  63403. }
  63404. #endif
  63405. /*
  63406. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  63407. **
  63408. ** The prepared statements need to know in advance the complete set of
  63409. ** attached databases that will be use. A mask of these databases
  63410. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  63411. ** p->btreeMask of databases that will require a lock.
  63412. */
  63413. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  63414. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  63415. assert( i<(int)sizeof(p->btreeMask)*8 );
  63416. DbMaskSet(p->btreeMask, i);
  63417. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  63418. DbMaskSet(p->lockMask, i);
  63419. }
  63420. }
  63421. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  63422. /*
  63423. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  63424. ** this routine obtains the mutex associated with each BtShared structure
  63425. ** that may be accessed by the VM passed as an argument. In doing so it also
  63426. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  63427. ** that the correct busy-handler callback is invoked if required.
  63428. **
  63429. ** If SQLite is not threadsafe but does support shared-cache mode, then
  63430. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  63431. ** of all of BtShared structures accessible via the database handle
  63432. ** associated with the VM.
  63433. **
  63434. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  63435. ** function is a no-op.
  63436. **
  63437. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  63438. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  63439. ** corresponding to btrees that use shared cache. Then the runtime of
  63440. ** this routine is N*N. But as N is rarely more than 1, this should not
  63441. ** be a problem.
  63442. */
  63443. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  63444. int i;
  63445. sqlite3 *db;
  63446. Db *aDb;
  63447. int nDb;
  63448. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  63449. db = p->db;
  63450. aDb = db->aDb;
  63451. nDb = db->nDb;
  63452. for(i=0; i<nDb; i++){
  63453. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  63454. sqlite3BtreeEnter(aDb[i].pBt);
  63455. }
  63456. }
  63457. }
  63458. #endif
  63459. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  63460. /*
  63461. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  63462. */
  63463. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  63464. int i;
  63465. sqlite3 *db;
  63466. Db *aDb;
  63467. int nDb;
  63468. db = p->db;
  63469. aDb = db->aDb;
  63470. nDb = db->nDb;
  63471. for(i=0; i<nDb; i++){
  63472. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  63473. sqlite3BtreeLeave(aDb[i].pBt);
  63474. }
  63475. }
  63476. }
  63477. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  63478. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  63479. vdbeLeave(p);
  63480. }
  63481. #endif
  63482. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  63483. /*
  63484. ** Print a single opcode. This routine is used for debugging only.
  63485. */
  63486. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  63487. char *zP4;
  63488. char zPtr[50];
  63489. char zCom[100];
  63490. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  63491. if( pOut==0 ) pOut = stdout;
  63492. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  63493. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63494. displayComment(pOp, zP4, zCom, sizeof(zCom));
  63495. #else
  63496. zCom[0] = 0;
  63497. #endif
  63498. /* NB: The sqlite3OpcodeName() function is implemented by code created
  63499. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  63500. ** information from the vdbe.c source text */
  63501. fprintf(pOut, zFormat1, pc,
  63502. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  63503. zCom
  63504. );
  63505. fflush(pOut);
  63506. }
  63507. #endif
  63508. /*
  63509. ** Release an array of N Mem elements
  63510. */
  63511. static void releaseMemArray(Mem *p, int N){
  63512. if( p && N ){
  63513. Mem *pEnd = &p[N];
  63514. sqlite3 *db = p->db;
  63515. u8 malloc_failed = db->mallocFailed;
  63516. if( db->pnBytesFreed ){
  63517. do{
  63518. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  63519. }while( (++p)<pEnd );
  63520. return;
  63521. }
  63522. do{
  63523. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  63524. assert( sqlite3VdbeCheckMemInvariants(p) );
  63525. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  63526. ** that takes advantage of the fact that the memory cell value is
  63527. ** being set to NULL after releasing any dynamic resources.
  63528. **
  63529. ** The justification for duplicating code is that according to
  63530. ** callgrind, this causes a certain test case to hit the CPU 4.7
  63531. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  63532. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  63533. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  63534. ** with no indexes using a single prepared INSERT statement, bind()
  63535. ** and reset(). Inserts are grouped into a transaction.
  63536. */
  63537. testcase( p->flags & MEM_Agg );
  63538. testcase( p->flags & MEM_Dyn );
  63539. testcase( p->flags & MEM_Frame );
  63540. testcase( p->flags & MEM_RowSet );
  63541. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  63542. sqlite3VdbeMemRelease(p);
  63543. }else if( p->szMalloc ){
  63544. sqlite3DbFree(db, p->zMalloc);
  63545. p->szMalloc = 0;
  63546. }
  63547. p->flags = MEM_Undefined;
  63548. }while( (++p)<pEnd );
  63549. db->mallocFailed = malloc_failed;
  63550. }
  63551. }
  63552. /*
  63553. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  63554. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  63555. */
  63556. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  63557. int i;
  63558. Mem *aMem = VdbeFrameMem(p);
  63559. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  63560. for(i=0; i<p->nChildCsr; i++){
  63561. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  63562. }
  63563. releaseMemArray(aMem, p->nChildMem);
  63564. sqlite3DbFree(p->v->db, p);
  63565. }
  63566. #ifndef SQLITE_OMIT_EXPLAIN
  63567. /*
  63568. ** Give a listing of the program in the virtual machine.
  63569. **
  63570. ** The interface is the same as sqlite3VdbeExec(). But instead of
  63571. ** running the code, it invokes the callback once for each instruction.
  63572. ** This feature is used to implement "EXPLAIN".
  63573. **
  63574. ** When p->explain==1, each instruction is listed. When
  63575. ** p->explain==2, only OP_Explain instructions are listed and these
  63576. ** are shown in a different format. p->explain==2 is used to implement
  63577. ** EXPLAIN QUERY PLAN.
  63578. **
  63579. ** When p->explain==1, first the main program is listed, then each of
  63580. ** the trigger subprograms are listed one by one.
  63581. */
  63582. SQLITE_PRIVATE int sqlite3VdbeList(
  63583. Vdbe *p /* The VDBE */
  63584. ){
  63585. int nRow; /* Stop when row count reaches this */
  63586. int nSub = 0; /* Number of sub-vdbes seen so far */
  63587. SubProgram **apSub = 0; /* Array of sub-vdbes */
  63588. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  63589. sqlite3 *db = p->db; /* The database connection */
  63590. int i; /* Loop counter */
  63591. int rc = SQLITE_OK; /* Return code */
  63592. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  63593. assert( p->explain );
  63594. assert( p->magic==VDBE_MAGIC_RUN );
  63595. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  63596. /* Even though this opcode does not use dynamic strings for
  63597. ** the result, result columns may become dynamic if the user calls
  63598. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  63599. */
  63600. releaseMemArray(pMem, 8);
  63601. p->pResultSet = 0;
  63602. if( p->rc==SQLITE_NOMEM ){
  63603. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  63604. ** sqlite3_column_text16() failed. */
  63605. db->mallocFailed = 1;
  63606. return SQLITE_ERROR;
  63607. }
  63608. /* When the number of output rows reaches nRow, that means the
  63609. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  63610. ** nRow is the sum of the number of rows in the main program, plus
  63611. ** the sum of the number of rows in all trigger subprograms encountered
  63612. ** so far. The nRow value will increase as new trigger subprograms are
  63613. ** encountered, but p->pc will eventually catch up to nRow.
  63614. */
  63615. nRow = p->nOp;
  63616. if( p->explain==1 ){
  63617. /* The first 8 memory cells are used for the result set. So we will
  63618. ** commandeer the 9th cell to use as storage for an array of pointers
  63619. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  63620. ** cells. */
  63621. assert( p->nMem>9 );
  63622. pSub = &p->aMem[9];
  63623. if( pSub->flags&MEM_Blob ){
  63624. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  63625. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  63626. nSub = pSub->n/sizeof(Vdbe*);
  63627. apSub = (SubProgram **)pSub->z;
  63628. }
  63629. for(i=0; i<nSub; i++){
  63630. nRow += apSub[i]->nOp;
  63631. }
  63632. }
  63633. do{
  63634. i = p->pc++;
  63635. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  63636. if( i>=nRow ){
  63637. p->rc = SQLITE_OK;
  63638. rc = SQLITE_DONE;
  63639. }else if( db->u1.isInterrupted ){
  63640. p->rc = SQLITE_INTERRUPT;
  63641. rc = SQLITE_ERROR;
  63642. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  63643. }else{
  63644. char *zP4;
  63645. Op *pOp;
  63646. if( i<p->nOp ){
  63647. /* The output line number is small enough that we are still in the
  63648. ** main program. */
  63649. pOp = &p->aOp[i];
  63650. }else{
  63651. /* We are currently listing subprograms. Figure out which one and
  63652. ** pick up the appropriate opcode. */
  63653. int j;
  63654. i -= p->nOp;
  63655. for(j=0; i>=apSub[j]->nOp; j++){
  63656. i -= apSub[j]->nOp;
  63657. }
  63658. pOp = &apSub[j]->aOp[i];
  63659. }
  63660. if( p->explain==1 ){
  63661. pMem->flags = MEM_Int;
  63662. pMem->u.i = i; /* Program counter */
  63663. pMem++;
  63664. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  63665. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  63666. assert( pMem->z!=0 );
  63667. pMem->n = sqlite3Strlen30(pMem->z);
  63668. pMem->enc = SQLITE_UTF8;
  63669. pMem++;
  63670. /* When an OP_Program opcode is encounter (the only opcode that has
  63671. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  63672. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  63673. ** has not already been seen.
  63674. */
  63675. if( pOp->p4type==P4_SUBPROGRAM ){
  63676. int nByte = (nSub+1)*sizeof(SubProgram*);
  63677. int j;
  63678. for(j=0; j<nSub; j++){
  63679. if( apSub[j]==pOp->p4.pProgram ) break;
  63680. }
  63681. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  63682. apSub = (SubProgram **)pSub->z;
  63683. apSub[nSub++] = pOp->p4.pProgram;
  63684. pSub->flags |= MEM_Blob;
  63685. pSub->n = nSub*sizeof(SubProgram*);
  63686. }
  63687. }
  63688. }
  63689. pMem->flags = MEM_Int;
  63690. pMem->u.i = pOp->p1; /* P1 */
  63691. pMem++;
  63692. pMem->flags = MEM_Int;
  63693. pMem->u.i = pOp->p2; /* P2 */
  63694. pMem++;
  63695. pMem->flags = MEM_Int;
  63696. pMem->u.i = pOp->p3; /* P3 */
  63697. pMem++;
  63698. if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
  63699. assert( p->db->mallocFailed );
  63700. return SQLITE_ERROR;
  63701. }
  63702. pMem->flags = MEM_Str|MEM_Term;
  63703. zP4 = displayP4(pOp, pMem->z, 32);
  63704. if( zP4!=pMem->z ){
  63705. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  63706. }else{
  63707. assert( pMem->z!=0 );
  63708. pMem->n = sqlite3Strlen30(pMem->z);
  63709. pMem->enc = SQLITE_UTF8;
  63710. }
  63711. pMem++;
  63712. if( p->explain==1 ){
  63713. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  63714. assert( p->db->mallocFailed );
  63715. return SQLITE_ERROR;
  63716. }
  63717. pMem->flags = MEM_Str|MEM_Term;
  63718. pMem->n = 2;
  63719. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  63720. pMem->enc = SQLITE_UTF8;
  63721. pMem++;
  63722. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63723. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  63724. assert( p->db->mallocFailed );
  63725. return SQLITE_ERROR;
  63726. }
  63727. pMem->flags = MEM_Str|MEM_Term;
  63728. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  63729. pMem->enc = SQLITE_UTF8;
  63730. #else
  63731. pMem->flags = MEM_Null; /* Comment */
  63732. #endif
  63733. }
  63734. p->nResColumn = 8 - 4*(p->explain-1);
  63735. p->pResultSet = &p->aMem[1];
  63736. p->rc = SQLITE_OK;
  63737. rc = SQLITE_ROW;
  63738. }
  63739. return rc;
  63740. }
  63741. #endif /* SQLITE_OMIT_EXPLAIN */
  63742. #ifdef SQLITE_DEBUG
  63743. /*
  63744. ** Print the SQL that was used to generate a VDBE program.
  63745. */
  63746. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  63747. const char *z = 0;
  63748. if( p->zSql ){
  63749. z = p->zSql;
  63750. }else if( p->nOp>=1 ){
  63751. const VdbeOp *pOp = &p->aOp[0];
  63752. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  63753. z = pOp->p4.z;
  63754. while( sqlite3Isspace(*z) ) z++;
  63755. }
  63756. }
  63757. if( z ) printf("SQL: [%s]\n", z);
  63758. }
  63759. #endif
  63760. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  63761. /*
  63762. ** Print an IOTRACE message showing SQL content.
  63763. */
  63764. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  63765. int nOp = p->nOp;
  63766. VdbeOp *pOp;
  63767. if( sqlite3IoTrace==0 ) return;
  63768. if( nOp<1 ) return;
  63769. pOp = &p->aOp[0];
  63770. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  63771. int i, j;
  63772. char z[1000];
  63773. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  63774. for(i=0; sqlite3Isspace(z[i]); i++){}
  63775. for(j=0; z[i]; i++){
  63776. if( sqlite3Isspace(z[i]) ){
  63777. if( z[i-1]!=' ' ){
  63778. z[j++] = ' ';
  63779. }
  63780. }else{
  63781. z[j++] = z[i];
  63782. }
  63783. }
  63784. z[j] = 0;
  63785. sqlite3IoTrace("SQL %s\n", z);
  63786. }
  63787. }
  63788. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  63789. /*
  63790. ** Allocate space from a fixed size buffer and return a pointer to
  63791. ** that space. If insufficient space is available, return NULL.
  63792. **
  63793. ** The pBuf parameter is the initial value of a pointer which will
  63794. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  63795. ** NULL, it means that memory space has already been allocated and that
  63796. ** this routine should not allocate any new memory. When pBuf is not
  63797. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  63798. ** is NULL.
  63799. **
  63800. ** nByte is the number of bytes of space needed.
  63801. **
  63802. ** *ppFrom points to available space and pEnd points to the end of the
  63803. ** available space. When space is allocated, *ppFrom is advanced past
  63804. ** the end of the allocated space.
  63805. **
  63806. ** *pnByte is a counter of the number of bytes of space that have failed
  63807. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  63808. ** request, then increment *pnByte by the amount of the request.
  63809. */
  63810. static void *allocSpace(
  63811. void *pBuf, /* Where return pointer will be stored */
  63812. int nByte, /* Number of bytes to allocate */
  63813. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  63814. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  63815. int *pnByte /* If allocation cannot be made, increment *pnByte */
  63816. ){
  63817. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  63818. if( pBuf ) return pBuf;
  63819. nByte = ROUND8(nByte);
  63820. if( &(*ppFrom)[nByte] <= pEnd ){
  63821. pBuf = (void*)*ppFrom;
  63822. *ppFrom += nByte;
  63823. }else{
  63824. *pnByte += nByte;
  63825. }
  63826. return pBuf;
  63827. }
  63828. /*
  63829. ** Rewind the VDBE back to the beginning in preparation for
  63830. ** running it.
  63831. */
  63832. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  63833. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  63834. int i;
  63835. #endif
  63836. assert( p!=0 );
  63837. assert( p->magic==VDBE_MAGIC_INIT );
  63838. /* There should be at least one opcode.
  63839. */
  63840. assert( p->nOp>0 );
  63841. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  63842. p->magic = VDBE_MAGIC_RUN;
  63843. #ifdef SQLITE_DEBUG
  63844. for(i=1; i<p->nMem; i++){
  63845. assert( p->aMem[i].db==p->db );
  63846. }
  63847. #endif
  63848. p->pc = -1;
  63849. p->rc = SQLITE_OK;
  63850. p->errorAction = OE_Abort;
  63851. p->magic = VDBE_MAGIC_RUN;
  63852. p->nChange = 0;
  63853. p->cacheCtr = 1;
  63854. p->minWriteFileFormat = 255;
  63855. p->iStatement = 0;
  63856. p->nFkConstraint = 0;
  63857. #ifdef VDBE_PROFILE
  63858. for(i=0; i<p->nOp; i++){
  63859. p->aOp[i].cnt = 0;
  63860. p->aOp[i].cycles = 0;
  63861. }
  63862. #endif
  63863. }
  63864. /*
  63865. ** Prepare a virtual machine for execution for the first time after
  63866. ** creating the virtual machine. This involves things such
  63867. ** as allocating registers and initializing the program counter.
  63868. ** After the VDBE has be prepped, it can be executed by one or more
  63869. ** calls to sqlite3VdbeExec().
  63870. **
  63871. ** This function may be called exactly once on each virtual machine.
  63872. ** After this routine is called the VM has been "packaged" and is ready
  63873. ** to run. After this routine is called, further calls to
  63874. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  63875. ** the Vdbe from the Parse object that helped generate it so that the
  63876. ** the Vdbe becomes an independent entity and the Parse object can be
  63877. ** destroyed.
  63878. **
  63879. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  63880. ** to its initial state after it has been run.
  63881. */
  63882. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  63883. Vdbe *p, /* The VDBE */
  63884. Parse *pParse /* Parsing context */
  63885. ){
  63886. sqlite3 *db; /* The database connection */
  63887. int nVar; /* Number of parameters */
  63888. int nMem; /* Number of VM memory registers */
  63889. int nCursor; /* Number of cursors required */
  63890. int nArg; /* Number of arguments in subprograms */
  63891. int nOnce; /* Number of OP_Once instructions */
  63892. int n; /* Loop counter */
  63893. u8 *zCsr; /* Memory available for allocation */
  63894. u8 *zEnd; /* First byte past allocated memory */
  63895. int nByte; /* How much extra memory is needed */
  63896. assert( p!=0 );
  63897. assert( p->nOp>0 );
  63898. assert( pParse!=0 );
  63899. assert( p->magic==VDBE_MAGIC_INIT );
  63900. assert( pParse==p->pParse );
  63901. db = p->db;
  63902. assert( db->mallocFailed==0 );
  63903. nVar = pParse->nVar;
  63904. nMem = pParse->nMem;
  63905. nCursor = pParse->nTab;
  63906. nArg = pParse->nMaxArg;
  63907. nOnce = pParse->nOnce;
  63908. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  63909. /* For each cursor required, also allocate a memory cell. Memory
  63910. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  63911. ** the vdbe program. Instead they are used to allocate space for
  63912. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  63913. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  63914. ** stores the blob of memory associated with cursor 1, etc.
  63915. **
  63916. ** See also: allocateCursor().
  63917. */
  63918. nMem += nCursor;
  63919. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  63920. ** an array to marshal SQL function arguments in.
  63921. */
  63922. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  63923. zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
  63924. resolveP2Values(p, &nArg);
  63925. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  63926. if( pParse->explain && nMem<10 ){
  63927. nMem = 10;
  63928. }
  63929. memset(zCsr, 0, zEnd-zCsr);
  63930. zCsr += (zCsr - (u8*)0)&7;
  63931. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  63932. p->expired = 0;
  63933. /* Memory for registers, parameters, cursor, etc, is allocated in two
  63934. ** passes. On the first pass, we try to reuse unused space at the
  63935. ** end of the opcode array. If we are unable to satisfy all memory
  63936. ** requirements by reusing the opcode array tail, then the second
  63937. ** pass will fill in the rest using a fresh allocation.
  63938. **
  63939. ** This two-pass approach that reuses as much memory as possible from
  63940. ** the leftover space at the end of the opcode array can significantly
  63941. ** reduce the amount of memory held by a prepared statement.
  63942. */
  63943. do {
  63944. nByte = 0;
  63945. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  63946. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  63947. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  63948. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  63949. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  63950. &zCsr, zEnd, &nByte);
  63951. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  63952. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  63953. p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
  63954. #endif
  63955. if( nByte ){
  63956. p->pFree = sqlite3DbMallocZero(db, nByte);
  63957. }
  63958. zCsr = p->pFree;
  63959. zEnd = &zCsr[nByte];
  63960. }while( nByte && !db->mallocFailed );
  63961. p->nCursor = nCursor;
  63962. p->nOnceFlag = nOnce;
  63963. if( p->aVar ){
  63964. p->nVar = (ynVar)nVar;
  63965. for(n=0; n<nVar; n++){
  63966. p->aVar[n].flags = MEM_Null;
  63967. p->aVar[n].db = db;
  63968. }
  63969. }
  63970. if( p->azVar && pParse->nzVar>0 ){
  63971. p->nzVar = pParse->nzVar;
  63972. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  63973. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  63974. }
  63975. if( p->aMem ){
  63976. p->aMem--; /* aMem[] goes from 1..nMem */
  63977. p->nMem = nMem; /* not from 0..nMem-1 */
  63978. for(n=1; n<=nMem; n++){
  63979. p->aMem[n].flags = MEM_Undefined;
  63980. p->aMem[n].db = db;
  63981. }
  63982. }
  63983. p->explain = pParse->explain;
  63984. sqlite3VdbeRewind(p);
  63985. }
  63986. /*
  63987. ** Close a VDBE cursor and release all the resources that cursor
  63988. ** happens to hold.
  63989. */
  63990. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  63991. if( pCx==0 ){
  63992. return;
  63993. }
  63994. sqlite3VdbeSorterClose(p->db, pCx);
  63995. if( pCx->pBt ){
  63996. sqlite3BtreeClose(pCx->pBt);
  63997. /* The pCx->pCursor will be close automatically, if it exists, by
  63998. ** the call above. */
  63999. }else if( pCx->pCursor ){
  64000. sqlite3BtreeCloseCursor(pCx->pCursor);
  64001. }
  64002. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64003. else if( pCx->pVtabCursor ){
  64004. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  64005. const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
  64006. assert( pVtabCursor->pVtab->nRef>0 );
  64007. pVtabCursor->pVtab->nRef--;
  64008. pModule->xClose(pVtabCursor);
  64009. }
  64010. #endif
  64011. }
  64012. /*
  64013. ** Close all cursors in the current frame.
  64014. */
  64015. static void closeCursorsInFrame(Vdbe *p){
  64016. if( p->apCsr ){
  64017. int i;
  64018. for(i=0; i<p->nCursor; i++){
  64019. VdbeCursor *pC = p->apCsr[i];
  64020. if( pC ){
  64021. sqlite3VdbeFreeCursor(p, pC);
  64022. p->apCsr[i] = 0;
  64023. }
  64024. }
  64025. }
  64026. }
  64027. /*
  64028. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  64029. ** is used, for example, when a trigger sub-program is halted to restore
  64030. ** control to the main program.
  64031. */
  64032. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  64033. Vdbe *v = pFrame->v;
  64034. closeCursorsInFrame(v);
  64035. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  64036. v->anExec = pFrame->anExec;
  64037. #endif
  64038. v->aOnceFlag = pFrame->aOnceFlag;
  64039. v->nOnceFlag = pFrame->nOnceFlag;
  64040. v->aOp = pFrame->aOp;
  64041. v->nOp = pFrame->nOp;
  64042. v->aMem = pFrame->aMem;
  64043. v->nMem = pFrame->nMem;
  64044. v->apCsr = pFrame->apCsr;
  64045. v->nCursor = pFrame->nCursor;
  64046. v->db->lastRowid = pFrame->lastRowid;
  64047. v->nChange = pFrame->nChange;
  64048. v->db->nChange = pFrame->nDbChange;
  64049. return pFrame->pc;
  64050. }
  64051. /*
  64052. ** Close all cursors.
  64053. **
  64054. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  64055. ** cell array. This is necessary as the memory cell array may contain
  64056. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  64057. ** open cursors.
  64058. */
  64059. static void closeAllCursors(Vdbe *p){
  64060. if( p->pFrame ){
  64061. VdbeFrame *pFrame;
  64062. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  64063. sqlite3VdbeFrameRestore(pFrame);
  64064. p->pFrame = 0;
  64065. p->nFrame = 0;
  64066. }
  64067. assert( p->nFrame==0 );
  64068. closeCursorsInFrame(p);
  64069. if( p->aMem ){
  64070. releaseMemArray(&p->aMem[1], p->nMem);
  64071. }
  64072. while( p->pDelFrame ){
  64073. VdbeFrame *pDel = p->pDelFrame;
  64074. p->pDelFrame = pDel->pParent;
  64075. sqlite3VdbeFrameDelete(pDel);
  64076. }
  64077. /* Delete any auxdata allocations made by the VM */
  64078. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  64079. assert( p->pAuxData==0 );
  64080. }
  64081. /*
  64082. ** Clean up the VM after a single run.
  64083. */
  64084. static void Cleanup(Vdbe *p){
  64085. sqlite3 *db = p->db;
  64086. #ifdef SQLITE_DEBUG
  64087. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  64088. ** Vdbe.aMem[] arrays have already been cleaned up. */
  64089. int i;
  64090. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  64091. if( p->aMem ){
  64092. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  64093. }
  64094. #endif
  64095. sqlite3DbFree(db, p->zErrMsg);
  64096. p->zErrMsg = 0;
  64097. p->pResultSet = 0;
  64098. }
  64099. /*
  64100. ** Set the number of result columns that will be returned by this SQL
  64101. ** statement. This is now set at compile time, rather than during
  64102. ** execution of the vdbe program so that sqlite3_column_count() can
  64103. ** be called on an SQL statement before sqlite3_step().
  64104. */
  64105. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  64106. Mem *pColName;
  64107. int n;
  64108. sqlite3 *db = p->db;
  64109. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  64110. sqlite3DbFree(db, p->aColName);
  64111. n = nResColumn*COLNAME_N;
  64112. p->nResColumn = (u16)nResColumn;
  64113. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  64114. if( p->aColName==0 ) return;
  64115. while( n-- > 0 ){
  64116. pColName->flags = MEM_Null;
  64117. pColName->db = p->db;
  64118. pColName++;
  64119. }
  64120. }
  64121. /*
  64122. ** Set the name of the idx'th column to be returned by the SQL statement.
  64123. ** zName must be a pointer to a nul terminated string.
  64124. **
  64125. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  64126. **
  64127. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  64128. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  64129. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  64130. */
  64131. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  64132. Vdbe *p, /* Vdbe being configured */
  64133. int idx, /* Index of column zName applies to */
  64134. int var, /* One of the COLNAME_* constants */
  64135. const char *zName, /* Pointer to buffer containing name */
  64136. void (*xDel)(void*) /* Memory management strategy for zName */
  64137. ){
  64138. int rc;
  64139. Mem *pColName;
  64140. assert( idx<p->nResColumn );
  64141. assert( var<COLNAME_N );
  64142. if( p->db->mallocFailed ){
  64143. assert( !zName || xDel!=SQLITE_DYNAMIC );
  64144. return SQLITE_NOMEM;
  64145. }
  64146. assert( p->aColName!=0 );
  64147. pColName = &(p->aColName[idx+var*p->nResColumn]);
  64148. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  64149. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  64150. return rc;
  64151. }
  64152. /*
  64153. ** A read or write transaction may or may not be active on database handle
  64154. ** db. If a transaction is active, commit it. If there is a
  64155. ** write-transaction spanning more than one database file, this routine
  64156. ** takes care of the master journal trickery.
  64157. */
  64158. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  64159. int i;
  64160. int nTrans = 0; /* Number of databases with an active write-transaction */
  64161. int rc = SQLITE_OK;
  64162. int needXcommit = 0;
  64163. #ifdef SQLITE_OMIT_VIRTUALTABLE
  64164. /* With this option, sqlite3VtabSync() is defined to be simply
  64165. ** SQLITE_OK so p is not used.
  64166. */
  64167. UNUSED_PARAMETER(p);
  64168. #endif
  64169. /* Before doing anything else, call the xSync() callback for any
  64170. ** virtual module tables written in this transaction. This has to
  64171. ** be done before determining whether a master journal file is
  64172. ** required, as an xSync() callback may add an attached database
  64173. ** to the transaction.
  64174. */
  64175. rc = sqlite3VtabSync(db, p);
  64176. /* This loop determines (a) if the commit hook should be invoked and
  64177. ** (b) how many database files have open write transactions, not
  64178. ** including the temp database. (b) is important because if more than
  64179. ** one database file has an open write transaction, a master journal
  64180. ** file is required for an atomic commit.
  64181. */
  64182. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64183. Btree *pBt = db->aDb[i].pBt;
  64184. if( sqlite3BtreeIsInTrans(pBt) ){
  64185. needXcommit = 1;
  64186. if( i!=1 ) nTrans++;
  64187. sqlite3BtreeEnter(pBt);
  64188. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  64189. sqlite3BtreeLeave(pBt);
  64190. }
  64191. }
  64192. if( rc!=SQLITE_OK ){
  64193. return rc;
  64194. }
  64195. /* If there are any write-transactions at all, invoke the commit hook */
  64196. if( needXcommit && db->xCommitCallback ){
  64197. rc = db->xCommitCallback(db->pCommitArg);
  64198. if( rc ){
  64199. return SQLITE_CONSTRAINT_COMMITHOOK;
  64200. }
  64201. }
  64202. /* The simple case - no more than one database file (not counting the
  64203. ** TEMP database) has a transaction active. There is no need for the
  64204. ** master-journal.
  64205. **
  64206. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  64207. ** string, it means the main database is :memory: or a temp file. In
  64208. ** that case we do not support atomic multi-file commits, so use the
  64209. ** simple case then too.
  64210. */
  64211. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  64212. || nTrans<=1
  64213. ){
  64214. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64215. Btree *pBt = db->aDb[i].pBt;
  64216. if( pBt ){
  64217. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  64218. }
  64219. }
  64220. /* Do the commit only if all databases successfully complete phase 1.
  64221. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  64222. ** IO error while deleting or truncating a journal file. It is unlikely,
  64223. ** but could happen. In this case abandon processing and return the error.
  64224. */
  64225. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64226. Btree *pBt = db->aDb[i].pBt;
  64227. if( pBt ){
  64228. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  64229. }
  64230. }
  64231. if( rc==SQLITE_OK ){
  64232. sqlite3VtabCommit(db);
  64233. }
  64234. }
  64235. /* The complex case - There is a multi-file write-transaction active.
  64236. ** This requires a master journal file to ensure the transaction is
  64237. ** committed atomically.
  64238. */
  64239. #ifndef SQLITE_OMIT_DISKIO
  64240. else{
  64241. sqlite3_vfs *pVfs = db->pVfs;
  64242. int needSync = 0;
  64243. char *zMaster = 0; /* File-name for the master journal */
  64244. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  64245. sqlite3_file *pMaster = 0;
  64246. i64 offset = 0;
  64247. int res;
  64248. int retryCount = 0;
  64249. int nMainFile;
  64250. /* Select a master journal file name */
  64251. nMainFile = sqlite3Strlen30(zMainFile);
  64252. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  64253. if( zMaster==0 ) return SQLITE_NOMEM;
  64254. do {
  64255. u32 iRandom;
  64256. if( retryCount ){
  64257. if( retryCount>100 ){
  64258. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  64259. sqlite3OsDelete(pVfs, zMaster, 0);
  64260. break;
  64261. }else if( retryCount==1 ){
  64262. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  64263. }
  64264. }
  64265. retryCount++;
  64266. sqlite3_randomness(sizeof(iRandom), &iRandom);
  64267. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  64268. (iRandom>>8)&0xffffff, iRandom&0xff);
  64269. /* The antipenultimate character of the master journal name must
  64270. ** be "9" to avoid name collisions when using 8+3 filenames. */
  64271. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  64272. sqlite3FileSuffix3(zMainFile, zMaster);
  64273. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  64274. }while( rc==SQLITE_OK && res );
  64275. if( rc==SQLITE_OK ){
  64276. /* Open the master journal. */
  64277. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  64278. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  64279. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  64280. );
  64281. }
  64282. if( rc!=SQLITE_OK ){
  64283. sqlite3DbFree(db, zMaster);
  64284. return rc;
  64285. }
  64286. /* Write the name of each database file in the transaction into the new
  64287. ** master journal file. If an error occurs at this point close
  64288. ** and delete the master journal file. All the individual journal files
  64289. ** still have 'null' as the master journal pointer, so they will roll
  64290. ** back independently if a failure occurs.
  64291. */
  64292. for(i=0; i<db->nDb; i++){
  64293. Btree *pBt = db->aDb[i].pBt;
  64294. if( sqlite3BtreeIsInTrans(pBt) ){
  64295. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  64296. if( zFile==0 ){
  64297. continue; /* Ignore TEMP and :memory: databases */
  64298. }
  64299. assert( zFile[0]!=0 );
  64300. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  64301. needSync = 1;
  64302. }
  64303. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  64304. offset += sqlite3Strlen30(zFile)+1;
  64305. if( rc!=SQLITE_OK ){
  64306. sqlite3OsCloseFree(pMaster);
  64307. sqlite3OsDelete(pVfs, zMaster, 0);
  64308. sqlite3DbFree(db, zMaster);
  64309. return rc;
  64310. }
  64311. }
  64312. }
  64313. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  64314. ** flag is set this is not required.
  64315. */
  64316. if( needSync
  64317. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  64318. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  64319. ){
  64320. sqlite3OsCloseFree(pMaster);
  64321. sqlite3OsDelete(pVfs, zMaster, 0);
  64322. sqlite3DbFree(db, zMaster);
  64323. return rc;
  64324. }
  64325. /* Sync all the db files involved in the transaction. The same call
  64326. ** sets the master journal pointer in each individual journal. If
  64327. ** an error occurs here, do not delete the master journal file.
  64328. **
  64329. ** If the error occurs during the first call to
  64330. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  64331. ** master journal file will be orphaned. But we cannot delete it,
  64332. ** in case the master journal file name was written into the journal
  64333. ** file before the failure occurred.
  64334. */
  64335. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64336. Btree *pBt = db->aDb[i].pBt;
  64337. if( pBt ){
  64338. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  64339. }
  64340. }
  64341. sqlite3OsCloseFree(pMaster);
  64342. assert( rc!=SQLITE_BUSY );
  64343. if( rc!=SQLITE_OK ){
  64344. sqlite3DbFree(db, zMaster);
  64345. return rc;
  64346. }
  64347. /* Delete the master journal file. This commits the transaction. After
  64348. ** doing this the directory is synced again before any individual
  64349. ** transaction files are deleted.
  64350. */
  64351. rc = sqlite3OsDelete(pVfs, zMaster, needSync);
  64352. sqlite3DbFree(db, zMaster);
  64353. zMaster = 0;
  64354. if( rc ){
  64355. return rc;
  64356. }
  64357. /* All files and directories have already been synced, so the following
  64358. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  64359. ** deleting or truncating journals. If something goes wrong while
  64360. ** this is happening we don't really care. The integrity of the
  64361. ** transaction is already guaranteed, but some stray 'cold' journals
  64362. ** may be lying around. Returning an error code won't help matters.
  64363. */
  64364. disable_simulated_io_errors();
  64365. sqlite3BeginBenignMalloc();
  64366. for(i=0; i<db->nDb; i++){
  64367. Btree *pBt = db->aDb[i].pBt;
  64368. if( pBt ){
  64369. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  64370. }
  64371. }
  64372. sqlite3EndBenignMalloc();
  64373. enable_simulated_io_errors();
  64374. sqlite3VtabCommit(db);
  64375. }
  64376. #endif
  64377. return rc;
  64378. }
  64379. /*
  64380. ** This routine checks that the sqlite3.nVdbeActive count variable
  64381. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  64382. ** currently active. An assertion fails if the two counts do not match.
  64383. ** This is an internal self-check only - it is not an essential processing
  64384. ** step.
  64385. **
  64386. ** This is a no-op if NDEBUG is defined.
  64387. */
  64388. #ifndef NDEBUG
  64389. static void checkActiveVdbeCnt(sqlite3 *db){
  64390. Vdbe *p;
  64391. int cnt = 0;
  64392. int nWrite = 0;
  64393. int nRead = 0;
  64394. p = db->pVdbe;
  64395. while( p ){
  64396. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  64397. cnt++;
  64398. if( p->readOnly==0 ) nWrite++;
  64399. if( p->bIsReader ) nRead++;
  64400. }
  64401. p = p->pNext;
  64402. }
  64403. assert( cnt==db->nVdbeActive );
  64404. assert( nWrite==db->nVdbeWrite );
  64405. assert( nRead==db->nVdbeRead );
  64406. }
  64407. #else
  64408. #define checkActiveVdbeCnt(x)
  64409. #endif
  64410. /*
  64411. ** If the Vdbe passed as the first argument opened a statement-transaction,
  64412. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  64413. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  64414. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  64415. ** statement transaction is committed.
  64416. **
  64417. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  64418. ** Otherwise SQLITE_OK.
  64419. */
  64420. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  64421. sqlite3 *const db = p->db;
  64422. int rc = SQLITE_OK;
  64423. /* If p->iStatement is greater than zero, then this Vdbe opened a
  64424. ** statement transaction that should be closed here. The only exception
  64425. ** is that an IO error may have occurred, causing an emergency rollback.
  64426. ** In this case (db->nStatement==0), and there is nothing to do.
  64427. */
  64428. if( db->nStatement && p->iStatement ){
  64429. int i;
  64430. const int iSavepoint = p->iStatement-1;
  64431. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  64432. assert( db->nStatement>0 );
  64433. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  64434. for(i=0; i<db->nDb; i++){
  64435. int rc2 = SQLITE_OK;
  64436. Btree *pBt = db->aDb[i].pBt;
  64437. if( pBt ){
  64438. if( eOp==SAVEPOINT_ROLLBACK ){
  64439. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  64440. }
  64441. if( rc2==SQLITE_OK ){
  64442. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  64443. }
  64444. if( rc==SQLITE_OK ){
  64445. rc = rc2;
  64446. }
  64447. }
  64448. }
  64449. db->nStatement--;
  64450. p->iStatement = 0;
  64451. if( rc==SQLITE_OK ){
  64452. if( eOp==SAVEPOINT_ROLLBACK ){
  64453. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  64454. }
  64455. if( rc==SQLITE_OK ){
  64456. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  64457. }
  64458. }
  64459. /* If the statement transaction is being rolled back, also restore the
  64460. ** database handles deferred constraint counter to the value it had when
  64461. ** the statement transaction was opened. */
  64462. if( eOp==SAVEPOINT_ROLLBACK ){
  64463. db->nDeferredCons = p->nStmtDefCons;
  64464. db->nDeferredImmCons = p->nStmtDefImmCons;
  64465. }
  64466. }
  64467. return rc;
  64468. }
  64469. /*
  64470. ** This function is called when a transaction opened by the database
  64471. ** handle associated with the VM passed as an argument is about to be
  64472. ** committed. If there are outstanding deferred foreign key constraint
  64473. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  64474. **
  64475. ** If there are outstanding FK violations and this function returns
  64476. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  64477. ** and write an error message to it. Then return SQLITE_ERROR.
  64478. */
  64479. #ifndef SQLITE_OMIT_FOREIGN_KEY
  64480. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  64481. sqlite3 *db = p->db;
  64482. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  64483. || (!deferred && p->nFkConstraint>0)
  64484. ){
  64485. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  64486. p->errorAction = OE_Abort;
  64487. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  64488. return SQLITE_ERROR;
  64489. }
  64490. return SQLITE_OK;
  64491. }
  64492. #endif
  64493. /*
  64494. ** This routine is called the when a VDBE tries to halt. If the VDBE
  64495. ** has made changes and is in autocommit mode, then commit those
  64496. ** changes. If a rollback is needed, then do the rollback.
  64497. **
  64498. ** This routine is the only way to move the state of a VM from
  64499. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  64500. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  64501. **
  64502. ** Return an error code. If the commit could not complete because of
  64503. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  64504. ** means the close did not happen and needs to be repeated.
  64505. */
  64506. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  64507. int rc; /* Used to store transient return codes */
  64508. sqlite3 *db = p->db;
  64509. /* This function contains the logic that determines if a statement or
  64510. ** transaction will be committed or rolled back as a result of the
  64511. ** execution of this virtual machine.
  64512. **
  64513. ** If any of the following errors occur:
  64514. **
  64515. ** SQLITE_NOMEM
  64516. ** SQLITE_IOERR
  64517. ** SQLITE_FULL
  64518. ** SQLITE_INTERRUPT
  64519. **
  64520. ** Then the internal cache might have been left in an inconsistent
  64521. ** state. We need to rollback the statement transaction, if there is
  64522. ** one, or the complete transaction if there is no statement transaction.
  64523. */
  64524. if( p->db->mallocFailed ){
  64525. p->rc = SQLITE_NOMEM;
  64526. }
  64527. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  64528. closeAllCursors(p);
  64529. if( p->magic!=VDBE_MAGIC_RUN ){
  64530. return SQLITE_OK;
  64531. }
  64532. checkActiveVdbeCnt(db);
  64533. /* No commit or rollback needed if the program never started or if the
  64534. ** SQL statement does not read or write a database file. */
  64535. if( p->pc>=0 && p->bIsReader ){
  64536. int mrc; /* Primary error code from p->rc */
  64537. int eStatementOp = 0;
  64538. int isSpecialError; /* Set to true if a 'special' error */
  64539. /* Lock all btrees used by the statement */
  64540. sqlite3VdbeEnter(p);
  64541. /* Check for one of the special errors */
  64542. mrc = p->rc & 0xff;
  64543. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  64544. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  64545. if( isSpecialError ){
  64546. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  64547. ** no rollback is necessary. Otherwise, at least a savepoint
  64548. ** transaction must be rolled back to restore the database to a
  64549. ** consistent state.
  64550. **
  64551. ** Even if the statement is read-only, it is important to perform
  64552. ** a statement or transaction rollback operation. If the error
  64553. ** occurred while writing to the journal, sub-journal or database
  64554. ** file as part of an effort to free up cache space (see function
  64555. ** pagerStress() in pager.c), the rollback is required to restore
  64556. ** the pager to a consistent state.
  64557. */
  64558. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  64559. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  64560. eStatementOp = SAVEPOINT_ROLLBACK;
  64561. }else{
  64562. /* We are forced to roll back the active transaction. Before doing
  64563. ** so, abort any other statements this handle currently has active.
  64564. */
  64565. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  64566. sqlite3CloseSavepoints(db);
  64567. db->autoCommit = 1;
  64568. p->nChange = 0;
  64569. }
  64570. }
  64571. }
  64572. /* Check for immediate foreign key violations. */
  64573. if( p->rc==SQLITE_OK ){
  64574. sqlite3VdbeCheckFk(p, 0);
  64575. }
  64576. /* If the auto-commit flag is set and this is the only active writer
  64577. ** VM, then we do either a commit or rollback of the current transaction.
  64578. **
  64579. ** Note: This block also runs if one of the special errors handled
  64580. ** above has occurred.
  64581. */
  64582. if( !sqlite3VtabInSync(db)
  64583. && db->autoCommit
  64584. && db->nVdbeWrite==(p->readOnly==0)
  64585. ){
  64586. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  64587. rc = sqlite3VdbeCheckFk(p, 1);
  64588. if( rc!=SQLITE_OK ){
  64589. if( NEVER(p->readOnly) ){
  64590. sqlite3VdbeLeave(p);
  64591. return SQLITE_ERROR;
  64592. }
  64593. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  64594. }else{
  64595. /* The auto-commit flag is true, the vdbe program was successful
  64596. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  64597. ** key constraints to hold up the transaction. This means a commit
  64598. ** is required. */
  64599. rc = vdbeCommit(db, p);
  64600. }
  64601. if( rc==SQLITE_BUSY && p->readOnly ){
  64602. sqlite3VdbeLeave(p);
  64603. return SQLITE_BUSY;
  64604. }else if( rc!=SQLITE_OK ){
  64605. p->rc = rc;
  64606. sqlite3RollbackAll(db, SQLITE_OK);
  64607. p->nChange = 0;
  64608. }else{
  64609. db->nDeferredCons = 0;
  64610. db->nDeferredImmCons = 0;
  64611. db->flags &= ~SQLITE_DeferFKs;
  64612. sqlite3CommitInternalChanges(db);
  64613. }
  64614. }else{
  64615. sqlite3RollbackAll(db, SQLITE_OK);
  64616. p->nChange = 0;
  64617. }
  64618. db->nStatement = 0;
  64619. }else if( eStatementOp==0 ){
  64620. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  64621. eStatementOp = SAVEPOINT_RELEASE;
  64622. }else if( p->errorAction==OE_Abort ){
  64623. eStatementOp = SAVEPOINT_ROLLBACK;
  64624. }else{
  64625. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  64626. sqlite3CloseSavepoints(db);
  64627. db->autoCommit = 1;
  64628. p->nChange = 0;
  64629. }
  64630. }
  64631. /* If eStatementOp is non-zero, then a statement transaction needs to
  64632. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  64633. ** do so. If this operation returns an error, and the current statement
  64634. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  64635. ** current statement error code.
  64636. */
  64637. if( eStatementOp ){
  64638. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  64639. if( rc ){
  64640. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  64641. p->rc = rc;
  64642. sqlite3DbFree(db, p->zErrMsg);
  64643. p->zErrMsg = 0;
  64644. }
  64645. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  64646. sqlite3CloseSavepoints(db);
  64647. db->autoCommit = 1;
  64648. p->nChange = 0;
  64649. }
  64650. }
  64651. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  64652. ** has been rolled back, update the database connection change-counter.
  64653. */
  64654. if( p->changeCntOn ){
  64655. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  64656. sqlite3VdbeSetChanges(db, p->nChange);
  64657. }else{
  64658. sqlite3VdbeSetChanges(db, 0);
  64659. }
  64660. p->nChange = 0;
  64661. }
  64662. /* Release the locks */
  64663. sqlite3VdbeLeave(p);
  64664. }
  64665. /* We have successfully halted and closed the VM. Record this fact. */
  64666. if( p->pc>=0 ){
  64667. db->nVdbeActive--;
  64668. if( !p->readOnly ) db->nVdbeWrite--;
  64669. if( p->bIsReader ) db->nVdbeRead--;
  64670. assert( db->nVdbeActive>=db->nVdbeRead );
  64671. assert( db->nVdbeRead>=db->nVdbeWrite );
  64672. assert( db->nVdbeWrite>=0 );
  64673. }
  64674. p->magic = VDBE_MAGIC_HALT;
  64675. checkActiveVdbeCnt(db);
  64676. if( p->db->mallocFailed ){
  64677. p->rc = SQLITE_NOMEM;
  64678. }
  64679. /* If the auto-commit flag is set to true, then any locks that were held
  64680. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  64681. ** to invoke any required unlock-notify callbacks.
  64682. */
  64683. if( db->autoCommit ){
  64684. sqlite3ConnectionUnlocked(db);
  64685. }
  64686. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  64687. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  64688. }
  64689. /*
  64690. ** Each VDBE holds the result of the most recent sqlite3_step() call
  64691. ** in p->rc. This routine sets that result back to SQLITE_OK.
  64692. */
  64693. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  64694. p->rc = SQLITE_OK;
  64695. }
  64696. /*
  64697. ** Copy the error code and error message belonging to the VDBE passed
  64698. ** as the first argument to its database handle (so that they will be
  64699. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  64700. **
  64701. ** This function does not clear the VDBE error code or message, just
  64702. ** copies them to the database handle.
  64703. */
  64704. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  64705. sqlite3 *db = p->db;
  64706. int rc = p->rc;
  64707. if( p->zErrMsg ){
  64708. u8 mallocFailed = db->mallocFailed;
  64709. sqlite3BeginBenignMalloc();
  64710. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  64711. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  64712. sqlite3EndBenignMalloc();
  64713. db->mallocFailed = mallocFailed;
  64714. db->errCode = rc;
  64715. }else{
  64716. sqlite3Error(db, rc);
  64717. }
  64718. return rc;
  64719. }
  64720. #ifdef SQLITE_ENABLE_SQLLOG
  64721. /*
  64722. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  64723. ** invoke it.
  64724. */
  64725. static void vdbeInvokeSqllog(Vdbe *v){
  64726. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  64727. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  64728. assert( v->db->init.busy==0 );
  64729. if( zExpanded ){
  64730. sqlite3GlobalConfig.xSqllog(
  64731. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  64732. );
  64733. sqlite3DbFree(v->db, zExpanded);
  64734. }
  64735. }
  64736. }
  64737. #else
  64738. # define vdbeInvokeSqllog(x)
  64739. #endif
  64740. /*
  64741. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  64742. ** Write any error messages into *pzErrMsg. Return the result code.
  64743. **
  64744. ** After this routine is run, the VDBE should be ready to be executed
  64745. ** again.
  64746. **
  64747. ** To look at it another way, this routine resets the state of the
  64748. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  64749. ** VDBE_MAGIC_INIT.
  64750. */
  64751. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  64752. sqlite3 *db;
  64753. db = p->db;
  64754. /* If the VM did not run to completion or if it encountered an
  64755. ** error, then it might not have been halted properly. So halt
  64756. ** it now.
  64757. */
  64758. sqlite3VdbeHalt(p);
  64759. /* If the VDBE has be run even partially, then transfer the error code
  64760. ** and error message from the VDBE into the main database structure. But
  64761. ** if the VDBE has just been set to run but has not actually executed any
  64762. ** instructions yet, leave the main database error information unchanged.
  64763. */
  64764. if( p->pc>=0 ){
  64765. vdbeInvokeSqllog(p);
  64766. sqlite3VdbeTransferError(p);
  64767. sqlite3DbFree(db, p->zErrMsg);
  64768. p->zErrMsg = 0;
  64769. if( p->runOnlyOnce ) p->expired = 1;
  64770. }else if( p->rc && p->expired ){
  64771. /* The expired flag was set on the VDBE before the first call
  64772. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  64773. ** called), set the database error in this case as well.
  64774. */
  64775. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  64776. sqlite3DbFree(db, p->zErrMsg);
  64777. p->zErrMsg = 0;
  64778. }
  64779. /* Reclaim all memory used by the VDBE
  64780. */
  64781. Cleanup(p);
  64782. /* Save profiling information from this VDBE run.
  64783. */
  64784. #ifdef VDBE_PROFILE
  64785. {
  64786. FILE *out = fopen("vdbe_profile.out", "a");
  64787. if( out ){
  64788. int i;
  64789. fprintf(out, "---- ");
  64790. for(i=0; i<p->nOp; i++){
  64791. fprintf(out, "%02x", p->aOp[i].opcode);
  64792. }
  64793. fprintf(out, "\n");
  64794. if( p->zSql ){
  64795. char c, pc = 0;
  64796. fprintf(out, "-- ");
  64797. for(i=0; (c = p->zSql[i])!=0; i++){
  64798. if( pc=='\n' ) fprintf(out, "-- ");
  64799. putc(c, out);
  64800. pc = c;
  64801. }
  64802. if( pc!='\n' ) fprintf(out, "\n");
  64803. }
  64804. for(i=0; i<p->nOp; i++){
  64805. char zHdr[100];
  64806. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  64807. p->aOp[i].cnt,
  64808. p->aOp[i].cycles,
  64809. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  64810. );
  64811. fprintf(out, "%s", zHdr);
  64812. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  64813. }
  64814. fclose(out);
  64815. }
  64816. }
  64817. #endif
  64818. p->iCurrentTime = 0;
  64819. p->magic = VDBE_MAGIC_INIT;
  64820. return p->rc & db->errMask;
  64821. }
  64822. /*
  64823. ** Clean up and delete a VDBE after execution. Return an integer which is
  64824. ** the result code. Write any error message text into *pzErrMsg.
  64825. */
  64826. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  64827. int rc = SQLITE_OK;
  64828. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  64829. rc = sqlite3VdbeReset(p);
  64830. assert( (rc & p->db->errMask)==rc );
  64831. }
  64832. sqlite3VdbeDelete(p);
  64833. return rc;
  64834. }
  64835. /*
  64836. ** If parameter iOp is less than zero, then invoke the destructor for
  64837. ** all auxiliary data pointers currently cached by the VM passed as
  64838. ** the first argument.
  64839. **
  64840. ** Or, if iOp is greater than or equal to zero, then the destructor is
  64841. ** only invoked for those auxiliary data pointers created by the user
  64842. ** function invoked by the OP_Function opcode at instruction iOp of
  64843. ** VM pVdbe, and only then if:
  64844. **
  64845. ** * the associated function parameter is the 32nd or later (counting
  64846. ** from left to right), or
  64847. **
  64848. ** * the corresponding bit in argument mask is clear (where the first
  64849. ** function parameter corresponds to bit 0 etc.).
  64850. */
  64851. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  64852. AuxData **pp = &pVdbe->pAuxData;
  64853. while( *pp ){
  64854. AuxData *pAux = *pp;
  64855. if( (iOp<0)
  64856. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  64857. ){
  64858. testcase( pAux->iArg==31 );
  64859. if( pAux->xDelete ){
  64860. pAux->xDelete(pAux->pAux);
  64861. }
  64862. *pp = pAux->pNext;
  64863. sqlite3DbFree(pVdbe->db, pAux);
  64864. }else{
  64865. pp= &pAux->pNext;
  64866. }
  64867. }
  64868. }
  64869. /*
  64870. ** Free all memory associated with the Vdbe passed as the second argument,
  64871. ** except for object itself, which is preserved.
  64872. **
  64873. ** The difference between this function and sqlite3VdbeDelete() is that
  64874. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  64875. ** the database connection and frees the object itself.
  64876. */
  64877. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  64878. SubProgram *pSub, *pNext;
  64879. int i;
  64880. assert( p->db==0 || p->db==db );
  64881. releaseMemArray(p->aVar, p->nVar);
  64882. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  64883. for(pSub=p->pProgram; pSub; pSub=pNext){
  64884. pNext = pSub->pNext;
  64885. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  64886. sqlite3DbFree(db, pSub);
  64887. }
  64888. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  64889. vdbeFreeOpArray(db, p->aOp, p->nOp);
  64890. sqlite3DbFree(db, p->aColName);
  64891. sqlite3DbFree(db, p->zSql);
  64892. sqlite3DbFree(db, p->pFree);
  64893. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  64894. for(i=0; i<p->nScan; i++){
  64895. sqlite3DbFree(db, p->aScan[i].zName);
  64896. }
  64897. sqlite3DbFree(db, p->aScan);
  64898. #endif
  64899. }
  64900. /*
  64901. ** Delete an entire VDBE.
  64902. */
  64903. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  64904. sqlite3 *db;
  64905. if( NEVER(p==0) ) return;
  64906. db = p->db;
  64907. assert( sqlite3_mutex_held(db->mutex) );
  64908. sqlite3VdbeClearObject(db, p);
  64909. if( p->pPrev ){
  64910. p->pPrev->pNext = p->pNext;
  64911. }else{
  64912. assert( db->pVdbe==p );
  64913. db->pVdbe = p->pNext;
  64914. }
  64915. if( p->pNext ){
  64916. p->pNext->pPrev = p->pPrev;
  64917. }
  64918. p->magic = VDBE_MAGIC_DEAD;
  64919. p->db = 0;
  64920. sqlite3DbFree(db, p);
  64921. }
  64922. /*
  64923. ** The cursor "p" has a pending seek operation that has not yet been
  64924. ** carried out. Seek the cursor now. If an error occurs, return
  64925. ** the appropriate error code.
  64926. */
  64927. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  64928. int res, rc;
  64929. #ifdef SQLITE_TEST
  64930. extern int sqlite3_search_count;
  64931. #endif
  64932. assert( p->deferredMoveto );
  64933. assert( p->isTable );
  64934. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  64935. if( rc ) return rc;
  64936. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  64937. #ifdef SQLITE_TEST
  64938. sqlite3_search_count++;
  64939. #endif
  64940. p->deferredMoveto = 0;
  64941. p->cacheStatus = CACHE_STALE;
  64942. return SQLITE_OK;
  64943. }
  64944. /*
  64945. ** Something has moved cursor "p" out of place. Maybe the row it was
  64946. ** pointed to was deleted out from under it. Or maybe the btree was
  64947. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  64948. ** is supposed to be pointing. If the row was deleted out from under the
  64949. ** cursor, set the cursor to point to a NULL row.
  64950. */
  64951. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  64952. int isDifferentRow, rc;
  64953. assert( p->pCursor!=0 );
  64954. assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
  64955. rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
  64956. p->cacheStatus = CACHE_STALE;
  64957. if( isDifferentRow ) p->nullRow = 1;
  64958. return rc;
  64959. }
  64960. /*
  64961. ** Check to ensure that the cursor is valid. Restore the cursor
  64962. ** if need be. Return any I/O error from the restore operation.
  64963. */
  64964. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  64965. if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
  64966. return handleMovedCursor(p);
  64967. }
  64968. return SQLITE_OK;
  64969. }
  64970. /*
  64971. ** Make sure the cursor p is ready to read or write the row to which it
  64972. ** was last positioned. Return an error code if an OOM fault or I/O error
  64973. ** prevents us from positioning the cursor to its correct position.
  64974. **
  64975. ** If a MoveTo operation is pending on the given cursor, then do that
  64976. ** MoveTo now. If no move is pending, check to see if the row has been
  64977. ** deleted out from under the cursor and if it has, mark the row as
  64978. ** a NULL row.
  64979. **
  64980. ** If the cursor is already pointing to the correct row and that row has
  64981. ** not been deleted out from under the cursor, then this routine is a no-op.
  64982. */
  64983. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  64984. if( p->deferredMoveto ){
  64985. return handleDeferredMoveto(p);
  64986. }
  64987. if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
  64988. return handleMovedCursor(p);
  64989. }
  64990. return SQLITE_OK;
  64991. }
  64992. /*
  64993. ** The following functions:
  64994. **
  64995. ** sqlite3VdbeSerialType()
  64996. ** sqlite3VdbeSerialTypeLen()
  64997. ** sqlite3VdbeSerialLen()
  64998. ** sqlite3VdbeSerialPut()
  64999. ** sqlite3VdbeSerialGet()
  65000. **
  65001. ** encapsulate the code that serializes values for storage in SQLite
  65002. ** data and index records. Each serialized value consists of a
  65003. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  65004. ** integer, stored as a varint.
  65005. **
  65006. ** In an SQLite index record, the serial type is stored directly before
  65007. ** the blob of data that it corresponds to. In a table record, all serial
  65008. ** types are stored at the start of the record, and the blobs of data at
  65009. ** the end. Hence these functions allow the caller to handle the
  65010. ** serial-type and data blob separately.
  65011. **
  65012. ** The following table describes the various storage classes for data:
  65013. **
  65014. ** serial type bytes of data type
  65015. ** -------------- --------------- ---------------
  65016. ** 0 0 NULL
  65017. ** 1 1 signed integer
  65018. ** 2 2 signed integer
  65019. ** 3 3 signed integer
  65020. ** 4 4 signed integer
  65021. ** 5 6 signed integer
  65022. ** 6 8 signed integer
  65023. ** 7 8 IEEE float
  65024. ** 8 0 Integer constant 0
  65025. ** 9 0 Integer constant 1
  65026. ** 10,11 reserved for expansion
  65027. ** N>=12 and even (N-12)/2 BLOB
  65028. ** N>=13 and odd (N-13)/2 text
  65029. **
  65030. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  65031. ** of SQLite will not understand those serial types.
  65032. */
  65033. /*
  65034. ** Return the serial-type for the value stored in pMem.
  65035. */
  65036. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  65037. int flags = pMem->flags;
  65038. u32 n;
  65039. if( flags&MEM_Null ){
  65040. return 0;
  65041. }
  65042. if( flags&MEM_Int ){
  65043. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  65044. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  65045. i64 i = pMem->u.i;
  65046. u64 u;
  65047. if( i<0 ){
  65048. u = ~i;
  65049. }else{
  65050. u = i;
  65051. }
  65052. if( u<=127 ){
  65053. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  65054. }
  65055. if( u<=32767 ) return 2;
  65056. if( u<=8388607 ) return 3;
  65057. if( u<=2147483647 ) return 4;
  65058. if( u<=MAX_6BYTE ) return 5;
  65059. return 6;
  65060. }
  65061. if( flags&MEM_Real ){
  65062. return 7;
  65063. }
  65064. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  65065. assert( pMem->n>=0 );
  65066. n = (u32)pMem->n;
  65067. if( flags & MEM_Zero ){
  65068. n += pMem->u.nZero;
  65069. }
  65070. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  65071. }
  65072. /*
  65073. ** The sizes for serial types less than 12
  65074. */
  65075. static const u8 sqlite3SmallTypeSizes[] = {
  65076. 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0
  65077. };
  65078. /*
  65079. ** Return the length of the data corresponding to the supplied serial-type.
  65080. */
  65081. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  65082. if( serial_type>=12 ){
  65083. return (serial_type-12)/2;
  65084. }else{
  65085. return sqlite3SmallTypeSizes[serial_type];
  65086. }
  65087. }
  65088. /*
  65089. ** If we are on an architecture with mixed-endian floating
  65090. ** points (ex: ARM7) then swap the lower 4 bytes with the
  65091. ** upper 4 bytes. Return the result.
  65092. **
  65093. ** For most architectures, this is a no-op.
  65094. **
  65095. ** (later): It is reported to me that the mixed-endian problem
  65096. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  65097. ** that early versions of GCC stored the two words of a 64-bit
  65098. ** float in the wrong order. And that error has been propagated
  65099. ** ever since. The blame is not necessarily with GCC, though.
  65100. ** GCC might have just copying the problem from a prior compiler.
  65101. ** I am also told that newer versions of GCC that follow a different
  65102. ** ABI get the byte order right.
  65103. **
  65104. ** Developers using SQLite on an ARM7 should compile and run their
  65105. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  65106. ** enabled, some asserts below will ensure that the byte order of
  65107. ** floating point values is correct.
  65108. **
  65109. ** (2007-08-30) Frank van Vugt has studied this problem closely
  65110. ** and has send his findings to the SQLite developers. Frank
  65111. ** writes that some Linux kernels offer floating point hardware
  65112. ** emulation that uses only 32-bit mantissas instead of a full
  65113. ** 48-bits as required by the IEEE standard. (This is the
  65114. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  65115. ** byte swapping becomes very complicated. To avoid problems,
  65116. ** the necessary byte swapping is carried out using a 64-bit integer
  65117. ** rather than a 64-bit float. Frank assures us that the code here
  65118. ** works for him. We, the developers, have no way to independently
  65119. ** verify this, but Frank seems to know what he is talking about
  65120. ** so we trust him.
  65121. */
  65122. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  65123. static u64 floatSwap(u64 in){
  65124. union {
  65125. u64 r;
  65126. u32 i[2];
  65127. } u;
  65128. u32 t;
  65129. u.r = in;
  65130. t = u.i[0];
  65131. u.i[0] = u.i[1];
  65132. u.i[1] = t;
  65133. return u.r;
  65134. }
  65135. # define swapMixedEndianFloat(X) X = floatSwap(X)
  65136. #else
  65137. # define swapMixedEndianFloat(X)
  65138. #endif
  65139. /*
  65140. ** Write the serialized data blob for the value stored in pMem into
  65141. ** buf. It is assumed that the caller has allocated sufficient space.
  65142. ** Return the number of bytes written.
  65143. **
  65144. ** nBuf is the amount of space left in buf[]. The caller is responsible
  65145. ** for allocating enough space to buf[] to hold the entire field, exclusive
  65146. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  65147. **
  65148. ** Return the number of bytes actually written into buf[]. The number
  65149. ** of bytes in the zero-filled tail is included in the return value only
  65150. ** if those bytes were zeroed in buf[].
  65151. */
  65152. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  65153. u32 len;
  65154. /* Integer and Real */
  65155. if( serial_type<=7 && serial_type>0 ){
  65156. u64 v;
  65157. u32 i;
  65158. if( serial_type==7 ){
  65159. assert( sizeof(v)==sizeof(pMem->u.r) );
  65160. memcpy(&v, &pMem->u.r, sizeof(v));
  65161. swapMixedEndianFloat(v);
  65162. }else{
  65163. v = pMem->u.i;
  65164. }
  65165. len = i = sqlite3SmallTypeSizes[serial_type];
  65166. assert( i>0 );
  65167. do{
  65168. buf[--i] = (u8)(v&0xFF);
  65169. v >>= 8;
  65170. }while( i );
  65171. return len;
  65172. }
  65173. /* String or blob */
  65174. if( serial_type>=12 ){
  65175. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  65176. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  65177. len = pMem->n;
  65178. memcpy(buf, pMem->z, len);
  65179. return len;
  65180. }
  65181. /* NULL or constants 0 or 1 */
  65182. return 0;
  65183. }
  65184. /* Input "x" is a sequence of unsigned characters that represent a
  65185. ** big-endian integer. Return the equivalent native integer
  65186. */
  65187. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  65188. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  65189. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  65190. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  65191. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  65192. /*
  65193. ** Deserialize the data blob pointed to by buf as serial type serial_type
  65194. ** and store the result in pMem. Return the number of bytes read.
  65195. **
  65196. ** This function is implemented as two separate routines for performance.
  65197. ** The few cases that require local variables are broken out into a separate
  65198. ** routine so that in most cases the overhead of moving the stack pointer
  65199. ** is avoided.
  65200. */
  65201. static u32 SQLITE_NOINLINE serialGet(
  65202. const unsigned char *buf, /* Buffer to deserialize from */
  65203. u32 serial_type, /* Serial type to deserialize */
  65204. Mem *pMem /* Memory cell to write value into */
  65205. ){
  65206. u64 x = FOUR_BYTE_UINT(buf);
  65207. u32 y = FOUR_BYTE_UINT(buf+4);
  65208. x = (x<<32) + y;
  65209. if( serial_type==6 ){
  65210. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  65211. ** twos-complement integer. */
  65212. pMem->u.i = *(i64*)&x;
  65213. pMem->flags = MEM_Int;
  65214. testcase( pMem->u.i<0 );
  65215. }else{
  65216. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  65217. ** floating point number. */
  65218. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  65219. /* Verify that integers and floating point values use the same
  65220. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  65221. ** defined that 64-bit floating point values really are mixed
  65222. ** endian.
  65223. */
  65224. static const u64 t1 = ((u64)0x3ff00000)<<32;
  65225. static const double r1 = 1.0;
  65226. u64 t2 = t1;
  65227. swapMixedEndianFloat(t2);
  65228. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  65229. #endif
  65230. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  65231. swapMixedEndianFloat(x);
  65232. memcpy(&pMem->u.r, &x, sizeof(x));
  65233. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  65234. }
  65235. return 8;
  65236. }
  65237. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  65238. const unsigned char *buf, /* Buffer to deserialize from */
  65239. u32 serial_type, /* Serial type to deserialize */
  65240. Mem *pMem /* Memory cell to write value into */
  65241. ){
  65242. switch( serial_type ){
  65243. case 10: /* Reserved for future use */
  65244. case 11: /* Reserved for future use */
  65245. case 0: { /* Null */
  65246. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  65247. pMem->flags = MEM_Null;
  65248. break;
  65249. }
  65250. case 1: {
  65251. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  65252. ** integer. */
  65253. pMem->u.i = ONE_BYTE_INT(buf);
  65254. pMem->flags = MEM_Int;
  65255. testcase( pMem->u.i<0 );
  65256. return 1;
  65257. }
  65258. case 2: { /* 2-byte signed integer */
  65259. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  65260. ** twos-complement integer. */
  65261. pMem->u.i = TWO_BYTE_INT(buf);
  65262. pMem->flags = MEM_Int;
  65263. testcase( pMem->u.i<0 );
  65264. return 2;
  65265. }
  65266. case 3: { /* 3-byte signed integer */
  65267. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  65268. ** twos-complement integer. */
  65269. pMem->u.i = THREE_BYTE_INT(buf);
  65270. pMem->flags = MEM_Int;
  65271. testcase( pMem->u.i<0 );
  65272. return 3;
  65273. }
  65274. case 4: { /* 4-byte signed integer */
  65275. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  65276. ** twos-complement integer. */
  65277. pMem->u.i = FOUR_BYTE_INT(buf);
  65278. pMem->flags = MEM_Int;
  65279. testcase( pMem->u.i<0 );
  65280. return 4;
  65281. }
  65282. case 5: { /* 6-byte signed integer */
  65283. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  65284. ** twos-complement integer. */
  65285. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  65286. pMem->flags = MEM_Int;
  65287. testcase( pMem->u.i<0 );
  65288. return 6;
  65289. }
  65290. case 6: /* 8-byte signed integer */
  65291. case 7: { /* IEEE floating point */
  65292. /* These use local variables, so do them in a separate routine
  65293. ** to avoid having to move the frame pointer in the common case */
  65294. return serialGet(buf,serial_type,pMem);
  65295. }
  65296. case 8: /* Integer 0 */
  65297. case 9: { /* Integer 1 */
  65298. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  65299. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  65300. pMem->u.i = serial_type-8;
  65301. pMem->flags = MEM_Int;
  65302. return 0;
  65303. }
  65304. default: {
  65305. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  65306. ** length.
  65307. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  65308. ** (N-13)/2 bytes in length. */
  65309. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  65310. pMem->z = (char *)buf;
  65311. pMem->n = (serial_type-12)/2;
  65312. pMem->flags = aFlag[serial_type&1];
  65313. return pMem->n;
  65314. }
  65315. }
  65316. return 0;
  65317. }
  65318. /*
  65319. ** This routine is used to allocate sufficient space for an UnpackedRecord
  65320. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  65321. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  65322. **
  65323. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  65324. ** the unaligned buffer passed via the second and third arguments (presumably
  65325. ** stack space). If the former, then *ppFree is set to a pointer that should
  65326. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  65327. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  65328. ** before returning.
  65329. **
  65330. ** If an OOM error occurs, NULL is returned.
  65331. */
  65332. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  65333. KeyInfo *pKeyInfo, /* Description of the record */
  65334. char *pSpace, /* Unaligned space available */
  65335. int szSpace, /* Size of pSpace[] in bytes */
  65336. char **ppFree /* OUT: Caller should free this pointer */
  65337. ){
  65338. UnpackedRecord *p; /* Unpacked record to return */
  65339. int nOff; /* Increment pSpace by nOff to align it */
  65340. int nByte; /* Number of bytes required for *p */
  65341. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  65342. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  65343. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  65344. */
  65345. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  65346. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  65347. if( nByte>szSpace+nOff ){
  65348. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  65349. *ppFree = (char *)p;
  65350. if( !p ) return 0;
  65351. }else{
  65352. p = (UnpackedRecord*)&pSpace[nOff];
  65353. *ppFree = 0;
  65354. }
  65355. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  65356. assert( pKeyInfo->aSortOrder!=0 );
  65357. p->pKeyInfo = pKeyInfo;
  65358. p->nField = pKeyInfo->nField + 1;
  65359. return p;
  65360. }
  65361. /*
  65362. ** Given the nKey-byte encoding of a record in pKey[], populate the
  65363. ** UnpackedRecord structure indicated by the fourth argument with the
  65364. ** contents of the decoded record.
  65365. */
  65366. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  65367. KeyInfo *pKeyInfo, /* Information about the record format */
  65368. int nKey, /* Size of the binary record */
  65369. const void *pKey, /* The binary record */
  65370. UnpackedRecord *p /* Populate this structure before returning. */
  65371. ){
  65372. const unsigned char *aKey = (const unsigned char *)pKey;
  65373. int d;
  65374. u32 idx; /* Offset in aKey[] to read from */
  65375. u16 u; /* Unsigned loop counter */
  65376. u32 szHdr;
  65377. Mem *pMem = p->aMem;
  65378. p->default_rc = 0;
  65379. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65380. idx = getVarint32(aKey, szHdr);
  65381. d = szHdr;
  65382. u = 0;
  65383. while( idx<szHdr && d<=nKey ){
  65384. u32 serial_type;
  65385. idx += getVarint32(&aKey[idx], serial_type);
  65386. pMem->enc = pKeyInfo->enc;
  65387. pMem->db = pKeyInfo->db;
  65388. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  65389. pMem->szMalloc = 0;
  65390. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  65391. pMem++;
  65392. if( (++u)>=p->nField ) break;
  65393. }
  65394. assert( u<=pKeyInfo->nField + 1 );
  65395. p->nField = u;
  65396. }
  65397. #if SQLITE_DEBUG
  65398. /*
  65399. ** This function compares two index or table record keys in the same way
  65400. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  65401. ** this function deserializes and compares values using the
  65402. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  65403. ** in assert() statements to ensure that the optimized code in
  65404. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  65405. **
  65406. ** Return true if the result of comparison is equivalent to desiredResult.
  65407. ** Return false if there is a disagreement.
  65408. */
  65409. static int vdbeRecordCompareDebug(
  65410. int nKey1, const void *pKey1, /* Left key */
  65411. const UnpackedRecord *pPKey2, /* Right key */
  65412. int desiredResult /* Correct answer */
  65413. ){
  65414. u32 d1; /* Offset into aKey[] of next data element */
  65415. u32 idx1; /* Offset into aKey[] of next header element */
  65416. u32 szHdr1; /* Number of bytes in header */
  65417. int i = 0;
  65418. int rc = 0;
  65419. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  65420. KeyInfo *pKeyInfo;
  65421. Mem mem1;
  65422. pKeyInfo = pPKey2->pKeyInfo;
  65423. if( pKeyInfo->db==0 ) return 1;
  65424. mem1.enc = pKeyInfo->enc;
  65425. mem1.db = pKeyInfo->db;
  65426. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  65427. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  65428. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  65429. ** We could initialize it, as shown here, to silence those complaints.
  65430. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  65431. ** the unnecessary initialization has a measurable negative performance
  65432. ** impact, since this routine is a very high runner. And so, we choose
  65433. ** to ignore the compiler warnings and leave this variable uninitialized.
  65434. */
  65435. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  65436. idx1 = getVarint32(aKey1, szHdr1);
  65437. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  65438. d1 = szHdr1;
  65439. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  65440. assert( pKeyInfo->aSortOrder!=0 );
  65441. assert( pKeyInfo->nField>0 );
  65442. assert( idx1<=szHdr1 || CORRUPT_DB );
  65443. do{
  65444. u32 serial_type1;
  65445. /* Read the serial types for the next element in each key. */
  65446. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  65447. /* Verify that there is enough key space remaining to avoid
  65448. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  65449. ** always be greater than or equal to the amount of required key space.
  65450. ** Use that approximation to avoid the more expensive call to
  65451. ** sqlite3VdbeSerialTypeLen() in the common case.
  65452. */
  65453. if( d1+serial_type1+2>(u32)nKey1
  65454. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  65455. ){
  65456. break;
  65457. }
  65458. /* Extract the values to be compared.
  65459. */
  65460. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  65461. /* Do the comparison
  65462. */
  65463. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  65464. if( rc!=0 ){
  65465. assert( mem1.szMalloc==0 ); /* See comment below */
  65466. if( pKeyInfo->aSortOrder[i] ){
  65467. rc = -rc; /* Invert the result for DESC sort order. */
  65468. }
  65469. goto debugCompareEnd;
  65470. }
  65471. i++;
  65472. }while( idx1<szHdr1 && i<pPKey2->nField );
  65473. /* No memory allocation is ever used on mem1. Prove this using
  65474. ** the following assert(). If the assert() fails, it indicates a
  65475. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  65476. */
  65477. assert( mem1.szMalloc==0 );
  65478. /* rc==0 here means that one of the keys ran out of fields and
  65479. ** all the fields up to that point were equal. Return the default_rc
  65480. ** value. */
  65481. rc = pPKey2->default_rc;
  65482. debugCompareEnd:
  65483. if( desiredResult==0 && rc==0 ) return 1;
  65484. if( desiredResult<0 && rc<0 ) return 1;
  65485. if( desiredResult>0 && rc>0 ) return 1;
  65486. if( CORRUPT_DB ) return 1;
  65487. if( pKeyInfo->db->mallocFailed ) return 1;
  65488. return 0;
  65489. }
  65490. #endif
  65491. #if SQLITE_DEBUG
  65492. /*
  65493. ** Count the number of fields (a.k.a. columns) in the record given by
  65494. ** pKey,nKey. The verify that this count is less than or equal to the
  65495. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  65496. **
  65497. ** If this constraint is not satisfied, it means that the high-speed
  65498. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  65499. ** not work correctly. If this assert() ever fires, it probably means
  65500. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  65501. ** incorrectly.
  65502. */
  65503. static void vdbeAssertFieldCountWithinLimits(
  65504. int nKey, const void *pKey, /* The record to verify */
  65505. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  65506. ){
  65507. int nField = 0;
  65508. u32 szHdr;
  65509. u32 idx;
  65510. u32 notUsed;
  65511. const unsigned char *aKey = (const unsigned char*)pKey;
  65512. if( CORRUPT_DB ) return;
  65513. idx = getVarint32(aKey, szHdr);
  65514. assert( nKey>=0 );
  65515. assert( szHdr<=(u32)nKey );
  65516. while( idx<szHdr ){
  65517. idx += getVarint32(aKey+idx, notUsed);
  65518. nField++;
  65519. }
  65520. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  65521. }
  65522. #else
  65523. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  65524. #endif
  65525. /*
  65526. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  65527. ** using the collation sequence pColl. As usual, return a negative , zero
  65528. ** or positive value if *pMem1 is less than, equal to or greater than
  65529. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  65530. */
  65531. static int vdbeCompareMemString(
  65532. const Mem *pMem1,
  65533. const Mem *pMem2,
  65534. const CollSeq *pColl,
  65535. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  65536. ){
  65537. if( pMem1->enc==pColl->enc ){
  65538. /* The strings are already in the correct encoding. Call the
  65539. ** comparison function directly */
  65540. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  65541. }else{
  65542. int rc;
  65543. const void *v1, *v2;
  65544. int n1, n2;
  65545. Mem c1;
  65546. Mem c2;
  65547. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  65548. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  65549. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  65550. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  65551. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  65552. n1 = v1==0 ? 0 : c1.n;
  65553. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  65554. n2 = v2==0 ? 0 : c2.n;
  65555. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  65556. sqlite3VdbeMemRelease(&c1);
  65557. sqlite3VdbeMemRelease(&c2);
  65558. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  65559. return rc;
  65560. }
  65561. }
  65562. /*
  65563. ** Compare two blobs. Return negative, zero, or positive if the first
  65564. ** is less than, equal to, or greater than the second, respectively.
  65565. ** If one blob is a prefix of the other, then the shorter is the lessor.
  65566. */
  65567. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  65568. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  65569. if( c ) return c;
  65570. return pB1->n - pB2->n;
  65571. }
  65572. /*
  65573. ** Compare the values contained by the two memory cells, returning
  65574. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  65575. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  65576. ** and reals) sorted numerically, followed by text ordered by the collating
  65577. ** sequence pColl and finally blob's ordered by memcmp().
  65578. **
  65579. ** Two NULL values are considered equal by this function.
  65580. */
  65581. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  65582. int f1, f2;
  65583. int combined_flags;
  65584. f1 = pMem1->flags;
  65585. f2 = pMem2->flags;
  65586. combined_flags = f1|f2;
  65587. assert( (combined_flags & MEM_RowSet)==0 );
  65588. /* If one value is NULL, it is less than the other. If both values
  65589. ** are NULL, return 0.
  65590. */
  65591. if( combined_flags&MEM_Null ){
  65592. return (f2&MEM_Null) - (f1&MEM_Null);
  65593. }
  65594. /* If one value is a number and the other is not, the number is less.
  65595. ** If both are numbers, compare as reals if one is a real, or as integers
  65596. ** if both values are integers.
  65597. */
  65598. if( combined_flags&(MEM_Int|MEM_Real) ){
  65599. double r1, r2;
  65600. if( (f1 & f2 & MEM_Int)!=0 ){
  65601. if( pMem1->u.i < pMem2->u.i ) return -1;
  65602. if( pMem1->u.i > pMem2->u.i ) return 1;
  65603. return 0;
  65604. }
  65605. if( (f1&MEM_Real)!=0 ){
  65606. r1 = pMem1->u.r;
  65607. }else if( (f1&MEM_Int)!=0 ){
  65608. r1 = (double)pMem1->u.i;
  65609. }else{
  65610. return 1;
  65611. }
  65612. if( (f2&MEM_Real)!=0 ){
  65613. r2 = pMem2->u.r;
  65614. }else if( (f2&MEM_Int)!=0 ){
  65615. r2 = (double)pMem2->u.i;
  65616. }else{
  65617. return -1;
  65618. }
  65619. if( r1<r2 ) return -1;
  65620. if( r1>r2 ) return 1;
  65621. return 0;
  65622. }
  65623. /* If one value is a string and the other is a blob, the string is less.
  65624. ** If both are strings, compare using the collating functions.
  65625. */
  65626. if( combined_flags&MEM_Str ){
  65627. if( (f1 & MEM_Str)==0 ){
  65628. return 1;
  65629. }
  65630. if( (f2 & MEM_Str)==0 ){
  65631. return -1;
  65632. }
  65633. assert( pMem1->enc==pMem2->enc );
  65634. assert( pMem1->enc==SQLITE_UTF8 ||
  65635. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  65636. /* The collation sequence must be defined at this point, even if
  65637. ** the user deletes the collation sequence after the vdbe program is
  65638. ** compiled (this was not always the case).
  65639. */
  65640. assert( !pColl || pColl->xCmp );
  65641. if( pColl ){
  65642. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  65643. }
  65644. /* If a NULL pointer was passed as the collate function, fall through
  65645. ** to the blob case and use memcmp(). */
  65646. }
  65647. /* Both values must be blobs. Compare using memcmp(). */
  65648. return sqlite3BlobCompare(pMem1, pMem2);
  65649. }
  65650. /*
  65651. ** The first argument passed to this function is a serial-type that
  65652. ** corresponds to an integer - all values between 1 and 9 inclusive
  65653. ** except 7. The second points to a buffer containing an integer value
  65654. ** serialized according to serial_type. This function deserializes
  65655. ** and returns the value.
  65656. */
  65657. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  65658. u32 y;
  65659. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  65660. switch( serial_type ){
  65661. case 0:
  65662. case 1:
  65663. testcase( aKey[0]&0x80 );
  65664. return ONE_BYTE_INT(aKey);
  65665. case 2:
  65666. testcase( aKey[0]&0x80 );
  65667. return TWO_BYTE_INT(aKey);
  65668. case 3:
  65669. testcase( aKey[0]&0x80 );
  65670. return THREE_BYTE_INT(aKey);
  65671. case 4: {
  65672. testcase( aKey[0]&0x80 );
  65673. y = FOUR_BYTE_UINT(aKey);
  65674. return (i64)*(int*)&y;
  65675. }
  65676. case 5: {
  65677. testcase( aKey[0]&0x80 );
  65678. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  65679. }
  65680. case 6: {
  65681. u64 x = FOUR_BYTE_UINT(aKey);
  65682. testcase( aKey[0]&0x80 );
  65683. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  65684. return (i64)*(i64*)&x;
  65685. }
  65686. }
  65687. return (serial_type - 8);
  65688. }
  65689. /*
  65690. ** This function compares the two table rows or index records
  65691. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  65692. ** or positive integer if key1 is less than, equal to or
  65693. ** greater than key2. The {nKey1, pKey1} key must be a blob
  65694. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  65695. ** key must be a parsed key such as obtained from
  65696. ** sqlite3VdbeParseRecord.
  65697. **
  65698. ** If argument bSkip is non-zero, it is assumed that the caller has already
  65699. ** determined that the first fields of the keys are equal.
  65700. **
  65701. ** Key1 and Key2 do not have to contain the same number of fields. If all
  65702. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  65703. ** returned.
  65704. **
  65705. ** If database corruption is discovered, set pPKey2->errCode to
  65706. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  65707. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  65708. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  65709. */
  65710. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  65711. int nKey1, const void *pKey1, /* Left key */
  65712. UnpackedRecord *pPKey2, /* Right key */
  65713. int bSkip /* If true, skip the first field */
  65714. ){
  65715. u32 d1; /* Offset into aKey[] of next data element */
  65716. int i; /* Index of next field to compare */
  65717. u32 szHdr1; /* Size of record header in bytes */
  65718. u32 idx1; /* Offset of first type in header */
  65719. int rc = 0; /* Return value */
  65720. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  65721. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  65722. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  65723. Mem mem1;
  65724. /* If bSkip is true, then the caller has already determined that the first
  65725. ** two elements in the keys are equal. Fix the various stack variables so
  65726. ** that this routine begins comparing at the second field. */
  65727. if( bSkip ){
  65728. u32 s1;
  65729. idx1 = 1 + getVarint32(&aKey1[1], s1);
  65730. szHdr1 = aKey1[0];
  65731. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  65732. i = 1;
  65733. pRhs++;
  65734. }else{
  65735. idx1 = getVarint32(aKey1, szHdr1);
  65736. d1 = szHdr1;
  65737. if( d1>(unsigned)nKey1 ){
  65738. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65739. return 0; /* Corruption */
  65740. }
  65741. i = 0;
  65742. }
  65743. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  65744. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  65745. || CORRUPT_DB );
  65746. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  65747. assert( pPKey2->pKeyInfo->nField>0 );
  65748. assert( idx1<=szHdr1 || CORRUPT_DB );
  65749. do{
  65750. u32 serial_type;
  65751. /* RHS is an integer */
  65752. if( pRhs->flags & MEM_Int ){
  65753. serial_type = aKey1[idx1];
  65754. testcase( serial_type==12 );
  65755. if( serial_type>=10 ){
  65756. rc = +1;
  65757. }else if( serial_type==0 ){
  65758. rc = -1;
  65759. }else if( serial_type==7 ){
  65760. double rhs = (double)pRhs->u.i;
  65761. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  65762. if( mem1.u.r<rhs ){
  65763. rc = -1;
  65764. }else if( mem1.u.r>rhs ){
  65765. rc = +1;
  65766. }
  65767. }else{
  65768. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  65769. i64 rhs = pRhs->u.i;
  65770. if( lhs<rhs ){
  65771. rc = -1;
  65772. }else if( lhs>rhs ){
  65773. rc = +1;
  65774. }
  65775. }
  65776. }
  65777. /* RHS is real */
  65778. else if( pRhs->flags & MEM_Real ){
  65779. serial_type = aKey1[idx1];
  65780. if( serial_type>=10 ){
  65781. /* Serial types 12 or greater are strings and blobs (greater than
  65782. ** numbers). Types 10 and 11 are currently "reserved for future
  65783. ** use", so it doesn't really matter what the results of comparing
  65784. ** them to numberic values are. */
  65785. rc = +1;
  65786. }else if( serial_type==0 ){
  65787. rc = -1;
  65788. }else{
  65789. double rhs = pRhs->u.r;
  65790. double lhs;
  65791. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  65792. if( serial_type==7 ){
  65793. lhs = mem1.u.r;
  65794. }else{
  65795. lhs = (double)mem1.u.i;
  65796. }
  65797. if( lhs<rhs ){
  65798. rc = -1;
  65799. }else if( lhs>rhs ){
  65800. rc = +1;
  65801. }
  65802. }
  65803. }
  65804. /* RHS is a string */
  65805. else if( pRhs->flags & MEM_Str ){
  65806. getVarint32(&aKey1[idx1], serial_type);
  65807. testcase( serial_type==12 );
  65808. if( serial_type<12 ){
  65809. rc = -1;
  65810. }else if( !(serial_type & 0x01) ){
  65811. rc = +1;
  65812. }else{
  65813. mem1.n = (serial_type - 12) / 2;
  65814. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  65815. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  65816. if( (d1+mem1.n) > (unsigned)nKey1 ){
  65817. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65818. return 0; /* Corruption */
  65819. }else if( pKeyInfo->aColl[i] ){
  65820. mem1.enc = pKeyInfo->enc;
  65821. mem1.db = pKeyInfo->db;
  65822. mem1.flags = MEM_Str;
  65823. mem1.z = (char*)&aKey1[d1];
  65824. rc = vdbeCompareMemString(
  65825. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  65826. );
  65827. }else{
  65828. int nCmp = MIN(mem1.n, pRhs->n);
  65829. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  65830. if( rc==0 ) rc = mem1.n - pRhs->n;
  65831. }
  65832. }
  65833. }
  65834. /* RHS is a blob */
  65835. else if( pRhs->flags & MEM_Blob ){
  65836. getVarint32(&aKey1[idx1], serial_type);
  65837. testcase( serial_type==12 );
  65838. if( serial_type<12 || (serial_type & 0x01) ){
  65839. rc = -1;
  65840. }else{
  65841. int nStr = (serial_type - 12) / 2;
  65842. testcase( (d1+nStr)==(unsigned)nKey1 );
  65843. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  65844. if( (d1+nStr) > (unsigned)nKey1 ){
  65845. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65846. return 0; /* Corruption */
  65847. }else{
  65848. int nCmp = MIN(nStr, pRhs->n);
  65849. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  65850. if( rc==0 ) rc = nStr - pRhs->n;
  65851. }
  65852. }
  65853. }
  65854. /* RHS is null */
  65855. else{
  65856. serial_type = aKey1[idx1];
  65857. rc = (serial_type!=0);
  65858. }
  65859. if( rc!=0 ){
  65860. if( pKeyInfo->aSortOrder[i] ){
  65861. rc = -rc;
  65862. }
  65863. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  65864. assert( mem1.szMalloc==0 ); /* See comment below */
  65865. return rc;
  65866. }
  65867. i++;
  65868. pRhs++;
  65869. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  65870. idx1 += sqlite3VarintLen(serial_type);
  65871. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  65872. /* No memory allocation is ever used on mem1. Prove this using
  65873. ** the following assert(). If the assert() fails, it indicates a
  65874. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  65875. assert( mem1.szMalloc==0 );
  65876. /* rc==0 here means that one or both of the keys ran out of fields and
  65877. ** all the fields up to that point were equal. Return the default_rc
  65878. ** value. */
  65879. assert( CORRUPT_DB
  65880. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  65881. || pKeyInfo->db->mallocFailed
  65882. );
  65883. return pPKey2->default_rc;
  65884. }
  65885. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  65886. int nKey1, const void *pKey1, /* Left key */
  65887. UnpackedRecord *pPKey2 /* Right key */
  65888. ){
  65889. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  65890. }
  65891. /*
  65892. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  65893. ** that (a) the first field of pPKey2 is an integer, and (b) the
  65894. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  65895. ** byte (i.e. is less than 128).
  65896. **
  65897. ** To avoid concerns about buffer overreads, this routine is only used
  65898. ** on schemas where the maximum valid header size is 63 bytes or less.
  65899. */
  65900. static int vdbeRecordCompareInt(
  65901. int nKey1, const void *pKey1, /* Left key */
  65902. UnpackedRecord *pPKey2 /* Right key */
  65903. ){
  65904. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  65905. int serial_type = ((const u8*)pKey1)[1];
  65906. int res;
  65907. u32 y;
  65908. u64 x;
  65909. i64 v = pPKey2->aMem[0].u.i;
  65910. i64 lhs;
  65911. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  65912. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  65913. switch( serial_type ){
  65914. case 1: { /* 1-byte signed integer */
  65915. lhs = ONE_BYTE_INT(aKey);
  65916. testcase( lhs<0 );
  65917. break;
  65918. }
  65919. case 2: { /* 2-byte signed integer */
  65920. lhs = TWO_BYTE_INT(aKey);
  65921. testcase( lhs<0 );
  65922. break;
  65923. }
  65924. case 3: { /* 3-byte signed integer */
  65925. lhs = THREE_BYTE_INT(aKey);
  65926. testcase( lhs<0 );
  65927. break;
  65928. }
  65929. case 4: { /* 4-byte signed integer */
  65930. y = FOUR_BYTE_UINT(aKey);
  65931. lhs = (i64)*(int*)&y;
  65932. testcase( lhs<0 );
  65933. break;
  65934. }
  65935. case 5: { /* 6-byte signed integer */
  65936. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  65937. testcase( lhs<0 );
  65938. break;
  65939. }
  65940. case 6: { /* 8-byte signed integer */
  65941. x = FOUR_BYTE_UINT(aKey);
  65942. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  65943. lhs = *(i64*)&x;
  65944. testcase( lhs<0 );
  65945. break;
  65946. }
  65947. case 8:
  65948. lhs = 0;
  65949. break;
  65950. case 9:
  65951. lhs = 1;
  65952. break;
  65953. /* This case could be removed without changing the results of running
  65954. ** this code. Including it causes gcc to generate a faster switch
  65955. ** statement (since the range of switch targets now starts at zero and
  65956. ** is contiguous) but does not cause any duplicate code to be generated
  65957. ** (as gcc is clever enough to combine the two like cases). Other
  65958. ** compilers might be similar. */
  65959. case 0: case 7:
  65960. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  65961. default:
  65962. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  65963. }
  65964. if( v>lhs ){
  65965. res = pPKey2->r1;
  65966. }else if( v<lhs ){
  65967. res = pPKey2->r2;
  65968. }else if( pPKey2->nField>1 ){
  65969. /* The first fields of the two keys are equal. Compare the trailing
  65970. ** fields. */
  65971. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  65972. }else{
  65973. /* The first fields of the two keys are equal and there are no trailing
  65974. ** fields. Return pPKey2->default_rc in this case. */
  65975. res = pPKey2->default_rc;
  65976. }
  65977. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  65978. return res;
  65979. }
  65980. /*
  65981. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  65982. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  65983. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  65984. ** at the start of (pKey1/nKey1) fits in a single byte.
  65985. */
  65986. static int vdbeRecordCompareString(
  65987. int nKey1, const void *pKey1, /* Left key */
  65988. UnpackedRecord *pPKey2 /* Right key */
  65989. ){
  65990. const u8 *aKey1 = (const u8*)pKey1;
  65991. int serial_type;
  65992. int res;
  65993. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  65994. getVarint32(&aKey1[1], serial_type);
  65995. if( serial_type<12 ){
  65996. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  65997. }else if( !(serial_type & 0x01) ){
  65998. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  65999. }else{
  66000. int nCmp;
  66001. int nStr;
  66002. int szHdr = aKey1[0];
  66003. nStr = (serial_type-12) / 2;
  66004. if( (szHdr + nStr) > nKey1 ){
  66005. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  66006. return 0; /* Corruption */
  66007. }
  66008. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  66009. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  66010. if( res==0 ){
  66011. res = nStr - pPKey2->aMem[0].n;
  66012. if( res==0 ){
  66013. if( pPKey2->nField>1 ){
  66014. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  66015. }else{
  66016. res = pPKey2->default_rc;
  66017. }
  66018. }else if( res>0 ){
  66019. res = pPKey2->r2;
  66020. }else{
  66021. res = pPKey2->r1;
  66022. }
  66023. }else if( res>0 ){
  66024. res = pPKey2->r2;
  66025. }else{
  66026. res = pPKey2->r1;
  66027. }
  66028. }
  66029. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  66030. || CORRUPT_DB
  66031. || pPKey2->pKeyInfo->db->mallocFailed
  66032. );
  66033. return res;
  66034. }
  66035. /*
  66036. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  66037. ** suitable for comparing serialized records to the unpacked record passed
  66038. ** as the only argument.
  66039. */
  66040. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  66041. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  66042. ** that the size-of-header varint that occurs at the start of each record
  66043. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  66044. ** also assumes that it is safe to overread a buffer by at least the
  66045. ** maximum possible legal header size plus 8 bytes. Because there is
  66046. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  66047. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  66048. ** limit the size of the header to 64 bytes in cases where the first field
  66049. ** is an integer.
  66050. **
  66051. ** The easiest way to enforce this limit is to consider only records with
  66052. ** 13 fields or less. If the first field is an integer, the maximum legal
  66053. ** header size is (12*5 + 1 + 1) bytes. */
  66054. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  66055. int flags = p->aMem[0].flags;
  66056. if( p->pKeyInfo->aSortOrder[0] ){
  66057. p->r1 = 1;
  66058. p->r2 = -1;
  66059. }else{
  66060. p->r1 = -1;
  66061. p->r2 = 1;
  66062. }
  66063. if( (flags & MEM_Int) ){
  66064. return vdbeRecordCompareInt;
  66065. }
  66066. testcase( flags & MEM_Real );
  66067. testcase( flags & MEM_Null );
  66068. testcase( flags & MEM_Blob );
  66069. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  66070. assert( flags & MEM_Str );
  66071. return vdbeRecordCompareString;
  66072. }
  66073. }
  66074. return sqlite3VdbeRecordCompare;
  66075. }
  66076. /*
  66077. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  66078. ** Read the rowid (the last field in the record) and store it in *rowid.
  66079. ** Return SQLITE_OK if everything works, or an error code otherwise.
  66080. **
  66081. ** pCur might be pointing to text obtained from a corrupt database file.
  66082. ** So the content cannot be trusted. Do appropriate checks on the content.
  66083. */
  66084. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  66085. i64 nCellKey = 0;
  66086. int rc;
  66087. u32 szHdr; /* Size of the header */
  66088. u32 typeRowid; /* Serial type of the rowid */
  66089. u32 lenRowid; /* Size of the rowid */
  66090. Mem m, v;
  66091. /* Get the size of the index entry. Only indices entries of less
  66092. ** than 2GiB are support - anything large must be database corruption.
  66093. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  66094. ** this code can safely assume that nCellKey is 32-bits
  66095. */
  66096. assert( sqlite3BtreeCursorIsValid(pCur) );
  66097. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  66098. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  66099. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  66100. /* Read in the complete content of the index entry */
  66101. sqlite3VdbeMemInit(&m, db, 0);
  66102. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  66103. if( rc ){
  66104. return rc;
  66105. }
  66106. /* The index entry must begin with a header size */
  66107. (void)getVarint32((u8*)m.z, szHdr);
  66108. testcase( szHdr==3 );
  66109. testcase( szHdr==m.n );
  66110. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  66111. goto idx_rowid_corruption;
  66112. }
  66113. /* The last field of the index should be an integer - the ROWID.
  66114. ** Verify that the last entry really is an integer. */
  66115. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  66116. testcase( typeRowid==1 );
  66117. testcase( typeRowid==2 );
  66118. testcase( typeRowid==3 );
  66119. testcase( typeRowid==4 );
  66120. testcase( typeRowid==5 );
  66121. testcase( typeRowid==6 );
  66122. testcase( typeRowid==8 );
  66123. testcase( typeRowid==9 );
  66124. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  66125. goto idx_rowid_corruption;
  66126. }
  66127. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  66128. testcase( (u32)m.n==szHdr+lenRowid );
  66129. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  66130. goto idx_rowid_corruption;
  66131. }
  66132. /* Fetch the integer off the end of the index record */
  66133. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  66134. *rowid = v.u.i;
  66135. sqlite3VdbeMemRelease(&m);
  66136. return SQLITE_OK;
  66137. /* Jump here if database corruption is detected after m has been
  66138. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  66139. idx_rowid_corruption:
  66140. testcase( m.szMalloc!=0 );
  66141. sqlite3VdbeMemRelease(&m);
  66142. return SQLITE_CORRUPT_BKPT;
  66143. }
  66144. /*
  66145. ** Compare the key of the index entry that cursor pC is pointing to against
  66146. ** the key string in pUnpacked. Write into *pRes a number
  66147. ** that is negative, zero, or positive if pC is less than, equal to,
  66148. ** or greater than pUnpacked. Return SQLITE_OK on success.
  66149. **
  66150. ** pUnpacked is either created without a rowid or is truncated so that it
  66151. ** omits the rowid at the end. The rowid at the end of the index entry
  66152. ** is ignored as well. Hence, this routine only compares the prefixes
  66153. ** of the keys prior to the final rowid, not the entire key.
  66154. */
  66155. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  66156. sqlite3 *db, /* Database connection */
  66157. VdbeCursor *pC, /* The cursor to compare against */
  66158. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  66159. int *res /* Write the comparison result here */
  66160. ){
  66161. i64 nCellKey = 0;
  66162. int rc;
  66163. BtCursor *pCur = pC->pCursor;
  66164. Mem m;
  66165. assert( sqlite3BtreeCursorIsValid(pCur) );
  66166. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  66167. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  66168. /* nCellKey will always be between 0 and 0xffffffff because of the way
  66169. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  66170. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  66171. *res = 0;
  66172. return SQLITE_CORRUPT_BKPT;
  66173. }
  66174. sqlite3VdbeMemInit(&m, db, 0);
  66175. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  66176. if( rc ){
  66177. return rc;
  66178. }
  66179. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  66180. sqlite3VdbeMemRelease(&m);
  66181. return SQLITE_OK;
  66182. }
  66183. /*
  66184. ** This routine sets the value to be returned by subsequent calls to
  66185. ** sqlite3_changes() on the database handle 'db'.
  66186. */
  66187. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  66188. assert( sqlite3_mutex_held(db->mutex) );
  66189. db->nChange = nChange;
  66190. db->nTotalChange += nChange;
  66191. }
  66192. /*
  66193. ** Set a flag in the vdbe to update the change counter when it is finalised
  66194. ** or reset.
  66195. */
  66196. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  66197. v->changeCntOn = 1;
  66198. }
  66199. /*
  66200. ** Mark every prepared statement associated with a database connection
  66201. ** as expired.
  66202. **
  66203. ** An expired statement means that recompilation of the statement is
  66204. ** recommend. Statements expire when things happen that make their
  66205. ** programs obsolete. Removing user-defined functions or collating
  66206. ** sequences, or changing an authorization function are the types of
  66207. ** things that make prepared statements obsolete.
  66208. */
  66209. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  66210. Vdbe *p;
  66211. for(p = db->pVdbe; p; p=p->pNext){
  66212. p->expired = 1;
  66213. }
  66214. }
  66215. /*
  66216. ** Return the database associated with the Vdbe.
  66217. */
  66218. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  66219. return v->db;
  66220. }
  66221. /*
  66222. ** Return a pointer to an sqlite3_value structure containing the value bound
  66223. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  66224. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  66225. ** constants) to the value before returning it.
  66226. **
  66227. ** The returned value must be freed by the caller using sqlite3ValueFree().
  66228. */
  66229. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  66230. assert( iVar>0 );
  66231. if( v ){
  66232. Mem *pMem = &v->aVar[iVar-1];
  66233. if( 0==(pMem->flags & MEM_Null) ){
  66234. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  66235. if( pRet ){
  66236. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  66237. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  66238. }
  66239. return pRet;
  66240. }
  66241. }
  66242. return 0;
  66243. }
  66244. /*
  66245. ** Configure SQL variable iVar so that binding a new value to it signals
  66246. ** to sqlite3_reoptimize() that re-preparing the statement may result
  66247. ** in a better query plan.
  66248. */
  66249. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  66250. assert( iVar>0 );
  66251. if( iVar>32 ){
  66252. v->expmask = 0xffffffff;
  66253. }else{
  66254. v->expmask |= ((u32)1 << (iVar-1));
  66255. }
  66256. }
  66257. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66258. /*
  66259. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  66260. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  66261. ** in memory obtained from sqlite3DbMalloc).
  66262. */
  66263. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  66264. sqlite3 *db = p->db;
  66265. sqlite3DbFree(db, p->zErrMsg);
  66266. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  66267. sqlite3_free(pVtab->zErrMsg);
  66268. pVtab->zErrMsg = 0;
  66269. }
  66270. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66271. /************** End of vdbeaux.c *********************************************/
  66272. /************** Begin file vdbeapi.c *****************************************/
  66273. /*
  66274. ** 2004 May 26
  66275. **
  66276. ** The author disclaims copyright to this source code. In place of
  66277. ** a legal notice, here is a blessing:
  66278. **
  66279. ** May you do good and not evil.
  66280. ** May you find forgiveness for yourself and forgive others.
  66281. ** May you share freely, never taking more than you give.
  66282. **
  66283. *************************************************************************
  66284. **
  66285. ** This file contains code use to implement APIs that are part of the
  66286. ** VDBE.
  66287. */
  66288. /* #include "sqliteInt.h" */
  66289. /* #include "vdbeInt.h" */
  66290. #ifndef SQLITE_OMIT_DEPRECATED
  66291. /*
  66292. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  66293. ** to be recompiled. A statement needs to be recompiled whenever the
  66294. ** execution environment changes in a way that would alter the program
  66295. ** that sqlite3_prepare() generates. For example, if new functions or
  66296. ** collating sequences are registered or if an authorizer function is
  66297. ** added or changed.
  66298. */
  66299. SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
  66300. Vdbe *p = (Vdbe*)pStmt;
  66301. return p==0 || p->expired;
  66302. }
  66303. #endif
  66304. /*
  66305. ** Check on a Vdbe to make sure it has not been finalized. Log
  66306. ** an error and return true if it has been finalized (or is otherwise
  66307. ** invalid). Return false if it is ok.
  66308. */
  66309. static int vdbeSafety(Vdbe *p){
  66310. if( p->db==0 ){
  66311. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  66312. return 1;
  66313. }else{
  66314. return 0;
  66315. }
  66316. }
  66317. static int vdbeSafetyNotNull(Vdbe *p){
  66318. if( p==0 ){
  66319. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  66320. return 1;
  66321. }else{
  66322. return vdbeSafety(p);
  66323. }
  66324. }
  66325. #ifndef SQLITE_OMIT_TRACE
  66326. /*
  66327. ** Invoke the profile callback. This routine is only called if we already
  66328. ** know that the profile callback is defined and needs to be invoked.
  66329. */
  66330. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  66331. sqlite3_int64 iNow;
  66332. assert( p->startTime>0 );
  66333. assert( db->xProfile!=0 );
  66334. assert( db->init.busy==0 );
  66335. assert( p->zSql!=0 );
  66336. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  66337. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  66338. p->startTime = 0;
  66339. }
  66340. /*
  66341. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  66342. ** is needed, and it invokes the callback if it is needed.
  66343. */
  66344. # define checkProfileCallback(DB,P) \
  66345. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  66346. #else
  66347. # define checkProfileCallback(DB,P) /*no-op*/
  66348. #endif
  66349. /*
  66350. ** The following routine destroys a virtual machine that is created by
  66351. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  66352. ** success/failure code that describes the result of executing the virtual
  66353. ** machine.
  66354. **
  66355. ** This routine sets the error code and string returned by
  66356. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  66357. */
  66358. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
  66359. int rc;
  66360. if( pStmt==0 ){
  66361. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  66362. ** pointer is a harmless no-op. */
  66363. rc = SQLITE_OK;
  66364. }else{
  66365. Vdbe *v = (Vdbe*)pStmt;
  66366. sqlite3 *db = v->db;
  66367. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  66368. sqlite3_mutex_enter(db->mutex);
  66369. checkProfileCallback(db, v);
  66370. rc = sqlite3VdbeFinalize(v);
  66371. rc = sqlite3ApiExit(db, rc);
  66372. sqlite3LeaveMutexAndCloseZombie(db);
  66373. }
  66374. return rc;
  66375. }
  66376. /*
  66377. ** Terminate the current execution of an SQL statement and reset it
  66378. ** back to its starting state so that it can be reused. A success code from
  66379. ** the prior execution is returned.
  66380. **
  66381. ** This routine sets the error code and string returned by
  66382. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  66383. */
  66384. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
  66385. int rc;
  66386. if( pStmt==0 ){
  66387. rc = SQLITE_OK;
  66388. }else{
  66389. Vdbe *v = (Vdbe*)pStmt;
  66390. sqlite3 *db = v->db;
  66391. sqlite3_mutex_enter(db->mutex);
  66392. checkProfileCallback(db, v);
  66393. rc = sqlite3VdbeReset(v);
  66394. sqlite3VdbeRewind(v);
  66395. assert( (rc & (db->errMask))==rc );
  66396. rc = sqlite3ApiExit(db, rc);
  66397. sqlite3_mutex_leave(db->mutex);
  66398. }
  66399. return rc;
  66400. }
  66401. /*
  66402. ** Set all the parameters in the compiled SQL statement to NULL.
  66403. */
  66404. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  66405. int i;
  66406. int rc = SQLITE_OK;
  66407. Vdbe *p = (Vdbe*)pStmt;
  66408. #if SQLITE_THREADSAFE
  66409. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  66410. #endif
  66411. sqlite3_mutex_enter(mutex);
  66412. for(i=0; i<p->nVar; i++){
  66413. sqlite3VdbeMemRelease(&p->aVar[i]);
  66414. p->aVar[i].flags = MEM_Null;
  66415. }
  66416. if( p->isPrepareV2 && p->expmask ){
  66417. p->expired = 1;
  66418. }
  66419. sqlite3_mutex_leave(mutex);
  66420. return rc;
  66421. }
  66422. /**************************** sqlite3_value_ *******************************
  66423. ** The following routines extract information from a Mem or sqlite3_value
  66424. ** structure.
  66425. */
  66426. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
  66427. Mem *p = (Mem*)pVal;
  66428. if( p->flags & (MEM_Blob|MEM_Str) ){
  66429. if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
  66430. assert( p->flags==MEM_Null && p->z==0 );
  66431. return 0;
  66432. }
  66433. p->flags |= MEM_Blob;
  66434. return p->n ? p->z : 0;
  66435. }else{
  66436. return sqlite3_value_text(pVal);
  66437. }
  66438. }
  66439. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
  66440. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  66441. }
  66442. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
  66443. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  66444. }
  66445. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
  66446. return sqlite3VdbeRealValue((Mem*)pVal);
  66447. }
  66448. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
  66449. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  66450. }
  66451. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
  66452. return sqlite3VdbeIntValue((Mem*)pVal);
  66453. }
  66454. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
  66455. return ((Mem*)pVal)->eSubtype;
  66456. }
  66457. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
  66458. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  66459. }
  66460. #ifndef SQLITE_OMIT_UTF16
  66461. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
  66462. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  66463. }
  66464. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
  66465. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  66466. }
  66467. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
  66468. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  66469. }
  66470. #endif /* SQLITE_OMIT_UTF16 */
  66471. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  66472. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  66473. ** point number string BLOB NULL
  66474. */
  66475. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
  66476. static const u8 aType[] = {
  66477. SQLITE_BLOB, /* 0x00 */
  66478. SQLITE_NULL, /* 0x01 */
  66479. SQLITE_TEXT, /* 0x02 */
  66480. SQLITE_NULL, /* 0x03 */
  66481. SQLITE_INTEGER, /* 0x04 */
  66482. SQLITE_NULL, /* 0x05 */
  66483. SQLITE_INTEGER, /* 0x06 */
  66484. SQLITE_NULL, /* 0x07 */
  66485. SQLITE_FLOAT, /* 0x08 */
  66486. SQLITE_NULL, /* 0x09 */
  66487. SQLITE_FLOAT, /* 0x0a */
  66488. SQLITE_NULL, /* 0x0b */
  66489. SQLITE_INTEGER, /* 0x0c */
  66490. SQLITE_NULL, /* 0x0d */
  66491. SQLITE_INTEGER, /* 0x0e */
  66492. SQLITE_NULL, /* 0x0f */
  66493. SQLITE_BLOB, /* 0x10 */
  66494. SQLITE_NULL, /* 0x11 */
  66495. SQLITE_TEXT, /* 0x12 */
  66496. SQLITE_NULL, /* 0x13 */
  66497. SQLITE_INTEGER, /* 0x14 */
  66498. SQLITE_NULL, /* 0x15 */
  66499. SQLITE_INTEGER, /* 0x16 */
  66500. SQLITE_NULL, /* 0x17 */
  66501. SQLITE_FLOAT, /* 0x18 */
  66502. SQLITE_NULL, /* 0x19 */
  66503. SQLITE_FLOAT, /* 0x1a */
  66504. SQLITE_NULL, /* 0x1b */
  66505. SQLITE_INTEGER, /* 0x1c */
  66506. SQLITE_NULL, /* 0x1d */
  66507. SQLITE_INTEGER, /* 0x1e */
  66508. SQLITE_NULL, /* 0x1f */
  66509. };
  66510. return aType[pVal->flags&MEM_AffMask];
  66511. }
  66512. /* Make a copy of an sqlite3_value object
  66513. */
  66514. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
  66515. sqlite3_value *pNew;
  66516. if( pOrig==0 ) return 0;
  66517. pNew = sqlite3_malloc( sizeof(*pNew) );
  66518. if( pNew==0 ) return 0;
  66519. memset(pNew, 0, sizeof(*pNew));
  66520. memcpy(pNew, pOrig, MEMCELLSIZE);
  66521. pNew->flags &= ~MEM_Dyn;
  66522. pNew->db = 0;
  66523. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  66524. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  66525. pNew->flags |= MEM_Ephem;
  66526. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  66527. sqlite3ValueFree(pNew);
  66528. pNew = 0;
  66529. }
  66530. }
  66531. return pNew;
  66532. }
  66533. /* Destroy an sqlite3_value object previously obtained from
  66534. ** sqlite3_value_dup().
  66535. */
  66536. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
  66537. sqlite3ValueFree(pOld);
  66538. }
  66539. /**************************** sqlite3_result_ *******************************
  66540. ** The following routines are used by user-defined functions to specify
  66541. ** the function result.
  66542. **
  66543. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  66544. ** result as a string or blob but if the string or blob is too large, it
  66545. ** then sets the error code to SQLITE_TOOBIG
  66546. **
  66547. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  66548. ** on value P is not going to be used and need to be destroyed.
  66549. */
  66550. static void setResultStrOrError(
  66551. sqlite3_context *pCtx, /* Function context */
  66552. const char *z, /* String pointer */
  66553. int n, /* Bytes in string, or negative */
  66554. u8 enc, /* Encoding of z. 0 for BLOBs */
  66555. void (*xDel)(void*) /* Destructor function */
  66556. ){
  66557. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  66558. sqlite3_result_error_toobig(pCtx);
  66559. }
  66560. }
  66561. static int invokeValueDestructor(
  66562. const void *p, /* Value to destroy */
  66563. void (*xDel)(void*), /* The destructor */
  66564. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  66565. ){
  66566. assert( xDel!=SQLITE_DYNAMIC );
  66567. if( xDel==0 ){
  66568. /* noop */
  66569. }else if( xDel==SQLITE_TRANSIENT ){
  66570. /* noop */
  66571. }else{
  66572. xDel((void*)p);
  66573. }
  66574. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  66575. return SQLITE_TOOBIG;
  66576. }
  66577. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
  66578. sqlite3_context *pCtx,
  66579. const void *z,
  66580. int n,
  66581. void (*xDel)(void *)
  66582. ){
  66583. assert( n>=0 );
  66584. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66585. setResultStrOrError(pCtx, z, n, 0, xDel);
  66586. }
  66587. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
  66588. sqlite3_context *pCtx,
  66589. const void *z,
  66590. sqlite3_uint64 n,
  66591. void (*xDel)(void *)
  66592. ){
  66593. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66594. assert( xDel!=SQLITE_DYNAMIC );
  66595. if( n>0x7fffffff ){
  66596. (void)invokeValueDestructor(z, xDel, pCtx);
  66597. }else{
  66598. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  66599. }
  66600. }
  66601. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  66602. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66603. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  66604. }
  66605. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  66606. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66607. pCtx->isError = SQLITE_ERROR;
  66608. pCtx->fErrorOrAux = 1;
  66609. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  66610. }
  66611. #ifndef SQLITE_OMIT_UTF16
  66612. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  66613. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66614. pCtx->isError = SQLITE_ERROR;
  66615. pCtx->fErrorOrAux = 1;
  66616. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  66617. }
  66618. #endif
  66619. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  66620. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66621. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  66622. }
  66623. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  66624. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66625. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  66626. }
  66627. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
  66628. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66629. sqlite3VdbeMemSetNull(pCtx->pOut);
  66630. }
  66631. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  66632. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66633. pCtx->pOut->eSubtype = eSubtype & 0xff;
  66634. }
  66635. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
  66636. sqlite3_context *pCtx,
  66637. const char *z,
  66638. int n,
  66639. void (*xDel)(void *)
  66640. ){
  66641. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66642. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  66643. }
  66644. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
  66645. sqlite3_context *pCtx,
  66646. const char *z,
  66647. sqlite3_uint64 n,
  66648. void (*xDel)(void *),
  66649. unsigned char enc
  66650. ){
  66651. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66652. assert( xDel!=SQLITE_DYNAMIC );
  66653. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  66654. if( n>0x7fffffff ){
  66655. (void)invokeValueDestructor(z, xDel, pCtx);
  66656. }else{
  66657. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  66658. }
  66659. }
  66660. #ifndef SQLITE_OMIT_UTF16
  66661. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
  66662. sqlite3_context *pCtx,
  66663. const void *z,
  66664. int n,
  66665. void (*xDel)(void *)
  66666. ){
  66667. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66668. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  66669. }
  66670. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
  66671. sqlite3_context *pCtx,
  66672. const void *z,
  66673. int n,
  66674. void (*xDel)(void *)
  66675. ){
  66676. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66677. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  66678. }
  66679. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
  66680. sqlite3_context *pCtx,
  66681. const void *z,
  66682. int n,
  66683. void (*xDel)(void *)
  66684. ){
  66685. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66686. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  66687. }
  66688. #endif /* SQLITE_OMIT_UTF16 */
  66689. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  66690. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66691. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  66692. }
  66693. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  66694. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66695. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  66696. }
  66697. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  66698. Mem *pOut = pCtx->pOut;
  66699. assert( sqlite3_mutex_held(pOut->db->mutex) );
  66700. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66701. return SQLITE_TOOBIG;
  66702. }
  66703. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  66704. return SQLITE_OK;
  66705. }
  66706. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  66707. pCtx->isError = errCode;
  66708. pCtx->fErrorOrAux = 1;
  66709. #ifdef SQLITE_DEBUG
  66710. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  66711. #endif
  66712. if( pCtx->pOut->flags & MEM_Null ){
  66713. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  66714. SQLITE_UTF8, SQLITE_STATIC);
  66715. }
  66716. }
  66717. /* Force an SQLITE_TOOBIG error. */
  66718. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
  66719. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66720. pCtx->isError = SQLITE_TOOBIG;
  66721. pCtx->fErrorOrAux = 1;
  66722. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  66723. SQLITE_UTF8, SQLITE_STATIC);
  66724. }
  66725. /* An SQLITE_NOMEM error. */
  66726. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
  66727. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66728. sqlite3VdbeMemSetNull(pCtx->pOut);
  66729. pCtx->isError = SQLITE_NOMEM;
  66730. pCtx->fErrorOrAux = 1;
  66731. pCtx->pOut->db->mallocFailed = 1;
  66732. }
  66733. /*
  66734. ** This function is called after a transaction has been committed. It
  66735. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  66736. */
  66737. static int doWalCallbacks(sqlite3 *db){
  66738. int rc = SQLITE_OK;
  66739. #ifndef SQLITE_OMIT_WAL
  66740. int i;
  66741. for(i=0; i<db->nDb; i++){
  66742. Btree *pBt = db->aDb[i].pBt;
  66743. if( pBt ){
  66744. int nEntry;
  66745. sqlite3BtreeEnter(pBt);
  66746. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  66747. sqlite3BtreeLeave(pBt);
  66748. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  66749. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  66750. }
  66751. }
  66752. }
  66753. #endif
  66754. return rc;
  66755. }
  66756. /*
  66757. ** Execute the statement pStmt, either until a row of data is ready, the
  66758. ** statement is completely executed or an error occurs.
  66759. **
  66760. ** This routine implements the bulk of the logic behind the sqlite_step()
  66761. ** API. The only thing omitted is the automatic recompile if a
  66762. ** schema change has occurred. That detail is handled by the
  66763. ** outer sqlite3_step() wrapper procedure.
  66764. */
  66765. static int sqlite3Step(Vdbe *p){
  66766. sqlite3 *db;
  66767. int rc;
  66768. assert(p);
  66769. if( p->magic!=VDBE_MAGIC_RUN ){
  66770. /* We used to require that sqlite3_reset() be called before retrying
  66771. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  66772. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  66773. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  66774. ** This "automatic-reset" change is not technically an incompatibility,
  66775. ** since any application that receives an SQLITE_MISUSE is broken by
  66776. ** definition.
  66777. **
  66778. ** Nevertheless, some published applications that were originally written
  66779. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  66780. ** returns, and those were broken by the automatic-reset change. As a
  66781. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  66782. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  66783. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  66784. ** or SQLITE_BUSY error.
  66785. */
  66786. #ifdef SQLITE_OMIT_AUTORESET
  66787. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  66788. sqlite3_reset((sqlite3_stmt*)p);
  66789. }else{
  66790. return SQLITE_MISUSE_BKPT;
  66791. }
  66792. #else
  66793. sqlite3_reset((sqlite3_stmt*)p);
  66794. #endif
  66795. }
  66796. /* Check that malloc() has not failed. If it has, return early. */
  66797. db = p->db;
  66798. if( db->mallocFailed ){
  66799. p->rc = SQLITE_NOMEM;
  66800. return SQLITE_NOMEM;
  66801. }
  66802. if( p->pc<=0 && p->expired ){
  66803. p->rc = SQLITE_SCHEMA;
  66804. rc = SQLITE_ERROR;
  66805. goto end_of_step;
  66806. }
  66807. if( p->pc<0 ){
  66808. /* If there are no other statements currently running, then
  66809. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  66810. ** from interrupting a statement that has not yet started.
  66811. */
  66812. if( db->nVdbeActive==0 ){
  66813. db->u1.isInterrupted = 0;
  66814. }
  66815. assert( db->nVdbeWrite>0 || db->autoCommit==0
  66816. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  66817. );
  66818. #ifndef SQLITE_OMIT_TRACE
  66819. if( db->xProfile && !db->init.busy && p->zSql ){
  66820. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  66821. }else{
  66822. assert( p->startTime==0 );
  66823. }
  66824. #endif
  66825. db->nVdbeActive++;
  66826. if( p->readOnly==0 ) db->nVdbeWrite++;
  66827. if( p->bIsReader ) db->nVdbeRead++;
  66828. p->pc = 0;
  66829. }
  66830. #ifdef SQLITE_DEBUG
  66831. p->rcApp = SQLITE_OK;
  66832. #endif
  66833. #ifndef SQLITE_OMIT_EXPLAIN
  66834. if( p->explain ){
  66835. rc = sqlite3VdbeList(p);
  66836. }else
  66837. #endif /* SQLITE_OMIT_EXPLAIN */
  66838. {
  66839. db->nVdbeExec++;
  66840. rc = sqlite3VdbeExec(p);
  66841. db->nVdbeExec--;
  66842. }
  66843. #ifndef SQLITE_OMIT_TRACE
  66844. /* If the statement completed successfully, invoke the profile callback */
  66845. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  66846. #endif
  66847. if( rc==SQLITE_DONE ){
  66848. assert( p->rc==SQLITE_OK );
  66849. p->rc = doWalCallbacks(db);
  66850. if( p->rc!=SQLITE_OK ){
  66851. rc = SQLITE_ERROR;
  66852. }
  66853. }
  66854. db->errCode = rc;
  66855. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  66856. p->rc = SQLITE_NOMEM;
  66857. }
  66858. end_of_step:
  66859. /* At this point local variable rc holds the value that should be
  66860. ** returned if this statement was compiled using the legacy
  66861. ** sqlite3_prepare() interface. According to the docs, this can only
  66862. ** be one of the values in the first assert() below. Variable p->rc
  66863. ** contains the value that would be returned if sqlite3_finalize()
  66864. ** were called on statement p.
  66865. */
  66866. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  66867. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  66868. );
  66869. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  66870. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  66871. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  66872. ** error has occurred, then return the error code in p->rc to the
  66873. ** caller. Set the error code in the database handle to the same value.
  66874. */
  66875. rc = sqlite3VdbeTransferError(p);
  66876. }
  66877. return (rc&db->errMask);
  66878. }
  66879. /*
  66880. ** This is the top-level implementation of sqlite3_step(). Call
  66881. ** sqlite3Step() to do most of the work. If a schema error occurs,
  66882. ** call sqlite3Reprepare() and try again.
  66883. */
  66884. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
  66885. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  66886. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  66887. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  66888. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  66889. sqlite3 *db; /* The database connection */
  66890. if( vdbeSafetyNotNull(v) ){
  66891. return SQLITE_MISUSE_BKPT;
  66892. }
  66893. db = v->db;
  66894. sqlite3_mutex_enter(db->mutex);
  66895. v->doingRerun = 0;
  66896. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  66897. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  66898. int savedPc = v->pc;
  66899. rc2 = rc = sqlite3Reprepare(v);
  66900. if( rc!=SQLITE_OK) break;
  66901. sqlite3_reset(pStmt);
  66902. if( savedPc>=0 ) v->doingRerun = 1;
  66903. assert( v->expired==0 );
  66904. }
  66905. if( rc2!=SQLITE_OK ){
  66906. /* This case occurs after failing to recompile an sql statement.
  66907. ** The error message from the SQL compiler has already been loaded
  66908. ** into the database handle. This block copies the error message
  66909. ** from the database handle into the statement and sets the statement
  66910. ** program counter to 0 to ensure that when the statement is
  66911. ** finalized or reset the parser error message is available via
  66912. ** sqlite3_errmsg() and sqlite3_errcode().
  66913. */
  66914. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  66915. sqlite3DbFree(db, v->zErrMsg);
  66916. if( !db->mallocFailed ){
  66917. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  66918. v->rc = rc2;
  66919. } else {
  66920. v->zErrMsg = 0;
  66921. v->rc = rc = SQLITE_NOMEM;
  66922. }
  66923. }
  66924. rc = sqlite3ApiExit(db, rc);
  66925. sqlite3_mutex_leave(db->mutex);
  66926. return rc;
  66927. }
  66928. /*
  66929. ** Extract the user data from a sqlite3_context structure and return a
  66930. ** pointer to it.
  66931. */
  66932. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
  66933. assert( p && p->pFunc );
  66934. return p->pFunc->pUserData;
  66935. }
  66936. /*
  66937. ** Extract the user data from a sqlite3_context structure and return a
  66938. ** pointer to it.
  66939. **
  66940. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  66941. ** returns a copy of the pointer to the database connection (the 1st
  66942. ** parameter) of the sqlite3_create_function() and
  66943. ** sqlite3_create_function16() routines that originally registered the
  66944. ** application defined function.
  66945. */
  66946. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
  66947. assert( p && p->pOut );
  66948. return p->pOut->db;
  66949. }
  66950. /*
  66951. ** Return the current time for a statement. If the current time
  66952. ** is requested more than once within the same run of a single prepared
  66953. ** statement, the exact same time is returned for each invocation regardless
  66954. ** of the amount of time that elapses between invocations. In other words,
  66955. ** the time returned is always the time of the first call.
  66956. */
  66957. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  66958. int rc;
  66959. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  66960. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  66961. assert( p->pVdbe!=0 );
  66962. #else
  66963. sqlite3_int64 iTime = 0;
  66964. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  66965. #endif
  66966. if( *piTime==0 ){
  66967. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  66968. if( rc ) *piTime = 0;
  66969. }
  66970. return *piTime;
  66971. }
  66972. /*
  66973. ** The following is the implementation of an SQL function that always
  66974. ** fails with an error message stating that the function is used in the
  66975. ** wrong context. The sqlite3_overload_function() API might construct
  66976. ** SQL function that use this routine so that the functions will exist
  66977. ** for name resolution but are actually overloaded by the xFindFunction
  66978. ** method of virtual tables.
  66979. */
  66980. SQLITE_PRIVATE void sqlite3InvalidFunction(
  66981. sqlite3_context *context, /* The function calling context */
  66982. int NotUsed, /* Number of arguments to the function */
  66983. sqlite3_value **NotUsed2 /* Value of each argument */
  66984. ){
  66985. const char *zName = context->pFunc->zName;
  66986. char *zErr;
  66987. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  66988. zErr = sqlite3_mprintf(
  66989. "unable to use function %s in the requested context", zName);
  66990. sqlite3_result_error(context, zErr, -1);
  66991. sqlite3_free(zErr);
  66992. }
  66993. /*
  66994. ** Create a new aggregate context for p and return a pointer to
  66995. ** its pMem->z element.
  66996. */
  66997. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  66998. Mem *pMem = p->pMem;
  66999. assert( (pMem->flags & MEM_Agg)==0 );
  67000. if( nByte<=0 ){
  67001. sqlite3VdbeMemSetNull(pMem);
  67002. pMem->z = 0;
  67003. }else{
  67004. sqlite3VdbeMemClearAndResize(pMem, nByte);
  67005. pMem->flags = MEM_Agg;
  67006. pMem->u.pDef = p->pFunc;
  67007. if( pMem->z ){
  67008. memset(pMem->z, 0, nByte);
  67009. }
  67010. }
  67011. return (void*)pMem->z;
  67012. }
  67013. /*
  67014. ** Allocate or return the aggregate context for a user function. A new
  67015. ** context is allocated on the first call. Subsequent calls return the
  67016. ** same context that was returned on prior calls.
  67017. */
  67018. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  67019. assert( p && p->pFunc && p->pFunc->xStep );
  67020. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  67021. testcase( nByte<0 );
  67022. if( (p->pMem->flags & MEM_Agg)==0 ){
  67023. return createAggContext(p, nByte);
  67024. }else{
  67025. return (void*)p->pMem->z;
  67026. }
  67027. }
  67028. /*
  67029. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  67030. ** the user-function defined by pCtx.
  67031. */
  67032. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  67033. AuxData *pAuxData;
  67034. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67035. #if SQLITE_ENABLE_STAT3_OR_STAT4
  67036. if( pCtx->pVdbe==0 ) return 0;
  67037. #else
  67038. assert( pCtx->pVdbe!=0 );
  67039. #endif
  67040. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  67041. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  67042. }
  67043. return (pAuxData ? pAuxData->pAux : 0);
  67044. }
  67045. /*
  67046. ** Set the auxiliary data pointer and delete function, for the iArg'th
  67047. ** argument to the user-function defined by pCtx. Any previous value is
  67048. ** deleted by calling the delete function specified when it was set.
  67049. */
  67050. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
  67051. sqlite3_context *pCtx,
  67052. int iArg,
  67053. void *pAux,
  67054. void (*xDelete)(void*)
  67055. ){
  67056. AuxData *pAuxData;
  67057. Vdbe *pVdbe = pCtx->pVdbe;
  67058. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67059. if( iArg<0 ) goto failed;
  67060. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67061. if( pVdbe==0 ) goto failed;
  67062. #else
  67063. assert( pVdbe!=0 );
  67064. #endif
  67065. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  67066. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  67067. }
  67068. if( pAuxData==0 ){
  67069. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  67070. if( !pAuxData ) goto failed;
  67071. pAuxData->iOp = pCtx->iOp;
  67072. pAuxData->iArg = iArg;
  67073. pAuxData->pNext = pVdbe->pAuxData;
  67074. pVdbe->pAuxData = pAuxData;
  67075. if( pCtx->fErrorOrAux==0 ){
  67076. pCtx->isError = 0;
  67077. pCtx->fErrorOrAux = 1;
  67078. }
  67079. }else if( pAuxData->xDelete ){
  67080. pAuxData->xDelete(pAuxData->pAux);
  67081. }
  67082. pAuxData->pAux = pAux;
  67083. pAuxData->xDelete = xDelete;
  67084. return;
  67085. failed:
  67086. if( xDelete ){
  67087. xDelete(pAux);
  67088. }
  67089. }
  67090. #ifndef SQLITE_OMIT_DEPRECATED
  67091. /*
  67092. ** Return the number of times the Step function of an aggregate has been
  67093. ** called.
  67094. **
  67095. ** This function is deprecated. Do not use it for new code. It is
  67096. ** provide only to avoid breaking legacy code. New aggregate function
  67097. ** implementations should keep their own counts within their aggregate
  67098. ** context.
  67099. */
  67100. SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
  67101. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  67102. return p->pMem->n;
  67103. }
  67104. #endif
  67105. /*
  67106. ** Return the number of columns in the result set for the statement pStmt.
  67107. */
  67108. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
  67109. Vdbe *pVm = (Vdbe *)pStmt;
  67110. return pVm ? pVm->nResColumn : 0;
  67111. }
  67112. /*
  67113. ** Return the number of values available from the current row of the
  67114. ** currently executing statement pStmt.
  67115. */
  67116. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
  67117. Vdbe *pVm = (Vdbe *)pStmt;
  67118. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  67119. return pVm->nResColumn;
  67120. }
  67121. /*
  67122. ** Return a pointer to static memory containing an SQL NULL value.
  67123. */
  67124. static const Mem *columnNullValue(void){
  67125. /* Even though the Mem structure contains an element
  67126. ** of type i64, on certain architectures (x86) with certain compiler
  67127. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  67128. ** instead of an 8-byte one. This all works fine, except that when
  67129. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  67130. ** that a Mem structure is located on an 8-byte boundary. To prevent
  67131. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  67132. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  67133. ** __attribute__((aligned(8))) macro. */
  67134. static const Mem nullMem
  67135. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  67136. __attribute__((aligned(8)))
  67137. #endif
  67138. = {
  67139. /* .u = */ {0},
  67140. /* .flags = */ (u16)MEM_Null,
  67141. /* .enc = */ (u8)0,
  67142. /* .eSubtype = */ (u8)0,
  67143. /* .n = */ (int)0,
  67144. /* .z = */ (char*)0,
  67145. /* .zMalloc = */ (char*)0,
  67146. /* .szMalloc = */ (int)0,
  67147. /* .uTemp = */ (u32)0,
  67148. /* .db = */ (sqlite3*)0,
  67149. /* .xDel = */ (void(*)(void*))0,
  67150. #ifdef SQLITE_DEBUG
  67151. /* .pScopyFrom = */ (Mem*)0,
  67152. /* .pFiller = */ (void*)0,
  67153. #endif
  67154. };
  67155. return &nullMem;
  67156. }
  67157. /*
  67158. ** Check to see if column iCol of the given statement is valid. If
  67159. ** it is, return a pointer to the Mem for the value of that column.
  67160. ** If iCol is not valid, return a pointer to a Mem which has a value
  67161. ** of NULL.
  67162. */
  67163. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  67164. Vdbe *pVm;
  67165. Mem *pOut;
  67166. pVm = (Vdbe *)pStmt;
  67167. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  67168. sqlite3_mutex_enter(pVm->db->mutex);
  67169. pOut = &pVm->pResultSet[i];
  67170. }else{
  67171. if( pVm && ALWAYS(pVm->db) ){
  67172. sqlite3_mutex_enter(pVm->db->mutex);
  67173. sqlite3Error(pVm->db, SQLITE_RANGE);
  67174. }
  67175. pOut = (Mem*)columnNullValue();
  67176. }
  67177. return pOut;
  67178. }
  67179. /*
  67180. ** This function is called after invoking an sqlite3_value_XXX function on a
  67181. ** column value (i.e. a value returned by evaluating an SQL expression in the
  67182. ** select list of a SELECT statement) that may cause a malloc() failure. If
  67183. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  67184. ** code of statement pStmt set to SQLITE_NOMEM.
  67185. **
  67186. ** Specifically, this is called from within:
  67187. **
  67188. ** sqlite3_column_int()
  67189. ** sqlite3_column_int64()
  67190. ** sqlite3_column_text()
  67191. ** sqlite3_column_text16()
  67192. ** sqlite3_column_real()
  67193. ** sqlite3_column_bytes()
  67194. ** sqlite3_column_bytes16()
  67195. ** sqiite3_column_blob()
  67196. */
  67197. static void columnMallocFailure(sqlite3_stmt *pStmt)
  67198. {
  67199. /* If malloc() failed during an encoding conversion within an
  67200. ** sqlite3_column_XXX API, then set the return code of the statement to
  67201. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  67202. ** and _finalize() will return NOMEM.
  67203. */
  67204. Vdbe *p = (Vdbe *)pStmt;
  67205. if( p ){
  67206. p->rc = sqlite3ApiExit(p->db, p->rc);
  67207. sqlite3_mutex_leave(p->db->mutex);
  67208. }
  67209. }
  67210. /**************************** sqlite3_column_ *******************************
  67211. ** The following routines are used to access elements of the current row
  67212. ** in the result set.
  67213. */
  67214. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  67215. const void *val;
  67216. val = sqlite3_value_blob( columnMem(pStmt,i) );
  67217. /* Even though there is no encoding conversion, value_blob() might
  67218. ** need to call malloc() to expand the result of a zeroblob()
  67219. ** expression.
  67220. */
  67221. columnMallocFailure(pStmt);
  67222. return val;
  67223. }
  67224. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  67225. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  67226. columnMallocFailure(pStmt);
  67227. return val;
  67228. }
  67229. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  67230. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  67231. columnMallocFailure(pStmt);
  67232. return val;
  67233. }
  67234. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  67235. double val = sqlite3_value_double( columnMem(pStmt,i) );
  67236. columnMallocFailure(pStmt);
  67237. return val;
  67238. }
  67239. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  67240. int val = sqlite3_value_int( columnMem(pStmt,i) );
  67241. columnMallocFailure(pStmt);
  67242. return val;
  67243. }
  67244. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  67245. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  67246. columnMallocFailure(pStmt);
  67247. return val;
  67248. }
  67249. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  67250. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  67251. columnMallocFailure(pStmt);
  67252. return val;
  67253. }
  67254. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  67255. Mem *pOut = columnMem(pStmt, i);
  67256. if( pOut->flags&MEM_Static ){
  67257. pOut->flags &= ~MEM_Static;
  67258. pOut->flags |= MEM_Ephem;
  67259. }
  67260. columnMallocFailure(pStmt);
  67261. return (sqlite3_value *)pOut;
  67262. }
  67263. #ifndef SQLITE_OMIT_UTF16
  67264. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  67265. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  67266. columnMallocFailure(pStmt);
  67267. return val;
  67268. }
  67269. #endif /* SQLITE_OMIT_UTF16 */
  67270. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  67271. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  67272. columnMallocFailure(pStmt);
  67273. return iType;
  67274. }
  67275. /*
  67276. ** Convert the N-th element of pStmt->pColName[] into a string using
  67277. ** xFunc() then return that string. If N is out of range, return 0.
  67278. **
  67279. ** There are up to 5 names for each column. useType determines which
  67280. ** name is returned. Here are the names:
  67281. **
  67282. ** 0 The column name as it should be displayed for output
  67283. ** 1 The datatype name for the column
  67284. ** 2 The name of the database that the column derives from
  67285. ** 3 The name of the table that the column derives from
  67286. ** 4 The name of the table column that the result column derives from
  67287. **
  67288. ** If the result is not a simple column reference (if it is an expression
  67289. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  67290. */
  67291. static const void *columnName(
  67292. sqlite3_stmt *pStmt,
  67293. int N,
  67294. const void *(*xFunc)(Mem*),
  67295. int useType
  67296. ){
  67297. const void *ret;
  67298. Vdbe *p;
  67299. int n;
  67300. sqlite3 *db;
  67301. #ifdef SQLITE_ENABLE_API_ARMOR
  67302. if( pStmt==0 ){
  67303. (void)SQLITE_MISUSE_BKPT;
  67304. return 0;
  67305. }
  67306. #endif
  67307. ret = 0;
  67308. p = (Vdbe *)pStmt;
  67309. db = p->db;
  67310. assert( db!=0 );
  67311. n = sqlite3_column_count(pStmt);
  67312. if( N<n && N>=0 ){
  67313. N += useType*n;
  67314. sqlite3_mutex_enter(db->mutex);
  67315. assert( db->mallocFailed==0 );
  67316. ret = xFunc(&p->aColName[N]);
  67317. /* A malloc may have failed inside of the xFunc() call. If this
  67318. ** is the case, clear the mallocFailed flag and return NULL.
  67319. */
  67320. if( db->mallocFailed ){
  67321. db->mallocFailed = 0;
  67322. ret = 0;
  67323. }
  67324. sqlite3_mutex_leave(db->mutex);
  67325. }
  67326. return ret;
  67327. }
  67328. /*
  67329. ** Return the name of the Nth column of the result set returned by SQL
  67330. ** statement pStmt.
  67331. */
  67332. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  67333. return columnName(
  67334. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  67335. }
  67336. #ifndef SQLITE_OMIT_UTF16
  67337. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  67338. return columnName(
  67339. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  67340. }
  67341. #endif
  67342. /*
  67343. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  67344. ** not define OMIT_DECLTYPE.
  67345. */
  67346. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  67347. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  67348. and SQLITE_ENABLE_COLUMN_METADATA"
  67349. #endif
  67350. #ifndef SQLITE_OMIT_DECLTYPE
  67351. /*
  67352. ** Return the column declaration type (if applicable) of the 'i'th column
  67353. ** of the result set of SQL statement pStmt.
  67354. */
  67355. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  67356. return columnName(
  67357. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  67358. }
  67359. #ifndef SQLITE_OMIT_UTF16
  67360. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  67361. return columnName(
  67362. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  67363. }
  67364. #endif /* SQLITE_OMIT_UTF16 */
  67365. #endif /* SQLITE_OMIT_DECLTYPE */
  67366. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  67367. /*
  67368. ** Return the name of the database from which a result column derives.
  67369. ** NULL is returned if the result column is an expression or constant or
  67370. ** anything else which is not an unambiguous reference to a database column.
  67371. */
  67372. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  67373. return columnName(
  67374. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  67375. }
  67376. #ifndef SQLITE_OMIT_UTF16
  67377. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  67378. return columnName(
  67379. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  67380. }
  67381. #endif /* SQLITE_OMIT_UTF16 */
  67382. /*
  67383. ** Return the name of the table from which a result column derives.
  67384. ** NULL is returned if the result column is an expression or constant or
  67385. ** anything else which is not an unambiguous reference to a database column.
  67386. */
  67387. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  67388. return columnName(
  67389. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  67390. }
  67391. #ifndef SQLITE_OMIT_UTF16
  67392. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  67393. return columnName(
  67394. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  67395. }
  67396. #endif /* SQLITE_OMIT_UTF16 */
  67397. /*
  67398. ** Return the name of the table column from which a result column derives.
  67399. ** NULL is returned if the result column is an expression or constant or
  67400. ** anything else which is not an unambiguous reference to a database column.
  67401. */
  67402. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  67403. return columnName(
  67404. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  67405. }
  67406. #ifndef SQLITE_OMIT_UTF16
  67407. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  67408. return columnName(
  67409. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  67410. }
  67411. #endif /* SQLITE_OMIT_UTF16 */
  67412. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  67413. /******************************* sqlite3_bind_ ***************************
  67414. **
  67415. ** Routines used to attach values to wildcards in a compiled SQL statement.
  67416. */
  67417. /*
  67418. ** Unbind the value bound to variable i in virtual machine p. This is the
  67419. ** the same as binding a NULL value to the column. If the "i" parameter is
  67420. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  67421. **
  67422. ** A successful evaluation of this routine acquires the mutex on p.
  67423. ** the mutex is released if any kind of error occurs.
  67424. **
  67425. ** The error code stored in database p->db is overwritten with the return
  67426. ** value in any case.
  67427. */
  67428. static int vdbeUnbind(Vdbe *p, int i){
  67429. Mem *pVar;
  67430. if( vdbeSafetyNotNull(p) ){
  67431. return SQLITE_MISUSE_BKPT;
  67432. }
  67433. sqlite3_mutex_enter(p->db->mutex);
  67434. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  67435. sqlite3Error(p->db, SQLITE_MISUSE);
  67436. sqlite3_mutex_leave(p->db->mutex);
  67437. sqlite3_log(SQLITE_MISUSE,
  67438. "bind on a busy prepared statement: [%s]", p->zSql);
  67439. return SQLITE_MISUSE_BKPT;
  67440. }
  67441. if( i<1 || i>p->nVar ){
  67442. sqlite3Error(p->db, SQLITE_RANGE);
  67443. sqlite3_mutex_leave(p->db->mutex);
  67444. return SQLITE_RANGE;
  67445. }
  67446. i--;
  67447. pVar = &p->aVar[i];
  67448. sqlite3VdbeMemRelease(pVar);
  67449. pVar->flags = MEM_Null;
  67450. sqlite3Error(p->db, SQLITE_OK);
  67451. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  67452. ** binding a new value to this variable invalidates the current query plan.
  67453. **
  67454. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  67455. ** parameter in the WHERE clause might influence the choice of query plan
  67456. ** for a statement, then the statement will be automatically recompiled,
  67457. ** as if there had been a schema change, on the first sqlite3_step() call
  67458. ** following any change to the bindings of that parameter.
  67459. */
  67460. if( p->isPrepareV2 &&
  67461. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  67462. ){
  67463. p->expired = 1;
  67464. }
  67465. return SQLITE_OK;
  67466. }
  67467. /*
  67468. ** Bind a text or BLOB value.
  67469. */
  67470. static int bindText(
  67471. sqlite3_stmt *pStmt, /* The statement to bind against */
  67472. int i, /* Index of the parameter to bind */
  67473. const void *zData, /* Pointer to the data to be bound */
  67474. int nData, /* Number of bytes of data to be bound */
  67475. void (*xDel)(void*), /* Destructor for the data */
  67476. u8 encoding /* Encoding for the data */
  67477. ){
  67478. Vdbe *p = (Vdbe *)pStmt;
  67479. Mem *pVar;
  67480. int rc;
  67481. rc = vdbeUnbind(p, i);
  67482. if( rc==SQLITE_OK ){
  67483. if( zData!=0 ){
  67484. pVar = &p->aVar[i-1];
  67485. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  67486. if( rc==SQLITE_OK && encoding!=0 ){
  67487. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  67488. }
  67489. sqlite3Error(p->db, rc);
  67490. rc = sqlite3ApiExit(p->db, rc);
  67491. }
  67492. sqlite3_mutex_leave(p->db->mutex);
  67493. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  67494. xDel((void*)zData);
  67495. }
  67496. return rc;
  67497. }
  67498. /*
  67499. ** Bind a blob value to an SQL statement variable.
  67500. */
  67501. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
  67502. sqlite3_stmt *pStmt,
  67503. int i,
  67504. const void *zData,
  67505. int nData,
  67506. void (*xDel)(void*)
  67507. ){
  67508. return bindText(pStmt, i, zData, nData, xDel, 0);
  67509. }
  67510. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
  67511. sqlite3_stmt *pStmt,
  67512. int i,
  67513. const void *zData,
  67514. sqlite3_uint64 nData,
  67515. void (*xDel)(void*)
  67516. ){
  67517. assert( xDel!=SQLITE_DYNAMIC );
  67518. if( nData>0x7fffffff ){
  67519. return invokeValueDestructor(zData, xDel, 0);
  67520. }else{
  67521. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  67522. }
  67523. }
  67524. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  67525. int rc;
  67526. Vdbe *p = (Vdbe *)pStmt;
  67527. rc = vdbeUnbind(p, i);
  67528. if( rc==SQLITE_OK ){
  67529. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  67530. sqlite3_mutex_leave(p->db->mutex);
  67531. }
  67532. return rc;
  67533. }
  67534. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  67535. return sqlite3_bind_int64(p, i, (i64)iValue);
  67536. }
  67537. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  67538. int rc;
  67539. Vdbe *p = (Vdbe *)pStmt;
  67540. rc = vdbeUnbind(p, i);
  67541. if( rc==SQLITE_OK ){
  67542. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  67543. sqlite3_mutex_leave(p->db->mutex);
  67544. }
  67545. return rc;
  67546. }
  67547. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  67548. int rc;
  67549. Vdbe *p = (Vdbe*)pStmt;
  67550. rc = vdbeUnbind(p, i);
  67551. if( rc==SQLITE_OK ){
  67552. sqlite3_mutex_leave(p->db->mutex);
  67553. }
  67554. return rc;
  67555. }
  67556. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
  67557. sqlite3_stmt *pStmt,
  67558. int i,
  67559. const char *zData,
  67560. int nData,
  67561. void (*xDel)(void*)
  67562. ){
  67563. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  67564. }
  67565. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
  67566. sqlite3_stmt *pStmt,
  67567. int i,
  67568. const char *zData,
  67569. sqlite3_uint64 nData,
  67570. void (*xDel)(void*),
  67571. unsigned char enc
  67572. ){
  67573. assert( xDel!=SQLITE_DYNAMIC );
  67574. if( nData>0x7fffffff ){
  67575. return invokeValueDestructor(zData, xDel, 0);
  67576. }else{
  67577. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  67578. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  67579. }
  67580. }
  67581. #ifndef SQLITE_OMIT_UTF16
  67582. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
  67583. sqlite3_stmt *pStmt,
  67584. int i,
  67585. const void *zData,
  67586. int nData,
  67587. void (*xDel)(void*)
  67588. ){
  67589. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  67590. }
  67591. #endif /* SQLITE_OMIT_UTF16 */
  67592. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  67593. int rc;
  67594. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  67595. case SQLITE_INTEGER: {
  67596. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  67597. break;
  67598. }
  67599. case SQLITE_FLOAT: {
  67600. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  67601. break;
  67602. }
  67603. case SQLITE_BLOB: {
  67604. if( pValue->flags & MEM_Zero ){
  67605. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  67606. }else{
  67607. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  67608. }
  67609. break;
  67610. }
  67611. case SQLITE_TEXT: {
  67612. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  67613. pValue->enc);
  67614. break;
  67615. }
  67616. default: {
  67617. rc = sqlite3_bind_null(pStmt, i);
  67618. break;
  67619. }
  67620. }
  67621. return rc;
  67622. }
  67623. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  67624. int rc;
  67625. Vdbe *p = (Vdbe *)pStmt;
  67626. rc = vdbeUnbind(p, i);
  67627. if( rc==SQLITE_OK ){
  67628. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  67629. sqlite3_mutex_leave(p->db->mutex);
  67630. }
  67631. return rc;
  67632. }
  67633. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  67634. int rc;
  67635. Vdbe *p = (Vdbe *)pStmt;
  67636. sqlite3_mutex_enter(p->db->mutex);
  67637. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67638. rc = SQLITE_TOOBIG;
  67639. }else{
  67640. assert( (n & 0x7FFFFFFF)==n );
  67641. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  67642. }
  67643. rc = sqlite3ApiExit(p->db, rc);
  67644. sqlite3_mutex_leave(p->db->mutex);
  67645. return rc;
  67646. }
  67647. /*
  67648. ** Return the number of wildcards that can be potentially bound to.
  67649. ** This routine is added to support DBD::SQLite.
  67650. */
  67651. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  67652. Vdbe *p = (Vdbe*)pStmt;
  67653. return p ? p->nVar : 0;
  67654. }
  67655. /*
  67656. ** Return the name of a wildcard parameter. Return NULL if the index
  67657. ** is out of range or if the wildcard is unnamed.
  67658. **
  67659. ** The result is always UTF-8.
  67660. */
  67661. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  67662. Vdbe *p = (Vdbe*)pStmt;
  67663. if( p==0 || i<1 || i>p->nzVar ){
  67664. return 0;
  67665. }
  67666. return p->azVar[i-1];
  67667. }
  67668. /*
  67669. ** Given a wildcard parameter name, return the index of the variable
  67670. ** with that name. If there is no variable with the given name,
  67671. ** return 0.
  67672. */
  67673. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  67674. int i;
  67675. if( p==0 ){
  67676. return 0;
  67677. }
  67678. if( zName ){
  67679. for(i=0; i<p->nzVar; i++){
  67680. const char *z = p->azVar[i];
  67681. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  67682. return i+1;
  67683. }
  67684. }
  67685. }
  67686. return 0;
  67687. }
  67688. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  67689. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  67690. }
  67691. /*
  67692. ** Transfer all bindings from the first statement over to the second.
  67693. */
  67694. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  67695. Vdbe *pFrom = (Vdbe*)pFromStmt;
  67696. Vdbe *pTo = (Vdbe*)pToStmt;
  67697. int i;
  67698. assert( pTo->db==pFrom->db );
  67699. assert( pTo->nVar==pFrom->nVar );
  67700. sqlite3_mutex_enter(pTo->db->mutex);
  67701. for(i=0; i<pFrom->nVar; i++){
  67702. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  67703. }
  67704. sqlite3_mutex_leave(pTo->db->mutex);
  67705. return SQLITE_OK;
  67706. }
  67707. #ifndef SQLITE_OMIT_DEPRECATED
  67708. /*
  67709. ** Deprecated external interface. Internal/core SQLite code
  67710. ** should call sqlite3TransferBindings.
  67711. **
  67712. ** It is misuse to call this routine with statements from different
  67713. ** database connections. But as this is a deprecated interface, we
  67714. ** will not bother to check for that condition.
  67715. **
  67716. ** If the two statements contain a different number of bindings, then
  67717. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  67718. ** SQLITE_OK is returned.
  67719. */
  67720. SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  67721. Vdbe *pFrom = (Vdbe*)pFromStmt;
  67722. Vdbe *pTo = (Vdbe*)pToStmt;
  67723. if( pFrom->nVar!=pTo->nVar ){
  67724. return SQLITE_ERROR;
  67725. }
  67726. if( pTo->isPrepareV2 && pTo->expmask ){
  67727. pTo->expired = 1;
  67728. }
  67729. if( pFrom->isPrepareV2 && pFrom->expmask ){
  67730. pFrom->expired = 1;
  67731. }
  67732. return sqlite3TransferBindings(pFromStmt, pToStmt);
  67733. }
  67734. #endif
  67735. /*
  67736. ** Return the sqlite3* database handle to which the prepared statement given
  67737. ** in the argument belongs. This is the same database handle that was
  67738. ** the first argument to the sqlite3_prepare() that was used to create
  67739. ** the statement in the first place.
  67740. */
  67741. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
  67742. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  67743. }
  67744. /*
  67745. ** Return true if the prepared statement is guaranteed to not modify the
  67746. ** database.
  67747. */
  67748. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  67749. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  67750. }
  67751. /*
  67752. ** Return true if the prepared statement is in need of being reset.
  67753. */
  67754. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  67755. Vdbe *v = (Vdbe*)pStmt;
  67756. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  67757. }
  67758. /*
  67759. ** Return a pointer to the next prepared statement after pStmt associated
  67760. ** with database connection pDb. If pStmt is NULL, return the first
  67761. ** prepared statement for the database connection. Return NULL if there
  67762. ** are no more.
  67763. */
  67764. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  67765. sqlite3_stmt *pNext;
  67766. #ifdef SQLITE_ENABLE_API_ARMOR
  67767. if( !sqlite3SafetyCheckOk(pDb) ){
  67768. (void)SQLITE_MISUSE_BKPT;
  67769. return 0;
  67770. }
  67771. #endif
  67772. sqlite3_mutex_enter(pDb->mutex);
  67773. if( pStmt==0 ){
  67774. pNext = (sqlite3_stmt*)pDb->pVdbe;
  67775. }else{
  67776. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  67777. }
  67778. sqlite3_mutex_leave(pDb->mutex);
  67779. return pNext;
  67780. }
  67781. /*
  67782. ** Return the value of a status counter for a prepared statement
  67783. */
  67784. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  67785. Vdbe *pVdbe = (Vdbe*)pStmt;
  67786. u32 v;
  67787. #ifdef SQLITE_ENABLE_API_ARMOR
  67788. if( !pStmt ){
  67789. (void)SQLITE_MISUSE_BKPT;
  67790. return 0;
  67791. }
  67792. #endif
  67793. v = pVdbe->aCounter[op];
  67794. if( resetFlag ) pVdbe->aCounter[op] = 0;
  67795. return (int)v;
  67796. }
  67797. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  67798. /*
  67799. ** Return status data for a single loop within query pStmt.
  67800. */
  67801. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  67802. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  67803. int idx, /* Index of loop to report on */
  67804. int iScanStatusOp, /* Which metric to return */
  67805. void *pOut /* OUT: Write the answer here */
  67806. ){
  67807. Vdbe *p = (Vdbe*)pStmt;
  67808. ScanStatus *pScan;
  67809. if( idx<0 || idx>=p->nScan ) return 1;
  67810. pScan = &p->aScan[idx];
  67811. switch( iScanStatusOp ){
  67812. case SQLITE_SCANSTAT_NLOOP: {
  67813. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  67814. break;
  67815. }
  67816. case SQLITE_SCANSTAT_NVISIT: {
  67817. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  67818. break;
  67819. }
  67820. case SQLITE_SCANSTAT_EST: {
  67821. double r = 1.0;
  67822. LogEst x = pScan->nEst;
  67823. while( x<100 ){
  67824. x += 10;
  67825. r *= 0.5;
  67826. }
  67827. *(double*)pOut = r*sqlite3LogEstToInt(x);
  67828. break;
  67829. }
  67830. case SQLITE_SCANSTAT_NAME: {
  67831. *(const char**)pOut = pScan->zName;
  67832. break;
  67833. }
  67834. case SQLITE_SCANSTAT_EXPLAIN: {
  67835. if( pScan->addrExplain ){
  67836. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  67837. }else{
  67838. *(const char**)pOut = 0;
  67839. }
  67840. break;
  67841. }
  67842. case SQLITE_SCANSTAT_SELECTID: {
  67843. if( pScan->addrExplain ){
  67844. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  67845. }else{
  67846. *(int*)pOut = -1;
  67847. }
  67848. break;
  67849. }
  67850. default: {
  67851. return 1;
  67852. }
  67853. }
  67854. return 0;
  67855. }
  67856. /*
  67857. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  67858. */
  67859. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  67860. Vdbe *p = (Vdbe*)pStmt;
  67861. memset(p->anExec, 0, p->nOp * sizeof(i64));
  67862. }
  67863. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  67864. /************** End of vdbeapi.c *********************************************/
  67865. /************** Begin file vdbetrace.c ***************************************/
  67866. /*
  67867. ** 2009 November 25
  67868. **
  67869. ** The author disclaims copyright to this source code. In place of
  67870. ** a legal notice, here is a blessing:
  67871. **
  67872. ** May you do good and not evil.
  67873. ** May you find forgiveness for yourself and forgive others.
  67874. ** May you share freely, never taking more than you give.
  67875. **
  67876. *************************************************************************
  67877. **
  67878. ** This file contains code used to insert the values of host parameters
  67879. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  67880. **
  67881. ** The Vdbe parse-tree explainer is also found here.
  67882. */
  67883. /* #include "sqliteInt.h" */
  67884. /* #include "vdbeInt.h" */
  67885. #ifndef SQLITE_OMIT_TRACE
  67886. /*
  67887. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  67888. ** bytes in this text up to but excluding the first character in
  67889. ** a host parameter. If the text contains no host parameters, return
  67890. ** the total number of bytes in the text.
  67891. */
  67892. static int findNextHostParameter(const char *zSql, int *pnToken){
  67893. int tokenType;
  67894. int nTotal = 0;
  67895. int n;
  67896. *pnToken = 0;
  67897. while( zSql[0] ){
  67898. n = sqlite3GetToken((u8*)zSql, &tokenType);
  67899. assert( n>0 && tokenType!=TK_ILLEGAL );
  67900. if( tokenType==TK_VARIABLE ){
  67901. *pnToken = n;
  67902. break;
  67903. }
  67904. nTotal += n;
  67905. zSql += n;
  67906. }
  67907. return nTotal;
  67908. }
  67909. /*
  67910. ** This function returns a pointer to a nul-terminated string in memory
  67911. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  67912. ** string contains a copy of zRawSql but with host parameters expanded to
  67913. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  67914. ** then the returned string holds a copy of zRawSql with "-- " prepended
  67915. ** to each line of text.
  67916. **
  67917. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  67918. ** then long strings and blobs are truncated to that many bytes. This
  67919. ** can be used to prevent unreasonably large trace strings when dealing
  67920. ** with large (multi-megabyte) strings and blobs.
  67921. **
  67922. ** The calling function is responsible for making sure the memory returned
  67923. ** is eventually freed.
  67924. **
  67925. ** ALGORITHM: Scan the input string looking for host parameters in any of
  67926. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  67927. ** string literals, quoted identifier names, and comments. For text forms,
  67928. ** the host parameter index is found by scanning the prepared
  67929. ** statement for the corresponding OP_Variable opcode. Once the host
  67930. ** parameter index is known, locate the value in p->aVar[]. Then render
  67931. ** the value as a literal in place of the host parameter name.
  67932. */
  67933. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  67934. Vdbe *p, /* The prepared statement being evaluated */
  67935. const char *zRawSql /* Raw text of the SQL statement */
  67936. ){
  67937. sqlite3 *db; /* The database connection */
  67938. int idx = 0; /* Index of a host parameter */
  67939. int nextIndex = 1; /* Index of next ? host parameter */
  67940. int n; /* Length of a token prefix */
  67941. int nToken; /* Length of the parameter token */
  67942. int i; /* Loop counter */
  67943. Mem *pVar; /* Value of a host parameter */
  67944. StrAccum out; /* Accumulate the output here */
  67945. char zBase[100]; /* Initial working space */
  67946. db = p->db;
  67947. sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
  67948. db->aLimit[SQLITE_LIMIT_LENGTH]);
  67949. if( db->nVdbeExec>1 ){
  67950. while( *zRawSql ){
  67951. const char *zStart = zRawSql;
  67952. while( *(zRawSql++)!='\n' && *zRawSql );
  67953. sqlite3StrAccumAppend(&out, "-- ", 3);
  67954. assert( (zRawSql - zStart) > 0 );
  67955. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  67956. }
  67957. }else if( p->nVar==0 ){
  67958. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  67959. }else{
  67960. while( zRawSql[0] ){
  67961. n = findNextHostParameter(zRawSql, &nToken);
  67962. assert( n>0 );
  67963. sqlite3StrAccumAppend(&out, zRawSql, n);
  67964. zRawSql += n;
  67965. assert( zRawSql[0] || nToken==0 );
  67966. if( nToken==0 ) break;
  67967. if( zRawSql[0]=='?' ){
  67968. if( nToken>1 ){
  67969. assert( sqlite3Isdigit(zRawSql[1]) );
  67970. sqlite3GetInt32(&zRawSql[1], &idx);
  67971. }else{
  67972. idx = nextIndex;
  67973. }
  67974. }else{
  67975. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  67976. zRawSql[0]=='@' || zRawSql[0]=='#' );
  67977. testcase( zRawSql[0]==':' );
  67978. testcase( zRawSql[0]=='$' );
  67979. testcase( zRawSql[0]=='@' );
  67980. testcase( zRawSql[0]=='#' );
  67981. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  67982. assert( idx>0 );
  67983. }
  67984. zRawSql += nToken;
  67985. nextIndex = idx + 1;
  67986. assert( idx>0 && idx<=p->nVar );
  67987. pVar = &p->aVar[idx-1];
  67988. if( pVar->flags & MEM_Null ){
  67989. sqlite3StrAccumAppend(&out, "NULL", 4);
  67990. }else if( pVar->flags & MEM_Int ){
  67991. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  67992. }else if( pVar->flags & MEM_Real ){
  67993. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  67994. }else if( pVar->flags & MEM_Str ){
  67995. int nOut; /* Number of bytes of the string text to include in output */
  67996. #ifndef SQLITE_OMIT_UTF16
  67997. u8 enc = ENC(db);
  67998. Mem utf8;
  67999. if( enc!=SQLITE_UTF8 ){
  68000. memset(&utf8, 0, sizeof(utf8));
  68001. utf8.db = db;
  68002. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  68003. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  68004. pVar = &utf8;
  68005. }
  68006. #endif
  68007. nOut = pVar->n;
  68008. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68009. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  68010. nOut = SQLITE_TRACE_SIZE_LIMIT;
  68011. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  68012. }
  68013. #endif
  68014. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  68015. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68016. if( nOut<pVar->n ){
  68017. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  68018. }
  68019. #endif
  68020. #ifndef SQLITE_OMIT_UTF16
  68021. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  68022. #endif
  68023. }else if( pVar->flags & MEM_Zero ){
  68024. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  68025. }else{
  68026. int nOut; /* Number of bytes of the blob to include in output */
  68027. assert( pVar->flags & MEM_Blob );
  68028. sqlite3StrAccumAppend(&out, "x'", 2);
  68029. nOut = pVar->n;
  68030. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68031. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  68032. #endif
  68033. for(i=0; i<nOut; i++){
  68034. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  68035. }
  68036. sqlite3StrAccumAppend(&out, "'", 1);
  68037. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68038. if( nOut<pVar->n ){
  68039. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  68040. }
  68041. #endif
  68042. }
  68043. }
  68044. }
  68045. return sqlite3StrAccumFinish(&out);
  68046. }
  68047. #endif /* #ifndef SQLITE_OMIT_TRACE */
  68048. /************** End of vdbetrace.c *******************************************/
  68049. /************** Begin file vdbe.c ********************************************/
  68050. /*
  68051. ** 2001 September 15
  68052. **
  68053. ** The author disclaims copyright to this source code. In place of
  68054. ** a legal notice, here is a blessing:
  68055. **
  68056. ** May you do good and not evil.
  68057. ** May you find forgiveness for yourself and forgive others.
  68058. ** May you share freely, never taking more than you give.
  68059. **
  68060. *************************************************************************
  68061. ** The code in this file implements the function that runs the
  68062. ** bytecode of a prepared statement.
  68063. **
  68064. ** Various scripts scan this source file in order to generate HTML
  68065. ** documentation, headers files, or other derived files. The formatting
  68066. ** of the code in this file is, therefore, important. See other comments
  68067. ** in this file for details. If in doubt, do not deviate from existing
  68068. ** commenting and indentation practices when changing or adding code.
  68069. */
  68070. /* #include "sqliteInt.h" */
  68071. /* #include "vdbeInt.h" */
  68072. /*
  68073. ** Invoke this macro on memory cells just prior to changing the
  68074. ** value of the cell. This macro verifies that shallow copies are
  68075. ** not misused. A shallow copy of a string or blob just copies a
  68076. ** pointer to the string or blob, not the content. If the original
  68077. ** is changed while the copy is still in use, the string or blob might
  68078. ** be changed out from under the copy. This macro verifies that nothing
  68079. ** like that ever happens.
  68080. */
  68081. #ifdef SQLITE_DEBUG
  68082. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  68083. #else
  68084. # define memAboutToChange(P,M)
  68085. #endif
  68086. /*
  68087. ** The following global variable is incremented every time a cursor
  68088. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  68089. ** procedures use this information to make sure that indices are
  68090. ** working correctly. This variable has no function other than to
  68091. ** help verify the correct operation of the library.
  68092. */
  68093. #ifdef SQLITE_TEST
  68094. SQLITE_API int sqlite3_search_count = 0;
  68095. #endif
  68096. /*
  68097. ** When this global variable is positive, it gets decremented once before
  68098. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  68099. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  68100. **
  68101. ** This facility is used for testing purposes only. It does not function
  68102. ** in an ordinary build.
  68103. */
  68104. #ifdef SQLITE_TEST
  68105. SQLITE_API int sqlite3_interrupt_count = 0;
  68106. #endif
  68107. /*
  68108. ** The next global variable is incremented each type the OP_Sort opcode
  68109. ** is executed. The test procedures use this information to make sure that
  68110. ** sorting is occurring or not occurring at appropriate times. This variable
  68111. ** has no function other than to help verify the correct operation of the
  68112. ** library.
  68113. */
  68114. #ifdef SQLITE_TEST
  68115. SQLITE_API int sqlite3_sort_count = 0;
  68116. #endif
  68117. /*
  68118. ** The next global variable records the size of the largest MEM_Blob
  68119. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  68120. ** use this information to make sure that the zero-blob functionality
  68121. ** is working correctly. This variable has no function other than to
  68122. ** help verify the correct operation of the library.
  68123. */
  68124. #ifdef SQLITE_TEST
  68125. SQLITE_API int sqlite3_max_blobsize = 0;
  68126. static void updateMaxBlobsize(Mem *p){
  68127. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  68128. sqlite3_max_blobsize = p->n;
  68129. }
  68130. }
  68131. #endif
  68132. /*
  68133. ** The next global variable is incremented each time the OP_Found opcode
  68134. ** is executed. This is used to test whether or not the foreign key
  68135. ** operation implemented using OP_FkIsZero is working. This variable
  68136. ** has no function other than to help verify the correct operation of the
  68137. ** library.
  68138. */
  68139. #ifdef SQLITE_TEST
  68140. SQLITE_API int sqlite3_found_count = 0;
  68141. #endif
  68142. /*
  68143. ** Test a register to see if it exceeds the current maximum blob size.
  68144. ** If it does, record the new maximum blob size.
  68145. */
  68146. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  68147. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  68148. #else
  68149. # define UPDATE_MAX_BLOBSIZE(P)
  68150. #endif
  68151. /*
  68152. ** Invoke the VDBE coverage callback, if that callback is defined. This
  68153. ** feature is used for test suite validation only and does not appear an
  68154. ** production builds.
  68155. **
  68156. ** M is an integer, 2 or 3, that indices how many different ways the
  68157. ** branch can go. It is usually 2. "I" is the direction the branch
  68158. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  68159. ** second alternative branch is taken.
  68160. **
  68161. ** iSrcLine is the source code line (from the __LINE__ macro) that
  68162. ** generated the VDBE instruction. This instrumentation assumes that all
  68163. ** source code is in a single file (the amalgamation). Special values 1
  68164. ** and 2 for the iSrcLine parameter mean that this particular branch is
  68165. ** always taken or never taken, respectively.
  68166. */
  68167. #if !defined(SQLITE_VDBE_COVERAGE)
  68168. # define VdbeBranchTaken(I,M)
  68169. #else
  68170. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  68171. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  68172. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  68173. M = iSrcLine;
  68174. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  68175. ** VdbeCoverageNeverTaken() */
  68176. assert( (M & I)==I );
  68177. }else{
  68178. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  68179. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  68180. iSrcLine,I,M);
  68181. }
  68182. }
  68183. #endif
  68184. /*
  68185. ** Convert the given register into a string if it isn't one
  68186. ** already. Return non-zero if a malloc() fails.
  68187. */
  68188. #define Stringify(P, enc) \
  68189. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  68190. { goto no_mem; }
  68191. /*
  68192. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  68193. ** a pointer to a dynamically allocated string where some other entity
  68194. ** is responsible for deallocating that string. Because the register
  68195. ** does not control the string, it might be deleted without the register
  68196. ** knowing it.
  68197. **
  68198. ** This routine converts an ephemeral string into a dynamically allocated
  68199. ** string that the register itself controls. In other words, it
  68200. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  68201. */
  68202. #define Deephemeralize(P) \
  68203. if( ((P)->flags&MEM_Ephem)!=0 \
  68204. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  68205. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  68206. #define isSorter(x) ((x)->pSorter!=0)
  68207. /*
  68208. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  68209. ** if we run out of memory.
  68210. */
  68211. static VdbeCursor *allocateCursor(
  68212. Vdbe *p, /* The virtual machine */
  68213. int iCur, /* Index of the new VdbeCursor */
  68214. int nField, /* Number of fields in the table or index */
  68215. int iDb, /* Database the cursor belongs to, or -1 */
  68216. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  68217. ){
  68218. /* Find the memory cell that will be used to store the blob of memory
  68219. ** required for this VdbeCursor structure. It is convenient to use a
  68220. ** vdbe memory cell to manage the memory allocation required for a
  68221. ** VdbeCursor structure for the following reasons:
  68222. **
  68223. ** * Sometimes cursor numbers are used for a couple of different
  68224. ** purposes in a vdbe program. The different uses might require
  68225. ** different sized allocations. Memory cells provide growable
  68226. ** allocations.
  68227. **
  68228. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  68229. ** be freed lazily via the sqlite3_release_memory() API. This
  68230. ** minimizes the number of malloc calls made by the system.
  68231. **
  68232. ** Memory cells for cursors are allocated at the top of the address
  68233. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  68234. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  68235. */
  68236. Mem *pMem = &p->aMem[p->nMem-iCur];
  68237. int nByte;
  68238. VdbeCursor *pCx = 0;
  68239. nByte =
  68240. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  68241. (isBtreeCursor?sqlite3BtreeCursorSize():0);
  68242. assert( iCur<p->nCursor );
  68243. if( p->apCsr[iCur] ){
  68244. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  68245. p->apCsr[iCur] = 0;
  68246. }
  68247. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  68248. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  68249. memset(pCx, 0, sizeof(VdbeCursor));
  68250. pCx->iDb = iDb;
  68251. pCx->nField = nField;
  68252. pCx->aOffset = &pCx->aType[nField];
  68253. if( isBtreeCursor ){
  68254. pCx->pCursor = (BtCursor*)
  68255. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  68256. sqlite3BtreeCursorZero(pCx->pCursor);
  68257. }
  68258. }
  68259. return pCx;
  68260. }
  68261. /*
  68262. ** Try to convert a value into a numeric representation if we can
  68263. ** do so without loss of information. In other words, if the string
  68264. ** looks like a number, convert it into a number. If it does not
  68265. ** look like a number, leave it alone.
  68266. **
  68267. ** If the bTryForInt flag is true, then extra effort is made to give
  68268. ** an integer representation. Strings that look like floating point
  68269. ** values but which have no fractional component (example: '48.00')
  68270. ** will have a MEM_Int representation when bTryForInt is true.
  68271. **
  68272. ** If bTryForInt is false, then if the input string contains a decimal
  68273. ** point or exponential notation, the result is only MEM_Real, even
  68274. ** if there is an exact integer representation of the quantity.
  68275. */
  68276. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  68277. double rValue;
  68278. i64 iValue;
  68279. u8 enc = pRec->enc;
  68280. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  68281. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  68282. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  68283. pRec->u.i = iValue;
  68284. pRec->flags |= MEM_Int;
  68285. }else{
  68286. pRec->u.r = rValue;
  68287. pRec->flags |= MEM_Real;
  68288. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  68289. }
  68290. }
  68291. /*
  68292. ** Processing is determine by the affinity parameter:
  68293. **
  68294. ** SQLITE_AFF_INTEGER:
  68295. ** SQLITE_AFF_REAL:
  68296. ** SQLITE_AFF_NUMERIC:
  68297. ** Try to convert pRec to an integer representation or a
  68298. ** floating-point representation if an integer representation
  68299. ** is not possible. Note that the integer representation is
  68300. ** always preferred, even if the affinity is REAL, because
  68301. ** an integer representation is more space efficient on disk.
  68302. **
  68303. ** SQLITE_AFF_TEXT:
  68304. ** Convert pRec to a text representation.
  68305. **
  68306. ** SQLITE_AFF_BLOB:
  68307. ** No-op. pRec is unchanged.
  68308. */
  68309. static void applyAffinity(
  68310. Mem *pRec, /* The value to apply affinity to */
  68311. char affinity, /* The affinity to be applied */
  68312. u8 enc /* Use this text encoding */
  68313. ){
  68314. if( affinity>=SQLITE_AFF_NUMERIC ){
  68315. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  68316. || affinity==SQLITE_AFF_NUMERIC );
  68317. if( (pRec->flags & MEM_Int)==0 ){
  68318. if( (pRec->flags & MEM_Real)==0 ){
  68319. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  68320. }else{
  68321. sqlite3VdbeIntegerAffinity(pRec);
  68322. }
  68323. }
  68324. }else if( affinity==SQLITE_AFF_TEXT ){
  68325. /* Only attempt the conversion to TEXT if there is an integer or real
  68326. ** representation (blob and NULL do not get converted) but no string
  68327. ** representation.
  68328. */
  68329. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  68330. sqlite3VdbeMemStringify(pRec, enc, 1);
  68331. }
  68332. pRec->flags &= ~(MEM_Real|MEM_Int);
  68333. }
  68334. }
  68335. /*
  68336. ** Try to convert the type of a function argument or a result column
  68337. ** into a numeric representation. Use either INTEGER or REAL whichever
  68338. ** is appropriate. But only do the conversion if it is possible without
  68339. ** loss of information and return the revised type of the argument.
  68340. */
  68341. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
  68342. int eType = sqlite3_value_type(pVal);
  68343. if( eType==SQLITE_TEXT ){
  68344. Mem *pMem = (Mem*)pVal;
  68345. applyNumericAffinity(pMem, 0);
  68346. eType = sqlite3_value_type(pVal);
  68347. }
  68348. return eType;
  68349. }
  68350. /*
  68351. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  68352. ** not the internal Mem* type.
  68353. */
  68354. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  68355. sqlite3_value *pVal,
  68356. u8 affinity,
  68357. u8 enc
  68358. ){
  68359. applyAffinity((Mem *)pVal, affinity, enc);
  68360. }
  68361. /*
  68362. ** pMem currently only holds a string type (or maybe a BLOB that we can
  68363. ** interpret as a string if we want to). Compute its corresponding
  68364. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  68365. ** accordingly.
  68366. */
  68367. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  68368. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  68369. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  68370. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  68371. return 0;
  68372. }
  68373. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  68374. return MEM_Int;
  68375. }
  68376. return MEM_Real;
  68377. }
  68378. /*
  68379. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  68380. ** none.
  68381. **
  68382. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  68383. ** But it does set pMem->u.r and pMem->u.i appropriately.
  68384. */
  68385. static u16 numericType(Mem *pMem){
  68386. if( pMem->flags & (MEM_Int|MEM_Real) ){
  68387. return pMem->flags & (MEM_Int|MEM_Real);
  68388. }
  68389. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  68390. return computeNumericType(pMem);
  68391. }
  68392. return 0;
  68393. }
  68394. #ifdef SQLITE_DEBUG
  68395. /*
  68396. ** Write a nice string representation of the contents of cell pMem
  68397. ** into buffer zBuf, length nBuf.
  68398. */
  68399. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  68400. char *zCsr = zBuf;
  68401. int f = pMem->flags;
  68402. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  68403. if( f&MEM_Blob ){
  68404. int i;
  68405. char c;
  68406. if( f & MEM_Dyn ){
  68407. c = 'z';
  68408. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  68409. }else if( f & MEM_Static ){
  68410. c = 't';
  68411. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  68412. }else if( f & MEM_Ephem ){
  68413. c = 'e';
  68414. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  68415. }else{
  68416. c = 's';
  68417. }
  68418. sqlite3_snprintf(100, zCsr, "%c", c);
  68419. zCsr += sqlite3Strlen30(zCsr);
  68420. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  68421. zCsr += sqlite3Strlen30(zCsr);
  68422. for(i=0; i<16 && i<pMem->n; i++){
  68423. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  68424. zCsr += sqlite3Strlen30(zCsr);
  68425. }
  68426. for(i=0; i<16 && i<pMem->n; i++){
  68427. char z = pMem->z[i];
  68428. if( z<32 || z>126 ) *zCsr++ = '.';
  68429. else *zCsr++ = z;
  68430. }
  68431. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  68432. zCsr += sqlite3Strlen30(zCsr);
  68433. if( f & MEM_Zero ){
  68434. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  68435. zCsr += sqlite3Strlen30(zCsr);
  68436. }
  68437. *zCsr = '\0';
  68438. }else if( f & MEM_Str ){
  68439. int j, k;
  68440. zBuf[0] = ' ';
  68441. if( f & MEM_Dyn ){
  68442. zBuf[1] = 'z';
  68443. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  68444. }else if( f & MEM_Static ){
  68445. zBuf[1] = 't';
  68446. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  68447. }else if( f & MEM_Ephem ){
  68448. zBuf[1] = 'e';
  68449. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  68450. }else{
  68451. zBuf[1] = 's';
  68452. }
  68453. k = 2;
  68454. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  68455. k += sqlite3Strlen30(&zBuf[k]);
  68456. zBuf[k++] = '[';
  68457. for(j=0; j<15 && j<pMem->n; j++){
  68458. u8 c = pMem->z[j];
  68459. if( c>=0x20 && c<0x7f ){
  68460. zBuf[k++] = c;
  68461. }else{
  68462. zBuf[k++] = '.';
  68463. }
  68464. }
  68465. zBuf[k++] = ']';
  68466. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  68467. k += sqlite3Strlen30(&zBuf[k]);
  68468. zBuf[k++] = 0;
  68469. }
  68470. }
  68471. #endif
  68472. #ifdef SQLITE_DEBUG
  68473. /*
  68474. ** Print the value of a register for tracing purposes:
  68475. */
  68476. static void memTracePrint(Mem *p){
  68477. if( p->flags & MEM_Undefined ){
  68478. printf(" undefined");
  68479. }else if( p->flags & MEM_Null ){
  68480. printf(" NULL");
  68481. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  68482. printf(" si:%lld", p->u.i);
  68483. }else if( p->flags & MEM_Int ){
  68484. printf(" i:%lld", p->u.i);
  68485. #ifndef SQLITE_OMIT_FLOATING_POINT
  68486. }else if( p->flags & MEM_Real ){
  68487. printf(" r:%g", p->u.r);
  68488. #endif
  68489. }else if( p->flags & MEM_RowSet ){
  68490. printf(" (rowset)");
  68491. }else{
  68492. char zBuf[200];
  68493. sqlite3VdbeMemPrettyPrint(p, zBuf);
  68494. printf(" %s", zBuf);
  68495. }
  68496. }
  68497. static void registerTrace(int iReg, Mem *p){
  68498. printf("REG[%d] = ", iReg);
  68499. memTracePrint(p);
  68500. printf("\n");
  68501. }
  68502. #endif
  68503. #ifdef SQLITE_DEBUG
  68504. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  68505. #else
  68506. # define REGISTER_TRACE(R,M)
  68507. #endif
  68508. #ifdef VDBE_PROFILE
  68509. /*
  68510. ** hwtime.h contains inline assembler code for implementing
  68511. ** high-performance timing routines.
  68512. */
  68513. /************** Include hwtime.h in the middle of vdbe.c *********************/
  68514. /************** Begin file hwtime.h ******************************************/
  68515. /*
  68516. ** 2008 May 27
  68517. **
  68518. ** The author disclaims copyright to this source code. In place of
  68519. ** a legal notice, here is a blessing:
  68520. **
  68521. ** May you do good and not evil.
  68522. ** May you find forgiveness for yourself and forgive others.
  68523. ** May you share freely, never taking more than you give.
  68524. **
  68525. ******************************************************************************
  68526. **
  68527. ** This file contains inline asm code for retrieving "high-performance"
  68528. ** counters for x86 class CPUs.
  68529. */
  68530. #ifndef _HWTIME_H_
  68531. #define _HWTIME_H_
  68532. /*
  68533. ** The following routine only works on pentium-class (or newer) processors.
  68534. ** It uses the RDTSC opcode to read the cycle count value out of the
  68535. ** processor and returns that value. This can be used for high-res
  68536. ** profiling.
  68537. */
  68538. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  68539. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  68540. #if defined(__GNUC__)
  68541. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  68542. unsigned int lo, hi;
  68543. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  68544. return (sqlite_uint64)hi << 32 | lo;
  68545. }
  68546. #elif defined(_MSC_VER)
  68547. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  68548. __asm {
  68549. rdtsc
  68550. ret ; return value at EDX:EAX
  68551. }
  68552. }
  68553. #endif
  68554. #elif (defined(__GNUC__) && defined(__x86_64__))
  68555. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  68556. unsigned long val;
  68557. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  68558. return val;
  68559. }
  68560. #elif (defined(__GNUC__) && defined(__ppc__))
  68561. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  68562. unsigned long long retval;
  68563. unsigned long junk;
  68564. __asm__ __volatile__ ("\n\
  68565. 1: mftbu %1\n\
  68566. mftb %L0\n\
  68567. mftbu %0\n\
  68568. cmpw %0,%1\n\
  68569. bne 1b"
  68570. : "=r" (retval), "=r" (junk));
  68571. return retval;
  68572. }
  68573. #else
  68574. #error Need implementation of sqlite3Hwtime() for your platform.
  68575. /*
  68576. ** To compile without implementing sqlite3Hwtime() for your platform,
  68577. ** you can remove the above #error and use the following
  68578. ** stub function. You will lose timing support for many
  68579. ** of the debugging and testing utilities, but it should at
  68580. ** least compile and run.
  68581. */
  68582. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  68583. #endif
  68584. #endif /* !defined(_HWTIME_H_) */
  68585. /************** End of hwtime.h **********************************************/
  68586. /************** Continuing where we left off in vdbe.c ***********************/
  68587. #endif
  68588. #ifndef NDEBUG
  68589. /*
  68590. ** This function is only called from within an assert() expression. It
  68591. ** checks that the sqlite3.nTransaction variable is correctly set to
  68592. ** the number of non-transaction savepoints currently in the
  68593. ** linked list starting at sqlite3.pSavepoint.
  68594. **
  68595. ** Usage:
  68596. **
  68597. ** assert( checkSavepointCount(db) );
  68598. */
  68599. static int checkSavepointCount(sqlite3 *db){
  68600. int n = 0;
  68601. Savepoint *p;
  68602. for(p=db->pSavepoint; p; p=p->pNext) n++;
  68603. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  68604. return 1;
  68605. }
  68606. #endif
  68607. /*
  68608. ** Return the register of pOp->p2 after first preparing it to be
  68609. ** overwritten with an integer value.
  68610. */
  68611. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  68612. Mem *pOut;
  68613. assert( pOp->p2>0 );
  68614. assert( pOp->p2<=(p->nMem-p->nCursor) );
  68615. pOut = &p->aMem[pOp->p2];
  68616. memAboutToChange(p, pOut);
  68617. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  68618. pOut->flags = MEM_Int;
  68619. return pOut;
  68620. }
  68621. /*
  68622. ** Execute as much of a VDBE program as we can.
  68623. ** This is the core of sqlite3_step().
  68624. */
  68625. SQLITE_PRIVATE int sqlite3VdbeExec(
  68626. Vdbe *p /* The VDBE */
  68627. ){
  68628. Op *aOp = p->aOp; /* Copy of p->aOp */
  68629. Op *pOp = aOp; /* Current operation */
  68630. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68631. Op *pOrigOp; /* Value of pOp at the top of the loop */
  68632. #endif
  68633. int rc = SQLITE_OK; /* Value to return */
  68634. sqlite3 *db = p->db; /* The database */
  68635. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  68636. u8 encoding = ENC(db); /* The database encoding */
  68637. int iCompare = 0; /* Result of last OP_Compare operation */
  68638. unsigned nVmStep = 0; /* Number of virtual machine steps */
  68639. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  68640. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  68641. #endif
  68642. Mem *aMem = p->aMem; /* Copy of p->aMem */
  68643. Mem *pIn1 = 0; /* 1st input operand */
  68644. Mem *pIn2 = 0; /* 2nd input operand */
  68645. Mem *pIn3 = 0; /* 3rd input operand */
  68646. Mem *pOut = 0; /* Output operand */
  68647. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  68648. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  68649. #ifdef VDBE_PROFILE
  68650. u64 start; /* CPU clock count at start of opcode */
  68651. #endif
  68652. /*** INSERT STACK UNION HERE ***/
  68653. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  68654. sqlite3VdbeEnter(p);
  68655. if( p->rc==SQLITE_NOMEM ){
  68656. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  68657. ** sqlite3_column_text16() failed. */
  68658. goto no_mem;
  68659. }
  68660. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  68661. assert( p->bIsReader || p->readOnly!=0 );
  68662. p->rc = SQLITE_OK;
  68663. p->iCurrentTime = 0;
  68664. assert( p->explain==0 );
  68665. p->pResultSet = 0;
  68666. db->busyHandler.nBusy = 0;
  68667. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  68668. sqlite3VdbeIOTraceSql(p);
  68669. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  68670. if( db->xProgress ){
  68671. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  68672. assert( 0 < db->nProgressOps );
  68673. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  68674. }
  68675. #endif
  68676. #ifdef SQLITE_DEBUG
  68677. sqlite3BeginBenignMalloc();
  68678. if( p->pc==0
  68679. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  68680. ){
  68681. int i;
  68682. int once = 1;
  68683. sqlite3VdbePrintSql(p);
  68684. if( p->db->flags & SQLITE_VdbeListing ){
  68685. printf("VDBE Program Listing:\n");
  68686. for(i=0; i<p->nOp; i++){
  68687. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  68688. }
  68689. }
  68690. if( p->db->flags & SQLITE_VdbeEQP ){
  68691. for(i=0; i<p->nOp; i++){
  68692. if( aOp[i].opcode==OP_Explain ){
  68693. if( once ) printf("VDBE Query Plan:\n");
  68694. printf("%s\n", aOp[i].p4.z);
  68695. once = 0;
  68696. }
  68697. }
  68698. }
  68699. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  68700. }
  68701. sqlite3EndBenignMalloc();
  68702. #endif
  68703. for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
  68704. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  68705. if( db->mallocFailed ) goto no_mem;
  68706. #ifdef VDBE_PROFILE
  68707. start = sqlite3Hwtime();
  68708. #endif
  68709. nVmStep++;
  68710. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68711. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  68712. #endif
  68713. /* Only allow tracing if SQLITE_DEBUG is defined.
  68714. */
  68715. #ifdef SQLITE_DEBUG
  68716. if( db->flags & SQLITE_VdbeTrace ){
  68717. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  68718. }
  68719. #endif
  68720. /* Check to see if we need to simulate an interrupt. This only happens
  68721. ** if we have a special test build.
  68722. */
  68723. #ifdef SQLITE_TEST
  68724. if( sqlite3_interrupt_count>0 ){
  68725. sqlite3_interrupt_count--;
  68726. if( sqlite3_interrupt_count==0 ){
  68727. sqlite3_interrupt(db);
  68728. }
  68729. }
  68730. #endif
  68731. /* Sanity checking on other operands */
  68732. #ifdef SQLITE_DEBUG
  68733. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  68734. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  68735. assert( pOp->p1>0 );
  68736. assert( pOp->p1<=(p->nMem-p->nCursor) );
  68737. assert( memIsValid(&aMem[pOp->p1]) );
  68738. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  68739. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  68740. }
  68741. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  68742. assert( pOp->p2>0 );
  68743. assert( pOp->p2<=(p->nMem-p->nCursor) );
  68744. assert( memIsValid(&aMem[pOp->p2]) );
  68745. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  68746. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  68747. }
  68748. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  68749. assert( pOp->p3>0 );
  68750. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68751. assert( memIsValid(&aMem[pOp->p3]) );
  68752. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  68753. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  68754. }
  68755. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  68756. assert( pOp->p2>0 );
  68757. assert( pOp->p2<=(p->nMem-p->nCursor) );
  68758. memAboutToChange(p, &aMem[pOp->p2]);
  68759. }
  68760. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  68761. assert( pOp->p3>0 );
  68762. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68763. memAboutToChange(p, &aMem[pOp->p3]);
  68764. }
  68765. #endif
  68766. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68767. pOrigOp = pOp;
  68768. #endif
  68769. switch( pOp->opcode ){
  68770. /*****************************************************************************
  68771. ** What follows is a massive switch statement where each case implements a
  68772. ** separate instruction in the virtual machine. If we follow the usual
  68773. ** indentation conventions, each case should be indented by 6 spaces. But
  68774. ** that is a lot of wasted space on the left margin. So the code within
  68775. ** the switch statement will break with convention and be flush-left. Another
  68776. ** big comment (similar to this one) will mark the point in the code where
  68777. ** we transition back to normal indentation.
  68778. **
  68779. ** The formatting of each case is important. The makefile for SQLite
  68780. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  68781. ** file looking for lines that begin with "case OP_". The opcodes.h files
  68782. ** will be filled with #defines that give unique integer values to each
  68783. ** opcode and the opcodes.c file is filled with an array of strings where
  68784. ** each string is the symbolic name for the corresponding opcode. If the
  68785. ** case statement is followed by a comment of the form "/# same as ... #/"
  68786. ** that comment is used to determine the particular value of the opcode.
  68787. **
  68788. ** Other keywords in the comment that follows each case are used to
  68789. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  68790. ** Keywords include: in1, in2, in3, out2, out3. See
  68791. ** the mkopcodeh.awk script for additional information.
  68792. **
  68793. ** Documentation about VDBE opcodes is generated by scanning this file
  68794. ** for lines of that contain "Opcode:". That line and all subsequent
  68795. ** comment lines are used in the generation of the opcode.html documentation
  68796. ** file.
  68797. **
  68798. ** SUMMARY:
  68799. **
  68800. ** Formatting is important to scripts that scan this file.
  68801. ** Do not deviate from the formatting style currently in use.
  68802. **
  68803. *****************************************************************************/
  68804. /* Opcode: Goto * P2 * * *
  68805. **
  68806. ** An unconditional jump to address P2.
  68807. ** The next instruction executed will be
  68808. ** the one at index P2 from the beginning of
  68809. ** the program.
  68810. **
  68811. ** The P1 parameter is not actually used by this opcode. However, it
  68812. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  68813. ** that this Goto is the bottom of a loop and that the lines from P2 down
  68814. ** to the current line should be indented for EXPLAIN output.
  68815. */
  68816. case OP_Goto: { /* jump */
  68817. jump_to_p2_and_check_for_interrupt:
  68818. pOp = &aOp[pOp->p2 - 1];
  68819. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  68820. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  68821. ** completion. Check to see if sqlite3_interrupt() has been called
  68822. ** or if the progress callback needs to be invoked.
  68823. **
  68824. ** This code uses unstructured "goto" statements and does not look clean.
  68825. ** But that is not due to sloppy coding habits. The code is written this
  68826. ** way for performance, to avoid having to run the interrupt and progress
  68827. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  68828. ** faster according to "valgrind --tool=cachegrind" */
  68829. check_for_interrupt:
  68830. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  68831. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  68832. /* Call the progress callback if it is configured and the required number
  68833. ** of VDBE ops have been executed (either since this invocation of
  68834. ** sqlite3VdbeExec() or since last time the progress callback was called).
  68835. ** If the progress callback returns non-zero, exit the virtual machine with
  68836. ** a return code SQLITE_ABORT.
  68837. */
  68838. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  68839. assert( db->nProgressOps!=0 );
  68840. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  68841. if( db->xProgress(db->pProgressArg) ){
  68842. rc = SQLITE_INTERRUPT;
  68843. goto vdbe_error_halt;
  68844. }
  68845. }
  68846. #endif
  68847. break;
  68848. }
  68849. /* Opcode: Gosub P1 P2 * * *
  68850. **
  68851. ** Write the current address onto register P1
  68852. ** and then jump to address P2.
  68853. */
  68854. case OP_Gosub: { /* jump */
  68855. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  68856. pIn1 = &aMem[pOp->p1];
  68857. assert( VdbeMemDynamic(pIn1)==0 );
  68858. memAboutToChange(p, pIn1);
  68859. pIn1->flags = MEM_Int;
  68860. pIn1->u.i = (int)(pOp-aOp);
  68861. REGISTER_TRACE(pOp->p1, pIn1);
  68862. /* Most jump operations do a goto to this spot in order to update
  68863. ** the pOp pointer. */
  68864. jump_to_p2:
  68865. pOp = &aOp[pOp->p2 - 1];
  68866. break;
  68867. }
  68868. /* Opcode: Return P1 * * * *
  68869. **
  68870. ** Jump to the next instruction after the address in register P1. After
  68871. ** the jump, register P1 becomes undefined.
  68872. */
  68873. case OP_Return: { /* in1 */
  68874. pIn1 = &aMem[pOp->p1];
  68875. assert( pIn1->flags==MEM_Int );
  68876. pOp = &aOp[pIn1->u.i];
  68877. pIn1->flags = MEM_Undefined;
  68878. break;
  68879. }
  68880. /* Opcode: InitCoroutine P1 P2 P3 * *
  68881. **
  68882. ** Set up register P1 so that it will Yield to the coroutine
  68883. ** located at address P3.
  68884. **
  68885. ** If P2!=0 then the coroutine implementation immediately follows
  68886. ** this opcode. So jump over the coroutine implementation to
  68887. ** address P2.
  68888. **
  68889. ** See also: EndCoroutine
  68890. */
  68891. case OP_InitCoroutine: { /* jump */
  68892. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  68893. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  68894. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  68895. pOut = &aMem[pOp->p1];
  68896. assert( !VdbeMemDynamic(pOut) );
  68897. pOut->u.i = pOp->p3 - 1;
  68898. pOut->flags = MEM_Int;
  68899. if( pOp->p2 ) goto jump_to_p2;
  68900. break;
  68901. }
  68902. /* Opcode: EndCoroutine P1 * * * *
  68903. **
  68904. ** The instruction at the address in register P1 is a Yield.
  68905. ** Jump to the P2 parameter of that Yield.
  68906. ** After the jump, register P1 becomes undefined.
  68907. **
  68908. ** See also: InitCoroutine
  68909. */
  68910. case OP_EndCoroutine: { /* in1 */
  68911. VdbeOp *pCaller;
  68912. pIn1 = &aMem[pOp->p1];
  68913. assert( pIn1->flags==MEM_Int );
  68914. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  68915. pCaller = &aOp[pIn1->u.i];
  68916. assert( pCaller->opcode==OP_Yield );
  68917. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  68918. pOp = &aOp[pCaller->p2 - 1];
  68919. pIn1->flags = MEM_Undefined;
  68920. break;
  68921. }
  68922. /* Opcode: Yield P1 P2 * * *
  68923. **
  68924. ** Swap the program counter with the value in register P1. This
  68925. ** has the effect of yielding to a coroutine.
  68926. **
  68927. ** If the coroutine that is launched by this instruction ends with
  68928. ** Yield or Return then continue to the next instruction. But if
  68929. ** the coroutine launched by this instruction ends with
  68930. ** EndCoroutine, then jump to P2 rather than continuing with the
  68931. ** next instruction.
  68932. **
  68933. ** See also: InitCoroutine
  68934. */
  68935. case OP_Yield: { /* in1, jump */
  68936. int pcDest;
  68937. pIn1 = &aMem[pOp->p1];
  68938. assert( VdbeMemDynamic(pIn1)==0 );
  68939. pIn1->flags = MEM_Int;
  68940. pcDest = (int)pIn1->u.i;
  68941. pIn1->u.i = (int)(pOp - aOp);
  68942. REGISTER_TRACE(pOp->p1, pIn1);
  68943. pOp = &aOp[pcDest];
  68944. break;
  68945. }
  68946. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  68947. ** Synopsis: if r[P3]=null halt
  68948. **
  68949. ** Check the value in register P3. If it is NULL then Halt using
  68950. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  68951. ** value in register P3 is not NULL, then this routine is a no-op.
  68952. ** The P5 parameter should be 1.
  68953. */
  68954. case OP_HaltIfNull: { /* in3 */
  68955. pIn3 = &aMem[pOp->p3];
  68956. if( (pIn3->flags & MEM_Null)==0 ) break;
  68957. /* Fall through into OP_Halt */
  68958. }
  68959. /* Opcode: Halt P1 P2 * P4 P5
  68960. **
  68961. ** Exit immediately. All open cursors, etc are closed
  68962. ** automatically.
  68963. **
  68964. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  68965. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  68966. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  68967. ** whether or not to rollback the current transaction. Do not rollback
  68968. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  68969. ** then back out all changes that have occurred during this execution of the
  68970. ** VDBE, but do not rollback the transaction.
  68971. **
  68972. ** If P4 is not null then it is an error message string.
  68973. **
  68974. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  68975. **
  68976. ** 0: (no change)
  68977. ** 1: NOT NULL contraint failed: P4
  68978. ** 2: UNIQUE constraint failed: P4
  68979. ** 3: CHECK constraint failed: P4
  68980. ** 4: FOREIGN KEY constraint failed: P4
  68981. **
  68982. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  68983. ** omitted.
  68984. **
  68985. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  68986. ** every program. So a jump past the last instruction of the program
  68987. ** is the same as executing Halt.
  68988. */
  68989. case OP_Halt: {
  68990. const char *zType;
  68991. const char *zLogFmt;
  68992. VdbeFrame *pFrame;
  68993. int pcx;
  68994. pcx = (int)(pOp - aOp);
  68995. if( pOp->p1==SQLITE_OK && p->pFrame ){
  68996. /* Halt the sub-program. Return control to the parent frame. */
  68997. pFrame = p->pFrame;
  68998. p->pFrame = pFrame->pParent;
  68999. p->nFrame--;
  69000. sqlite3VdbeSetChanges(db, p->nChange);
  69001. pcx = sqlite3VdbeFrameRestore(pFrame);
  69002. lastRowid = db->lastRowid;
  69003. if( pOp->p2==OE_Ignore ){
  69004. /* Instruction pcx is the OP_Program that invoked the sub-program
  69005. ** currently being halted. If the p2 instruction of this OP_Halt
  69006. ** instruction is set to OE_Ignore, then the sub-program is throwing
  69007. ** an IGNORE exception. In this case jump to the address specified
  69008. ** as the p2 of the calling OP_Program. */
  69009. pcx = p->aOp[pcx].p2-1;
  69010. }
  69011. aOp = p->aOp;
  69012. aMem = p->aMem;
  69013. pOp = &aOp[pcx];
  69014. break;
  69015. }
  69016. p->rc = pOp->p1;
  69017. p->errorAction = (u8)pOp->p2;
  69018. p->pc = pcx;
  69019. if( p->rc ){
  69020. if( pOp->p5 ){
  69021. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  69022. "FOREIGN KEY" };
  69023. assert( pOp->p5>=1 && pOp->p5<=4 );
  69024. testcase( pOp->p5==1 );
  69025. testcase( pOp->p5==2 );
  69026. testcase( pOp->p5==3 );
  69027. testcase( pOp->p5==4 );
  69028. zType = azType[pOp->p5-1];
  69029. }else{
  69030. zType = 0;
  69031. }
  69032. assert( zType!=0 || pOp->p4.z!=0 );
  69033. zLogFmt = "abort at %d in [%s]: %s";
  69034. if( zType && pOp->p4.z ){
  69035. sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
  69036. }else if( pOp->p4.z ){
  69037. sqlite3VdbeError(p, "%s", pOp->p4.z);
  69038. }else{
  69039. sqlite3VdbeError(p, "%s constraint failed", zType);
  69040. }
  69041. sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
  69042. }
  69043. rc = sqlite3VdbeHalt(p);
  69044. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  69045. if( rc==SQLITE_BUSY ){
  69046. p->rc = rc = SQLITE_BUSY;
  69047. }else{
  69048. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  69049. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  69050. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  69051. }
  69052. goto vdbe_return;
  69053. }
  69054. /* Opcode: Integer P1 P2 * * *
  69055. ** Synopsis: r[P2]=P1
  69056. **
  69057. ** The 32-bit integer value P1 is written into register P2.
  69058. */
  69059. case OP_Integer: { /* out2 */
  69060. pOut = out2Prerelease(p, pOp);
  69061. pOut->u.i = pOp->p1;
  69062. break;
  69063. }
  69064. /* Opcode: Int64 * P2 * P4 *
  69065. ** Synopsis: r[P2]=P4
  69066. **
  69067. ** P4 is a pointer to a 64-bit integer value.
  69068. ** Write that value into register P2.
  69069. */
  69070. case OP_Int64: { /* out2 */
  69071. pOut = out2Prerelease(p, pOp);
  69072. assert( pOp->p4.pI64!=0 );
  69073. pOut->u.i = *pOp->p4.pI64;
  69074. break;
  69075. }
  69076. #ifndef SQLITE_OMIT_FLOATING_POINT
  69077. /* Opcode: Real * P2 * P4 *
  69078. ** Synopsis: r[P2]=P4
  69079. **
  69080. ** P4 is a pointer to a 64-bit floating point value.
  69081. ** Write that value into register P2.
  69082. */
  69083. case OP_Real: { /* same as TK_FLOAT, out2 */
  69084. pOut = out2Prerelease(p, pOp);
  69085. pOut->flags = MEM_Real;
  69086. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  69087. pOut->u.r = *pOp->p4.pReal;
  69088. break;
  69089. }
  69090. #endif
  69091. /* Opcode: String8 * P2 * P4 *
  69092. ** Synopsis: r[P2]='P4'
  69093. **
  69094. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  69095. ** into a String opcode before it is executed for the first time. During
  69096. ** this transformation, the length of string P4 is computed and stored
  69097. ** as the P1 parameter.
  69098. */
  69099. case OP_String8: { /* same as TK_STRING, out2 */
  69100. assert( pOp->p4.z!=0 );
  69101. pOut = out2Prerelease(p, pOp);
  69102. pOp->opcode = OP_String;
  69103. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  69104. #ifndef SQLITE_OMIT_UTF16
  69105. if( encoding!=SQLITE_UTF8 ){
  69106. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  69107. if( rc==SQLITE_TOOBIG ) goto too_big;
  69108. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  69109. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  69110. assert( VdbeMemDynamic(pOut)==0 );
  69111. pOut->szMalloc = 0;
  69112. pOut->flags |= MEM_Static;
  69113. if( pOp->p4type==P4_DYNAMIC ){
  69114. sqlite3DbFree(db, pOp->p4.z);
  69115. }
  69116. pOp->p4type = P4_DYNAMIC;
  69117. pOp->p4.z = pOut->z;
  69118. pOp->p1 = pOut->n;
  69119. }
  69120. #endif
  69121. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69122. goto too_big;
  69123. }
  69124. /* Fall through to the next case, OP_String */
  69125. }
  69126. /* Opcode: String P1 P2 P3 P4 P5
  69127. ** Synopsis: r[P2]='P4' (len=P1)
  69128. **
  69129. ** The string value P4 of length P1 (bytes) is stored in register P2.
  69130. **
  69131. ** If P5!=0 and the content of register P3 is greater than zero, then
  69132. ** the datatype of the register P2 is converted to BLOB. The content is
  69133. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  69134. ** of a string, as if it had been CAST.
  69135. */
  69136. case OP_String: { /* out2 */
  69137. assert( pOp->p4.z!=0 );
  69138. pOut = out2Prerelease(p, pOp);
  69139. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  69140. pOut->z = pOp->p4.z;
  69141. pOut->n = pOp->p1;
  69142. pOut->enc = encoding;
  69143. UPDATE_MAX_BLOBSIZE(pOut);
  69144. if( pOp->p5 ){
  69145. assert( pOp->p3>0 );
  69146. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69147. pIn3 = &aMem[pOp->p3];
  69148. assert( pIn3->flags & MEM_Int );
  69149. if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  69150. }
  69151. break;
  69152. }
  69153. /* Opcode: Null P1 P2 P3 * *
  69154. ** Synopsis: r[P2..P3]=NULL
  69155. **
  69156. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  69157. ** NULL into register P3 and every register in between P2 and P3. If P3
  69158. ** is less than P2 (typically P3 is zero) then only register P2 is
  69159. ** set to NULL.
  69160. **
  69161. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  69162. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  69163. ** OP_Ne or OP_Eq.
  69164. */
  69165. case OP_Null: { /* out2 */
  69166. int cnt;
  69167. u16 nullFlag;
  69168. pOut = out2Prerelease(p, pOp);
  69169. cnt = pOp->p3-pOp->p2;
  69170. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69171. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  69172. while( cnt>0 ){
  69173. pOut++;
  69174. memAboutToChange(p, pOut);
  69175. sqlite3VdbeMemSetNull(pOut);
  69176. pOut->flags = nullFlag;
  69177. cnt--;
  69178. }
  69179. break;
  69180. }
  69181. /* Opcode: SoftNull P1 * * * *
  69182. ** Synopsis: r[P1]=NULL
  69183. **
  69184. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  69185. ** instruction, but do not free any string or blob memory associated with
  69186. ** the register, so that if the value was a string or blob that was
  69187. ** previously copied using OP_SCopy, the copies will continue to be valid.
  69188. */
  69189. case OP_SoftNull: {
  69190. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69191. pOut = &aMem[pOp->p1];
  69192. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  69193. break;
  69194. }
  69195. /* Opcode: Blob P1 P2 * P4 *
  69196. ** Synopsis: r[P2]=P4 (len=P1)
  69197. **
  69198. ** P4 points to a blob of data P1 bytes long. Store this
  69199. ** blob in register P2.
  69200. */
  69201. case OP_Blob: { /* out2 */
  69202. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  69203. pOut = out2Prerelease(p, pOp);
  69204. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  69205. pOut->enc = encoding;
  69206. UPDATE_MAX_BLOBSIZE(pOut);
  69207. break;
  69208. }
  69209. /* Opcode: Variable P1 P2 * P4 *
  69210. ** Synopsis: r[P2]=parameter(P1,P4)
  69211. **
  69212. ** Transfer the values of bound parameter P1 into register P2
  69213. **
  69214. ** If the parameter is named, then its name appears in P4.
  69215. ** The P4 value is used by sqlite3_bind_parameter_name().
  69216. */
  69217. case OP_Variable: { /* out2 */
  69218. Mem *pVar; /* Value being transferred */
  69219. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  69220. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  69221. pVar = &p->aVar[pOp->p1 - 1];
  69222. if( sqlite3VdbeMemTooBig(pVar) ){
  69223. goto too_big;
  69224. }
  69225. pOut = out2Prerelease(p, pOp);
  69226. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  69227. UPDATE_MAX_BLOBSIZE(pOut);
  69228. break;
  69229. }
  69230. /* Opcode: Move P1 P2 P3 * *
  69231. ** Synopsis: r[P2@P3]=r[P1@P3]
  69232. **
  69233. ** Move the P3 values in register P1..P1+P3-1 over into
  69234. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  69235. ** left holding a NULL. It is an error for register ranges
  69236. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  69237. ** for P3 to be less than 1.
  69238. */
  69239. case OP_Move: {
  69240. int n; /* Number of registers left to copy */
  69241. int p1; /* Register to copy from */
  69242. int p2; /* Register to copy to */
  69243. n = pOp->p3;
  69244. p1 = pOp->p1;
  69245. p2 = pOp->p2;
  69246. assert( n>0 && p1>0 && p2>0 );
  69247. assert( p1+n<=p2 || p2+n<=p1 );
  69248. pIn1 = &aMem[p1];
  69249. pOut = &aMem[p2];
  69250. do{
  69251. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  69252. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  69253. assert( memIsValid(pIn1) );
  69254. memAboutToChange(p, pOut);
  69255. sqlite3VdbeMemMove(pOut, pIn1);
  69256. #ifdef SQLITE_DEBUG
  69257. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  69258. pOut->pScopyFrom += pOp->p2 - p1;
  69259. }
  69260. #endif
  69261. Deephemeralize(pOut);
  69262. REGISTER_TRACE(p2++, pOut);
  69263. pIn1++;
  69264. pOut++;
  69265. }while( --n );
  69266. break;
  69267. }
  69268. /* Opcode: Copy P1 P2 P3 * *
  69269. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  69270. **
  69271. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  69272. **
  69273. ** This instruction makes a deep copy of the value. A duplicate
  69274. ** is made of any string or blob constant. See also OP_SCopy.
  69275. */
  69276. case OP_Copy: {
  69277. int n;
  69278. n = pOp->p3;
  69279. pIn1 = &aMem[pOp->p1];
  69280. pOut = &aMem[pOp->p2];
  69281. assert( pOut!=pIn1 );
  69282. while( 1 ){
  69283. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  69284. Deephemeralize(pOut);
  69285. #ifdef SQLITE_DEBUG
  69286. pOut->pScopyFrom = 0;
  69287. #endif
  69288. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  69289. if( (n--)==0 ) break;
  69290. pOut++;
  69291. pIn1++;
  69292. }
  69293. break;
  69294. }
  69295. /* Opcode: SCopy P1 P2 * * *
  69296. ** Synopsis: r[P2]=r[P1]
  69297. **
  69298. ** Make a shallow copy of register P1 into register P2.
  69299. **
  69300. ** This instruction makes a shallow copy of the value. If the value
  69301. ** is a string or blob, then the copy is only a pointer to the
  69302. ** original and hence if the original changes so will the copy.
  69303. ** Worse, if the original is deallocated, the copy becomes invalid.
  69304. ** Thus the program must guarantee that the original will not change
  69305. ** during the lifetime of the copy. Use OP_Copy to make a complete
  69306. ** copy.
  69307. */
  69308. case OP_SCopy: { /* out2 */
  69309. pIn1 = &aMem[pOp->p1];
  69310. pOut = &aMem[pOp->p2];
  69311. assert( pOut!=pIn1 );
  69312. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  69313. #ifdef SQLITE_DEBUG
  69314. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  69315. #endif
  69316. break;
  69317. }
  69318. /* Opcode: ResultRow P1 P2 * * *
  69319. ** Synopsis: output=r[P1@P2]
  69320. **
  69321. ** The registers P1 through P1+P2-1 contain a single row of
  69322. ** results. This opcode causes the sqlite3_step() call to terminate
  69323. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  69324. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  69325. ** the result row.
  69326. */
  69327. case OP_ResultRow: {
  69328. Mem *pMem;
  69329. int i;
  69330. assert( p->nResColumn==pOp->p2 );
  69331. assert( pOp->p1>0 );
  69332. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  69333. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  69334. /* Run the progress counter just before returning.
  69335. */
  69336. if( db->xProgress!=0
  69337. && nVmStep>=nProgressLimit
  69338. && db->xProgress(db->pProgressArg)!=0
  69339. ){
  69340. rc = SQLITE_INTERRUPT;
  69341. goto vdbe_error_halt;
  69342. }
  69343. #endif
  69344. /* If this statement has violated immediate foreign key constraints, do
  69345. ** not return the number of rows modified. And do not RELEASE the statement
  69346. ** transaction. It needs to be rolled back. */
  69347. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  69348. assert( db->flags&SQLITE_CountRows );
  69349. assert( p->usesStmtJournal );
  69350. break;
  69351. }
  69352. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  69353. ** DML statements invoke this opcode to return the number of rows
  69354. ** modified to the user. This is the only way that a VM that
  69355. ** opens a statement transaction may invoke this opcode.
  69356. **
  69357. ** In case this is such a statement, close any statement transaction
  69358. ** opened by this VM before returning control to the user. This is to
  69359. ** ensure that statement-transactions are always nested, not overlapping.
  69360. ** If the open statement-transaction is not closed here, then the user
  69361. ** may step another VM that opens its own statement transaction. This
  69362. ** may lead to overlapping statement transactions.
  69363. **
  69364. ** The statement transaction is never a top-level transaction. Hence
  69365. ** the RELEASE call below can never fail.
  69366. */
  69367. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  69368. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  69369. if( NEVER(rc!=SQLITE_OK) ){
  69370. break;
  69371. }
  69372. /* Invalidate all ephemeral cursor row caches */
  69373. p->cacheCtr = (p->cacheCtr + 2)|1;
  69374. /* Make sure the results of the current row are \000 terminated
  69375. ** and have an assigned type. The results are de-ephemeralized as
  69376. ** a side effect.
  69377. */
  69378. pMem = p->pResultSet = &aMem[pOp->p1];
  69379. for(i=0; i<pOp->p2; i++){
  69380. assert( memIsValid(&pMem[i]) );
  69381. Deephemeralize(&pMem[i]);
  69382. assert( (pMem[i].flags & MEM_Ephem)==0
  69383. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  69384. sqlite3VdbeMemNulTerminate(&pMem[i]);
  69385. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  69386. }
  69387. if( db->mallocFailed ) goto no_mem;
  69388. /* Return SQLITE_ROW
  69389. */
  69390. p->pc = (int)(pOp - aOp) + 1;
  69391. rc = SQLITE_ROW;
  69392. goto vdbe_return;
  69393. }
  69394. /* Opcode: Concat P1 P2 P3 * *
  69395. ** Synopsis: r[P3]=r[P2]+r[P1]
  69396. **
  69397. ** Add the text in register P1 onto the end of the text in
  69398. ** register P2 and store the result in register P3.
  69399. ** If either the P1 or P2 text are NULL then store NULL in P3.
  69400. **
  69401. ** P3 = P2 || P1
  69402. **
  69403. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  69404. ** if P3 is the same register as P2, the implementation is able
  69405. ** to avoid a memcpy().
  69406. */
  69407. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  69408. i64 nByte;
  69409. pIn1 = &aMem[pOp->p1];
  69410. pIn2 = &aMem[pOp->p2];
  69411. pOut = &aMem[pOp->p3];
  69412. assert( pIn1!=pOut );
  69413. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  69414. sqlite3VdbeMemSetNull(pOut);
  69415. break;
  69416. }
  69417. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  69418. Stringify(pIn1, encoding);
  69419. Stringify(pIn2, encoding);
  69420. nByte = pIn1->n + pIn2->n;
  69421. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69422. goto too_big;
  69423. }
  69424. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  69425. goto no_mem;
  69426. }
  69427. MemSetTypeFlag(pOut, MEM_Str);
  69428. if( pOut!=pIn2 ){
  69429. memcpy(pOut->z, pIn2->z, pIn2->n);
  69430. }
  69431. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  69432. pOut->z[nByte]=0;
  69433. pOut->z[nByte+1] = 0;
  69434. pOut->flags |= MEM_Term;
  69435. pOut->n = (int)nByte;
  69436. pOut->enc = encoding;
  69437. UPDATE_MAX_BLOBSIZE(pOut);
  69438. break;
  69439. }
  69440. /* Opcode: Add P1 P2 P3 * *
  69441. ** Synopsis: r[P3]=r[P1]+r[P2]
  69442. **
  69443. ** Add the value in register P1 to the value in register P2
  69444. ** and store the result in register P3.
  69445. ** If either input is NULL, the result is NULL.
  69446. */
  69447. /* Opcode: Multiply P1 P2 P3 * *
  69448. ** Synopsis: r[P3]=r[P1]*r[P2]
  69449. **
  69450. **
  69451. ** Multiply the value in register P1 by the value in register P2
  69452. ** and store the result in register P3.
  69453. ** If either input is NULL, the result is NULL.
  69454. */
  69455. /* Opcode: Subtract P1 P2 P3 * *
  69456. ** Synopsis: r[P3]=r[P2]-r[P1]
  69457. **
  69458. ** Subtract the value in register P1 from the value in register P2
  69459. ** and store the result in register P3.
  69460. ** If either input is NULL, the result is NULL.
  69461. */
  69462. /* Opcode: Divide P1 P2 P3 * *
  69463. ** Synopsis: r[P3]=r[P2]/r[P1]
  69464. **
  69465. ** Divide the value in register P1 by the value in register P2
  69466. ** and store the result in register P3 (P3=P2/P1). If the value in
  69467. ** register P1 is zero, then the result is NULL. If either input is
  69468. ** NULL, the result is NULL.
  69469. */
  69470. /* Opcode: Remainder P1 P2 P3 * *
  69471. ** Synopsis: r[P3]=r[P2]%r[P1]
  69472. **
  69473. ** Compute the remainder after integer register P2 is divided by
  69474. ** register P1 and store the result in register P3.
  69475. ** If the value in register P1 is zero the result is NULL.
  69476. ** If either operand is NULL, the result is NULL.
  69477. */
  69478. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  69479. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  69480. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  69481. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  69482. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  69483. char bIntint; /* Started out as two integer operands */
  69484. u16 flags; /* Combined MEM_* flags from both inputs */
  69485. u16 type1; /* Numeric type of left operand */
  69486. u16 type2; /* Numeric type of right operand */
  69487. i64 iA; /* Integer value of left operand */
  69488. i64 iB; /* Integer value of right operand */
  69489. double rA; /* Real value of left operand */
  69490. double rB; /* Real value of right operand */
  69491. pIn1 = &aMem[pOp->p1];
  69492. type1 = numericType(pIn1);
  69493. pIn2 = &aMem[pOp->p2];
  69494. type2 = numericType(pIn2);
  69495. pOut = &aMem[pOp->p3];
  69496. flags = pIn1->flags | pIn2->flags;
  69497. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  69498. if( (type1 & type2 & MEM_Int)!=0 ){
  69499. iA = pIn1->u.i;
  69500. iB = pIn2->u.i;
  69501. bIntint = 1;
  69502. switch( pOp->opcode ){
  69503. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  69504. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  69505. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  69506. case OP_Divide: {
  69507. if( iA==0 ) goto arithmetic_result_is_null;
  69508. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  69509. iB /= iA;
  69510. break;
  69511. }
  69512. default: {
  69513. if( iA==0 ) goto arithmetic_result_is_null;
  69514. if( iA==-1 ) iA = 1;
  69515. iB %= iA;
  69516. break;
  69517. }
  69518. }
  69519. pOut->u.i = iB;
  69520. MemSetTypeFlag(pOut, MEM_Int);
  69521. }else{
  69522. bIntint = 0;
  69523. fp_math:
  69524. rA = sqlite3VdbeRealValue(pIn1);
  69525. rB = sqlite3VdbeRealValue(pIn2);
  69526. switch( pOp->opcode ){
  69527. case OP_Add: rB += rA; break;
  69528. case OP_Subtract: rB -= rA; break;
  69529. case OP_Multiply: rB *= rA; break;
  69530. case OP_Divide: {
  69531. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  69532. if( rA==(double)0 ) goto arithmetic_result_is_null;
  69533. rB /= rA;
  69534. break;
  69535. }
  69536. default: {
  69537. iA = (i64)rA;
  69538. iB = (i64)rB;
  69539. if( iA==0 ) goto arithmetic_result_is_null;
  69540. if( iA==-1 ) iA = 1;
  69541. rB = (double)(iB % iA);
  69542. break;
  69543. }
  69544. }
  69545. #ifdef SQLITE_OMIT_FLOATING_POINT
  69546. pOut->u.i = rB;
  69547. MemSetTypeFlag(pOut, MEM_Int);
  69548. #else
  69549. if( sqlite3IsNaN(rB) ){
  69550. goto arithmetic_result_is_null;
  69551. }
  69552. pOut->u.r = rB;
  69553. MemSetTypeFlag(pOut, MEM_Real);
  69554. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  69555. sqlite3VdbeIntegerAffinity(pOut);
  69556. }
  69557. #endif
  69558. }
  69559. break;
  69560. arithmetic_result_is_null:
  69561. sqlite3VdbeMemSetNull(pOut);
  69562. break;
  69563. }
  69564. /* Opcode: CollSeq P1 * * P4
  69565. **
  69566. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  69567. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  69568. ** be returned. This is used by the built-in min(), max() and nullif()
  69569. ** functions.
  69570. **
  69571. ** If P1 is not zero, then it is a register that a subsequent min() or
  69572. ** max() aggregate will set to 1 if the current row is not the minimum or
  69573. ** maximum. The P1 register is initialized to 0 by this instruction.
  69574. **
  69575. ** The interface used by the implementation of the aforementioned functions
  69576. ** to retrieve the collation sequence set by this opcode is not available
  69577. ** publicly. Only built-in functions have access to this feature.
  69578. */
  69579. case OP_CollSeq: {
  69580. assert( pOp->p4type==P4_COLLSEQ );
  69581. if( pOp->p1 ){
  69582. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  69583. }
  69584. break;
  69585. }
  69586. /* Opcode: Function0 P1 P2 P3 P4 P5
  69587. ** Synopsis: r[P3]=func(r[P2@P5])
  69588. **
  69589. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  69590. ** defines the function) with P5 arguments taken from register P2 and
  69591. ** successors. The result of the function is stored in register P3.
  69592. ** Register P3 must not be one of the function inputs.
  69593. **
  69594. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  69595. ** function was determined to be constant at compile time. If the first
  69596. ** argument was constant then bit 0 of P1 is set. This is used to determine
  69597. ** whether meta data associated with a user function argument using the
  69598. ** sqlite3_set_auxdata() API may be safely retained until the next
  69599. ** invocation of this opcode.
  69600. **
  69601. ** See also: Function, AggStep, AggFinal
  69602. */
  69603. /* Opcode: Function P1 P2 P3 P4 P5
  69604. ** Synopsis: r[P3]=func(r[P2@P5])
  69605. **
  69606. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  69607. ** contains a pointer to the function to be run) with P5 arguments taken
  69608. ** from register P2 and successors. The result of the function is stored
  69609. ** in register P3. Register P3 must not be one of the function inputs.
  69610. **
  69611. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  69612. ** function was determined to be constant at compile time. If the first
  69613. ** argument was constant then bit 0 of P1 is set. This is used to determine
  69614. ** whether meta data associated with a user function argument using the
  69615. ** sqlite3_set_auxdata() API may be safely retained until the next
  69616. ** invocation of this opcode.
  69617. **
  69618. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  69619. ** to a FuncDef object. But on first evaluation, the P4 operand is
  69620. ** automatically converted into an sqlite3_context object and the operation
  69621. ** changed to this OP_Function opcode. In this way, the initialization of
  69622. ** the sqlite3_context object occurs only once, rather than once for each
  69623. ** evaluation of the function.
  69624. **
  69625. ** See also: Function0, AggStep, AggFinal
  69626. */
  69627. case OP_Function0: {
  69628. int n;
  69629. sqlite3_context *pCtx;
  69630. assert( pOp->p4type==P4_FUNCDEF );
  69631. n = pOp->p5;
  69632. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69633. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  69634. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  69635. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  69636. if( pCtx==0 ) goto no_mem;
  69637. pCtx->pOut = 0;
  69638. pCtx->pFunc = pOp->p4.pFunc;
  69639. pCtx->iOp = (int)(pOp - aOp);
  69640. pCtx->pVdbe = p;
  69641. pCtx->argc = n;
  69642. pOp->p4type = P4_FUNCCTX;
  69643. pOp->p4.pCtx = pCtx;
  69644. pOp->opcode = OP_Function;
  69645. /* Fall through into OP_Function */
  69646. }
  69647. case OP_Function: {
  69648. int i;
  69649. sqlite3_context *pCtx;
  69650. assert( pOp->p4type==P4_FUNCCTX );
  69651. pCtx = pOp->p4.pCtx;
  69652. /* If this function is inside of a trigger, the register array in aMem[]
  69653. ** might change from one evaluation to the next. The next block of code
  69654. ** checks to see if the register array has changed, and if so it
  69655. ** reinitializes the relavant parts of the sqlite3_context object */
  69656. pOut = &aMem[pOp->p3];
  69657. if( pCtx->pOut != pOut ){
  69658. pCtx->pOut = pOut;
  69659. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  69660. }
  69661. memAboutToChange(p, pCtx->pOut);
  69662. #ifdef SQLITE_DEBUG
  69663. for(i=0; i<pCtx->argc; i++){
  69664. assert( memIsValid(pCtx->argv[i]) );
  69665. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  69666. }
  69667. #endif
  69668. MemSetTypeFlag(pCtx->pOut, MEM_Null);
  69669. pCtx->fErrorOrAux = 0;
  69670. db->lastRowid = lastRowid;
  69671. (*pCtx->pFunc->xFunc)(pCtx, pCtx->argc, pCtx->argv); /* IMP: R-24505-23230 */
  69672. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  69673. /* If the function returned an error, throw an exception */
  69674. if( pCtx->fErrorOrAux ){
  69675. if( pCtx->isError ){
  69676. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  69677. rc = pCtx->isError;
  69678. }
  69679. sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
  69680. }
  69681. /* Copy the result of the function into register P3 */
  69682. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  69683. sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
  69684. if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
  69685. }
  69686. REGISTER_TRACE(pOp->p3, pCtx->pOut);
  69687. UPDATE_MAX_BLOBSIZE(pCtx->pOut);
  69688. break;
  69689. }
  69690. /* Opcode: BitAnd P1 P2 P3 * *
  69691. ** Synopsis: r[P3]=r[P1]&r[P2]
  69692. **
  69693. ** Take the bit-wise AND of the values in register P1 and P2 and
  69694. ** store the result in register P3.
  69695. ** If either input is NULL, the result is NULL.
  69696. */
  69697. /* Opcode: BitOr P1 P2 P3 * *
  69698. ** Synopsis: r[P3]=r[P1]|r[P2]
  69699. **
  69700. ** Take the bit-wise OR of the values in register P1 and P2 and
  69701. ** store the result in register P3.
  69702. ** If either input is NULL, the result is NULL.
  69703. */
  69704. /* Opcode: ShiftLeft P1 P2 P3 * *
  69705. ** Synopsis: r[P3]=r[P2]<<r[P1]
  69706. **
  69707. ** Shift the integer value in register P2 to the left by the
  69708. ** number of bits specified by the integer in register P1.
  69709. ** Store the result in register P3.
  69710. ** If either input is NULL, the result is NULL.
  69711. */
  69712. /* Opcode: ShiftRight P1 P2 P3 * *
  69713. ** Synopsis: r[P3]=r[P2]>>r[P1]
  69714. **
  69715. ** Shift the integer value in register P2 to the right by the
  69716. ** number of bits specified by the integer in register P1.
  69717. ** Store the result in register P3.
  69718. ** If either input is NULL, the result is NULL.
  69719. */
  69720. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  69721. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  69722. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  69723. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  69724. i64 iA;
  69725. u64 uA;
  69726. i64 iB;
  69727. u8 op;
  69728. pIn1 = &aMem[pOp->p1];
  69729. pIn2 = &aMem[pOp->p2];
  69730. pOut = &aMem[pOp->p3];
  69731. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  69732. sqlite3VdbeMemSetNull(pOut);
  69733. break;
  69734. }
  69735. iA = sqlite3VdbeIntValue(pIn2);
  69736. iB = sqlite3VdbeIntValue(pIn1);
  69737. op = pOp->opcode;
  69738. if( op==OP_BitAnd ){
  69739. iA &= iB;
  69740. }else if( op==OP_BitOr ){
  69741. iA |= iB;
  69742. }else if( iB!=0 ){
  69743. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  69744. /* If shifting by a negative amount, shift in the other direction */
  69745. if( iB<0 ){
  69746. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  69747. op = 2*OP_ShiftLeft + 1 - op;
  69748. iB = iB>(-64) ? -iB : 64;
  69749. }
  69750. if( iB>=64 ){
  69751. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  69752. }else{
  69753. memcpy(&uA, &iA, sizeof(uA));
  69754. if( op==OP_ShiftLeft ){
  69755. uA <<= iB;
  69756. }else{
  69757. uA >>= iB;
  69758. /* Sign-extend on a right shift of a negative number */
  69759. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  69760. }
  69761. memcpy(&iA, &uA, sizeof(iA));
  69762. }
  69763. }
  69764. pOut->u.i = iA;
  69765. MemSetTypeFlag(pOut, MEM_Int);
  69766. break;
  69767. }
  69768. /* Opcode: AddImm P1 P2 * * *
  69769. ** Synopsis: r[P1]=r[P1]+P2
  69770. **
  69771. ** Add the constant P2 to the value in register P1.
  69772. ** The result is always an integer.
  69773. **
  69774. ** To force any register to be an integer, just add 0.
  69775. */
  69776. case OP_AddImm: { /* in1 */
  69777. pIn1 = &aMem[pOp->p1];
  69778. memAboutToChange(p, pIn1);
  69779. sqlite3VdbeMemIntegerify(pIn1);
  69780. pIn1->u.i += pOp->p2;
  69781. break;
  69782. }
  69783. /* Opcode: MustBeInt P1 P2 * * *
  69784. **
  69785. ** Force the value in register P1 to be an integer. If the value
  69786. ** in P1 is not an integer and cannot be converted into an integer
  69787. ** without data loss, then jump immediately to P2, or if P2==0
  69788. ** raise an SQLITE_MISMATCH exception.
  69789. */
  69790. case OP_MustBeInt: { /* jump, in1 */
  69791. pIn1 = &aMem[pOp->p1];
  69792. if( (pIn1->flags & MEM_Int)==0 ){
  69793. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  69794. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  69795. if( (pIn1->flags & MEM_Int)==0 ){
  69796. if( pOp->p2==0 ){
  69797. rc = SQLITE_MISMATCH;
  69798. goto abort_due_to_error;
  69799. }else{
  69800. goto jump_to_p2;
  69801. }
  69802. }
  69803. }
  69804. MemSetTypeFlag(pIn1, MEM_Int);
  69805. break;
  69806. }
  69807. #ifndef SQLITE_OMIT_FLOATING_POINT
  69808. /* Opcode: RealAffinity P1 * * * *
  69809. **
  69810. ** If register P1 holds an integer convert it to a real value.
  69811. **
  69812. ** This opcode is used when extracting information from a column that
  69813. ** has REAL affinity. Such column values may still be stored as
  69814. ** integers, for space efficiency, but after extraction we want them
  69815. ** to have only a real value.
  69816. */
  69817. case OP_RealAffinity: { /* in1 */
  69818. pIn1 = &aMem[pOp->p1];
  69819. if( pIn1->flags & MEM_Int ){
  69820. sqlite3VdbeMemRealify(pIn1);
  69821. }
  69822. break;
  69823. }
  69824. #endif
  69825. #ifndef SQLITE_OMIT_CAST
  69826. /* Opcode: Cast P1 P2 * * *
  69827. ** Synopsis: affinity(r[P1])
  69828. **
  69829. ** Force the value in register P1 to be the type defined by P2.
  69830. **
  69831. ** <ul>
  69832. ** <li value="97"> TEXT
  69833. ** <li value="98"> BLOB
  69834. ** <li value="99"> NUMERIC
  69835. ** <li value="100"> INTEGER
  69836. ** <li value="101"> REAL
  69837. ** </ul>
  69838. **
  69839. ** A NULL value is not changed by this routine. It remains NULL.
  69840. */
  69841. case OP_Cast: { /* in1 */
  69842. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  69843. testcase( pOp->p2==SQLITE_AFF_TEXT );
  69844. testcase( pOp->p2==SQLITE_AFF_BLOB );
  69845. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  69846. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  69847. testcase( pOp->p2==SQLITE_AFF_REAL );
  69848. pIn1 = &aMem[pOp->p1];
  69849. memAboutToChange(p, pIn1);
  69850. rc = ExpandBlob(pIn1);
  69851. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  69852. UPDATE_MAX_BLOBSIZE(pIn1);
  69853. break;
  69854. }
  69855. #endif /* SQLITE_OMIT_CAST */
  69856. /* Opcode: Lt P1 P2 P3 P4 P5
  69857. ** Synopsis: if r[P1]<r[P3] goto P2
  69858. **
  69859. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  69860. ** jump to address P2.
  69861. **
  69862. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  69863. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  69864. ** bit is clear then fall through if either operand is NULL.
  69865. **
  69866. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  69867. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  69868. ** to coerce both inputs according to this affinity before the
  69869. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  69870. ** affinity is used. Note that the affinity conversions are stored
  69871. ** back into the input registers P1 and P3. So this opcode can cause
  69872. ** persistent changes to registers P1 and P3.
  69873. **
  69874. ** Once any conversions have taken place, and neither value is NULL,
  69875. ** the values are compared. If both values are blobs then memcmp() is
  69876. ** used to determine the results of the comparison. If both values
  69877. ** are text, then the appropriate collating function specified in
  69878. ** P4 is used to do the comparison. If P4 is not specified then
  69879. ** memcmp() is used to compare text string. If both values are
  69880. ** numeric, then a numeric comparison is used. If the two values
  69881. ** are of different types, then numbers are considered less than
  69882. ** strings and strings are considered less than blobs.
  69883. **
  69884. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  69885. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  69886. **
  69887. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  69888. ** equal to one another, provided that they do not have their MEM_Cleared
  69889. ** bit set.
  69890. */
  69891. /* Opcode: Ne P1 P2 P3 P4 P5
  69892. ** Synopsis: if r[P1]!=r[P3] goto P2
  69893. **
  69894. ** This works just like the Lt opcode except that the jump is taken if
  69895. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  69896. ** additional information.
  69897. **
  69898. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  69899. ** true or false and is never NULL. If both operands are NULL then the result
  69900. ** of comparison is false. If either operand is NULL then the result is true.
  69901. ** If neither operand is NULL the result is the same as it would be if
  69902. ** the SQLITE_NULLEQ flag were omitted from P5.
  69903. */
  69904. /* Opcode: Eq P1 P2 P3 P4 P5
  69905. ** Synopsis: if r[P1]==r[P3] goto P2
  69906. **
  69907. ** This works just like the Lt opcode except that the jump is taken if
  69908. ** the operands in registers P1 and P3 are equal.
  69909. ** See the Lt opcode for additional information.
  69910. **
  69911. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  69912. ** true or false and is never NULL. If both operands are NULL then the result
  69913. ** of comparison is true. If either operand is NULL then the result is false.
  69914. ** If neither operand is NULL the result is the same as it would be if
  69915. ** the SQLITE_NULLEQ flag were omitted from P5.
  69916. */
  69917. /* Opcode: Le P1 P2 P3 P4 P5
  69918. ** Synopsis: if r[P1]<=r[P3] goto P2
  69919. **
  69920. ** This works just like the Lt opcode except that the jump is taken if
  69921. ** the content of register P3 is less than or equal to the content of
  69922. ** register P1. See the Lt opcode for additional information.
  69923. */
  69924. /* Opcode: Gt P1 P2 P3 P4 P5
  69925. ** Synopsis: if r[P1]>r[P3] goto P2
  69926. **
  69927. ** This works just like the Lt opcode except that the jump is taken if
  69928. ** the content of register P3 is greater than the content of
  69929. ** register P1. See the Lt opcode for additional information.
  69930. */
  69931. /* Opcode: Ge P1 P2 P3 P4 P5
  69932. ** Synopsis: if r[P1]>=r[P3] goto P2
  69933. **
  69934. ** This works just like the Lt opcode except that the jump is taken if
  69935. ** the content of register P3 is greater than or equal to the content of
  69936. ** register P1. See the Lt opcode for additional information.
  69937. */
  69938. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  69939. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  69940. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  69941. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  69942. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  69943. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  69944. int res; /* Result of the comparison of pIn1 against pIn3 */
  69945. char affinity; /* Affinity to use for comparison */
  69946. u16 flags1; /* Copy of initial value of pIn1->flags */
  69947. u16 flags3; /* Copy of initial value of pIn3->flags */
  69948. pIn1 = &aMem[pOp->p1];
  69949. pIn3 = &aMem[pOp->p3];
  69950. flags1 = pIn1->flags;
  69951. flags3 = pIn3->flags;
  69952. if( (flags1 | flags3)&MEM_Null ){
  69953. /* One or both operands are NULL */
  69954. if( pOp->p5 & SQLITE_NULLEQ ){
  69955. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  69956. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  69957. ** or not both operands are null.
  69958. */
  69959. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  69960. assert( (flags1 & MEM_Cleared)==0 );
  69961. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  69962. if( (flags1&MEM_Null)!=0
  69963. && (flags3&MEM_Null)!=0
  69964. && (flags3&MEM_Cleared)==0
  69965. ){
  69966. res = 0; /* Results are equal */
  69967. }else{
  69968. res = 1; /* Results are not equal */
  69969. }
  69970. }else{
  69971. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  69972. ** then the result is always NULL.
  69973. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  69974. */
  69975. if( pOp->p5 & SQLITE_STOREP2 ){
  69976. pOut = &aMem[pOp->p2];
  69977. MemSetTypeFlag(pOut, MEM_Null);
  69978. REGISTER_TRACE(pOp->p2, pOut);
  69979. }else{
  69980. VdbeBranchTaken(2,3);
  69981. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  69982. goto jump_to_p2;
  69983. }
  69984. }
  69985. break;
  69986. }
  69987. }else{
  69988. /* Neither operand is NULL. Do a comparison. */
  69989. affinity = pOp->p5 & SQLITE_AFF_MASK;
  69990. if( affinity>=SQLITE_AFF_NUMERIC ){
  69991. if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  69992. applyNumericAffinity(pIn1,0);
  69993. }
  69994. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  69995. applyNumericAffinity(pIn3,0);
  69996. }
  69997. }else if( affinity==SQLITE_AFF_TEXT ){
  69998. if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
  69999. testcase( pIn1->flags & MEM_Int );
  70000. testcase( pIn1->flags & MEM_Real );
  70001. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  70002. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  70003. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  70004. }
  70005. if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
  70006. testcase( pIn3->flags & MEM_Int );
  70007. testcase( pIn3->flags & MEM_Real );
  70008. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  70009. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  70010. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  70011. }
  70012. }
  70013. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  70014. if( pIn1->flags & MEM_Zero ){
  70015. sqlite3VdbeMemExpandBlob(pIn1);
  70016. flags1 &= ~MEM_Zero;
  70017. }
  70018. if( pIn3->flags & MEM_Zero ){
  70019. sqlite3VdbeMemExpandBlob(pIn3);
  70020. flags3 &= ~MEM_Zero;
  70021. }
  70022. if( db->mallocFailed ) goto no_mem;
  70023. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  70024. }
  70025. switch( pOp->opcode ){
  70026. case OP_Eq: res = res==0; break;
  70027. case OP_Ne: res = res!=0; break;
  70028. case OP_Lt: res = res<0; break;
  70029. case OP_Le: res = res<=0; break;
  70030. case OP_Gt: res = res>0; break;
  70031. default: res = res>=0; break;
  70032. }
  70033. /* Undo any changes made by applyAffinity() to the input registers. */
  70034. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  70035. pIn1->flags = flags1;
  70036. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  70037. pIn3->flags = flags3;
  70038. if( pOp->p5 & SQLITE_STOREP2 ){
  70039. pOut = &aMem[pOp->p2];
  70040. memAboutToChange(p, pOut);
  70041. MemSetTypeFlag(pOut, MEM_Int);
  70042. pOut->u.i = res;
  70043. REGISTER_TRACE(pOp->p2, pOut);
  70044. }else{
  70045. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  70046. if( res ){
  70047. goto jump_to_p2;
  70048. }
  70049. }
  70050. break;
  70051. }
  70052. /* Opcode: Permutation * * * P4 *
  70053. **
  70054. ** Set the permutation used by the OP_Compare operator to be the array
  70055. ** of integers in P4.
  70056. **
  70057. ** The permutation is only valid until the next OP_Compare that has
  70058. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  70059. ** occur immediately prior to the OP_Compare.
  70060. */
  70061. case OP_Permutation: {
  70062. assert( pOp->p4type==P4_INTARRAY );
  70063. assert( pOp->p4.ai );
  70064. aPermute = pOp->p4.ai;
  70065. break;
  70066. }
  70067. /* Opcode: Compare P1 P2 P3 P4 P5
  70068. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  70069. **
  70070. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  70071. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  70072. ** the comparison for use by the next OP_Jump instruct.
  70073. **
  70074. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  70075. ** determined by the most recent OP_Permutation operator. If the
  70076. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  70077. ** order.
  70078. **
  70079. ** P4 is a KeyInfo structure that defines collating sequences and sort
  70080. ** orders for the comparison. The permutation applies to registers
  70081. ** only. The KeyInfo elements are used sequentially.
  70082. **
  70083. ** The comparison is a sort comparison, so NULLs compare equal,
  70084. ** NULLs are less than numbers, numbers are less than strings,
  70085. ** and strings are less than blobs.
  70086. */
  70087. case OP_Compare: {
  70088. int n;
  70089. int i;
  70090. int p1;
  70091. int p2;
  70092. const KeyInfo *pKeyInfo;
  70093. int idx;
  70094. CollSeq *pColl; /* Collating sequence to use on this term */
  70095. int bRev; /* True for DESCENDING sort order */
  70096. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  70097. n = pOp->p3;
  70098. pKeyInfo = pOp->p4.pKeyInfo;
  70099. assert( n>0 );
  70100. assert( pKeyInfo!=0 );
  70101. p1 = pOp->p1;
  70102. p2 = pOp->p2;
  70103. #if SQLITE_DEBUG
  70104. if( aPermute ){
  70105. int k, mx = 0;
  70106. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  70107. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  70108. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  70109. }else{
  70110. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  70111. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  70112. }
  70113. #endif /* SQLITE_DEBUG */
  70114. for(i=0; i<n; i++){
  70115. idx = aPermute ? aPermute[i] : i;
  70116. assert( memIsValid(&aMem[p1+idx]) );
  70117. assert( memIsValid(&aMem[p2+idx]) );
  70118. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  70119. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  70120. assert( i<pKeyInfo->nField );
  70121. pColl = pKeyInfo->aColl[i];
  70122. bRev = pKeyInfo->aSortOrder[i];
  70123. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  70124. if( iCompare ){
  70125. if( bRev ) iCompare = -iCompare;
  70126. break;
  70127. }
  70128. }
  70129. aPermute = 0;
  70130. break;
  70131. }
  70132. /* Opcode: Jump P1 P2 P3 * *
  70133. **
  70134. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  70135. ** in the most recent OP_Compare instruction the P1 vector was less than
  70136. ** equal to, or greater than the P2 vector, respectively.
  70137. */
  70138. case OP_Jump: { /* jump */
  70139. if( iCompare<0 ){
  70140. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  70141. }else if( iCompare==0 ){
  70142. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  70143. }else{
  70144. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  70145. }
  70146. break;
  70147. }
  70148. /* Opcode: And P1 P2 P3 * *
  70149. ** Synopsis: r[P3]=(r[P1] && r[P2])
  70150. **
  70151. ** Take the logical AND of the values in registers P1 and P2 and
  70152. ** write the result into register P3.
  70153. **
  70154. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  70155. ** the other input is NULL. A NULL and true or two NULLs give
  70156. ** a NULL output.
  70157. */
  70158. /* Opcode: Or P1 P2 P3 * *
  70159. ** Synopsis: r[P3]=(r[P1] || r[P2])
  70160. **
  70161. ** Take the logical OR of the values in register P1 and P2 and
  70162. ** store the answer in register P3.
  70163. **
  70164. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  70165. ** even if the other input is NULL. A NULL and false or two NULLs
  70166. ** give a NULL output.
  70167. */
  70168. case OP_And: /* same as TK_AND, in1, in2, out3 */
  70169. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  70170. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  70171. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  70172. pIn1 = &aMem[pOp->p1];
  70173. if( pIn1->flags & MEM_Null ){
  70174. v1 = 2;
  70175. }else{
  70176. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  70177. }
  70178. pIn2 = &aMem[pOp->p2];
  70179. if( pIn2->flags & MEM_Null ){
  70180. v2 = 2;
  70181. }else{
  70182. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  70183. }
  70184. if( pOp->opcode==OP_And ){
  70185. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  70186. v1 = and_logic[v1*3+v2];
  70187. }else{
  70188. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  70189. v1 = or_logic[v1*3+v2];
  70190. }
  70191. pOut = &aMem[pOp->p3];
  70192. if( v1==2 ){
  70193. MemSetTypeFlag(pOut, MEM_Null);
  70194. }else{
  70195. pOut->u.i = v1;
  70196. MemSetTypeFlag(pOut, MEM_Int);
  70197. }
  70198. break;
  70199. }
  70200. /* Opcode: Not P1 P2 * * *
  70201. ** Synopsis: r[P2]= !r[P1]
  70202. **
  70203. ** Interpret the value in register P1 as a boolean value. Store the
  70204. ** boolean complement in register P2. If the value in register P1 is
  70205. ** NULL, then a NULL is stored in P2.
  70206. */
  70207. case OP_Not: { /* same as TK_NOT, in1, out2 */
  70208. pIn1 = &aMem[pOp->p1];
  70209. pOut = &aMem[pOp->p2];
  70210. sqlite3VdbeMemSetNull(pOut);
  70211. if( (pIn1->flags & MEM_Null)==0 ){
  70212. pOut->flags = MEM_Int;
  70213. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  70214. }
  70215. break;
  70216. }
  70217. /* Opcode: BitNot P1 P2 * * *
  70218. ** Synopsis: r[P1]= ~r[P1]
  70219. **
  70220. ** Interpret the content of register P1 as an integer. Store the
  70221. ** ones-complement of the P1 value into register P2. If P1 holds
  70222. ** a NULL then store a NULL in P2.
  70223. */
  70224. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  70225. pIn1 = &aMem[pOp->p1];
  70226. pOut = &aMem[pOp->p2];
  70227. sqlite3VdbeMemSetNull(pOut);
  70228. if( (pIn1->flags & MEM_Null)==0 ){
  70229. pOut->flags = MEM_Int;
  70230. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  70231. }
  70232. break;
  70233. }
  70234. /* Opcode: Once P1 P2 * * *
  70235. **
  70236. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  70237. ** Otherwise, set the flag and fall through to the next instruction.
  70238. ** In other words, this opcode causes all following opcodes up through P2
  70239. ** (but not including P2) to run just once and to be skipped on subsequent
  70240. ** times through the loop.
  70241. **
  70242. ** All "once" flags are initially cleared whenever a prepared statement
  70243. ** first begins to run.
  70244. */
  70245. case OP_Once: { /* jump */
  70246. assert( pOp->p1<p->nOnceFlag );
  70247. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  70248. if( p->aOnceFlag[pOp->p1] ){
  70249. goto jump_to_p2;
  70250. }else{
  70251. p->aOnceFlag[pOp->p1] = 1;
  70252. }
  70253. break;
  70254. }
  70255. /* Opcode: If P1 P2 P3 * *
  70256. **
  70257. ** Jump to P2 if the value in register P1 is true. The value
  70258. ** is considered true if it is numeric and non-zero. If the value
  70259. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  70260. */
  70261. /* Opcode: IfNot P1 P2 P3 * *
  70262. **
  70263. ** Jump to P2 if the value in register P1 is False. The value
  70264. ** is considered false if it has a numeric value of zero. If the value
  70265. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  70266. */
  70267. case OP_If: /* jump, in1 */
  70268. case OP_IfNot: { /* jump, in1 */
  70269. int c;
  70270. pIn1 = &aMem[pOp->p1];
  70271. if( pIn1->flags & MEM_Null ){
  70272. c = pOp->p3;
  70273. }else{
  70274. #ifdef SQLITE_OMIT_FLOATING_POINT
  70275. c = sqlite3VdbeIntValue(pIn1)!=0;
  70276. #else
  70277. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  70278. #endif
  70279. if( pOp->opcode==OP_IfNot ) c = !c;
  70280. }
  70281. VdbeBranchTaken(c!=0, 2);
  70282. if( c ){
  70283. goto jump_to_p2;
  70284. }
  70285. break;
  70286. }
  70287. /* Opcode: IsNull P1 P2 * * *
  70288. ** Synopsis: if r[P1]==NULL goto P2
  70289. **
  70290. ** Jump to P2 if the value in register P1 is NULL.
  70291. */
  70292. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  70293. pIn1 = &aMem[pOp->p1];
  70294. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  70295. if( (pIn1->flags & MEM_Null)!=0 ){
  70296. goto jump_to_p2;
  70297. }
  70298. break;
  70299. }
  70300. /* Opcode: NotNull P1 P2 * * *
  70301. ** Synopsis: if r[P1]!=NULL goto P2
  70302. **
  70303. ** Jump to P2 if the value in register P1 is not NULL.
  70304. */
  70305. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  70306. pIn1 = &aMem[pOp->p1];
  70307. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  70308. if( (pIn1->flags & MEM_Null)==0 ){
  70309. goto jump_to_p2;
  70310. }
  70311. break;
  70312. }
  70313. /* Opcode: Column P1 P2 P3 P4 P5
  70314. ** Synopsis: r[P3]=PX
  70315. **
  70316. ** Interpret the data that cursor P1 points to as a structure built using
  70317. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  70318. ** information about the format of the data.) Extract the P2-th column
  70319. ** from this record. If there are less that (P2+1)
  70320. ** values in the record, extract a NULL.
  70321. **
  70322. ** The value extracted is stored in register P3.
  70323. **
  70324. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  70325. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  70326. ** the result.
  70327. **
  70328. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  70329. ** then the cache of the cursor is reset prior to extracting the column.
  70330. ** The first OP_Column against a pseudo-table after the value of the content
  70331. ** register has changed should have this bit set.
  70332. **
  70333. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  70334. ** the result is guaranteed to only be used as the argument of a length()
  70335. ** or typeof() function, respectively. The loading of large blobs can be
  70336. ** skipped for length() and all content loading can be skipped for typeof().
  70337. */
  70338. case OP_Column: {
  70339. i64 payloadSize64; /* Number of bytes in the record */
  70340. int p2; /* column number to retrieve */
  70341. VdbeCursor *pC; /* The VDBE cursor */
  70342. BtCursor *pCrsr; /* The BTree cursor */
  70343. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  70344. int len; /* The length of the serialized data for the column */
  70345. int i; /* Loop counter */
  70346. Mem *pDest; /* Where to write the extracted value */
  70347. Mem sMem; /* For storing the record being decoded */
  70348. const u8 *zData; /* Part of the record being decoded */
  70349. const u8 *zHdr; /* Next unparsed byte of the header */
  70350. const u8 *zEndHdr; /* Pointer to first byte after the header */
  70351. u32 offset; /* Offset into the data */
  70352. u32 szField; /* Number of bytes in the content of a field */
  70353. u32 avail; /* Number of bytes of available data */
  70354. u32 t; /* A type code from the record header */
  70355. u16 fx; /* pDest->flags value */
  70356. Mem *pReg; /* PseudoTable input register */
  70357. p2 = pOp->p2;
  70358. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70359. pDest = &aMem[pOp->p3];
  70360. memAboutToChange(p, pDest);
  70361. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70362. pC = p->apCsr[pOp->p1];
  70363. assert( pC!=0 );
  70364. assert( p2<pC->nField );
  70365. aOffset = pC->aOffset;
  70366. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70367. assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
  70368. #endif
  70369. pCrsr = pC->pCursor;
  70370. assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
  70371. assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
  70372. /* If the cursor cache is stale, bring it up-to-date */
  70373. rc = sqlite3VdbeCursorMoveto(pC);
  70374. if( rc ) goto abort_due_to_error;
  70375. if( pC->cacheStatus!=p->cacheCtr ){
  70376. if( pC->nullRow ){
  70377. if( pCrsr==0 ){
  70378. assert( pC->pseudoTableReg>0 );
  70379. pReg = &aMem[pC->pseudoTableReg];
  70380. assert( pReg->flags & MEM_Blob );
  70381. assert( memIsValid(pReg) );
  70382. pC->payloadSize = pC->szRow = avail = pReg->n;
  70383. pC->aRow = (u8*)pReg->z;
  70384. }else{
  70385. sqlite3VdbeMemSetNull(pDest);
  70386. goto op_column_out;
  70387. }
  70388. }else{
  70389. assert( pCrsr );
  70390. if( pC->isTable==0 ){
  70391. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  70392. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  70393. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  70394. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  70395. ** payload size, so it is impossible for payloadSize64 to be
  70396. ** larger than 32 bits. */
  70397. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  70398. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  70399. pC->payloadSize = (u32)payloadSize64;
  70400. }else{
  70401. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  70402. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  70403. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  70404. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  70405. }
  70406. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  70407. if( pC->payloadSize <= (u32)avail ){
  70408. pC->szRow = pC->payloadSize;
  70409. }else{
  70410. pC->szRow = avail;
  70411. }
  70412. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70413. goto too_big;
  70414. }
  70415. }
  70416. pC->cacheStatus = p->cacheCtr;
  70417. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  70418. pC->nHdrParsed = 0;
  70419. aOffset[0] = offset;
  70420. /* Make sure a corrupt database has not given us an oversize header.
  70421. ** Do this now to avoid an oversize memory allocation.
  70422. **
  70423. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  70424. ** types use so much data space that there can only be 4096 and 32 of
  70425. ** them, respectively. So the maximum header length results from a
  70426. ** 3-byte type for each of the maximum of 32768 columns plus three
  70427. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  70428. */
  70429. if( offset > 98307 || offset > pC->payloadSize ){
  70430. rc = SQLITE_CORRUPT_BKPT;
  70431. goto op_column_error;
  70432. }
  70433. if( avail<offset ){
  70434. /* pC->aRow does not have to hold the entire row, but it does at least
  70435. ** need to cover the header of the record. If pC->aRow does not contain
  70436. ** the complete header, then set it to zero, forcing the header to be
  70437. ** dynamically allocated. */
  70438. pC->aRow = 0;
  70439. pC->szRow = 0;
  70440. }
  70441. /* The following goto is an optimization. It can be omitted and
  70442. ** everything will still work. But OP_Column is measurably faster
  70443. ** by skipping the subsequent conditional, which is always true.
  70444. */
  70445. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  70446. goto op_column_read_header;
  70447. }
  70448. /* Make sure at least the first p2+1 entries of the header have been
  70449. ** parsed and valid information is in aOffset[] and pC->aType[].
  70450. */
  70451. if( pC->nHdrParsed<=p2 ){
  70452. /* If there is more header available for parsing in the record, try
  70453. ** to extract additional fields up through the p2+1-th field
  70454. */
  70455. op_column_read_header:
  70456. if( pC->iHdrOffset<aOffset[0] ){
  70457. /* Make sure zData points to enough of the record to cover the header. */
  70458. if( pC->aRow==0 ){
  70459. memset(&sMem, 0, sizeof(sMem));
  70460. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
  70461. !pC->isTable, &sMem);
  70462. if( rc!=SQLITE_OK ){
  70463. goto op_column_error;
  70464. }
  70465. zData = (u8*)sMem.z;
  70466. }else{
  70467. zData = pC->aRow;
  70468. }
  70469. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  70470. i = pC->nHdrParsed;
  70471. offset = aOffset[i];
  70472. zHdr = zData + pC->iHdrOffset;
  70473. zEndHdr = zData + aOffset[0];
  70474. assert( i<=p2 && zHdr<zEndHdr );
  70475. do{
  70476. if( zHdr[0]<0x80 ){
  70477. t = zHdr[0];
  70478. zHdr++;
  70479. }else{
  70480. zHdr += sqlite3GetVarint32(zHdr, &t);
  70481. }
  70482. pC->aType[i] = t;
  70483. szField = sqlite3VdbeSerialTypeLen(t);
  70484. offset += szField;
  70485. if( offset<szField ){ /* True if offset overflows */
  70486. zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  70487. break;
  70488. }
  70489. i++;
  70490. aOffset[i] = offset;
  70491. }while( i<=p2 && zHdr<zEndHdr );
  70492. pC->nHdrParsed = i;
  70493. pC->iHdrOffset = (u32)(zHdr - zData);
  70494. if( pC->aRow==0 ){
  70495. sqlite3VdbeMemRelease(&sMem);
  70496. sMem.flags = MEM_Null;
  70497. }
  70498. /* The record is corrupt if any of the following are true:
  70499. ** (1) the bytes of the header extend past the declared header size
  70500. ** (zHdr>zEndHdr)
  70501. ** (2) the entire header was used but not all data was used
  70502. ** (zHdr==zEndHdr && offset!=pC->payloadSize)
  70503. ** (3) the end of the data extends beyond the end of the record.
  70504. ** (offset > pC->payloadSize)
  70505. */
  70506. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
  70507. || (offset > pC->payloadSize)
  70508. ){
  70509. rc = SQLITE_CORRUPT_BKPT;
  70510. goto op_column_error;
  70511. }
  70512. }
  70513. /* If after trying to extract new entries from the header, nHdrParsed is
  70514. ** still not up to p2, that means that the record has fewer than p2
  70515. ** columns. So the result will be either the default value or a NULL.
  70516. */
  70517. if( pC->nHdrParsed<=p2 ){
  70518. if( pOp->p4type==P4_MEM ){
  70519. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  70520. }else{
  70521. sqlite3VdbeMemSetNull(pDest);
  70522. }
  70523. goto op_column_out;
  70524. }
  70525. }
  70526. /* Extract the content for the p2+1-th column. Control can only
  70527. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  70528. ** all valid.
  70529. */
  70530. assert( p2<pC->nHdrParsed );
  70531. assert( rc==SQLITE_OK );
  70532. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  70533. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  70534. t = pC->aType[p2];
  70535. if( pC->szRow>=aOffset[p2+1] ){
  70536. /* This is the common case where the desired content fits on the original
  70537. ** page - where the content is not on an overflow page */
  70538. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  70539. }else{
  70540. /* This branch happens only when content is on overflow pages */
  70541. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  70542. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  70543. || (len = sqlite3VdbeSerialTypeLen(t))==0
  70544. ){
  70545. /* Content is irrelevant for
  70546. ** 1. the typeof() function,
  70547. ** 2. the length(X) function if X is a blob, and
  70548. ** 3. if the content length is zero.
  70549. ** So we might as well use bogus content rather than reading
  70550. ** content from disk. NULL will work for the value for strings
  70551. ** and blobs and whatever is in the payloadSize64 variable
  70552. ** will work for everything else. */
  70553. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  70554. }else{
  70555. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  70556. pDest);
  70557. if( rc!=SQLITE_OK ){
  70558. goto op_column_error;
  70559. }
  70560. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  70561. pDest->flags &= ~MEM_Ephem;
  70562. }
  70563. }
  70564. pDest->enc = encoding;
  70565. op_column_out:
  70566. /* If the column value is an ephemeral string, go ahead and persist
  70567. ** that string in case the cursor moves before the column value is
  70568. ** used. The following code does the equivalent of Deephemeralize()
  70569. ** but does it faster. */
  70570. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  70571. fx = pDest->flags & (MEM_Str|MEM_Blob);
  70572. assert( fx!=0 );
  70573. zData = (const u8*)pDest->z;
  70574. len = pDest->n;
  70575. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  70576. memcpy(pDest->z, zData, len);
  70577. pDest->z[len] = 0;
  70578. pDest->z[len+1] = 0;
  70579. pDest->flags = fx|MEM_Term;
  70580. }
  70581. op_column_error:
  70582. UPDATE_MAX_BLOBSIZE(pDest);
  70583. REGISTER_TRACE(pOp->p3, pDest);
  70584. break;
  70585. }
  70586. /* Opcode: Affinity P1 P2 * P4 *
  70587. ** Synopsis: affinity(r[P1@P2])
  70588. **
  70589. ** Apply affinities to a range of P2 registers starting with P1.
  70590. **
  70591. ** P4 is a string that is P2 characters long. The nth character of the
  70592. ** string indicates the column affinity that should be used for the nth
  70593. ** memory cell in the range.
  70594. */
  70595. case OP_Affinity: {
  70596. const char *zAffinity; /* The affinity to be applied */
  70597. char cAff; /* A single character of affinity */
  70598. zAffinity = pOp->p4.z;
  70599. assert( zAffinity!=0 );
  70600. assert( zAffinity[pOp->p2]==0 );
  70601. pIn1 = &aMem[pOp->p1];
  70602. while( (cAff = *(zAffinity++))!=0 ){
  70603. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  70604. assert( memIsValid(pIn1) );
  70605. applyAffinity(pIn1, cAff, encoding);
  70606. pIn1++;
  70607. }
  70608. break;
  70609. }
  70610. /* Opcode: MakeRecord P1 P2 P3 P4 *
  70611. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  70612. **
  70613. ** Convert P2 registers beginning with P1 into the [record format]
  70614. ** use as a data record in a database table or as a key
  70615. ** in an index. The OP_Column opcode can decode the record later.
  70616. **
  70617. ** P4 may be a string that is P2 characters long. The nth character of the
  70618. ** string indicates the column affinity that should be used for the nth
  70619. ** field of the index key.
  70620. **
  70621. ** The mapping from character to affinity is given by the SQLITE_AFF_
  70622. ** macros defined in sqliteInt.h.
  70623. **
  70624. ** If P4 is NULL then all index fields have the affinity BLOB.
  70625. */
  70626. case OP_MakeRecord: {
  70627. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  70628. Mem *pRec; /* The new record */
  70629. u64 nData; /* Number of bytes of data space */
  70630. int nHdr; /* Number of bytes of header space */
  70631. i64 nByte; /* Data space required for this record */
  70632. i64 nZero; /* Number of zero bytes at the end of the record */
  70633. int nVarint; /* Number of bytes in a varint */
  70634. u32 serial_type; /* Type field */
  70635. Mem *pData0; /* First field to be combined into the record */
  70636. Mem *pLast; /* Last field of the record */
  70637. int nField; /* Number of fields in the record */
  70638. char *zAffinity; /* The affinity string for the record */
  70639. int file_format; /* File format to use for encoding */
  70640. int i; /* Space used in zNewRecord[] header */
  70641. int j; /* Space used in zNewRecord[] content */
  70642. int len; /* Length of a field */
  70643. /* Assuming the record contains N fields, the record format looks
  70644. ** like this:
  70645. **
  70646. ** ------------------------------------------------------------------------
  70647. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  70648. ** ------------------------------------------------------------------------
  70649. **
  70650. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  70651. ** and so forth.
  70652. **
  70653. ** Each type field is a varint representing the serial type of the
  70654. ** corresponding data element (see sqlite3VdbeSerialType()). The
  70655. ** hdr-size field is also a varint which is the offset from the beginning
  70656. ** of the record to data0.
  70657. */
  70658. nData = 0; /* Number of bytes of data space */
  70659. nHdr = 0; /* Number of bytes of header space */
  70660. nZero = 0; /* Number of zero bytes at the end of the record */
  70661. nField = pOp->p1;
  70662. zAffinity = pOp->p4.z;
  70663. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  70664. pData0 = &aMem[nField];
  70665. nField = pOp->p2;
  70666. pLast = &pData0[nField-1];
  70667. file_format = p->minWriteFileFormat;
  70668. /* Identify the output register */
  70669. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  70670. pOut = &aMem[pOp->p3];
  70671. memAboutToChange(p, pOut);
  70672. /* Apply the requested affinity to all inputs
  70673. */
  70674. assert( pData0<=pLast );
  70675. if( zAffinity ){
  70676. pRec = pData0;
  70677. do{
  70678. applyAffinity(pRec++, *(zAffinity++), encoding);
  70679. assert( zAffinity[0]==0 || pRec<=pLast );
  70680. }while( zAffinity[0] );
  70681. }
  70682. /* Loop through the elements that will make up the record to figure
  70683. ** out how much space is required for the new record.
  70684. */
  70685. pRec = pLast;
  70686. do{
  70687. assert( memIsValid(pRec) );
  70688. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
  70689. len = sqlite3VdbeSerialTypeLen(serial_type);
  70690. if( pRec->flags & MEM_Zero ){
  70691. if( nData ){
  70692. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  70693. }else{
  70694. nZero += pRec->u.nZero;
  70695. len -= pRec->u.nZero;
  70696. }
  70697. }
  70698. nData += len;
  70699. testcase( serial_type==127 );
  70700. testcase( serial_type==128 );
  70701. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  70702. }while( (--pRec)>=pData0 );
  70703. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  70704. ** which determines the total number of bytes in the header. The varint
  70705. ** value is the size of the header in bytes including the size varint
  70706. ** itself. */
  70707. testcase( nHdr==126 );
  70708. testcase( nHdr==127 );
  70709. if( nHdr<=126 ){
  70710. /* The common case */
  70711. nHdr += 1;
  70712. }else{
  70713. /* Rare case of a really large header */
  70714. nVarint = sqlite3VarintLen(nHdr);
  70715. nHdr += nVarint;
  70716. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  70717. }
  70718. nByte = nHdr+nData;
  70719. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70720. goto too_big;
  70721. }
  70722. /* Make sure the output register has a buffer large enough to store
  70723. ** the new record. The output register (pOp->p3) is not allowed to
  70724. ** be one of the input registers (because the following call to
  70725. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  70726. */
  70727. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  70728. goto no_mem;
  70729. }
  70730. zNewRecord = (u8 *)pOut->z;
  70731. /* Write the record */
  70732. i = putVarint32(zNewRecord, nHdr);
  70733. j = nHdr;
  70734. assert( pData0<=pLast );
  70735. pRec = pData0;
  70736. do{
  70737. serial_type = pRec->uTemp;
  70738. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  70739. ** additional varints, one per column. */
  70740. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  70741. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  70742. ** immediately follow the header. */
  70743. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  70744. }while( (++pRec)<=pLast );
  70745. assert( i==nHdr );
  70746. assert( j==nByte );
  70747. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70748. pOut->n = (int)nByte;
  70749. pOut->flags = MEM_Blob;
  70750. if( nZero ){
  70751. pOut->u.nZero = nZero;
  70752. pOut->flags |= MEM_Zero;
  70753. }
  70754. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  70755. REGISTER_TRACE(pOp->p3, pOut);
  70756. UPDATE_MAX_BLOBSIZE(pOut);
  70757. break;
  70758. }
  70759. /* Opcode: Count P1 P2 * * *
  70760. ** Synopsis: r[P2]=count()
  70761. **
  70762. ** Store the number of entries (an integer value) in the table or index
  70763. ** opened by cursor P1 in register P2
  70764. */
  70765. #ifndef SQLITE_OMIT_BTREECOUNT
  70766. case OP_Count: { /* out2 */
  70767. i64 nEntry;
  70768. BtCursor *pCrsr;
  70769. pCrsr = p->apCsr[pOp->p1]->pCursor;
  70770. assert( pCrsr );
  70771. nEntry = 0; /* Not needed. Only used to silence a warning. */
  70772. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  70773. pOut = out2Prerelease(p, pOp);
  70774. pOut->u.i = nEntry;
  70775. break;
  70776. }
  70777. #endif
  70778. /* Opcode: Savepoint P1 * * P4 *
  70779. **
  70780. ** Open, release or rollback the savepoint named by parameter P4, depending
  70781. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  70782. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  70783. */
  70784. case OP_Savepoint: {
  70785. int p1; /* Value of P1 operand */
  70786. char *zName; /* Name of savepoint */
  70787. int nName;
  70788. Savepoint *pNew;
  70789. Savepoint *pSavepoint;
  70790. Savepoint *pTmp;
  70791. int iSavepoint;
  70792. int ii;
  70793. p1 = pOp->p1;
  70794. zName = pOp->p4.z;
  70795. /* Assert that the p1 parameter is valid. Also that if there is no open
  70796. ** transaction, then there cannot be any savepoints.
  70797. */
  70798. assert( db->pSavepoint==0 || db->autoCommit==0 );
  70799. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  70800. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  70801. assert( checkSavepointCount(db) );
  70802. assert( p->bIsReader );
  70803. if( p1==SAVEPOINT_BEGIN ){
  70804. if( db->nVdbeWrite>0 ){
  70805. /* A new savepoint cannot be created if there are active write
  70806. ** statements (i.e. open read/write incremental blob handles).
  70807. */
  70808. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  70809. rc = SQLITE_BUSY;
  70810. }else{
  70811. nName = sqlite3Strlen30(zName);
  70812. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70813. /* This call is Ok even if this savepoint is actually a transaction
  70814. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  70815. ** If this is a transaction savepoint being opened, it is guaranteed
  70816. ** that the db->aVTrans[] array is empty. */
  70817. assert( db->autoCommit==0 || db->nVTrans==0 );
  70818. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  70819. db->nStatement+db->nSavepoint);
  70820. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70821. #endif
  70822. /* Create a new savepoint structure. */
  70823. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  70824. if( pNew ){
  70825. pNew->zName = (char *)&pNew[1];
  70826. memcpy(pNew->zName, zName, nName+1);
  70827. /* If there is no open transaction, then mark this as a special
  70828. ** "transaction savepoint". */
  70829. if( db->autoCommit ){
  70830. db->autoCommit = 0;
  70831. db->isTransactionSavepoint = 1;
  70832. }else{
  70833. db->nSavepoint++;
  70834. }
  70835. /* Link the new savepoint into the database handle's list. */
  70836. pNew->pNext = db->pSavepoint;
  70837. db->pSavepoint = pNew;
  70838. pNew->nDeferredCons = db->nDeferredCons;
  70839. pNew->nDeferredImmCons = db->nDeferredImmCons;
  70840. }
  70841. }
  70842. }else{
  70843. iSavepoint = 0;
  70844. /* Find the named savepoint. If there is no such savepoint, then an
  70845. ** an error is returned to the user. */
  70846. for(
  70847. pSavepoint = db->pSavepoint;
  70848. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  70849. pSavepoint = pSavepoint->pNext
  70850. ){
  70851. iSavepoint++;
  70852. }
  70853. if( !pSavepoint ){
  70854. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  70855. rc = SQLITE_ERROR;
  70856. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  70857. /* It is not possible to release (commit) a savepoint if there are
  70858. ** active write statements.
  70859. */
  70860. sqlite3VdbeError(p, "cannot release savepoint - "
  70861. "SQL statements in progress");
  70862. rc = SQLITE_BUSY;
  70863. }else{
  70864. /* Determine whether or not this is a transaction savepoint. If so,
  70865. ** and this is a RELEASE command, then the current transaction
  70866. ** is committed.
  70867. */
  70868. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  70869. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  70870. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  70871. goto vdbe_return;
  70872. }
  70873. db->autoCommit = 1;
  70874. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  70875. p->pc = (int)(pOp - aOp);
  70876. db->autoCommit = 0;
  70877. p->rc = rc = SQLITE_BUSY;
  70878. goto vdbe_return;
  70879. }
  70880. db->isTransactionSavepoint = 0;
  70881. rc = p->rc;
  70882. }else{
  70883. int isSchemaChange;
  70884. iSavepoint = db->nSavepoint - iSavepoint - 1;
  70885. if( p1==SAVEPOINT_ROLLBACK ){
  70886. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  70887. for(ii=0; ii<db->nDb; ii++){
  70888. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  70889. SQLITE_ABORT_ROLLBACK,
  70890. isSchemaChange==0);
  70891. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70892. }
  70893. }else{
  70894. isSchemaChange = 0;
  70895. }
  70896. for(ii=0; ii<db->nDb; ii++){
  70897. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  70898. if( rc!=SQLITE_OK ){
  70899. goto abort_due_to_error;
  70900. }
  70901. }
  70902. if( isSchemaChange ){
  70903. sqlite3ExpirePreparedStatements(db);
  70904. sqlite3ResetAllSchemasOfConnection(db);
  70905. db->flags = (db->flags | SQLITE_InternChanges);
  70906. }
  70907. }
  70908. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  70909. ** savepoints nested inside of the savepoint being operated on. */
  70910. while( db->pSavepoint!=pSavepoint ){
  70911. pTmp = db->pSavepoint;
  70912. db->pSavepoint = pTmp->pNext;
  70913. sqlite3DbFree(db, pTmp);
  70914. db->nSavepoint--;
  70915. }
  70916. /* If it is a RELEASE, then destroy the savepoint being operated on
  70917. ** too. If it is a ROLLBACK TO, then set the number of deferred
  70918. ** constraint violations present in the database to the value stored
  70919. ** when the savepoint was created. */
  70920. if( p1==SAVEPOINT_RELEASE ){
  70921. assert( pSavepoint==db->pSavepoint );
  70922. db->pSavepoint = pSavepoint->pNext;
  70923. sqlite3DbFree(db, pSavepoint);
  70924. if( !isTransaction ){
  70925. db->nSavepoint--;
  70926. }
  70927. }else{
  70928. db->nDeferredCons = pSavepoint->nDeferredCons;
  70929. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  70930. }
  70931. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  70932. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  70933. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70934. }
  70935. }
  70936. }
  70937. break;
  70938. }
  70939. /* Opcode: AutoCommit P1 P2 * * *
  70940. **
  70941. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  70942. ** back any currently active btree transactions. If there are any active
  70943. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  70944. ** there are active writing VMs or active VMs that use shared cache.
  70945. **
  70946. ** This instruction causes the VM to halt.
  70947. */
  70948. case OP_AutoCommit: {
  70949. int desiredAutoCommit;
  70950. int iRollback;
  70951. int turnOnAC;
  70952. desiredAutoCommit = pOp->p1;
  70953. iRollback = pOp->p2;
  70954. turnOnAC = desiredAutoCommit && !db->autoCommit;
  70955. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  70956. assert( desiredAutoCommit==1 || iRollback==0 );
  70957. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  70958. assert( p->bIsReader );
  70959. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  70960. /* If this instruction implements a COMMIT and other VMs are writing
  70961. ** return an error indicating that the other VMs must complete first.
  70962. */
  70963. sqlite3VdbeError(p, "cannot commit transaction - "
  70964. "SQL statements in progress");
  70965. rc = SQLITE_BUSY;
  70966. }else if( desiredAutoCommit!=db->autoCommit ){
  70967. if( iRollback ){
  70968. assert( desiredAutoCommit==1 );
  70969. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  70970. db->autoCommit = 1;
  70971. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  70972. goto vdbe_return;
  70973. }else{
  70974. db->autoCommit = (u8)desiredAutoCommit;
  70975. }
  70976. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  70977. p->pc = (int)(pOp - aOp);
  70978. db->autoCommit = (u8)(1-desiredAutoCommit);
  70979. p->rc = rc = SQLITE_BUSY;
  70980. goto vdbe_return;
  70981. }
  70982. assert( db->nStatement==0 );
  70983. sqlite3CloseSavepoints(db);
  70984. if( p->rc==SQLITE_OK ){
  70985. rc = SQLITE_DONE;
  70986. }else{
  70987. rc = SQLITE_ERROR;
  70988. }
  70989. goto vdbe_return;
  70990. }else{
  70991. sqlite3VdbeError(p,
  70992. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  70993. (iRollback)?"cannot rollback - no transaction is active":
  70994. "cannot commit - no transaction is active"));
  70995. rc = SQLITE_ERROR;
  70996. }
  70997. break;
  70998. }
  70999. /* Opcode: Transaction P1 P2 P3 P4 P5
  71000. **
  71001. ** Begin a transaction on database P1 if a transaction is not already
  71002. ** active.
  71003. ** If P2 is non-zero, then a write-transaction is started, or if a
  71004. ** read-transaction is already active, it is upgraded to a write-transaction.
  71005. ** If P2 is zero, then a read-transaction is started.
  71006. **
  71007. ** P1 is the index of the database file on which the transaction is
  71008. ** started. Index 0 is the main database file and index 1 is the
  71009. ** file used for temporary tables. Indices of 2 or more are used for
  71010. ** attached databases.
  71011. **
  71012. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  71013. ** true (this flag is set if the Vdbe may modify more than one row and may
  71014. ** throw an ABORT exception), a statement transaction may also be opened.
  71015. ** More specifically, a statement transaction is opened iff the database
  71016. ** connection is currently not in autocommit mode, or if there are other
  71017. ** active statements. A statement transaction allows the changes made by this
  71018. ** VDBE to be rolled back after an error without having to roll back the
  71019. ** entire transaction. If no error is encountered, the statement transaction
  71020. ** will automatically commit when the VDBE halts.
  71021. **
  71022. ** If P5!=0 then this opcode also checks the schema cookie against P3
  71023. ** and the schema generation counter against P4.
  71024. ** The cookie changes its value whenever the database schema changes.
  71025. ** This operation is used to detect when that the cookie has changed
  71026. ** and that the current process needs to reread the schema. If the schema
  71027. ** cookie in P3 differs from the schema cookie in the database header or
  71028. ** if the schema generation counter in P4 differs from the current
  71029. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  71030. ** halts. The sqlite3_step() wrapper function might then reprepare the
  71031. ** statement and rerun it from the beginning.
  71032. */
  71033. case OP_Transaction: {
  71034. Btree *pBt;
  71035. int iMeta;
  71036. int iGen;
  71037. assert( p->bIsReader );
  71038. assert( p->readOnly==0 || pOp->p2==0 );
  71039. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71040. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  71041. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  71042. rc = SQLITE_READONLY;
  71043. goto abort_due_to_error;
  71044. }
  71045. pBt = db->aDb[pOp->p1].pBt;
  71046. if( pBt ){
  71047. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  71048. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  71049. testcase( rc==SQLITE_BUSY_RECOVERY );
  71050. if( (rc&0xff)==SQLITE_BUSY ){
  71051. p->pc = (int)(pOp - aOp);
  71052. p->rc = rc;
  71053. goto vdbe_return;
  71054. }
  71055. if( rc!=SQLITE_OK ){
  71056. goto abort_due_to_error;
  71057. }
  71058. if( pOp->p2 && p->usesStmtJournal
  71059. && (db->autoCommit==0 || db->nVdbeRead>1)
  71060. ){
  71061. assert( sqlite3BtreeIsInTrans(pBt) );
  71062. if( p->iStatement==0 ){
  71063. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  71064. db->nStatement++;
  71065. p->iStatement = db->nSavepoint + db->nStatement;
  71066. }
  71067. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  71068. if( rc==SQLITE_OK ){
  71069. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  71070. }
  71071. /* Store the current value of the database handles deferred constraint
  71072. ** counter. If the statement transaction needs to be rolled back,
  71073. ** the value of this counter needs to be restored too. */
  71074. p->nStmtDefCons = db->nDeferredCons;
  71075. p->nStmtDefImmCons = db->nDeferredImmCons;
  71076. }
  71077. /* Gather the schema version number for checking:
  71078. ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
  71079. ** each time a query is executed to ensure that the internal cache of the
  71080. ** schema used when compiling the SQL query matches the schema of the
  71081. ** database against which the compiled query is actually executed.
  71082. */
  71083. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  71084. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  71085. }else{
  71086. iGen = iMeta = 0;
  71087. }
  71088. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  71089. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  71090. sqlite3DbFree(db, p->zErrMsg);
  71091. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  71092. /* If the schema-cookie from the database file matches the cookie
  71093. ** stored with the in-memory representation of the schema, do
  71094. ** not reload the schema from the database file.
  71095. **
  71096. ** If virtual-tables are in use, this is not just an optimization.
  71097. ** Often, v-tables store their data in other SQLite tables, which
  71098. ** are queried from within xNext() and other v-table methods using
  71099. ** prepared queries. If such a query is out-of-date, we do not want to
  71100. ** discard the database schema, as the user code implementing the
  71101. ** v-table would have to be ready for the sqlite3_vtab structure itself
  71102. ** to be invalidated whenever sqlite3_step() is called from within
  71103. ** a v-table method.
  71104. */
  71105. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  71106. sqlite3ResetOneSchema(db, pOp->p1);
  71107. }
  71108. p->expired = 1;
  71109. rc = SQLITE_SCHEMA;
  71110. }
  71111. break;
  71112. }
  71113. /* Opcode: ReadCookie P1 P2 P3 * *
  71114. **
  71115. ** Read cookie number P3 from database P1 and write it into register P2.
  71116. ** P3==1 is the schema version. P3==2 is the database format.
  71117. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  71118. ** the main database file and P1==1 is the database file used to store
  71119. ** temporary tables.
  71120. **
  71121. ** There must be a read-lock on the database (either a transaction
  71122. ** must be started or there must be an open cursor) before
  71123. ** executing this instruction.
  71124. */
  71125. case OP_ReadCookie: { /* out2 */
  71126. int iMeta;
  71127. int iDb;
  71128. int iCookie;
  71129. assert( p->bIsReader );
  71130. iDb = pOp->p1;
  71131. iCookie = pOp->p3;
  71132. assert( pOp->p3<SQLITE_N_BTREE_META );
  71133. assert( iDb>=0 && iDb<db->nDb );
  71134. assert( db->aDb[iDb].pBt!=0 );
  71135. assert( DbMaskTest(p->btreeMask, iDb) );
  71136. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  71137. pOut = out2Prerelease(p, pOp);
  71138. pOut->u.i = iMeta;
  71139. break;
  71140. }
  71141. /* Opcode: SetCookie P1 P2 P3 * *
  71142. **
  71143. ** Write the content of register P3 (interpreted as an integer)
  71144. ** into cookie number P2 of database P1. P2==1 is the schema version.
  71145. ** P2==2 is the database format. P2==3 is the recommended pager cache
  71146. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  71147. ** database file used to store temporary tables.
  71148. **
  71149. ** A transaction must be started before executing this opcode.
  71150. */
  71151. case OP_SetCookie: { /* in3 */
  71152. Db *pDb;
  71153. assert( pOp->p2<SQLITE_N_BTREE_META );
  71154. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71155. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  71156. assert( p->readOnly==0 );
  71157. pDb = &db->aDb[pOp->p1];
  71158. assert( pDb->pBt!=0 );
  71159. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  71160. pIn3 = &aMem[pOp->p3];
  71161. sqlite3VdbeMemIntegerify(pIn3);
  71162. /* See note about index shifting on OP_ReadCookie */
  71163. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  71164. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  71165. /* When the schema cookie changes, record the new cookie internally */
  71166. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  71167. db->flags |= SQLITE_InternChanges;
  71168. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  71169. /* Record changes in the file format */
  71170. pDb->pSchema->file_format = (u8)pIn3->u.i;
  71171. }
  71172. if( pOp->p1==1 ){
  71173. /* Invalidate all prepared statements whenever the TEMP database
  71174. ** schema is changed. Ticket #1644 */
  71175. sqlite3ExpirePreparedStatements(db);
  71176. p->expired = 0;
  71177. }
  71178. break;
  71179. }
  71180. /* Opcode: OpenRead P1 P2 P3 P4 P5
  71181. ** Synopsis: root=P2 iDb=P3
  71182. **
  71183. ** Open a read-only cursor for the database table whose root page is
  71184. ** P2 in a database file. The database file is determined by P3.
  71185. ** P3==0 means the main database, P3==1 means the database used for
  71186. ** temporary tables, and P3>1 means used the corresponding attached
  71187. ** database. Give the new cursor an identifier of P1. The P1
  71188. ** values need not be contiguous but all P1 values should be small integers.
  71189. ** It is an error for P1 to be negative.
  71190. **
  71191. ** If P5!=0 then use the content of register P2 as the root page, not
  71192. ** the value of P2 itself.
  71193. **
  71194. ** There will be a read lock on the database whenever there is an
  71195. ** open cursor. If the database was unlocked prior to this instruction
  71196. ** then a read lock is acquired as part of this instruction. A read
  71197. ** lock allows other processes to read the database but prohibits
  71198. ** any other process from modifying the database. The read lock is
  71199. ** released when all cursors are closed. If this instruction attempts
  71200. ** to get a read lock but fails, the script terminates with an
  71201. ** SQLITE_BUSY error code.
  71202. **
  71203. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  71204. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  71205. ** structure, then said structure defines the content and collating
  71206. ** sequence of the index being opened. Otherwise, if P4 is an integer
  71207. ** value, it is set to the number of columns in the table.
  71208. **
  71209. ** See also: OpenWrite, ReopenIdx
  71210. */
  71211. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  71212. ** Synopsis: root=P2 iDb=P3
  71213. **
  71214. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  71215. ** checks to see if the cursor on P1 is already open with a root page
  71216. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  71217. ** if the cursor is already open, do not reopen it.
  71218. **
  71219. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  71220. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  71221. ** every other ReopenIdx or OpenRead for the same cursor number.
  71222. **
  71223. ** See the OpenRead opcode documentation for additional information.
  71224. */
  71225. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  71226. ** Synopsis: root=P2 iDb=P3
  71227. **
  71228. ** Open a read/write cursor named P1 on the table or index whose root
  71229. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  71230. ** root page.
  71231. **
  71232. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  71233. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  71234. ** structure, then said structure defines the content and collating
  71235. ** sequence of the index being opened. Otherwise, if P4 is an integer
  71236. ** value, it is set to the number of columns in the table, or to the
  71237. ** largest index of any column of the table that is actually used.
  71238. **
  71239. ** This instruction works just like OpenRead except that it opens the cursor
  71240. ** in read/write mode. For a given table, there can be one or more read-only
  71241. ** cursors or a single read/write cursor but not both.
  71242. **
  71243. ** See also OpenRead.
  71244. */
  71245. case OP_ReopenIdx: {
  71246. int nField;
  71247. KeyInfo *pKeyInfo;
  71248. int p2;
  71249. int iDb;
  71250. int wrFlag;
  71251. Btree *pX;
  71252. VdbeCursor *pCur;
  71253. Db *pDb;
  71254. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  71255. assert( pOp->p4type==P4_KEYINFO );
  71256. pCur = p->apCsr[pOp->p1];
  71257. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  71258. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  71259. goto open_cursor_set_hints;
  71260. }
  71261. /* If the cursor is not currently open or is open on a different
  71262. ** index, then fall through into OP_OpenRead to force a reopen */
  71263. case OP_OpenRead:
  71264. case OP_OpenWrite:
  71265. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
  71266. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  71267. assert( p->bIsReader );
  71268. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  71269. || p->readOnly==0 );
  71270. if( p->expired ){
  71271. rc = SQLITE_ABORT_ROLLBACK;
  71272. break;
  71273. }
  71274. nField = 0;
  71275. pKeyInfo = 0;
  71276. p2 = pOp->p2;
  71277. iDb = pOp->p3;
  71278. assert( iDb>=0 && iDb<db->nDb );
  71279. assert( DbMaskTest(p->btreeMask, iDb) );
  71280. pDb = &db->aDb[iDb];
  71281. pX = pDb->pBt;
  71282. assert( pX!=0 );
  71283. if( pOp->opcode==OP_OpenWrite ){
  71284. wrFlag = 1;
  71285. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  71286. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  71287. p->minWriteFileFormat = pDb->pSchema->file_format;
  71288. }
  71289. }else{
  71290. wrFlag = 0;
  71291. }
  71292. if( pOp->p5 & OPFLAG_P2ISREG ){
  71293. assert( p2>0 );
  71294. assert( p2<=(p->nMem-p->nCursor) );
  71295. pIn2 = &aMem[p2];
  71296. assert( memIsValid(pIn2) );
  71297. assert( (pIn2->flags & MEM_Int)!=0 );
  71298. sqlite3VdbeMemIntegerify(pIn2);
  71299. p2 = (int)pIn2->u.i;
  71300. /* The p2 value always comes from a prior OP_CreateTable opcode and
  71301. ** that opcode will always set the p2 value to 2 or more or else fail.
  71302. ** If there were a failure, the prepared statement would have halted
  71303. ** before reaching this instruction. */
  71304. if( NEVER(p2<2) ) {
  71305. rc = SQLITE_CORRUPT_BKPT;
  71306. goto abort_due_to_error;
  71307. }
  71308. }
  71309. if( pOp->p4type==P4_KEYINFO ){
  71310. pKeyInfo = pOp->p4.pKeyInfo;
  71311. assert( pKeyInfo->enc==ENC(db) );
  71312. assert( pKeyInfo->db==db );
  71313. nField = pKeyInfo->nField+pKeyInfo->nXField;
  71314. }else if( pOp->p4type==P4_INT32 ){
  71315. nField = pOp->p4.i;
  71316. }
  71317. assert( pOp->p1>=0 );
  71318. assert( nField>=0 );
  71319. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  71320. pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  71321. if( pCur==0 ) goto no_mem;
  71322. pCur->nullRow = 1;
  71323. pCur->isOrdered = 1;
  71324. pCur->pgnoRoot = p2;
  71325. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  71326. pCur->pKeyInfo = pKeyInfo;
  71327. /* Set the VdbeCursor.isTable variable. Previous versions of
  71328. ** SQLite used to check if the root-page flags were sane at this point
  71329. ** and report database corruption if they were not, but this check has
  71330. ** since moved into the btree layer. */
  71331. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  71332. open_cursor_set_hints:
  71333. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  71334. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  71335. sqlite3BtreeCursorHints(pCur->pCursor,
  71336. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  71337. break;
  71338. }
  71339. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  71340. ** Synopsis: nColumn=P2
  71341. **
  71342. ** Open a new cursor P1 to a transient table.
  71343. ** The cursor is always opened read/write even if
  71344. ** the main database is read-only. The ephemeral
  71345. ** table is deleted automatically when the cursor is closed.
  71346. **
  71347. ** P2 is the number of columns in the ephemeral table.
  71348. ** The cursor points to a BTree table if P4==0 and to a BTree index
  71349. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  71350. ** that defines the format of keys in the index.
  71351. **
  71352. ** The P5 parameter can be a mask of the BTREE_* flags defined
  71353. ** in btree.h. These flags control aspects of the operation of
  71354. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  71355. ** added automatically.
  71356. */
  71357. /* Opcode: OpenAutoindex P1 P2 * P4 *
  71358. ** Synopsis: nColumn=P2
  71359. **
  71360. ** This opcode works the same as OP_OpenEphemeral. It has a
  71361. ** different name to distinguish its use. Tables created using
  71362. ** by this opcode will be used for automatically created transient
  71363. ** indices in joins.
  71364. */
  71365. case OP_OpenAutoindex:
  71366. case OP_OpenEphemeral: {
  71367. VdbeCursor *pCx;
  71368. KeyInfo *pKeyInfo;
  71369. static const int vfsFlags =
  71370. SQLITE_OPEN_READWRITE |
  71371. SQLITE_OPEN_CREATE |
  71372. SQLITE_OPEN_EXCLUSIVE |
  71373. SQLITE_OPEN_DELETEONCLOSE |
  71374. SQLITE_OPEN_TRANSIENT_DB;
  71375. assert( pOp->p1>=0 );
  71376. assert( pOp->p2>=0 );
  71377. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  71378. if( pCx==0 ) goto no_mem;
  71379. pCx->nullRow = 1;
  71380. pCx->isEphemeral = 1;
  71381. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  71382. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  71383. if( rc==SQLITE_OK ){
  71384. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  71385. }
  71386. if( rc==SQLITE_OK ){
  71387. /* If a transient index is required, create it by calling
  71388. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  71389. ** opening it. If a transient table is required, just use the
  71390. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  71391. */
  71392. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  71393. int pgno;
  71394. assert( pOp->p4type==P4_KEYINFO );
  71395. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  71396. if( rc==SQLITE_OK ){
  71397. assert( pgno==MASTER_ROOT+1 );
  71398. assert( pKeyInfo->db==db );
  71399. assert( pKeyInfo->enc==ENC(db) );
  71400. pCx->pKeyInfo = pKeyInfo;
  71401. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
  71402. }
  71403. pCx->isTable = 0;
  71404. }else{
  71405. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  71406. pCx->isTable = 1;
  71407. }
  71408. }
  71409. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  71410. break;
  71411. }
  71412. /* Opcode: SorterOpen P1 P2 P3 P4 *
  71413. **
  71414. ** This opcode works like OP_OpenEphemeral except that it opens
  71415. ** a transient index that is specifically designed to sort large
  71416. ** tables using an external merge-sort algorithm.
  71417. **
  71418. ** If argument P3 is non-zero, then it indicates that the sorter may
  71419. ** assume that a stable sort considering the first P3 fields of each
  71420. ** key is sufficient to produce the required results.
  71421. */
  71422. case OP_SorterOpen: {
  71423. VdbeCursor *pCx;
  71424. assert( pOp->p1>=0 );
  71425. assert( pOp->p2>=0 );
  71426. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  71427. if( pCx==0 ) goto no_mem;
  71428. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  71429. assert( pCx->pKeyInfo->db==db );
  71430. assert( pCx->pKeyInfo->enc==ENC(db) );
  71431. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  71432. break;
  71433. }
  71434. /* Opcode: SequenceTest P1 P2 * * *
  71435. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  71436. **
  71437. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  71438. ** to P2. Regardless of whether or not the jump is taken, increment the
  71439. ** the sequence value.
  71440. */
  71441. case OP_SequenceTest: {
  71442. VdbeCursor *pC;
  71443. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71444. pC = p->apCsr[pOp->p1];
  71445. assert( pC->pSorter );
  71446. if( (pC->seqCount++)==0 ){
  71447. goto jump_to_p2;
  71448. }
  71449. break;
  71450. }
  71451. /* Opcode: OpenPseudo P1 P2 P3 * *
  71452. ** Synopsis: P3 columns in r[P2]
  71453. **
  71454. ** Open a new cursor that points to a fake table that contains a single
  71455. ** row of data. The content of that one row is the content of memory
  71456. ** register P2. In other words, cursor P1 becomes an alias for the
  71457. ** MEM_Blob content contained in register P2.
  71458. **
  71459. ** A pseudo-table created by this opcode is used to hold a single
  71460. ** row output from the sorter so that the row can be decomposed into
  71461. ** individual columns using the OP_Column opcode. The OP_Column opcode
  71462. ** is the only cursor opcode that works with a pseudo-table.
  71463. **
  71464. ** P3 is the number of fields in the records that will be stored by
  71465. ** the pseudo-table.
  71466. */
  71467. case OP_OpenPseudo: {
  71468. VdbeCursor *pCx;
  71469. assert( pOp->p1>=0 );
  71470. assert( pOp->p3>=0 );
  71471. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  71472. if( pCx==0 ) goto no_mem;
  71473. pCx->nullRow = 1;
  71474. pCx->pseudoTableReg = pOp->p2;
  71475. pCx->isTable = 1;
  71476. assert( pOp->p5==0 );
  71477. break;
  71478. }
  71479. /* Opcode: Close P1 * * * *
  71480. **
  71481. ** Close a cursor previously opened as P1. If P1 is not
  71482. ** currently open, this instruction is a no-op.
  71483. */
  71484. case OP_Close: {
  71485. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71486. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  71487. p->apCsr[pOp->p1] = 0;
  71488. break;
  71489. }
  71490. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  71491. /* Opcode: ColumnsUsed P1 * * P4 *
  71492. **
  71493. ** This opcode (which only exists if SQLite was compiled with
  71494. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  71495. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  71496. ** (P4_INT64) in which the first 63 bits are one for each of the
  71497. ** first 63 columns of the table or index that are actually used
  71498. ** by the cursor. The high-order bit is set if any column after
  71499. ** the 64th is used.
  71500. */
  71501. case OP_ColumnsUsed: {
  71502. VdbeCursor *pC;
  71503. pC = p->apCsr[pOp->p1];
  71504. assert( pC->pCursor );
  71505. pC->maskUsed = *(u64*)pOp->p4.pI64;
  71506. break;
  71507. }
  71508. #endif
  71509. /* Opcode: SeekGE P1 P2 P3 P4 *
  71510. ** Synopsis: key=r[P3@P4]
  71511. **
  71512. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  71513. ** use the value in register P3 as the key. If cursor P1 refers
  71514. ** to an SQL index, then P3 is the first in an array of P4 registers
  71515. ** that are used as an unpacked index key.
  71516. **
  71517. ** Reposition cursor P1 so that it points to the smallest entry that
  71518. ** is greater than or equal to the key value. If there are no records
  71519. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  71520. **
  71521. ** This opcode leaves the cursor configured to move in forward order,
  71522. ** from the beginning toward the end. In other words, the cursor is
  71523. ** configured to use Next, not Prev.
  71524. **
  71525. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  71526. */
  71527. /* Opcode: SeekGT P1 P2 P3 P4 *
  71528. ** Synopsis: key=r[P3@P4]
  71529. **
  71530. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  71531. ** use the value in register P3 as a key. If cursor P1 refers
  71532. ** to an SQL index, then P3 is the first in an array of P4 registers
  71533. ** that are used as an unpacked index key.
  71534. **
  71535. ** Reposition cursor P1 so that it points to the smallest entry that
  71536. ** is greater than the key value. If there are no records greater than
  71537. ** the key and P2 is not zero, then jump to P2.
  71538. **
  71539. ** This opcode leaves the cursor configured to move in forward order,
  71540. ** from the beginning toward the end. In other words, the cursor is
  71541. ** configured to use Next, not Prev.
  71542. **
  71543. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  71544. */
  71545. /* Opcode: SeekLT P1 P2 P3 P4 *
  71546. ** Synopsis: key=r[P3@P4]
  71547. **
  71548. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  71549. ** use the value in register P3 as a key. If cursor P1 refers
  71550. ** to an SQL index, then P3 is the first in an array of P4 registers
  71551. ** that are used as an unpacked index key.
  71552. **
  71553. ** Reposition cursor P1 so that it points to the largest entry that
  71554. ** is less than the key value. If there are no records less than
  71555. ** the key and P2 is not zero, then jump to P2.
  71556. **
  71557. ** This opcode leaves the cursor configured to move in reverse order,
  71558. ** from the end toward the beginning. In other words, the cursor is
  71559. ** configured to use Prev, not Next.
  71560. **
  71561. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  71562. */
  71563. /* Opcode: SeekLE P1 P2 P3 P4 *
  71564. ** Synopsis: key=r[P3@P4]
  71565. **
  71566. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  71567. ** use the value in register P3 as a key. If cursor P1 refers
  71568. ** to an SQL index, then P3 is the first in an array of P4 registers
  71569. ** that are used as an unpacked index key.
  71570. **
  71571. ** Reposition cursor P1 so that it points to the largest entry that
  71572. ** is less than or equal to the key value. If there are no records
  71573. ** less than or equal to the key and P2 is not zero, then jump to P2.
  71574. **
  71575. ** This opcode leaves the cursor configured to move in reverse order,
  71576. ** from the end toward the beginning. In other words, the cursor is
  71577. ** configured to use Prev, not Next.
  71578. **
  71579. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  71580. */
  71581. case OP_SeekLT: /* jump, in3 */
  71582. case OP_SeekLE: /* jump, in3 */
  71583. case OP_SeekGE: /* jump, in3 */
  71584. case OP_SeekGT: { /* jump, in3 */
  71585. int res;
  71586. int oc;
  71587. VdbeCursor *pC;
  71588. UnpackedRecord r;
  71589. int nField;
  71590. i64 iKey; /* The rowid we are to seek to */
  71591. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71592. assert( pOp->p2!=0 );
  71593. pC = p->apCsr[pOp->p1];
  71594. assert( pC!=0 );
  71595. assert( pC->pseudoTableReg==0 );
  71596. assert( OP_SeekLE == OP_SeekLT+1 );
  71597. assert( OP_SeekGE == OP_SeekLT+2 );
  71598. assert( OP_SeekGT == OP_SeekLT+3 );
  71599. assert( pC->isOrdered );
  71600. assert( pC->pCursor!=0 );
  71601. oc = pOp->opcode;
  71602. pC->nullRow = 0;
  71603. #ifdef SQLITE_DEBUG
  71604. pC->seekOp = pOp->opcode;
  71605. #endif
  71606. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  71607. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  71608. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  71609. */
  71610. #ifdef SQLITE_DEBUG
  71611. if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
  71612. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  71613. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  71614. assert( pOp[1].p1==pOp[0].p1 );
  71615. assert( pOp[1].p2==pOp[0].p2 );
  71616. assert( pOp[1].p3==pOp[0].p3 );
  71617. assert( pOp[1].p4.i==pOp[0].p4.i );
  71618. }
  71619. #endif
  71620. if( pC->isTable ){
  71621. /* The input value in P3 might be of any type: integer, real, string,
  71622. ** blob, or NULL. But it needs to be an integer before we can do
  71623. ** the seek, so convert it. */
  71624. pIn3 = &aMem[pOp->p3];
  71625. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  71626. applyNumericAffinity(pIn3, 0);
  71627. }
  71628. iKey = sqlite3VdbeIntValue(pIn3);
  71629. /* If the P3 value could not be converted into an integer without
  71630. ** loss of information, then special processing is required... */
  71631. if( (pIn3->flags & MEM_Int)==0 ){
  71632. if( (pIn3->flags & MEM_Real)==0 ){
  71633. /* If the P3 value cannot be converted into any kind of a number,
  71634. ** then the seek is not possible, so jump to P2 */
  71635. VdbeBranchTaken(1,2); goto jump_to_p2;
  71636. break;
  71637. }
  71638. /* If the approximation iKey is larger than the actual real search
  71639. ** term, substitute >= for > and < for <=. e.g. if the search term
  71640. ** is 4.9 and the integer approximation 5:
  71641. **
  71642. ** (x > 4.9) -> (x >= 5)
  71643. ** (x <= 4.9) -> (x < 5)
  71644. */
  71645. if( pIn3->u.r<(double)iKey ){
  71646. assert( OP_SeekGE==(OP_SeekGT-1) );
  71647. assert( OP_SeekLT==(OP_SeekLE-1) );
  71648. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  71649. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  71650. }
  71651. /* If the approximation iKey is smaller than the actual real search
  71652. ** term, substitute <= for < and > for >=. */
  71653. else if( pIn3->u.r>(double)iKey ){
  71654. assert( OP_SeekLE==(OP_SeekLT+1) );
  71655. assert( OP_SeekGT==(OP_SeekGE+1) );
  71656. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  71657. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  71658. }
  71659. }
  71660. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  71661. pC->movetoTarget = iKey; /* Used by OP_Delete */
  71662. if( rc!=SQLITE_OK ){
  71663. goto abort_due_to_error;
  71664. }
  71665. }else{
  71666. nField = pOp->p4.i;
  71667. assert( pOp->p4type==P4_INT32 );
  71668. assert( nField>0 );
  71669. r.pKeyInfo = pC->pKeyInfo;
  71670. r.nField = (u16)nField;
  71671. /* The next line of code computes as follows, only faster:
  71672. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  71673. ** r.default_rc = -1;
  71674. ** }else{
  71675. ** r.default_rc = +1;
  71676. ** }
  71677. */
  71678. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  71679. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  71680. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  71681. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  71682. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  71683. r.aMem = &aMem[pOp->p3];
  71684. #ifdef SQLITE_DEBUG
  71685. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  71686. #endif
  71687. ExpandBlob(r.aMem);
  71688. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  71689. if( rc!=SQLITE_OK ){
  71690. goto abort_due_to_error;
  71691. }
  71692. }
  71693. pC->deferredMoveto = 0;
  71694. pC->cacheStatus = CACHE_STALE;
  71695. #ifdef SQLITE_TEST
  71696. sqlite3_search_count++;
  71697. #endif
  71698. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  71699. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  71700. res = 0;
  71701. rc = sqlite3BtreeNext(pC->pCursor, &res);
  71702. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71703. }else{
  71704. res = 0;
  71705. }
  71706. }else{
  71707. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  71708. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  71709. res = 0;
  71710. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  71711. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71712. }else{
  71713. /* res might be negative because the table is empty. Check to
  71714. ** see if this is the case.
  71715. */
  71716. res = sqlite3BtreeEof(pC->pCursor);
  71717. }
  71718. }
  71719. assert( pOp->p2>0 );
  71720. VdbeBranchTaken(res!=0,2);
  71721. if( res ){
  71722. goto jump_to_p2;
  71723. }
  71724. break;
  71725. }
  71726. /* Opcode: Seek P1 P2 * * *
  71727. ** Synopsis: intkey=r[P2]
  71728. **
  71729. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  71730. ** for P1 to move so that it points to the rowid given by P2.
  71731. **
  71732. ** This is actually a deferred seek. Nothing actually happens until
  71733. ** the cursor is used to read a record. That way, if no reads
  71734. ** occur, no unnecessary I/O happens.
  71735. */
  71736. case OP_Seek: { /* in2 */
  71737. VdbeCursor *pC;
  71738. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71739. pC = p->apCsr[pOp->p1];
  71740. assert( pC!=0 );
  71741. assert( pC->pCursor!=0 );
  71742. assert( pC->isTable );
  71743. pC->nullRow = 0;
  71744. pIn2 = &aMem[pOp->p2];
  71745. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  71746. pC->deferredMoveto = 1;
  71747. break;
  71748. }
  71749. /* Opcode: Found P1 P2 P3 P4 *
  71750. ** Synopsis: key=r[P3@P4]
  71751. **
  71752. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  71753. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  71754. ** record.
  71755. **
  71756. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  71757. ** is a prefix of any entry in P1 then a jump is made to P2 and
  71758. ** P1 is left pointing at the matching entry.
  71759. **
  71760. ** This operation leaves the cursor in a state where it can be
  71761. ** advanced in the forward direction. The Next instruction will work,
  71762. ** but not the Prev instruction.
  71763. **
  71764. ** See also: NotFound, NoConflict, NotExists. SeekGe
  71765. */
  71766. /* Opcode: NotFound P1 P2 P3 P4 *
  71767. ** Synopsis: key=r[P3@P4]
  71768. **
  71769. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  71770. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  71771. ** record.
  71772. **
  71773. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  71774. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  71775. ** does contain an entry whose prefix matches the P3/P4 record then control
  71776. ** falls through to the next instruction and P1 is left pointing at the
  71777. ** matching entry.
  71778. **
  71779. ** This operation leaves the cursor in a state where it cannot be
  71780. ** advanced in either direction. In other words, the Next and Prev
  71781. ** opcodes do not work after this operation.
  71782. **
  71783. ** See also: Found, NotExists, NoConflict
  71784. */
  71785. /* Opcode: NoConflict P1 P2 P3 P4 *
  71786. ** Synopsis: key=r[P3@P4]
  71787. **
  71788. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  71789. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  71790. ** record.
  71791. **
  71792. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  71793. ** contains any NULL value, jump immediately to P2. If all terms of the
  71794. ** record are not-NULL then a check is done to determine if any row in the
  71795. ** P1 index btree has a matching key prefix. If there are no matches, jump
  71796. ** immediately to P2. If there is a match, fall through and leave the P1
  71797. ** cursor pointing to the matching row.
  71798. **
  71799. ** This opcode is similar to OP_NotFound with the exceptions that the
  71800. ** branch is always taken if any part of the search key input is NULL.
  71801. **
  71802. ** This operation leaves the cursor in a state where it cannot be
  71803. ** advanced in either direction. In other words, the Next and Prev
  71804. ** opcodes do not work after this operation.
  71805. **
  71806. ** See also: NotFound, Found, NotExists
  71807. */
  71808. case OP_NoConflict: /* jump, in3 */
  71809. case OP_NotFound: /* jump, in3 */
  71810. case OP_Found: { /* jump, in3 */
  71811. int alreadyExists;
  71812. int takeJump;
  71813. int ii;
  71814. VdbeCursor *pC;
  71815. int res;
  71816. char *pFree;
  71817. UnpackedRecord *pIdxKey;
  71818. UnpackedRecord r;
  71819. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  71820. #ifdef SQLITE_TEST
  71821. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  71822. #endif
  71823. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71824. assert( pOp->p4type==P4_INT32 );
  71825. pC = p->apCsr[pOp->p1];
  71826. assert( pC!=0 );
  71827. #ifdef SQLITE_DEBUG
  71828. pC->seekOp = pOp->opcode;
  71829. #endif
  71830. pIn3 = &aMem[pOp->p3];
  71831. assert( pC->pCursor!=0 );
  71832. assert( pC->isTable==0 );
  71833. pFree = 0;
  71834. if( pOp->p4.i>0 ){
  71835. r.pKeyInfo = pC->pKeyInfo;
  71836. r.nField = (u16)pOp->p4.i;
  71837. r.aMem = pIn3;
  71838. for(ii=0; ii<r.nField; ii++){
  71839. assert( memIsValid(&r.aMem[ii]) );
  71840. ExpandBlob(&r.aMem[ii]);
  71841. #ifdef SQLITE_DEBUG
  71842. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  71843. #endif
  71844. }
  71845. pIdxKey = &r;
  71846. }else{
  71847. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  71848. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  71849. );
  71850. if( pIdxKey==0 ) goto no_mem;
  71851. assert( pIn3->flags & MEM_Blob );
  71852. ExpandBlob(pIn3);
  71853. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  71854. }
  71855. pIdxKey->default_rc = 0;
  71856. takeJump = 0;
  71857. if( pOp->opcode==OP_NoConflict ){
  71858. /* For the OP_NoConflict opcode, take the jump if any of the
  71859. ** input fields are NULL, since any key with a NULL will not
  71860. ** conflict */
  71861. for(ii=0; ii<pIdxKey->nField; ii++){
  71862. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  71863. takeJump = 1;
  71864. break;
  71865. }
  71866. }
  71867. }
  71868. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  71869. sqlite3DbFree(db, pFree);
  71870. if( rc!=SQLITE_OK ){
  71871. break;
  71872. }
  71873. pC->seekResult = res;
  71874. alreadyExists = (res==0);
  71875. pC->nullRow = 1-alreadyExists;
  71876. pC->deferredMoveto = 0;
  71877. pC->cacheStatus = CACHE_STALE;
  71878. if( pOp->opcode==OP_Found ){
  71879. VdbeBranchTaken(alreadyExists!=0,2);
  71880. if( alreadyExists ) goto jump_to_p2;
  71881. }else{
  71882. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  71883. if( takeJump || !alreadyExists ) goto jump_to_p2;
  71884. }
  71885. break;
  71886. }
  71887. /* Opcode: NotExists P1 P2 P3 * *
  71888. ** Synopsis: intkey=r[P3]
  71889. **
  71890. ** P1 is the index of a cursor open on an SQL table btree (with integer
  71891. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  71892. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  71893. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  71894. ** leave the cursor pointing at that record and fall through to the next
  71895. ** instruction.
  71896. **
  71897. ** The OP_NotFound opcode performs the same operation on index btrees
  71898. ** (with arbitrary multi-value keys).
  71899. **
  71900. ** This opcode leaves the cursor in a state where it cannot be advanced
  71901. ** in either direction. In other words, the Next and Prev opcodes will
  71902. ** not work following this opcode.
  71903. **
  71904. ** See also: Found, NotFound, NoConflict
  71905. */
  71906. case OP_NotExists: { /* jump, in3 */
  71907. VdbeCursor *pC;
  71908. BtCursor *pCrsr;
  71909. int res;
  71910. u64 iKey;
  71911. pIn3 = &aMem[pOp->p3];
  71912. assert( pIn3->flags & MEM_Int );
  71913. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71914. pC = p->apCsr[pOp->p1];
  71915. assert( pC!=0 );
  71916. #ifdef SQLITE_DEBUG
  71917. pC->seekOp = 0;
  71918. #endif
  71919. assert( pC->isTable );
  71920. assert( pC->pseudoTableReg==0 );
  71921. pCrsr = pC->pCursor;
  71922. assert( pCrsr!=0 );
  71923. res = 0;
  71924. iKey = pIn3->u.i;
  71925. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  71926. assert( rc==SQLITE_OK || res==0 );
  71927. pC->movetoTarget = iKey; /* Used by OP_Delete */
  71928. pC->nullRow = 0;
  71929. pC->cacheStatus = CACHE_STALE;
  71930. pC->deferredMoveto = 0;
  71931. VdbeBranchTaken(res!=0,2);
  71932. pC->seekResult = res;
  71933. if( res!=0 ){
  71934. assert( rc==SQLITE_OK );
  71935. if( pOp->p2==0 ){
  71936. rc = SQLITE_CORRUPT_BKPT;
  71937. }else{
  71938. goto jump_to_p2;
  71939. }
  71940. }
  71941. break;
  71942. }
  71943. /* Opcode: Sequence P1 P2 * * *
  71944. ** Synopsis: r[P2]=cursor[P1].ctr++
  71945. **
  71946. ** Find the next available sequence number for cursor P1.
  71947. ** Write the sequence number into register P2.
  71948. ** The sequence number on the cursor is incremented after this
  71949. ** instruction.
  71950. */
  71951. case OP_Sequence: { /* out2 */
  71952. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71953. assert( p->apCsr[pOp->p1]!=0 );
  71954. pOut = out2Prerelease(p, pOp);
  71955. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  71956. break;
  71957. }
  71958. /* Opcode: NewRowid P1 P2 P3 * *
  71959. ** Synopsis: r[P2]=rowid
  71960. **
  71961. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  71962. ** The record number is not previously used as a key in the database
  71963. ** table that cursor P1 points to. The new record number is written
  71964. ** written to register P2.
  71965. **
  71966. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  71967. ** the largest previously generated record number. No new record numbers are
  71968. ** allowed to be less than this value. When this value reaches its maximum,
  71969. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  71970. ** generated record number. This P3 mechanism is used to help implement the
  71971. ** AUTOINCREMENT feature.
  71972. */
  71973. case OP_NewRowid: { /* out2 */
  71974. i64 v; /* The new rowid */
  71975. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  71976. int res; /* Result of an sqlite3BtreeLast() */
  71977. int cnt; /* Counter to limit the number of searches */
  71978. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  71979. VdbeFrame *pFrame; /* Root frame of VDBE */
  71980. v = 0;
  71981. res = 0;
  71982. pOut = out2Prerelease(p, pOp);
  71983. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71984. pC = p->apCsr[pOp->p1];
  71985. assert( pC!=0 );
  71986. assert( pC->pCursor!=0 );
  71987. {
  71988. /* The next rowid or record number (different terms for the same
  71989. ** thing) is obtained in a two-step algorithm.
  71990. **
  71991. ** First we attempt to find the largest existing rowid and add one
  71992. ** to that. But if the largest existing rowid is already the maximum
  71993. ** positive integer, we have to fall through to the second
  71994. ** probabilistic algorithm
  71995. **
  71996. ** The second algorithm is to select a rowid at random and see if
  71997. ** it already exists in the table. If it does not exist, we have
  71998. ** succeeded. If the random rowid does exist, we select a new one
  71999. ** and try again, up to 100 times.
  72000. */
  72001. assert( pC->isTable );
  72002. #ifdef SQLITE_32BIT_ROWID
  72003. # define MAX_ROWID 0x7fffffff
  72004. #else
  72005. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  72006. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  72007. ** to provide the constant while making all compilers happy.
  72008. */
  72009. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  72010. #endif
  72011. if( !pC->useRandomRowid ){
  72012. rc = sqlite3BtreeLast(pC->pCursor, &res);
  72013. if( rc!=SQLITE_OK ){
  72014. goto abort_due_to_error;
  72015. }
  72016. if( res ){
  72017. v = 1; /* IMP: R-61914-48074 */
  72018. }else{
  72019. assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  72020. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  72021. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  72022. if( v>=MAX_ROWID ){
  72023. pC->useRandomRowid = 1;
  72024. }else{
  72025. v++; /* IMP: R-29538-34987 */
  72026. }
  72027. }
  72028. }
  72029. #ifndef SQLITE_OMIT_AUTOINCREMENT
  72030. if( pOp->p3 ){
  72031. /* Assert that P3 is a valid memory cell. */
  72032. assert( pOp->p3>0 );
  72033. if( p->pFrame ){
  72034. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  72035. /* Assert that P3 is a valid memory cell. */
  72036. assert( pOp->p3<=pFrame->nMem );
  72037. pMem = &pFrame->aMem[pOp->p3];
  72038. }else{
  72039. /* Assert that P3 is a valid memory cell. */
  72040. assert( pOp->p3<=(p->nMem-p->nCursor) );
  72041. pMem = &aMem[pOp->p3];
  72042. memAboutToChange(p, pMem);
  72043. }
  72044. assert( memIsValid(pMem) );
  72045. REGISTER_TRACE(pOp->p3, pMem);
  72046. sqlite3VdbeMemIntegerify(pMem);
  72047. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  72048. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  72049. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  72050. goto abort_due_to_error;
  72051. }
  72052. if( v<pMem->u.i+1 ){
  72053. v = pMem->u.i + 1;
  72054. }
  72055. pMem->u.i = v;
  72056. }
  72057. #endif
  72058. if( pC->useRandomRowid ){
  72059. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  72060. ** largest possible integer (9223372036854775807) then the database
  72061. ** engine starts picking positive candidate ROWIDs at random until
  72062. ** it finds one that is not previously used. */
  72063. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  72064. ** an AUTOINCREMENT table. */
  72065. cnt = 0;
  72066. do{
  72067. sqlite3_randomness(sizeof(v), &v);
  72068. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  72069. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  72070. 0, &res))==SQLITE_OK)
  72071. && (res==0)
  72072. && (++cnt<100));
  72073. if( rc==SQLITE_OK && res==0 ){
  72074. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  72075. goto abort_due_to_error;
  72076. }
  72077. assert( v>0 ); /* EV: R-40812-03570 */
  72078. }
  72079. pC->deferredMoveto = 0;
  72080. pC->cacheStatus = CACHE_STALE;
  72081. }
  72082. pOut->u.i = v;
  72083. break;
  72084. }
  72085. /* Opcode: Insert P1 P2 P3 P4 P5
  72086. ** Synopsis: intkey=r[P3] data=r[P2]
  72087. **
  72088. ** Write an entry into the table of cursor P1. A new entry is
  72089. ** created if it doesn't already exist or the data for an existing
  72090. ** entry is overwritten. The data is the value MEM_Blob stored in register
  72091. ** number P2. The key is stored in register P3. The key must
  72092. ** be a MEM_Int.
  72093. **
  72094. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  72095. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  72096. ** then rowid is stored for subsequent return by the
  72097. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  72098. **
  72099. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  72100. ** the last seek operation (OP_NotExists) was a success, then this
  72101. ** operation will not attempt to find the appropriate row before doing
  72102. ** the insert but will instead overwrite the row that the cursor is
  72103. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  72104. ** has already positioned the cursor correctly. This is an optimization
  72105. ** that boosts performance by avoiding redundant seeks.
  72106. **
  72107. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  72108. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  72109. ** is part of an INSERT operation. The difference is only important to
  72110. ** the update hook.
  72111. **
  72112. ** Parameter P4 may point to a string containing the table-name, or
  72113. ** may be NULL. If it is not NULL, then the update-hook
  72114. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  72115. **
  72116. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  72117. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  72118. ** and register P2 becomes ephemeral. If the cursor is changed, the
  72119. ** value of register P2 will then change. Make sure this does not
  72120. ** cause any problems.)
  72121. **
  72122. ** This instruction only works on tables. The equivalent instruction
  72123. ** for indices is OP_IdxInsert.
  72124. */
  72125. /* Opcode: InsertInt P1 P2 P3 P4 P5
  72126. ** Synopsis: intkey=P3 data=r[P2]
  72127. **
  72128. ** This works exactly like OP_Insert except that the key is the
  72129. ** integer value P3, not the value of the integer stored in register P3.
  72130. */
  72131. case OP_Insert:
  72132. case OP_InsertInt: {
  72133. Mem *pData; /* MEM cell holding data for the record to be inserted */
  72134. Mem *pKey; /* MEM cell holding key for the record */
  72135. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  72136. VdbeCursor *pC; /* Cursor to table into which insert is written */
  72137. int nZero; /* Number of zero-bytes to append */
  72138. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  72139. const char *zDb; /* database name - used by the update hook */
  72140. const char *zTbl; /* Table name - used by the opdate hook */
  72141. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  72142. pData = &aMem[pOp->p2];
  72143. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72144. assert( memIsValid(pData) );
  72145. pC = p->apCsr[pOp->p1];
  72146. assert( pC!=0 );
  72147. assert( pC->pCursor!=0 );
  72148. assert( pC->pseudoTableReg==0 );
  72149. assert( pC->isTable );
  72150. REGISTER_TRACE(pOp->p2, pData);
  72151. if( pOp->opcode==OP_Insert ){
  72152. pKey = &aMem[pOp->p3];
  72153. assert( pKey->flags & MEM_Int );
  72154. assert( memIsValid(pKey) );
  72155. REGISTER_TRACE(pOp->p3, pKey);
  72156. iKey = pKey->u.i;
  72157. }else{
  72158. assert( pOp->opcode==OP_InsertInt );
  72159. iKey = pOp->p3;
  72160. }
  72161. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  72162. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  72163. if( pData->flags & MEM_Null ){
  72164. pData->z = 0;
  72165. pData->n = 0;
  72166. }else{
  72167. assert( pData->flags & (MEM_Blob|MEM_Str) );
  72168. }
  72169. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  72170. if( pData->flags & MEM_Zero ){
  72171. nZero = pData->u.nZero;
  72172. }else{
  72173. nZero = 0;
  72174. }
  72175. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  72176. pData->z, pData->n, nZero,
  72177. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  72178. );
  72179. pC->deferredMoveto = 0;
  72180. pC->cacheStatus = CACHE_STALE;
  72181. /* Invoke the update-hook if required. */
  72182. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  72183. zDb = db->aDb[pC->iDb].zName;
  72184. zTbl = pOp->p4.z;
  72185. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  72186. assert( pC->isTable );
  72187. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  72188. assert( pC->iDb>=0 );
  72189. }
  72190. break;
  72191. }
  72192. /* Opcode: Delete P1 P2 * P4 P5
  72193. **
  72194. ** Delete the record at which the P1 cursor is currently pointing.
  72195. **
  72196. ** If the P5 parameter is non-zero, the cursor will be left pointing at
  72197. ** either the next or the previous record in the table. If it is left
  72198. ** pointing at the next record, then the next Next instruction will be a
  72199. ** no-op. As a result, in this case it is OK to delete a record from within a
  72200. ** Next loop. If P5 is zero, then the cursor is left in an undefined state.
  72201. **
  72202. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  72203. ** incremented (otherwise not).
  72204. **
  72205. ** P1 must not be pseudo-table. It has to be a real table with
  72206. ** multiple rows.
  72207. **
  72208. ** If P4 is not NULL, then it is the name of the table that P1 is
  72209. ** pointing to. The update hook will be invoked, if it exists.
  72210. ** If P4 is not NULL then the P1 cursor must have been positioned
  72211. ** using OP_NotFound prior to invoking this opcode.
  72212. */
  72213. case OP_Delete: {
  72214. VdbeCursor *pC;
  72215. u8 hasUpdateCallback;
  72216. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72217. pC = p->apCsr[pOp->p1];
  72218. assert( pC!=0 );
  72219. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  72220. assert( pC->deferredMoveto==0 );
  72221. hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
  72222. if( pOp->p5 && hasUpdateCallback ){
  72223. sqlite3BtreeKeySize(pC->pCursor, &pC->movetoTarget);
  72224. }
  72225. #ifdef SQLITE_DEBUG
  72226. /* The seek operation that positioned the cursor prior to OP_Delete will
  72227. ** have also set the pC->movetoTarget field to the rowid of the row that
  72228. ** is being deleted */
  72229. if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
  72230. i64 iKey = 0;
  72231. sqlite3BtreeKeySize(pC->pCursor, &iKey);
  72232. assert( pC->movetoTarget==iKey );
  72233. }
  72234. #endif
  72235. rc = sqlite3BtreeDelete(pC->pCursor, pOp->p5);
  72236. pC->cacheStatus = CACHE_STALE;
  72237. /* Invoke the update-hook if required. */
  72238. if( rc==SQLITE_OK && hasUpdateCallback ){
  72239. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  72240. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  72241. assert( pC->iDb>=0 );
  72242. }
  72243. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  72244. break;
  72245. }
  72246. /* Opcode: ResetCount * * * * *
  72247. **
  72248. ** The value of the change counter is copied to the database handle
  72249. ** change counter (returned by subsequent calls to sqlite3_changes()).
  72250. ** Then the VMs internal change counter resets to 0.
  72251. ** This is used by trigger programs.
  72252. */
  72253. case OP_ResetCount: {
  72254. sqlite3VdbeSetChanges(db, p->nChange);
  72255. p->nChange = 0;
  72256. break;
  72257. }
  72258. /* Opcode: SorterCompare P1 P2 P3 P4
  72259. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  72260. **
  72261. ** P1 is a sorter cursor. This instruction compares a prefix of the
  72262. ** record blob in register P3 against a prefix of the entry that
  72263. ** the sorter cursor currently points to. Only the first P4 fields
  72264. ** of r[P3] and the sorter record are compared.
  72265. **
  72266. ** If either P3 or the sorter contains a NULL in one of their significant
  72267. ** fields (not counting the P4 fields at the end which are ignored) then
  72268. ** the comparison is assumed to be equal.
  72269. **
  72270. ** Fall through to next instruction if the two records compare equal to
  72271. ** each other. Jump to P2 if they are different.
  72272. */
  72273. case OP_SorterCompare: {
  72274. VdbeCursor *pC;
  72275. int res;
  72276. int nKeyCol;
  72277. pC = p->apCsr[pOp->p1];
  72278. assert( isSorter(pC) );
  72279. assert( pOp->p4type==P4_INT32 );
  72280. pIn3 = &aMem[pOp->p3];
  72281. nKeyCol = pOp->p4.i;
  72282. res = 0;
  72283. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  72284. VdbeBranchTaken(res!=0,2);
  72285. if( res ) goto jump_to_p2;
  72286. break;
  72287. };
  72288. /* Opcode: SorterData P1 P2 P3 * *
  72289. ** Synopsis: r[P2]=data
  72290. **
  72291. ** Write into register P2 the current sorter data for sorter cursor P1.
  72292. ** Then clear the column header cache on cursor P3.
  72293. **
  72294. ** This opcode is normally use to move a record out of the sorter and into
  72295. ** a register that is the source for a pseudo-table cursor created using
  72296. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  72297. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  72298. ** us from having to issue a separate NullRow instruction to clear that cache.
  72299. */
  72300. case OP_SorterData: {
  72301. VdbeCursor *pC;
  72302. pOut = &aMem[pOp->p2];
  72303. pC = p->apCsr[pOp->p1];
  72304. assert( isSorter(pC) );
  72305. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  72306. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  72307. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72308. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  72309. break;
  72310. }
  72311. /* Opcode: RowData P1 P2 * * *
  72312. ** Synopsis: r[P2]=data
  72313. **
  72314. ** Write into register P2 the complete row data for cursor P1.
  72315. ** There is no interpretation of the data.
  72316. ** It is just copied onto the P2 register exactly as
  72317. ** it is found in the database file.
  72318. **
  72319. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  72320. ** of a real table, not a pseudo-table.
  72321. */
  72322. /* Opcode: RowKey P1 P2 * * *
  72323. ** Synopsis: r[P2]=key
  72324. **
  72325. ** Write into register P2 the complete row key for cursor P1.
  72326. ** There is no interpretation of the data.
  72327. ** The key is copied onto the P2 register exactly as
  72328. ** it is found in the database file.
  72329. **
  72330. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  72331. ** of a real table, not a pseudo-table.
  72332. */
  72333. case OP_RowKey:
  72334. case OP_RowData: {
  72335. VdbeCursor *pC;
  72336. BtCursor *pCrsr;
  72337. u32 n;
  72338. i64 n64;
  72339. pOut = &aMem[pOp->p2];
  72340. memAboutToChange(p, pOut);
  72341. /* Note that RowKey and RowData are really exactly the same instruction */
  72342. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72343. pC = p->apCsr[pOp->p1];
  72344. assert( isSorter(pC)==0 );
  72345. assert( pC->isTable || pOp->opcode!=OP_RowData );
  72346. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  72347. assert( pC!=0 );
  72348. assert( pC->nullRow==0 );
  72349. assert( pC->pseudoTableReg==0 );
  72350. assert( pC->pCursor!=0 );
  72351. pCrsr = pC->pCursor;
  72352. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  72353. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  72354. ** the cursor. If this where not the case, on of the following assert()s
  72355. ** would fail. Should this ever change (because of changes in the code
  72356. ** generator) then the fix would be to insert a call to
  72357. ** sqlite3VdbeCursorMoveto().
  72358. */
  72359. assert( pC->deferredMoveto==0 );
  72360. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  72361. #if 0 /* Not required due to the previous to assert() statements */
  72362. rc = sqlite3VdbeCursorMoveto(pC);
  72363. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72364. #endif
  72365. if( pC->isTable==0 ){
  72366. assert( !pC->isTable );
  72367. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  72368. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  72369. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72370. goto too_big;
  72371. }
  72372. n = (u32)n64;
  72373. }else{
  72374. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  72375. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  72376. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72377. goto too_big;
  72378. }
  72379. }
  72380. testcase( n==0 );
  72381. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  72382. goto no_mem;
  72383. }
  72384. pOut->n = n;
  72385. MemSetTypeFlag(pOut, MEM_Blob);
  72386. if( pC->isTable==0 ){
  72387. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  72388. }else{
  72389. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  72390. }
  72391. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  72392. UPDATE_MAX_BLOBSIZE(pOut);
  72393. REGISTER_TRACE(pOp->p2, pOut);
  72394. break;
  72395. }
  72396. /* Opcode: Rowid P1 P2 * * *
  72397. ** Synopsis: r[P2]=rowid
  72398. **
  72399. ** Store in register P2 an integer which is the key of the table entry that
  72400. ** P1 is currently point to.
  72401. **
  72402. ** P1 can be either an ordinary table or a virtual table. There used to
  72403. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  72404. ** one opcode now works for both table types.
  72405. */
  72406. case OP_Rowid: { /* out2 */
  72407. VdbeCursor *pC;
  72408. i64 v;
  72409. sqlite3_vtab *pVtab;
  72410. const sqlite3_module *pModule;
  72411. pOut = out2Prerelease(p, pOp);
  72412. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72413. pC = p->apCsr[pOp->p1];
  72414. assert( pC!=0 );
  72415. assert( pC->pseudoTableReg==0 || pC->nullRow );
  72416. if( pC->nullRow ){
  72417. pOut->flags = MEM_Null;
  72418. break;
  72419. }else if( pC->deferredMoveto ){
  72420. v = pC->movetoTarget;
  72421. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72422. }else if( pC->pVtabCursor ){
  72423. pVtab = pC->pVtabCursor->pVtab;
  72424. pModule = pVtab->pModule;
  72425. assert( pModule->xRowid );
  72426. rc = pModule->xRowid(pC->pVtabCursor, &v);
  72427. sqlite3VtabImportErrmsg(p, pVtab);
  72428. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  72429. }else{
  72430. assert( pC->pCursor!=0 );
  72431. rc = sqlite3VdbeCursorRestore(pC);
  72432. if( rc ) goto abort_due_to_error;
  72433. if( pC->nullRow ){
  72434. pOut->flags = MEM_Null;
  72435. break;
  72436. }
  72437. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  72438. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  72439. }
  72440. pOut->u.i = v;
  72441. break;
  72442. }
  72443. /* Opcode: NullRow P1 * * * *
  72444. **
  72445. ** Move the cursor P1 to a null row. Any OP_Column operations
  72446. ** that occur while the cursor is on the null row will always
  72447. ** write a NULL.
  72448. */
  72449. case OP_NullRow: {
  72450. VdbeCursor *pC;
  72451. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72452. pC = p->apCsr[pOp->p1];
  72453. assert( pC!=0 );
  72454. pC->nullRow = 1;
  72455. pC->cacheStatus = CACHE_STALE;
  72456. if( pC->pCursor ){
  72457. sqlite3BtreeClearCursor(pC->pCursor);
  72458. }
  72459. break;
  72460. }
  72461. /* Opcode: Last P1 P2 P3 * *
  72462. **
  72463. ** The next use of the Rowid or Column or Prev instruction for P1
  72464. ** will refer to the last entry in the database table or index.
  72465. ** If the table or index is empty and P2>0, then jump immediately to P2.
  72466. ** If P2 is 0 or if the table or index is not empty, fall through
  72467. ** to the following instruction.
  72468. **
  72469. ** This opcode leaves the cursor configured to move in reverse order,
  72470. ** from the end toward the beginning. In other words, the cursor is
  72471. ** configured to use Prev, not Next.
  72472. */
  72473. case OP_Last: { /* jump */
  72474. VdbeCursor *pC;
  72475. BtCursor *pCrsr;
  72476. int res;
  72477. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72478. pC = p->apCsr[pOp->p1];
  72479. assert( pC!=0 );
  72480. pCrsr = pC->pCursor;
  72481. res = 0;
  72482. assert( pCrsr!=0 );
  72483. rc = sqlite3BtreeLast(pCrsr, &res);
  72484. pC->nullRow = (u8)res;
  72485. pC->deferredMoveto = 0;
  72486. pC->cacheStatus = CACHE_STALE;
  72487. pC->seekResult = pOp->p3;
  72488. #ifdef SQLITE_DEBUG
  72489. pC->seekOp = OP_Last;
  72490. #endif
  72491. if( pOp->p2>0 ){
  72492. VdbeBranchTaken(res!=0,2);
  72493. if( res ) goto jump_to_p2;
  72494. }
  72495. break;
  72496. }
  72497. /* Opcode: Sort P1 P2 * * *
  72498. **
  72499. ** This opcode does exactly the same thing as OP_Rewind except that
  72500. ** it increments an undocumented global variable used for testing.
  72501. **
  72502. ** Sorting is accomplished by writing records into a sorting index,
  72503. ** then rewinding that index and playing it back from beginning to
  72504. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  72505. ** rewinding so that the global variable will be incremented and
  72506. ** regression tests can determine whether or not the optimizer is
  72507. ** correctly optimizing out sorts.
  72508. */
  72509. case OP_SorterSort: /* jump */
  72510. case OP_Sort: { /* jump */
  72511. #ifdef SQLITE_TEST
  72512. sqlite3_sort_count++;
  72513. sqlite3_search_count--;
  72514. #endif
  72515. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  72516. /* Fall through into OP_Rewind */
  72517. }
  72518. /* Opcode: Rewind P1 P2 * * *
  72519. **
  72520. ** The next use of the Rowid or Column or Next instruction for P1
  72521. ** will refer to the first entry in the database table or index.
  72522. ** If the table or index is empty, jump immediately to P2.
  72523. ** If the table or index is not empty, fall through to the following
  72524. ** instruction.
  72525. **
  72526. ** This opcode leaves the cursor configured to move in forward order,
  72527. ** from the beginning toward the end. In other words, the cursor is
  72528. ** configured to use Next, not Prev.
  72529. */
  72530. case OP_Rewind: { /* jump */
  72531. VdbeCursor *pC;
  72532. BtCursor *pCrsr;
  72533. int res;
  72534. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72535. pC = p->apCsr[pOp->p1];
  72536. assert( pC!=0 );
  72537. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  72538. res = 1;
  72539. #ifdef SQLITE_DEBUG
  72540. pC->seekOp = OP_Rewind;
  72541. #endif
  72542. if( isSorter(pC) ){
  72543. rc = sqlite3VdbeSorterRewind(pC, &res);
  72544. }else{
  72545. pCrsr = pC->pCursor;
  72546. assert( pCrsr );
  72547. rc = sqlite3BtreeFirst(pCrsr, &res);
  72548. pC->deferredMoveto = 0;
  72549. pC->cacheStatus = CACHE_STALE;
  72550. }
  72551. pC->nullRow = (u8)res;
  72552. assert( pOp->p2>0 && pOp->p2<p->nOp );
  72553. VdbeBranchTaken(res!=0,2);
  72554. if( res ) goto jump_to_p2;
  72555. break;
  72556. }
  72557. /* Opcode: Next P1 P2 P3 P4 P5
  72558. **
  72559. ** Advance cursor P1 so that it points to the next key/data pair in its
  72560. ** table or index. If there are no more key/value pairs then fall through
  72561. ** to the following instruction. But if the cursor advance was successful,
  72562. ** jump immediately to P2.
  72563. **
  72564. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  72565. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  72566. ** to follow SeekLT, SeekLE, or OP_Last.
  72567. **
  72568. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  72569. ** been opened prior to this opcode or the program will segfault.
  72570. **
  72571. ** The P3 value is a hint to the btree implementation. If P3==1, that
  72572. ** means P1 is an SQL index and that this instruction could have been
  72573. ** omitted if that index had been unique. P3 is usually 0. P3 is
  72574. ** always either 0 or 1.
  72575. **
  72576. ** P4 is always of type P4_ADVANCE. The function pointer points to
  72577. ** sqlite3BtreeNext().
  72578. **
  72579. ** If P5 is positive and the jump is taken, then event counter
  72580. ** number P5-1 in the prepared statement is incremented.
  72581. **
  72582. ** See also: Prev, NextIfOpen
  72583. */
  72584. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  72585. **
  72586. ** This opcode works just like Next except that if cursor P1 is not
  72587. ** open it behaves a no-op.
  72588. */
  72589. /* Opcode: Prev P1 P2 P3 P4 P5
  72590. **
  72591. ** Back up cursor P1 so that it points to the previous key/data pair in its
  72592. ** table or index. If there is no previous key/value pairs then fall through
  72593. ** to the following instruction. But if the cursor backup was successful,
  72594. ** jump immediately to P2.
  72595. **
  72596. **
  72597. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  72598. ** OP_Last opcode used to position the cursor. Prev is not allowed
  72599. ** to follow SeekGT, SeekGE, or OP_Rewind.
  72600. **
  72601. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  72602. ** not open then the behavior is undefined.
  72603. **
  72604. ** The P3 value is a hint to the btree implementation. If P3==1, that
  72605. ** means P1 is an SQL index and that this instruction could have been
  72606. ** omitted if that index had been unique. P3 is usually 0. P3 is
  72607. ** always either 0 or 1.
  72608. **
  72609. ** P4 is always of type P4_ADVANCE. The function pointer points to
  72610. ** sqlite3BtreePrevious().
  72611. **
  72612. ** If P5 is positive and the jump is taken, then event counter
  72613. ** number P5-1 in the prepared statement is incremented.
  72614. */
  72615. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  72616. **
  72617. ** This opcode works just like Prev except that if cursor P1 is not
  72618. ** open it behaves a no-op.
  72619. */
  72620. case OP_SorterNext: { /* jump */
  72621. VdbeCursor *pC;
  72622. int res;
  72623. pC = p->apCsr[pOp->p1];
  72624. assert( isSorter(pC) );
  72625. res = 0;
  72626. rc = sqlite3VdbeSorterNext(db, pC, &res);
  72627. goto next_tail;
  72628. case OP_PrevIfOpen: /* jump */
  72629. case OP_NextIfOpen: /* jump */
  72630. if( p->apCsr[pOp->p1]==0 ) break;
  72631. /* Fall through */
  72632. case OP_Prev: /* jump */
  72633. case OP_Next: /* jump */
  72634. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72635. assert( pOp->p5<ArraySize(p->aCounter) );
  72636. pC = p->apCsr[pOp->p1];
  72637. res = pOp->p3;
  72638. assert( pC!=0 );
  72639. assert( pC->deferredMoveto==0 );
  72640. assert( pC->pCursor );
  72641. assert( res==0 || (res==1 && pC->isTable==0) );
  72642. testcase( res==1 );
  72643. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  72644. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  72645. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  72646. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  72647. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  72648. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  72649. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  72650. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  72651. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  72652. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  72653. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  72654. || pC->seekOp==OP_Last );
  72655. rc = pOp->p4.xAdvance(pC->pCursor, &res);
  72656. next_tail:
  72657. pC->cacheStatus = CACHE_STALE;
  72658. VdbeBranchTaken(res==0,2);
  72659. if( res==0 ){
  72660. pC->nullRow = 0;
  72661. p->aCounter[pOp->p5]++;
  72662. #ifdef SQLITE_TEST
  72663. sqlite3_search_count++;
  72664. #endif
  72665. goto jump_to_p2_and_check_for_interrupt;
  72666. }else{
  72667. pC->nullRow = 1;
  72668. }
  72669. goto check_for_interrupt;
  72670. }
  72671. /* Opcode: IdxInsert P1 P2 P3 * P5
  72672. ** Synopsis: key=r[P2]
  72673. **
  72674. ** Register P2 holds an SQL index key made using the
  72675. ** MakeRecord instructions. This opcode writes that key
  72676. ** into the index P1. Data for the entry is nil.
  72677. **
  72678. ** P3 is a flag that provides a hint to the b-tree layer that this
  72679. ** insert is likely to be an append.
  72680. **
  72681. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  72682. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  72683. ** then the change counter is unchanged.
  72684. **
  72685. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  72686. ** just done a seek to the spot where the new entry is to be inserted.
  72687. ** This flag avoids doing an extra seek.
  72688. **
  72689. ** This instruction only works for indices. The equivalent instruction
  72690. ** for tables is OP_Insert.
  72691. */
  72692. case OP_SorterInsert: /* in2 */
  72693. case OP_IdxInsert: { /* in2 */
  72694. VdbeCursor *pC;
  72695. int nKey;
  72696. const char *zKey;
  72697. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72698. pC = p->apCsr[pOp->p1];
  72699. assert( pC!=0 );
  72700. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  72701. pIn2 = &aMem[pOp->p2];
  72702. assert( pIn2->flags & MEM_Blob );
  72703. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  72704. assert( pC->pCursor!=0 );
  72705. assert( pC->isTable==0 );
  72706. rc = ExpandBlob(pIn2);
  72707. if( rc==SQLITE_OK ){
  72708. if( pOp->opcode==OP_SorterInsert ){
  72709. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  72710. }else{
  72711. nKey = pIn2->n;
  72712. zKey = pIn2->z;
  72713. rc = sqlite3BtreeInsert(pC->pCursor, zKey, nKey, "", 0, 0, pOp->p3,
  72714. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  72715. );
  72716. assert( pC->deferredMoveto==0 );
  72717. pC->cacheStatus = CACHE_STALE;
  72718. }
  72719. }
  72720. break;
  72721. }
  72722. /* Opcode: IdxDelete P1 P2 P3 * *
  72723. ** Synopsis: key=r[P2@P3]
  72724. **
  72725. ** The content of P3 registers starting at register P2 form
  72726. ** an unpacked index key. This opcode removes that entry from the
  72727. ** index opened by cursor P1.
  72728. */
  72729. case OP_IdxDelete: {
  72730. VdbeCursor *pC;
  72731. BtCursor *pCrsr;
  72732. int res;
  72733. UnpackedRecord r;
  72734. assert( pOp->p3>0 );
  72735. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  72736. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72737. pC = p->apCsr[pOp->p1];
  72738. assert( pC!=0 );
  72739. pCrsr = pC->pCursor;
  72740. assert( pCrsr!=0 );
  72741. assert( pOp->p5==0 );
  72742. r.pKeyInfo = pC->pKeyInfo;
  72743. r.nField = (u16)pOp->p3;
  72744. r.default_rc = 0;
  72745. r.aMem = &aMem[pOp->p2];
  72746. #ifdef SQLITE_DEBUG
  72747. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  72748. #endif
  72749. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  72750. if( rc==SQLITE_OK && res==0 ){
  72751. rc = sqlite3BtreeDelete(pCrsr, 0);
  72752. }
  72753. assert( pC->deferredMoveto==0 );
  72754. pC->cacheStatus = CACHE_STALE;
  72755. break;
  72756. }
  72757. /* Opcode: IdxRowid P1 P2 * * *
  72758. ** Synopsis: r[P2]=rowid
  72759. **
  72760. ** Write into register P2 an integer which is the last entry in the record at
  72761. ** the end of the index key pointed to by cursor P1. This integer should be
  72762. ** the rowid of the table entry to which this index entry points.
  72763. **
  72764. ** See also: Rowid, MakeRecord.
  72765. */
  72766. case OP_IdxRowid: { /* out2 */
  72767. BtCursor *pCrsr;
  72768. VdbeCursor *pC;
  72769. i64 rowid;
  72770. pOut = out2Prerelease(p, pOp);
  72771. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72772. pC = p->apCsr[pOp->p1];
  72773. assert( pC!=0 );
  72774. pCrsr = pC->pCursor;
  72775. assert( pCrsr!=0 );
  72776. pOut->flags = MEM_Null;
  72777. assert( pC->isTable==0 );
  72778. assert( pC->deferredMoveto==0 );
  72779. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  72780. ** out from under the cursor. That will never happend for an IdxRowid
  72781. ** opcode, hence the NEVER() arround the check of the return value.
  72782. */
  72783. rc = sqlite3VdbeCursorRestore(pC);
  72784. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  72785. if( !pC->nullRow ){
  72786. rowid = 0; /* Not needed. Only used to silence a warning. */
  72787. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  72788. if( rc!=SQLITE_OK ){
  72789. goto abort_due_to_error;
  72790. }
  72791. pOut->u.i = rowid;
  72792. pOut->flags = MEM_Int;
  72793. }
  72794. break;
  72795. }
  72796. /* Opcode: IdxGE P1 P2 P3 P4 P5
  72797. ** Synopsis: key=r[P3@P4]
  72798. **
  72799. ** The P4 register values beginning with P3 form an unpacked index
  72800. ** key that omits the PRIMARY KEY. Compare this key value against the index
  72801. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  72802. ** fields at the end.
  72803. **
  72804. ** If the P1 index entry is greater than or equal to the key value
  72805. ** then jump to P2. Otherwise fall through to the next instruction.
  72806. */
  72807. /* Opcode: IdxGT P1 P2 P3 P4 P5
  72808. ** Synopsis: key=r[P3@P4]
  72809. **
  72810. ** The P4 register values beginning with P3 form an unpacked index
  72811. ** key that omits the PRIMARY KEY. Compare this key value against the index
  72812. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  72813. ** fields at the end.
  72814. **
  72815. ** If the P1 index entry is greater than the key value
  72816. ** then jump to P2. Otherwise fall through to the next instruction.
  72817. */
  72818. /* Opcode: IdxLT P1 P2 P3 P4 P5
  72819. ** Synopsis: key=r[P3@P4]
  72820. **
  72821. ** The P4 register values beginning with P3 form an unpacked index
  72822. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  72823. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  72824. ** ROWID on the P1 index.
  72825. **
  72826. ** If the P1 index entry is less than the key value then jump to P2.
  72827. ** Otherwise fall through to the next instruction.
  72828. */
  72829. /* Opcode: IdxLE P1 P2 P3 P4 P5
  72830. ** Synopsis: key=r[P3@P4]
  72831. **
  72832. ** The P4 register values beginning with P3 form an unpacked index
  72833. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  72834. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  72835. ** ROWID on the P1 index.
  72836. **
  72837. ** If the P1 index entry is less than or equal to the key value then jump
  72838. ** to P2. Otherwise fall through to the next instruction.
  72839. */
  72840. case OP_IdxLE: /* jump */
  72841. case OP_IdxGT: /* jump */
  72842. case OP_IdxLT: /* jump */
  72843. case OP_IdxGE: { /* jump */
  72844. VdbeCursor *pC;
  72845. int res;
  72846. UnpackedRecord r;
  72847. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72848. pC = p->apCsr[pOp->p1];
  72849. assert( pC!=0 );
  72850. assert( pC->isOrdered );
  72851. assert( pC->pCursor!=0);
  72852. assert( pC->deferredMoveto==0 );
  72853. assert( pOp->p5==0 || pOp->p5==1 );
  72854. assert( pOp->p4type==P4_INT32 );
  72855. r.pKeyInfo = pC->pKeyInfo;
  72856. r.nField = (u16)pOp->p4.i;
  72857. if( pOp->opcode<OP_IdxLT ){
  72858. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  72859. r.default_rc = -1;
  72860. }else{
  72861. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  72862. r.default_rc = 0;
  72863. }
  72864. r.aMem = &aMem[pOp->p3];
  72865. #ifdef SQLITE_DEBUG
  72866. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  72867. #endif
  72868. res = 0; /* Not needed. Only used to silence a warning. */
  72869. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  72870. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  72871. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  72872. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  72873. res = -res;
  72874. }else{
  72875. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  72876. res++;
  72877. }
  72878. VdbeBranchTaken(res>0,2);
  72879. if( res>0 ) goto jump_to_p2;
  72880. break;
  72881. }
  72882. /* Opcode: Destroy P1 P2 P3 * *
  72883. **
  72884. ** Delete an entire database table or index whose root page in the database
  72885. ** file is given by P1.
  72886. **
  72887. ** The table being destroyed is in the main database file if P3==0. If
  72888. ** P3==1 then the table to be clear is in the auxiliary database file
  72889. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  72890. **
  72891. ** If AUTOVACUUM is enabled then it is possible that another root page
  72892. ** might be moved into the newly deleted root page in order to keep all
  72893. ** root pages contiguous at the beginning of the database. The former
  72894. ** value of the root page that moved - its value before the move occurred -
  72895. ** is stored in register P2. If no page
  72896. ** movement was required (because the table being dropped was already
  72897. ** the last one in the database) then a zero is stored in register P2.
  72898. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  72899. **
  72900. ** See also: Clear
  72901. */
  72902. case OP_Destroy: { /* out2 */
  72903. int iMoved;
  72904. int iDb;
  72905. assert( p->readOnly==0 );
  72906. pOut = out2Prerelease(p, pOp);
  72907. pOut->flags = MEM_Null;
  72908. if( db->nVdbeRead > db->nVDestroy+1 ){
  72909. rc = SQLITE_LOCKED;
  72910. p->errorAction = OE_Abort;
  72911. }else{
  72912. iDb = pOp->p3;
  72913. assert( DbMaskTest(p->btreeMask, iDb) );
  72914. iMoved = 0; /* Not needed. Only to silence a warning. */
  72915. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  72916. pOut->flags = MEM_Int;
  72917. pOut->u.i = iMoved;
  72918. #ifndef SQLITE_OMIT_AUTOVACUUM
  72919. if( rc==SQLITE_OK && iMoved!=0 ){
  72920. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  72921. /* All OP_Destroy operations occur on the same btree */
  72922. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  72923. resetSchemaOnFault = iDb+1;
  72924. }
  72925. #endif
  72926. }
  72927. break;
  72928. }
  72929. /* Opcode: Clear P1 P2 P3
  72930. **
  72931. ** Delete all contents of the database table or index whose root page
  72932. ** in the database file is given by P1. But, unlike Destroy, do not
  72933. ** remove the table or index from the database file.
  72934. **
  72935. ** The table being clear is in the main database file if P2==0. If
  72936. ** P2==1 then the table to be clear is in the auxiliary database file
  72937. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  72938. **
  72939. ** If the P3 value is non-zero, then the table referred to must be an
  72940. ** intkey table (an SQL table, not an index). In this case the row change
  72941. ** count is incremented by the number of rows in the table being cleared.
  72942. ** If P3 is greater than zero, then the value stored in register P3 is
  72943. ** also incremented by the number of rows in the table being cleared.
  72944. **
  72945. ** See also: Destroy
  72946. */
  72947. case OP_Clear: {
  72948. int nChange;
  72949. nChange = 0;
  72950. assert( p->readOnly==0 );
  72951. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  72952. rc = sqlite3BtreeClearTable(
  72953. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  72954. );
  72955. if( pOp->p3 ){
  72956. p->nChange += nChange;
  72957. if( pOp->p3>0 ){
  72958. assert( memIsValid(&aMem[pOp->p3]) );
  72959. memAboutToChange(p, &aMem[pOp->p3]);
  72960. aMem[pOp->p3].u.i += nChange;
  72961. }
  72962. }
  72963. break;
  72964. }
  72965. /* Opcode: ResetSorter P1 * * * *
  72966. **
  72967. ** Delete all contents from the ephemeral table or sorter
  72968. ** that is open on cursor P1.
  72969. **
  72970. ** This opcode only works for cursors used for sorting and
  72971. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  72972. */
  72973. case OP_ResetSorter: {
  72974. VdbeCursor *pC;
  72975. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72976. pC = p->apCsr[pOp->p1];
  72977. assert( pC!=0 );
  72978. if( pC->pSorter ){
  72979. sqlite3VdbeSorterReset(db, pC->pSorter);
  72980. }else{
  72981. assert( pC->isEphemeral );
  72982. rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
  72983. }
  72984. break;
  72985. }
  72986. /* Opcode: CreateTable P1 P2 * * *
  72987. ** Synopsis: r[P2]=root iDb=P1
  72988. **
  72989. ** Allocate a new table in the main database file if P1==0 or in the
  72990. ** auxiliary database file if P1==1 or in an attached database if
  72991. ** P1>1. Write the root page number of the new table into
  72992. ** register P2
  72993. **
  72994. ** The difference between a table and an index is this: A table must
  72995. ** have a 4-byte integer key and can have arbitrary data. An index
  72996. ** has an arbitrary key but no data.
  72997. **
  72998. ** See also: CreateIndex
  72999. */
  73000. /* Opcode: CreateIndex P1 P2 * * *
  73001. ** Synopsis: r[P2]=root iDb=P1
  73002. **
  73003. ** Allocate a new index in the main database file if P1==0 or in the
  73004. ** auxiliary database file if P1==1 or in an attached database if
  73005. ** P1>1. Write the root page number of the new table into
  73006. ** register P2.
  73007. **
  73008. ** See documentation on OP_CreateTable for additional information.
  73009. */
  73010. case OP_CreateIndex: /* out2 */
  73011. case OP_CreateTable: { /* out2 */
  73012. int pgno;
  73013. int flags;
  73014. Db *pDb;
  73015. pOut = out2Prerelease(p, pOp);
  73016. pgno = 0;
  73017. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73018. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  73019. assert( p->readOnly==0 );
  73020. pDb = &db->aDb[pOp->p1];
  73021. assert( pDb->pBt!=0 );
  73022. if( pOp->opcode==OP_CreateTable ){
  73023. /* flags = BTREE_INTKEY; */
  73024. flags = BTREE_INTKEY;
  73025. }else{
  73026. flags = BTREE_BLOBKEY;
  73027. }
  73028. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  73029. pOut->u.i = pgno;
  73030. break;
  73031. }
  73032. /* Opcode: ParseSchema P1 * * P4 *
  73033. **
  73034. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  73035. ** that match the WHERE clause P4.
  73036. **
  73037. ** This opcode invokes the parser to create a new virtual machine,
  73038. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  73039. */
  73040. case OP_ParseSchema: {
  73041. int iDb;
  73042. const char *zMaster;
  73043. char *zSql;
  73044. InitData initData;
  73045. /* Any prepared statement that invokes this opcode will hold mutexes
  73046. ** on every btree. This is a prerequisite for invoking
  73047. ** sqlite3InitCallback().
  73048. */
  73049. #ifdef SQLITE_DEBUG
  73050. for(iDb=0; iDb<db->nDb; iDb++){
  73051. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  73052. }
  73053. #endif
  73054. iDb = pOp->p1;
  73055. assert( iDb>=0 && iDb<db->nDb );
  73056. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  73057. /* Used to be a conditional */ {
  73058. zMaster = SCHEMA_TABLE(iDb);
  73059. initData.db = db;
  73060. initData.iDb = pOp->p1;
  73061. initData.pzErrMsg = &p->zErrMsg;
  73062. zSql = sqlite3MPrintf(db,
  73063. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  73064. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  73065. if( zSql==0 ){
  73066. rc = SQLITE_NOMEM;
  73067. }else{
  73068. assert( db->init.busy==0 );
  73069. db->init.busy = 1;
  73070. initData.rc = SQLITE_OK;
  73071. assert( !db->mallocFailed );
  73072. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  73073. if( rc==SQLITE_OK ) rc = initData.rc;
  73074. sqlite3DbFree(db, zSql);
  73075. db->init.busy = 0;
  73076. }
  73077. }
  73078. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  73079. if( rc==SQLITE_NOMEM ){
  73080. goto no_mem;
  73081. }
  73082. break;
  73083. }
  73084. #if !defined(SQLITE_OMIT_ANALYZE)
  73085. /* Opcode: LoadAnalysis P1 * * * *
  73086. **
  73087. ** Read the sqlite_stat1 table for database P1 and load the content
  73088. ** of that table into the internal index hash table. This will cause
  73089. ** the analysis to be used when preparing all subsequent queries.
  73090. */
  73091. case OP_LoadAnalysis: {
  73092. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73093. rc = sqlite3AnalysisLoad(db, pOp->p1);
  73094. break;
  73095. }
  73096. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  73097. /* Opcode: DropTable P1 * * P4 *
  73098. **
  73099. ** Remove the internal (in-memory) data structures that describe
  73100. ** the table named P4 in database P1. This is called after a table
  73101. ** is dropped from disk (using the Destroy opcode) in order to keep
  73102. ** the internal representation of the
  73103. ** schema consistent with what is on disk.
  73104. */
  73105. case OP_DropTable: {
  73106. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  73107. break;
  73108. }
  73109. /* Opcode: DropIndex P1 * * P4 *
  73110. **
  73111. ** Remove the internal (in-memory) data structures that describe
  73112. ** the index named P4 in database P1. This is called after an index
  73113. ** is dropped from disk (using the Destroy opcode)
  73114. ** in order to keep the internal representation of the
  73115. ** schema consistent with what is on disk.
  73116. */
  73117. case OP_DropIndex: {
  73118. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  73119. break;
  73120. }
  73121. /* Opcode: DropTrigger P1 * * P4 *
  73122. **
  73123. ** Remove the internal (in-memory) data structures that describe
  73124. ** the trigger named P4 in database P1. This is called after a trigger
  73125. ** is dropped from disk (using the Destroy opcode) in order to keep
  73126. ** the internal representation of the
  73127. ** schema consistent with what is on disk.
  73128. */
  73129. case OP_DropTrigger: {
  73130. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  73131. break;
  73132. }
  73133. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  73134. /* Opcode: IntegrityCk P1 P2 P3 * P5
  73135. **
  73136. ** Do an analysis of the currently open database. Store in
  73137. ** register P1 the text of an error message describing any problems.
  73138. ** If no problems are found, store a NULL in register P1.
  73139. **
  73140. ** The register P3 contains the maximum number of allowed errors.
  73141. ** At most reg(P3) errors will be reported.
  73142. ** In other words, the analysis stops as soon as reg(P1) errors are
  73143. ** seen. Reg(P1) is updated with the number of errors remaining.
  73144. **
  73145. ** The root page numbers of all tables in the database are integer
  73146. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  73147. ** total.
  73148. **
  73149. ** If P5 is not zero, the check is done on the auxiliary database
  73150. ** file, not the main database file.
  73151. **
  73152. ** This opcode is used to implement the integrity_check pragma.
  73153. */
  73154. case OP_IntegrityCk: {
  73155. int nRoot; /* Number of tables to check. (Number of root pages.) */
  73156. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  73157. int j; /* Loop counter */
  73158. int nErr; /* Number of errors reported */
  73159. char *z; /* Text of the error report */
  73160. Mem *pnErr; /* Register keeping track of errors remaining */
  73161. assert( p->bIsReader );
  73162. nRoot = pOp->p2;
  73163. assert( nRoot>0 );
  73164. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  73165. if( aRoot==0 ) goto no_mem;
  73166. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  73167. pnErr = &aMem[pOp->p3];
  73168. assert( (pnErr->flags & MEM_Int)!=0 );
  73169. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  73170. pIn1 = &aMem[pOp->p1];
  73171. for(j=0; j<nRoot; j++){
  73172. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  73173. }
  73174. aRoot[j] = 0;
  73175. assert( pOp->p5<db->nDb );
  73176. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  73177. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  73178. (int)pnErr->u.i, &nErr);
  73179. sqlite3DbFree(db, aRoot);
  73180. pnErr->u.i -= nErr;
  73181. sqlite3VdbeMemSetNull(pIn1);
  73182. if( nErr==0 ){
  73183. assert( z==0 );
  73184. }else if( z==0 ){
  73185. goto no_mem;
  73186. }else{
  73187. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  73188. }
  73189. UPDATE_MAX_BLOBSIZE(pIn1);
  73190. sqlite3VdbeChangeEncoding(pIn1, encoding);
  73191. break;
  73192. }
  73193. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  73194. /* Opcode: RowSetAdd P1 P2 * * *
  73195. ** Synopsis: rowset(P1)=r[P2]
  73196. **
  73197. ** Insert the integer value held by register P2 into a boolean index
  73198. ** held in register P1.
  73199. **
  73200. ** An assertion fails if P2 is not an integer.
  73201. */
  73202. case OP_RowSetAdd: { /* in1, in2 */
  73203. pIn1 = &aMem[pOp->p1];
  73204. pIn2 = &aMem[pOp->p2];
  73205. assert( (pIn2->flags & MEM_Int)!=0 );
  73206. if( (pIn1->flags & MEM_RowSet)==0 ){
  73207. sqlite3VdbeMemSetRowSet(pIn1);
  73208. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  73209. }
  73210. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  73211. break;
  73212. }
  73213. /* Opcode: RowSetRead P1 P2 P3 * *
  73214. ** Synopsis: r[P3]=rowset(P1)
  73215. **
  73216. ** Extract the smallest value from boolean index P1 and put that value into
  73217. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  73218. ** unchanged and jump to instruction P2.
  73219. */
  73220. case OP_RowSetRead: { /* jump, in1, out3 */
  73221. i64 val;
  73222. pIn1 = &aMem[pOp->p1];
  73223. if( (pIn1->flags & MEM_RowSet)==0
  73224. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  73225. ){
  73226. /* The boolean index is empty */
  73227. sqlite3VdbeMemSetNull(pIn1);
  73228. VdbeBranchTaken(1,2);
  73229. goto jump_to_p2_and_check_for_interrupt;
  73230. }else{
  73231. /* A value was pulled from the index */
  73232. VdbeBranchTaken(0,2);
  73233. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  73234. }
  73235. goto check_for_interrupt;
  73236. }
  73237. /* Opcode: RowSetTest P1 P2 P3 P4
  73238. ** Synopsis: if r[P3] in rowset(P1) goto P2
  73239. **
  73240. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  73241. ** contains a RowSet object and that RowSet object contains
  73242. ** the value held in P3, jump to register P2. Otherwise, insert the
  73243. ** integer in P3 into the RowSet and continue on to the
  73244. ** next opcode.
  73245. **
  73246. ** The RowSet object is optimized for the case where successive sets
  73247. ** of integers, where each set contains no duplicates. Each set
  73248. ** of values is identified by a unique P4 value. The first set
  73249. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  73250. ** non-negative. For non-negative values of P4 only the lower 4
  73251. ** bits are significant.
  73252. **
  73253. ** This allows optimizations: (a) when P4==0 there is no need to test
  73254. ** the rowset object for P3, as it is guaranteed not to contain it,
  73255. ** (b) when P4==-1 there is no need to insert the value, as it will
  73256. ** never be tested for, and (c) when a value that is part of set X is
  73257. ** inserted, there is no need to search to see if the same value was
  73258. ** previously inserted as part of set X (only if it was previously
  73259. ** inserted as part of some other set).
  73260. */
  73261. case OP_RowSetTest: { /* jump, in1, in3 */
  73262. int iSet;
  73263. int exists;
  73264. pIn1 = &aMem[pOp->p1];
  73265. pIn3 = &aMem[pOp->p3];
  73266. iSet = pOp->p4.i;
  73267. assert( pIn3->flags&MEM_Int );
  73268. /* If there is anything other than a rowset object in memory cell P1,
  73269. ** delete it now and initialize P1 with an empty rowset
  73270. */
  73271. if( (pIn1->flags & MEM_RowSet)==0 ){
  73272. sqlite3VdbeMemSetRowSet(pIn1);
  73273. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  73274. }
  73275. assert( pOp->p4type==P4_INT32 );
  73276. assert( iSet==-1 || iSet>=0 );
  73277. if( iSet ){
  73278. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  73279. VdbeBranchTaken(exists!=0,2);
  73280. if( exists ) goto jump_to_p2;
  73281. }
  73282. if( iSet>=0 ){
  73283. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  73284. }
  73285. break;
  73286. }
  73287. #ifndef SQLITE_OMIT_TRIGGER
  73288. /* Opcode: Program P1 P2 P3 P4 P5
  73289. **
  73290. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  73291. **
  73292. ** P1 contains the address of the memory cell that contains the first memory
  73293. ** cell in an array of values used as arguments to the sub-program. P2
  73294. ** contains the address to jump to if the sub-program throws an IGNORE
  73295. ** exception using the RAISE() function. Register P3 contains the address
  73296. ** of a memory cell in this (the parent) VM that is used to allocate the
  73297. ** memory required by the sub-vdbe at runtime.
  73298. **
  73299. ** P4 is a pointer to the VM containing the trigger program.
  73300. **
  73301. ** If P5 is non-zero, then recursive program invocation is enabled.
  73302. */
  73303. case OP_Program: { /* jump */
  73304. int nMem; /* Number of memory registers for sub-program */
  73305. int nByte; /* Bytes of runtime space required for sub-program */
  73306. Mem *pRt; /* Register to allocate runtime space */
  73307. Mem *pMem; /* Used to iterate through memory cells */
  73308. Mem *pEnd; /* Last memory cell in new array */
  73309. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  73310. SubProgram *pProgram; /* Sub-program to execute */
  73311. void *t; /* Token identifying trigger */
  73312. pProgram = pOp->p4.pProgram;
  73313. pRt = &aMem[pOp->p3];
  73314. assert( pProgram->nOp>0 );
  73315. /* If the p5 flag is clear, then recursive invocation of triggers is
  73316. ** disabled for backwards compatibility (p5 is set if this sub-program
  73317. ** is really a trigger, not a foreign key action, and the flag set
  73318. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  73319. **
  73320. ** It is recursive invocation of triggers, at the SQL level, that is
  73321. ** disabled. In some cases a single trigger may generate more than one
  73322. ** SubProgram (if the trigger may be executed with more than one different
  73323. ** ON CONFLICT algorithm). SubProgram structures associated with a
  73324. ** single trigger all have the same value for the SubProgram.token
  73325. ** variable. */
  73326. if( pOp->p5 ){
  73327. t = pProgram->token;
  73328. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  73329. if( pFrame ) break;
  73330. }
  73331. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  73332. rc = SQLITE_ERROR;
  73333. sqlite3VdbeError(p, "too many levels of trigger recursion");
  73334. break;
  73335. }
  73336. /* Register pRt is used to store the memory required to save the state
  73337. ** of the current program, and the memory required at runtime to execute
  73338. ** the trigger program. If this trigger has been fired before, then pRt
  73339. ** is already allocated. Otherwise, it must be initialized. */
  73340. if( (pRt->flags&MEM_Frame)==0 ){
  73341. /* SubProgram.nMem is set to the number of memory cells used by the
  73342. ** program stored in SubProgram.aOp. As well as these, one memory
  73343. ** cell is required for each cursor used by the program. Set local
  73344. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  73345. */
  73346. nMem = pProgram->nMem + pProgram->nCsr;
  73347. nByte = ROUND8(sizeof(VdbeFrame))
  73348. + nMem * sizeof(Mem)
  73349. + pProgram->nCsr * sizeof(VdbeCursor *)
  73350. + pProgram->nOnce * sizeof(u8);
  73351. pFrame = sqlite3DbMallocZero(db, nByte);
  73352. if( !pFrame ){
  73353. goto no_mem;
  73354. }
  73355. sqlite3VdbeMemRelease(pRt);
  73356. pRt->flags = MEM_Frame;
  73357. pRt->u.pFrame = pFrame;
  73358. pFrame->v = p;
  73359. pFrame->nChildMem = nMem;
  73360. pFrame->nChildCsr = pProgram->nCsr;
  73361. pFrame->pc = (int)(pOp - aOp);
  73362. pFrame->aMem = p->aMem;
  73363. pFrame->nMem = p->nMem;
  73364. pFrame->apCsr = p->apCsr;
  73365. pFrame->nCursor = p->nCursor;
  73366. pFrame->aOp = p->aOp;
  73367. pFrame->nOp = p->nOp;
  73368. pFrame->token = pProgram->token;
  73369. pFrame->aOnceFlag = p->aOnceFlag;
  73370. pFrame->nOnceFlag = p->nOnceFlag;
  73371. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73372. pFrame->anExec = p->anExec;
  73373. #endif
  73374. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  73375. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  73376. pMem->flags = MEM_Undefined;
  73377. pMem->db = db;
  73378. }
  73379. }else{
  73380. pFrame = pRt->u.pFrame;
  73381. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  73382. assert( pProgram->nCsr==pFrame->nChildCsr );
  73383. assert( (int)(pOp - aOp)==pFrame->pc );
  73384. }
  73385. p->nFrame++;
  73386. pFrame->pParent = p->pFrame;
  73387. pFrame->lastRowid = lastRowid;
  73388. pFrame->nChange = p->nChange;
  73389. pFrame->nDbChange = p->db->nChange;
  73390. p->nChange = 0;
  73391. p->pFrame = pFrame;
  73392. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  73393. p->nMem = pFrame->nChildMem;
  73394. p->nCursor = (u16)pFrame->nChildCsr;
  73395. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  73396. p->aOp = aOp = pProgram->aOp;
  73397. p->nOp = pProgram->nOp;
  73398. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  73399. p->nOnceFlag = pProgram->nOnce;
  73400. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73401. p->anExec = 0;
  73402. #endif
  73403. pOp = &aOp[-1];
  73404. memset(p->aOnceFlag, 0, p->nOnceFlag);
  73405. break;
  73406. }
  73407. /* Opcode: Param P1 P2 * * *
  73408. **
  73409. ** This opcode is only ever present in sub-programs called via the
  73410. ** OP_Program instruction. Copy a value currently stored in a memory
  73411. ** cell of the calling (parent) frame to cell P2 in the current frames
  73412. ** address space. This is used by trigger programs to access the new.*
  73413. ** and old.* values.
  73414. **
  73415. ** The address of the cell in the parent frame is determined by adding
  73416. ** the value of the P1 argument to the value of the P1 argument to the
  73417. ** calling OP_Program instruction.
  73418. */
  73419. case OP_Param: { /* out2 */
  73420. VdbeFrame *pFrame;
  73421. Mem *pIn;
  73422. pOut = out2Prerelease(p, pOp);
  73423. pFrame = p->pFrame;
  73424. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  73425. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  73426. break;
  73427. }
  73428. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  73429. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73430. /* Opcode: FkCounter P1 P2 * * *
  73431. ** Synopsis: fkctr[P1]+=P2
  73432. **
  73433. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  73434. ** If P1 is non-zero, the database constraint counter is incremented
  73435. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  73436. ** statement counter is incremented (immediate foreign key constraints).
  73437. */
  73438. case OP_FkCounter: {
  73439. if( db->flags & SQLITE_DeferFKs ){
  73440. db->nDeferredImmCons += pOp->p2;
  73441. }else if( pOp->p1 ){
  73442. db->nDeferredCons += pOp->p2;
  73443. }else{
  73444. p->nFkConstraint += pOp->p2;
  73445. }
  73446. break;
  73447. }
  73448. /* Opcode: FkIfZero P1 P2 * * *
  73449. ** Synopsis: if fkctr[P1]==0 goto P2
  73450. **
  73451. ** This opcode tests if a foreign key constraint-counter is currently zero.
  73452. ** If so, jump to instruction P2. Otherwise, fall through to the next
  73453. ** instruction.
  73454. **
  73455. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  73456. ** is zero (the one that counts deferred constraint violations). If P1 is
  73457. ** zero, the jump is taken if the statement constraint-counter is zero
  73458. ** (immediate foreign key constraint violations).
  73459. */
  73460. case OP_FkIfZero: { /* jump */
  73461. if( pOp->p1 ){
  73462. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  73463. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  73464. }else{
  73465. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  73466. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  73467. }
  73468. break;
  73469. }
  73470. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  73471. #ifndef SQLITE_OMIT_AUTOINCREMENT
  73472. /* Opcode: MemMax P1 P2 * * *
  73473. ** Synopsis: r[P1]=max(r[P1],r[P2])
  73474. **
  73475. ** P1 is a register in the root frame of this VM (the root frame is
  73476. ** different from the current frame if this instruction is being executed
  73477. ** within a sub-program). Set the value of register P1 to the maximum of
  73478. ** its current value and the value in register P2.
  73479. **
  73480. ** This instruction throws an error if the memory cell is not initially
  73481. ** an integer.
  73482. */
  73483. case OP_MemMax: { /* in2 */
  73484. VdbeFrame *pFrame;
  73485. if( p->pFrame ){
  73486. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  73487. pIn1 = &pFrame->aMem[pOp->p1];
  73488. }else{
  73489. pIn1 = &aMem[pOp->p1];
  73490. }
  73491. assert( memIsValid(pIn1) );
  73492. sqlite3VdbeMemIntegerify(pIn1);
  73493. pIn2 = &aMem[pOp->p2];
  73494. sqlite3VdbeMemIntegerify(pIn2);
  73495. if( pIn1->u.i<pIn2->u.i){
  73496. pIn1->u.i = pIn2->u.i;
  73497. }
  73498. break;
  73499. }
  73500. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  73501. /* Opcode: IfPos P1 P2 P3 * *
  73502. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  73503. **
  73504. ** Register P1 must contain an integer.
  73505. ** If the value of register P1 is 1 or greater, subtract P3 from the
  73506. ** value in P1 and jump to P2.
  73507. **
  73508. ** If the initial value of register P1 is less than 1, then the
  73509. ** value is unchanged and control passes through to the next instruction.
  73510. */
  73511. case OP_IfPos: { /* jump, in1 */
  73512. pIn1 = &aMem[pOp->p1];
  73513. assert( pIn1->flags&MEM_Int );
  73514. VdbeBranchTaken( pIn1->u.i>0, 2);
  73515. if( pIn1->u.i>0 ){
  73516. pIn1->u.i -= pOp->p3;
  73517. goto jump_to_p2;
  73518. }
  73519. break;
  73520. }
  73521. /* Opcode: SetIfNotPos P1 P2 P3 * *
  73522. ** Synopsis: if r[P1]<=0 then r[P2]=P3
  73523. **
  73524. ** Register P1 must contain an integer.
  73525. ** If the value of register P1 is not positive (if it is less than 1) then
  73526. ** set the value of register P2 to be the integer P3.
  73527. */
  73528. case OP_SetIfNotPos: { /* in1, in2 */
  73529. pIn1 = &aMem[pOp->p1];
  73530. assert( pIn1->flags&MEM_Int );
  73531. if( pIn1->u.i<=0 ){
  73532. pOut = out2Prerelease(p, pOp);
  73533. pOut->u.i = pOp->p3;
  73534. }
  73535. break;
  73536. }
  73537. /* Opcode: IfNotZero P1 P2 P3 * *
  73538. ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
  73539. **
  73540. ** Register P1 must contain an integer. If the content of register P1 is
  73541. ** initially nonzero, then subtract P3 from the value in register P1 and
  73542. ** jump to P2. If register P1 is initially zero, leave it unchanged
  73543. ** and fall through.
  73544. */
  73545. case OP_IfNotZero: { /* jump, in1 */
  73546. pIn1 = &aMem[pOp->p1];
  73547. assert( pIn1->flags&MEM_Int );
  73548. VdbeBranchTaken(pIn1->u.i<0, 2);
  73549. if( pIn1->u.i ){
  73550. pIn1->u.i -= pOp->p3;
  73551. goto jump_to_p2;
  73552. }
  73553. break;
  73554. }
  73555. /* Opcode: DecrJumpZero P1 P2 * * *
  73556. ** Synopsis: if (--r[P1])==0 goto P2
  73557. **
  73558. ** Register P1 must hold an integer. Decrement the value in register P1
  73559. ** then jump to P2 if the new value is exactly zero.
  73560. */
  73561. case OP_DecrJumpZero: { /* jump, in1 */
  73562. pIn1 = &aMem[pOp->p1];
  73563. assert( pIn1->flags&MEM_Int );
  73564. pIn1->u.i--;
  73565. VdbeBranchTaken(pIn1->u.i==0, 2);
  73566. if( pIn1->u.i==0 ) goto jump_to_p2;
  73567. break;
  73568. }
  73569. /* Opcode: JumpZeroIncr P1 P2 * * *
  73570. ** Synopsis: if (r[P1]++)==0 ) goto P2
  73571. **
  73572. ** The register P1 must contain an integer. If register P1 is initially
  73573. ** zero, then jump to P2. Increment register P1 regardless of whether or
  73574. ** not the jump is taken.
  73575. */
  73576. case OP_JumpZeroIncr: { /* jump, in1 */
  73577. pIn1 = &aMem[pOp->p1];
  73578. assert( pIn1->flags&MEM_Int );
  73579. VdbeBranchTaken(pIn1->u.i==0, 2);
  73580. if( (pIn1->u.i++)==0 ) goto jump_to_p2;
  73581. break;
  73582. }
  73583. /* Opcode: AggStep0 * P2 P3 P4 P5
  73584. ** Synopsis: accum=r[P3] step(r[P2@P5])
  73585. **
  73586. ** Execute the step function for an aggregate. The
  73587. ** function has P5 arguments. P4 is a pointer to the FuncDef
  73588. ** structure that specifies the function. Register P3 is the
  73589. ** accumulator.
  73590. **
  73591. ** The P5 arguments are taken from register P2 and its
  73592. ** successors.
  73593. */
  73594. /* Opcode: AggStep * P2 P3 P4 P5
  73595. ** Synopsis: accum=r[P3] step(r[P2@P5])
  73596. **
  73597. ** Execute the step function for an aggregate. The
  73598. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  73599. ** object that is used to run the function. Register P3 is
  73600. ** as the accumulator.
  73601. **
  73602. ** The P5 arguments are taken from register P2 and its
  73603. ** successors.
  73604. **
  73605. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  73606. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  73607. ** the opcode is changed. In this way, the initialization of the
  73608. ** sqlite3_context only happens once, instead of on each call to the
  73609. ** step function.
  73610. */
  73611. case OP_AggStep0: {
  73612. int n;
  73613. sqlite3_context *pCtx;
  73614. assert( pOp->p4type==P4_FUNCDEF );
  73615. n = pOp->p5;
  73616. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  73617. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  73618. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  73619. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  73620. if( pCtx==0 ) goto no_mem;
  73621. pCtx->pMem = 0;
  73622. pCtx->pFunc = pOp->p4.pFunc;
  73623. pCtx->iOp = (int)(pOp - aOp);
  73624. pCtx->pVdbe = p;
  73625. pCtx->argc = n;
  73626. pOp->p4type = P4_FUNCCTX;
  73627. pOp->p4.pCtx = pCtx;
  73628. pOp->opcode = OP_AggStep;
  73629. /* Fall through into OP_AggStep */
  73630. }
  73631. case OP_AggStep: {
  73632. int i;
  73633. sqlite3_context *pCtx;
  73634. Mem *pMem;
  73635. Mem t;
  73636. assert( pOp->p4type==P4_FUNCCTX );
  73637. pCtx = pOp->p4.pCtx;
  73638. pMem = &aMem[pOp->p3];
  73639. /* If this function is inside of a trigger, the register array in aMem[]
  73640. ** might change from one evaluation to the next. The next block of code
  73641. ** checks to see if the register array has changed, and if so it
  73642. ** reinitializes the relavant parts of the sqlite3_context object */
  73643. if( pCtx->pMem != pMem ){
  73644. pCtx->pMem = pMem;
  73645. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  73646. }
  73647. #ifdef SQLITE_DEBUG
  73648. for(i=0; i<pCtx->argc; i++){
  73649. assert( memIsValid(pCtx->argv[i]) );
  73650. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  73651. }
  73652. #endif
  73653. pMem->n++;
  73654. sqlite3VdbeMemInit(&t, db, MEM_Null);
  73655. pCtx->pOut = &t;
  73656. pCtx->fErrorOrAux = 0;
  73657. pCtx->skipFlag = 0;
  73658. (pCtx->pFunc->xStep)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  73659. if( pCtx->fErrorOrAux ){
  73660. if( pCtx->isError ){
  73661. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  73662. rc = pCtx->isError;
  73663. }
  73664. sqlite3VdbeMemRelease(&t);
  73665. }else{
  73666. assert( t.flags==MEM_Null );
  73667. }
  73668. if( pCtx->skipFlag ){
  73669. assert( pOp[-1].opcode==OP_CollSeq );
  73670. i = pOp[-1].p1;
  73671. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  73672. }
  73673. break;
  73674. }
  73675. /* Opcode: AggFinal P1 P2 * P4 *
  73676. ** Synopsis: accum=r[P1] N=P2
  73677. **
  73678. ** Execute the finalizer function for an aggregate. P1 is
  73679. ** the memory location that is the accumulator for the aggregate.
  73680. **
  73681. ** P2 is the number of arguments that the step function takes and
  73682. ** P4 is a pointer to the FuncDef for this function. The P2
  73683. ** argument is not used by this opcode. It is only there to disambiguate
  73684. ** functions that can take varying numbers of arguments. The
  73685. ** P4 argument is only needed for the degenerate case where
  73686. ** the step function was not previously called.
  73687. */
  73688. case OP_AggFinal: {
  73689. Mem *pMem;
  73690. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  73691. pMem = &aMem[pOp->p1];
  73692. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  73693. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  73694. if( rc ){
  73695. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  73696. }
  73697. sqlite3VdbeChangeEncoding(pMem, encoding);
  73698. UPDATE_MAX_BLOBSIZE(pMem);
  73699. if( sqlite3VdbeMemTooBig(pMem) ){
  73700. goto too_big;
  73701. }
  73702. break;
  73703. }
  73704. #ifndef SQLITE_OMIT_WAL
  73705. /* Opcode: Checkpoint P1 P2 P3 * *
  73706. **
  73707. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  73708. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  73709. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  73710. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  73711. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  73712. ** in the WAL that have been checkpointed after the checkpoint
  73713. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  73714. ** mem[P3+2] are initialized to -1.
  73715. */
  73716. case OP_Checkpoint: {
  73717. int i; /* Loop counter */
  73718. int aRes[3]; /* Results */
  73719. Mem *pMem; /* Write results here */
  73720. assert( p->readOnly==0 );
  73721. aRes[0] = 0;
  73722. aRes[1] = aRes[2] = -1;
  73723. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  73724. || pOp->p2==SQLITE_CHECKPOINT_FULL
  73725. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  73726. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  73727. );
  73728. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  73729. if( rc==SQLITE_BUSY ){
  73730. rc = SQLITE_OK;
  73731. aRes[0] = 1;
  73732. }
  73733. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  73734. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  73735. }
  73736. break;
  73737. };
  73738. #endif
  73739. #ifndef SQLITE_OMIT_PRAGMA
  73740. /* Opcode: JournalMode P1 P2 P3 * *
  73741. **
  73742. ** Change the journal mode of database P1 to P3. P3 must be one of the
  73743. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  73744. ** modes (delete, truncate, persist, off and memory), this is a simple
  73745. ** operation. No IO is required.
  73746. **
  73747. ** If changing into or out of WAL mode the procedure is more complicated.
  73748. **
  73749. ** Write a string containing the final journal-mode to register P2.
  73750. */
  73751. case OP_JournalMode: { /* out2 */
  73752. Btree *pBt; /* Btree to change journal mode of */
  73753. Pager *pPager; /* Pager associated with pBt */
  73754. int eNew; /* New journal mode */
  73755. int eOld; /* The old journal mode */
  73756. #ifndef SQLITE_OMIT_WAL
  73757. const char *zFilename; /* Name of database file for pPager */
  73758. #endif
  73759. pOut = out2Prerelease(p, pOp);
  73760. eNew = pOp->p3;
  73761. assert( eNew==PAGER_JOURNALMODE_DELETE
  73762. || eNew==PAGER_JOURNALMODE_TRUNCATE
  73763. || eNew==PAGER_JOURNALMODE_PERSIST
  73764. || eNew==PAGER_JOURNALMODE_OFF
  73765. || eNew==PAGER_JOURNALMODE_MEMORY
  73766. || eNew==PAGER_JOURNALMODE_WAL
  73767. || eNew==PAGER_JOURNALMODE_QUERY
  73768. );
  73769. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73770. assert( p->readOnly==0 );
  73771. pBt = db->aDb[pOp->p1].pBt;
  73772. pPager = sqlite3BtreePager(pBt);
  73773. eOld = sqlite3PagerGetJournalMode(pPager);
  73774. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  73775. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  73776. #ifndef SQLITE_OMIT_WAL
  73777. zFilename = sqlite3PagerFilename(pPager, 1);
  73778. /* Do not allow a transition to journal_mode=WAL for a database
  73779. ** in temporary storage or if the VFS does not support shared memory
  73780. */
  73781. if( eNew==PAGER_JOURNALMODE_WAL
  73782. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  73783. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  73784. ){
  73785. eNew = eOld;
  73786. }
  73787. if( (eNew!=eOld)
  73788. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  73789. ){
  73790. if( !db->autoCommit || db->nVdbeRead>1 ){
  73791. rc = SQLITE_ERROR;
  73792. sqlite3VdbeError(p,
  73793. "cannot change %s wal mode from within a transaction",
  73794. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  73795. );
  73796. break;
  73797. }else{
  73798. if( eOld==PAGER_JOURNALMODE_WAL ){
  73799. /* If leaving WAL mode, close the log file. If successful, the call
  73800. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  73801. ** file. An EXCLUSIVE lock may still be held on the database file
  73802. ** after a successful return.
  73803. */
  73804. rc = sqlite3PagerCloseWal(pPager);
  73805. if( rc==SQLITE_OK ){
  73806. sqlite3PagerSetJournalMode(pPager, eNew);
  73807. }
  73808. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  73809. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  73810. ** as an intermediate */
  73811. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  73812. }
  73813. /* Open a transaction on the database file. Regardless of the journal
  73814. ** mode, this transaction always uses a rollback journal.
  73815. */
  73816. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  73817. if( rc==SQLITE_OK ){
  73818. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  73819. }
  73820. }
  73821. }
  73822. #endif /* ifndef SQLITE_OMIT_WAL */
  73823. if( rc ){
  73824. eNew = eOld;
  73825. }
  73826. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  73827. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  73828. pOut->z = (char *)sqlite3JournalModename(eNew);
  73829. pOut->n = sqlite3Strlen30(pOut->z);
  73830. pOut->enc = SQLITE_UTF8;
  73831. sqlite3VdbeChangeEncoding(pOut, encoding);
  73832. break;
  73833. };
  73834. #endif /* SQLITE_OMIT_PRAGMA */
  73835. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  73836. /* Opcode: Vacuum * * * * *
  73837. **
  73838. ** Vacuum the entire database. This opcode will cause other virtual
  73839. ** machines to be created and run. It may not be called from within
  73840. ** a transaction.
  73841. */
  73842. case OP_Vacuum: {
  73843. assert( p->readOnly==0 );
  73844. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  73845. break;
  73846. }
  73847. #endif
  73848. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  73849. /* Opcode: IncrVacuum P1 P2 * * *
  73850. **
  73851. ** Perform a single step of the incremental vacuum procedure on
  73852. ** the P1 database. If the vacuum has finished, jump to instruction
  73853. ** P2. Otherwise, fall through to the next instruction.
  73854. */
  73855. case OP_IncrVacuum: { /* jump */
  73856. Btree *pBt;
  73857. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73858. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  73859. assert( p->readOnly==0 );
  73860. pBt = db->aDb[pOp->p1].pBt;
  73861. rc = sqlite3BtreeIncrVacuum(pBt);
  73862. VdbeBranchTaken(rc==SQLITE_DONE,2);
  73863. if( rc==SQLITE_DONE ){
  73864. rc = SQLITE_OK;
  73865. goto jump_to_p2;
  73866. }
  73867. break;
  73868. }
  73869. #endif
  73870. /* Opcode: Expire P1 * * * *
  73871. **
  73872. ** Cause precompiled statements to expire. When an expired statement
  73873. ** is executed using sqlite3_step() it will either automatically
  73874. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  73875. ** or it will fail with SQLITE_SCHEMA.
  73876. **
  73877. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  73878. ** then only the currently executing statement is expired.
  73879. */
  73880. case OP_Expire: {
  73881. if( !pOp->p1 ){
  73882. sqlite3ExpirePreparedStatements(db);
  73883. }else{
  73884. p->expired = 1;
  73885. }
  73886. break;
  73887. }
  73888. #ifndef SQLITE_OMIT_SHARED_CACHE
  73889. /* Opcode: TableLock P1 P2 P3 P4 *
  73890. ** Synopsis: iDb=P1 root=P2 write=P3
  73891. **
  73892. ** Obtain a lock on a particular table. This instruction is only used when
  73893. ** the shared-cache feature is enabled.
  73894. **
  73895. ** P1 is the index of the database in sqlite3.aDb[] of the database
  73896. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  73897. ** a write lock if P3==1.
  73898. **
  73899. ** P2 contains the root-page of the table to lock.
  73900. **
  73901. ** P4 contains a pointer to the name of the table being locked. This is only
  73902. ** used to generate an error message if the lock cannot be obtained.
  73903. */
  73904. case OP_TableLock: {
  73905. u8 isWriteLock = (u8)pOp->p3;
  73906. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  73907. int p1 = pOp->p1;
  73908. assert( p1>=0 && p1<db->nDb );
  73909. assert( DbMaskTest(p->btreeMask, p1) );
  73910. assert( isWriteLock==0 || isWriteLock==1 );
  73911. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  73912. if( (rc&0xFF)==SQLITE_LOCKED ){
  73913. const char *z = pOp->p4.z;
  73914. sqlite3VdbeError(p, "database table is locked: %s", z);
  73915. }
  73916. }
  73917. break;
  73918. }
  73919. #endif /* SQLITE_OMIT_SHARED_CACHE */
  73920. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73921. /* Opcode: VBegin * * * P4 *
  73922. **
  73923. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  73924. ** xBegin method for that table.
  73925. **
  73926. ** Also, whether or not P4 is set, check that this is not being called from
  73927. ** within a callback to a virtual table xSync() method. If it is, the error
  73928. ** code will be set to SQLITE_LOCKED.
  73929. */
  73930. case OP_VBegin: {
  73931. VTable *pVTab;
  73932. pVTab = pOp->p4.pVtab;
  73933. rc = sqlite3VtabBegin(db, pVTab);
  73934. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  73935. break;
  73936. }
  73937. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73938. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73939. /* Opcode: VCreate P1 P2 * * *
  73940. **
  73941. ** P2 is a register that holds the name of a virtual table in database
  73942. ** P1. Call the xCreate method for that table.
  73943. */
  73944. case OP_VCreate: {
  73945. Mem sMem; /* For storing the record being decoded */
  73946. const char *zTab; /* Name of the virtual table */
  73947. memset(&sMem, 0, sizeof(sMem));
  73948. sMem.db = db;
  73949. /* Because P2 is always a static string, it is impossible for the
  73950. ** sqlite3VdbeMemCopy() to fail */
  73951. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  73952. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  73953. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  73954. assert( rc==SQLITE_OK );
  73955. zTab = (const char*)sqlite3_value_text(&sMem);
  73956. assert( zTab || db->mallocFailed );
  73957. if( zTab ){
  73958. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  73959. }
  73960. sqlite3VdbeMemRelease(&sMem);
  73961. break;
  73962. }
  73963. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73964. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73965. /* Opcode: VDestroy P1 * * P4 *
  73966. **
  73967. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  73968. ** of that table.
  73969. */
  73970. case OP_VDestroy: {
  73971. db->nVDestroy++;
  73972. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  73973. db->nVDestroy--;
  73974. break;
  73975. }
  73976. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73977. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73978. /* Opcode: VOpen P1 * * P4 *
  73979. **
  73980. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  73981. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  73982. ** table and stores that cursor in P1.
  73983. */
  73984. case OP_VOpen: {
  73985. VdbeCursor *pCur;
  73986. sqlite3_vtab_cursor *pVtabCursor;
  73987. sqlite3_vtab *pVtab;
  73988. const sqlite3_module *pModule;
  73989. assert( p->bIsReader );
  73990. pCur = 0;
  73991. pVtabCursor = 0;
  73992. pVtab = pOp->p4.pVtab->pVtab;
  73993. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  73994. rc = SQLITE_LOCKED;
  73995. break;
  73996. }
  73997. pModule = pVtab->pModule;
  73998. rc = pModule->xOpen(pVtab, &pVtabCursor);
  73999. sqlite3VtabImportErrmsg(p, pVtab);
  74000. if( SQLITE_OK==rc ){
  74001. /* Initialize sqlite3_vtab_cursor base class */
  74002. pVtabCursor->pVtab = pVtab;
  74003. /* Initialize vdbe cursor object */
  74004. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  74005. if( pCur ){
  74006. pCur->pVtabCursor = pVtabCursor;
  74007. pVtab->nRef++;
  74008. }else{
  74009. assert( db->mallocFailed );
  74010. pModule->xClose(pVtabCursor);
  74011. goto no_mem;
  74012. }
  74013. }
  74014. break;
  74015. }
  74016. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74017. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74018. /* Opcode: VFilter P1 P2 P3 P4 *
  74019. ** Synopsis: iplan=r[P3] zplan='P4'
  74020. **
  74021. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  74022. ** the filtered result set is empty.
  74023. **
  74024. ** P4 is either NULL or a string that was generated by the xBestIndex
  74025. ** method of the module. The interpretation of the P4 string is left
  74026. ** to the module implementation.
  74027. **
  74028. ** This opcode invokes the xFilter method on the virtual table specified
  74029. ** by P1. The integer query plan parameter to xFilter is stored in register
  74030. ** P3. Register P3+1 stores the argc parameter to be passed to the
  74031. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  74032. ** additional parameters which are passed to
  74033. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  74034. **
  74035. ** A jump is made to P2 if the result set after filtering would be empty.
  74036. */
  74037. case OP_VFilter: { /* jump */
  74038. int nArg;
  74039. int iQuery;
  74040. const sqlite3_module *pModule;
  74041. Mem *pQuery;
  74042. Mem *pArgc;
  74043. sqlite3_vtab_cursor *pVtabCursor;
  74044. sqlite3_vtab *pVtab;
  74045. VdbeCursor *pCur;
  74046. int res;
  74047. int i;
  74048. Mem **apArg;
  74049. pQuery = &aMem[pOp->p3];
  74050. pArgc = &pQuery[1];
  74051. pCur = p->apCsr[pOp->p1];
  74052. assert( memIsValid(pQuery) );
  74053. REGISTER_TRACE(pOp->p3, pQuery);
  74054. assert( pCur->pVtabCursor );
  74055. pVtabCursor = pCur->pVtabCursor;
  74056. pVtab = pVtabCursor->pVtab;
  74057. pModule = pVtab->pModule;
  74058. /* Grab the index number and argc parameters */
  74059. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  74060. nArg = (int)pArgc->u.i;
  74061. iQuery = (int)pQuery->u.i;
  74062. /* Invoke the xFilter method */
  74063. res = 0;
  74064. apArg = p->apArg;
  74065. for(i = 0; i<nArg; i++){
  74066. apArg[i] = &pArgc[i+1];
  74067. }
  74068. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  74069. sqlite3VtabImportErrmsg(p, pVtab);
  74070. if( rc==SQLITE_OK ){
  74071. res = pModule->xEof(pVtabCursor);
  74072. }
  74073. pCur->nullRow = 0;
  74074. VdbeBranchTaken(res!=0,2);
  74075. if( res ) goto jump_to_p2;
  74076. break;
  74077. }
  74078. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74079. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74080. /* Opcode: VColumn P1 P2 P3 * *
  74081. ** Synopsis: r[P3]=vcolumn(P2)
  74082. **
  74083. ** Store the value of the P2-th column of
  74084. ** the row of the virtual-table that the
  74085. ** P1 cursor is pointing to into register P3.
  74086. */
  74087. case OP_VColumn: {
  74088. sqlite3_vtab *pVtab;
  74089. const sqlite3_module *pModule;
  74090. Mem *pDest;
  74091. sqlite3_context sContext;
  74092. VdbeCursor *pCur = p->apCsr[pOp->p1];
  74093. assert( pCur->pVtabCursor );
  74094. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  74095. pDest = &aMem[pOp->p3];
  74096. memAboutToChange(p, pDest);
  74097. if( pCur->nullRow ){
  74098. sqlite3VdbeMemSetNull(pDest);
  74099. break;
  74100. }
  74101. pVtab = pCur->pVtabCursor->pVtab;
  74102. pModule = pVtab->pModule;
  74103. assert( pModule->xColumn );
  74104. memset(&sContext, 0, sizeof(sContext));
  74105. sContext.pOut = pDest;
  74106. MemSetTypeFlag(pDest, MEM_Null);
  74107. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  74108. sqlite3VtabImportErrmsg(p, pVtab);
  74109. if( sContext.isError ){
  74110. rc = sContext.isError;
  74111. }
  74112. sqlite3VdbeChangeEncoding(pDest, encoding);
  74113. REGISTER_TRACE(pOp->p3, pDest);
  74114. UPDATE_MAX_BLOBSIZE(pDest);
  74115. if( sqlite3VdbeMemTooBig(pDest) ){
  74116. goto too_big;
  74117. }
  74118. break;
  74119. }
  74120. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74121. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74122. /* Opcode: VNext P1 P2 * * *
  74123. **
  74124. ** Advance virtual table P1 to the next row in its result set and
  74125. ** jump to instruction P2. Or, if the virtual table has reached
  74126. ** the end of its result set, then fall through to the next instruction.
  74127. */
  74128. case OP_VNext: { /* jump */
  74129. sqlite3_vtab *pVtab;
  74130. const sqlite3_module *pModule;
  74131. int res;
  74132. VdbeCursor *pCur;
  74133. res = 0;
  74134. pCur = p->apCsr[pOp->p1];
  74135. assert( pCur->pVtabCursor );
  74136. if( pCur->nullRow ){
  74137. break;
  74138. }
  74139. pVtab = pCur->pVtabCursor->pVtab;
  74140. pModule = pVtab->pModule;
  74141. assert( pModule->xNext );
  74142. /* Invoke the xNext() method of the module. There is no way for the
  74143. ** underlying implementation to return an error if one occurs during
  74144. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  74145. ** data is available) and the error code returned when xColumn or
  74146. ** some other method is next invoked on the save virtual table cursor.
  74147. */
  74148. rc = pModule->xNext(pCur->pVtabCursor);
  74149. sqlite3VtabImportErrmsg(p, pVtab);
  74150. if( rc==SQLITE_OK ){
  74151. res = pModule->xEof(pCur->pVtabCursor);
  74152. }
  74153. VdbeBranchTaken(!res,2);
  74154. if( !res ){
  74155. /* If there is data, jump to P2 */
  74156. goto jump_to_p2_and_check_for_interrupt;
  74157. }
  74158. goto check_for_interrupt;
  74159. }
  74160. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74161. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74162. /* Opcode: VRename P1 * * P4 *
  74163. **
  74164. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  74165. ** This opcode invokes the corresponding xRename method. The value
  74166. ** in register P1 is passed as the zName argument to the xRename method.
  74167. */
  74168. case OP_VRename: {
  74169. sqlite3_vtab *pVtab;
  74170. Mem *pName;
  74171. pVtab = pOp->p4.pVtab->pVtab;
  74172. pName = &aMem[pOp->p1];
  74173. assert( pVtab->pModule->xRename );
  74174. assert( memIsValid(pName) );
  74175. assert( p->readOnly==0 );
  74176. REGISTER_TRACE(pOp->p1, pName);
  74177. assert( pName->flags & MEM_Str );
  74178. testcase( pName->enc==SQLITE_UTF8 );
  74179. testcase( pName->enc==SQLITE_UTF16BE );
  74180. testcase( pName->enc==SQLITE_UTF16LE );
  74181. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  74182. if( rc==SQLITE_OK ){
  74183. rc = pVtab->pModule->xRename(pVtab, pName->z);
  74184. sqlite3VtabImportErrmsg(p, pVtab);
  74185. p->expired = 0;
  74186. }
  74187. break;
  74188. }
  74189. #endif
  74190. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74191. /* Opcode: VUpdate P1 P2 P3 P4 P5
  74192. ** Synopsis: data=r[P3@P2]
  74193. **
  74194. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  74195. ** This opcode invokes the corresponding xUpdate method. P2 values
  74196. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  74197. ** invocation. The value in register (P3+P2-1) corresponds to the
  74198. ** p2th element of the argv array passed to xUpdate.
  74199. **
  74200. ** The xUpdate method will do a DELETE or an INSERT or both.
  74201. ** The argv[0] element (which corresponds to memory cell P3)
  74202. ** is the rowid of a row to delete. If argv[0] is NULL then no
  74203. ** deletion occurs. The argv[1] element is the rowid of the new
  74204. ** row. This can be NULL to have the virtual table select the new
  74205. ** rowid for itself. The subsequent elements in the array are
  74206. ** the values of columns in the new row.
  74207. **
  74208. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  74209. ** a row to delete.
  74210. **
  74211. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  74212. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  74213. ** is set to the value of the rowid for the row just inserted.
  74214. **
  74215. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  74216. ** apply in the case of a constraint failure on an insert or update.
  74217. */
  74218. case OP_VUpdate: {
  74219. sqlite3_vtab *pVtab;
  74220. const sqlite3_module *pModule;
  74221. int nArg;
  74222. int i;
  74223. sqlite_int64 rowid;
  74224. Mem **apArg;
  74225. Mem *pX;
  74226. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  74227. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  74228. );
  74229. assert( p->readOnly==0 );
  74230. pVtab = pOp->p4.pVtab->pVtab;
  74231. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  74232. rc = SQLITE_LOCKED;
  74233. break;
  74234. }
  74235. pModule = pVtab->pModule;
  74236. nArg = pOp->p2;
  74237. assert( pOp->p4type==P4_VTAB );
  74238. if( ALWAYS(pModule->xUpdate) ){
  74239. u8 vtabOnConflict = db->vtabOnConflict;
  74240. apArg = p->apArg;
  74241. pX = &aMem[pOp->p3];
  74242. for(i=0; i<nArg; i++){
  74243. assert( memIsValid(pX) );
  74244. memAboutToChange(p, pX);
  74245. apArg[i] = pX;
  74246. pX++;
  74247. }
  74248. db->vtabOnConflict = pOp->p5;
  74249. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  74250. db->vtabOnConflict = vtabOnConflict;
  74251. sqlite3VtabImportErrmsg(p, pVtab);
  74252. if( rc==SQLITE_OK && pOp->p1 ){
  74253. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  74254. db->lastRowid = lastRowid = rowid;
  74255. }
  74256. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  74257. if( pOp->p5==OE_Ignore ){
  74258. rc = SQLITE_OK;
  74259. }else{
  74260. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  74261. }
  74262. }else{
  74263. p->nChange++;
  74264. }
  74265. }
  74266. break;
  74267. }
  74268. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74269. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  74270. /* Opcode: Pagecount P1 P2 * * *
  74271. **
  74272. ** Write the current number of pages in database P1 to memory cell P2.
  74273. */
  74274. case OP_Pagecount: { /* out2 */
  74275. pOut = out2Prerelease(p, pOp);
  74276. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  74277. break;
  74278. }
  74279. #endif
  74280. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  74281. /* Opcode: MaxPgcnt P1 P2 P3 * *
  74282. **
  74283. ** Try to set the maximum page count for database P1 to the value in P3.
  74284. ** Do not let the maximum page count fall below the current page count and
  74285. ** do not change the maximum page count value if P3==0.
  74286. **
  74287. ** Store the maximum page count after the change in register P2.
  74288. */
  74289. case OP_MaxPgcnt: { /* out2 */
  74290. unsigned int newMax;
  74291. Btree *pBt;
  74292. pOut = out2Prerelease(p, pOp);
  74293. pBt = db->aDb[pOp->p1].pBt;
  74294. newMax = 0;
  74295. if( pOp->p3 ){
  74296. newMax = sqlite3BtreeLastPage(pBt);
  74297. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  74298. }
  74299. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  74300. break;
  74301. }
  74302. #endif
  74303. /* Opcode: Init * P2 * P4 *
  74304. ** Synopsis: Start at P2
  74305. **
  74306. ** Programs contain a single instance of this opcode as the very first
  74307. ** opcode.
  74308. **
  74309. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  74310. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  74311. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  74312. **
  74313. ** If P2 is not zero, jump to instruction P2.
  74314. */
  74315. case OP_Init: { /* jump */
  74316. char *zTrace;
  74317. char *z;
  74318. #ifndef SQLITE_OMIT_TRACE
  74319. if( db->xTrace
  74320. && !p->doingRerun
  74321. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  74322. ){
  74323. z = sqlite3VdbeExpandSql(p, zTrace);
  74324. db->xTrace(db->pTraceArg, z);
  74325. sqlite3DbFree(db, z);
  74326. }
  74327. #ifdef SQLITE_USE_FCNTL_TRACE
  74328. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  74329. if( zTrace ){
  74330. int i;
  74331. for(i=0; i<db->nDb; i++){
  74332. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  74333. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  74334. }
  74335. }
  74336. #endif /* SQLITE_USE_FCNTL_TRACE */
  74337. #ifdef SQLITE_DEBUG
  74338. if( (db->flags & SQLITE_SqlTrace)!=0
  74339. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  74340. ){
  74341. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  74342. }
  74343. #endif /* SQLITE_DEBUG */
  74344. #endif /* SQLITE_OMIT_TRACE */
  74345. if( pOp->p2 ) goto jump_to_p2;
  74346. break;
  74347. }
  74348. /* Opcode: Noop * * * * *
  74349. **
  74350. ** Do nothing. This instruction is often useful as a jump
  74351. ** destination.
  74352. */
  74353. /*
  74354. ** The magic Explain opcode are only inserted when explain==2 (which
  74355. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  74356. ** This opcode records information from the optimizer. It is the
  74357. ** the same as a no-op. This opcodesnever appears in a real VM program.
  74358. */
  74359. default: { /* This is really OP_Noop and OP_Explain */
  74360. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  74361. break;
  74362. }
  74363. /*****************************************************************************
  74364. ** The cases of the switch statement above this line should all be indented
  74365. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  74366. ** readability. From this point on down, the normal indentation rules are
  74367. ** restored.
  74368. *****************************************************************************/
  74369. }
  74370. #ifdef VDBE_PROFILE
  74371. {
  74372. u64 endTime = sqlite3Hwtime();
  74373. if( endTime>start ) pOrigOp->cycles += endTime - start;
  74374. pOrigOp->cnt++;
  74375. }
  74376. #endif
  74377. /* The following code adds nothing to the actual functionality
  74378. ** of the program. It is only here for testing and debugging.
  74379. ** On the other hand, it does burn CPU cycles every time through
  74380. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  74381. */
  74382. #ifndef NDEBUG
  74383. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  74384. #ifdef SQLITE_DEBUG
  74385. if( db->flags & SQLITE_VdbeTrace ){
  74386. if( rc!=0 ) printf("rc=%d\n",rc);
  74387. if( pOrigOp->opflags & (OPFLG_OUT2) ){
  74388. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  74389. }
  74390. if( pOrigOp->opflags & OPFLG_OUT3 ){
  74391. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  74392. }
  74393. }
  74394. #endif /* SQLITE_DEBUG */
  74395. #endif /* NDEBUG */
  74396. } /* The end of the for(;;) loop the loops through opcodes */
  74397. /* If we reach this point, it means that execution is finished with
  74398. ** an error of some kind.
  74399. */
  74400. vdbe_error_halt:
  74401. assert( rc );
  74402. p->rc = rc;
  74403. testcase( sqlite3GlobalConfig.xLog!=0 );
  74404. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  74405. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  74406. sqlite3VdbeHalt(p);
  74407. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  74408. rc = SQLITE_ERROR;
  74409. if( resetSchemaOnFault>0 ){
  74410. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  74411. }
  74412. /* This is the only way out of this procedure. We have to
  74413. ** release the mutexes on btrees that were acquired at the
  74414. ** top. */
  74415. vdbe_return:
  74416. db->lastRowid = lastRowid;
  74417. testcase( nVmStep>0 );
  74418. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  74419. sqlite3VdbeLeave(p);
  74420. return rc;
  74421. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  74422. ** is encountered.
  74423. */
  74424. too_big:
  74425. sqlite3VdbeError(p, "string or blob too big");
  74426. rc = SQLITE_TOOBIG;
  74427. goto vdbe_error_halt;
  74428. /* Jump to here if a malloc() fails.
  74429. */
  74430. no_mem:
  74431. db->mallocFailed = 1;
  74432. sqlite3VdbeError(p, "out of memory");
  74433. rc = SQLITE_NOMEM;
  74434. goto vdbe_error_halt;
  74435. /* Jump to here for any other kind of fatal error. The "rc" variable
  74436. ** should hold the error number.
  74437. */
  74438. abort_due_to_error:
  74439. assert( p->zErrMsg==0 );
  74440. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  74441. if( rc!=SQLITE_IOERR_NOMEM ){
  74442. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  74443. }
  74444. goto vdbe_error_halt;
  74445. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  74446. ** flag.
  74447. */
  74448. abort_due_to_interrupt:
  74449. assert( db->u1.isInterrupted );
  74450. rc = SQLITE_INTERRUPT;
  74451. p->rc = rc;
  74452. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  74453. goto vdbe_error_halt;
  74454. }
  74455. /************** End of vdbe.c ************************************************/
  74456. /************** Begin file vdbeblob.c ****************************************/
  74457. /*
  74458. ** 2007 May 1
  74459. **
  74460. ** The author disclaims copyright to this source code. In place of
  74461. ** a legal notice, here is a blessing:
  74462. **
  74463. ** May you do good and not evil.
  74464. ** May you find forgiveness for yourself and forgive others.
  74465. ** May you share freely, never taking more than you give.
  74466. **
  74467. *************************************************************************
  74468. **
  74469. ** This file contains code used to implement incremental BLOB I/O.
  74470. */
  74471. /* #include "sqliteInt.h" */
  74472. /* #include "vdbeInt.h" */
  74473. #ifndef SQLITE_OMIT_INCRBLOB
  74474. /*
  74475. ** Valid sqlite3_blob* handles point to Incrblob structures.
  74476. */
  74477. typedef struct Incrblob Incrblob;
  74478. struct Incrblob {
  74479. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  74480. int nByte; /* Size of open blob, in bytes */
  74481. int iOffset; /* Byte offset of blob in cursor data */
  74482. int iCol; /* Table column this handle is open on */
  74483. BtCursor *pCsr; /* Cursor pointing at blob row */
  74484. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  74485. sqlite3 *db; /* The associated database */
  74486. };
  74487. /*
  74488. ** This function is used by both blob_open() and blob_reopen(). It seeks
  74489. ** the b-tree cursor associated with blob handle p to point to row iRow.
  74490. ** If successful, SQLITE_OK is returned and subsequent calls to
  74491. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  74492. **
  74493. ** If an error occurs, or if the specified row does not exist or does not
  74494. ** contain a value of type TEXT or BLOB in the column nominated when the
  74495. ** blob handle was opened, then an error code is returned and *pzErr may
  74496. ** be set to point to a buffer containing an error message. It is the
  74497. ** responsibility of the caller to free the error message buffer using
  74498. ** sqlite3DbFree().
  74499. **
  74500. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  74501. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  74502. ** immediately return SQLITE_ABORT.
  74503. */
  74504. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  74505. int rc; /* Error code */
  74506. char *zErr = 0; /* Error message */
  74507. Vdbe *v = (Vdbe *)p->pStmt;
  74508. /* Set the value of the SQL statements only variable to integer iRow.
  74509. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  74510. ** triggering asserts related to mutexes.
  74511. */
  74512. assert( v->aVar[0].flags&MEM_Int );
  74513. v->aVar[0].u.i = iRow;
  74514. rc = sqlite3_step(p->pStmt);
  74515. if( rc==SQLITE_ROW ){
  74516. VdbeCursor *pC = v->apCsr[0];
  74517. u32 type = pC->aType[p->iCol];
  74518. if( type<12 ){
  74519. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  74520. type==0?"null": type==7?"real": "integer"
  74521. );
  74522. rc = SQLITE_ERROR;
  74523. sqlite3_finalize(p->pStmt);
  74524. p->pStmt = 0;
  74525. }else{
  74526. p->iOffset = pC->aType[p->iCol + pC->nField];
  74527. p->nByte = sqlite3VdbeSerialTypeLen(type);
  74528. p->pCsr = pC->pCursor;
  74529. sqlite3BtreeIncrblobCursor(p->pCsr);
  74530. }
  74531. }
  74532. if( rc==SQLITE_ROW ){
  74533. rc = SQLITE_OK;
  74534. }else if( p->pStmt ){
  74535. rc = sqlite3_finalize(p->pStmt);
  74536. p->pStmt = 0;
  74537. if( rc==SQLITE_OK ){
  74538. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  74539. rc = SQLITE_ERROR;
  74540. }else{
  74541. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  74542. }
  74543. }
  74544. assert( rc!=SQLITE_OK || zErr==0 );
  74545. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  74546. *pzErr = zErr;
  74547. return rc;
  74548. }
  74549. /*
  74550. ** Open a blob handle.
  74551. */
  74552. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  74553. sqlite3* db, /* The database connection */
  74554. const char *zDb, /* The attached database containing the blob */
  74555. const char *zTable, /* The table containing the blob */
  74556. const char *zColumn, /* The column containing the blob */
  74557. sqlite_int64 iRow, /* The row containing the glob */
  74558. int flags, /* True -> read/write access, false -> read-only */
  74559. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  74560. ){
  74561. int nAttempt = 0;
  74562. int iCol; /* Index of zColumn in row-record */
  74563. /* This VDBE program seeks a btree cursor to the identified
  74564. ** db/table/row entry. The reason for using a vdbe program instead
  74565. ** of writing code to use the b-tree layer directly is that the
  74566. ** vdbe program will take advantage of the various transaction,
  74567. ** locking and error handling infrastructure built into the vdbe.
  74568. **
  74569. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  74570. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  74571. ** uses it to implement the blob_read(), blob_write() and
  74572. ** blob_bytes() functions.
  74573. **
  74574. ** The sqlite3_blob_close() function finalizes the vdbe program,
  74575. ** which closes the b-tree cursor and (possibly) commits the
  74576. ** transaction.
  74577. */
  74578. static const int iLn = VDBE_OFFSET_LINENO(4);
  74579. static const VdbeOpList openBlob[] = {
  74580. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  74581. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  74582. /* One of the following two instructions is replaced by an OP_Noop. */
  74583. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  74584. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  74585. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  74586. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  74587. {OP_Column, 0, 0, 1}, /* 6 */
  74588. {OP_ResultRow, 1, 0, 0}, /* 7 */
  74589. {OP_Goto, 0, 4, 0}, /* 8 */
  74590. {OP_Close, 0, 0, 0}, /* 9 */
  74591. {OP_Halt, 0, 0, 0}, /* 10 */
  74592. };
  74593. int rc = SQLITE_OK;
  74594. char *zErr = 0;
  74595. Table *pTab;
  74596. Parse *pParse = 0;
  74597. Incrblob *pBlob = 0;
  74598. #ifdef SQLITE_ENABLE_API_ARMOR
  74599. if( ppBlob==0 ){
  74600. return SQLITE_MISUSE_BKPT;
  74601. }
  74602. #endif
  74603. *ppBlob = 0;
  74604. #ifdef SQLITE_ENABLE_API_ARMOR
  74605. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  74606. return SQLITE_MISUSE_BKPT;
  74607. }
  74608. #endif
  74609. flags = !!flags; /* flags = (flags ? 1 : 0); */
  74610. sqlite3_mutex_enter(db->mutex);
  74611. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  74612. if( !pBlob ) goto blob_open_out;
  74613. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  74614. if( !pParse ) goto blob_open_out;
  74615. do {
  74616. memset(pParse, 0, sizeof(Parse));
  74617. pParse->db = db;
  74618. sqlite3DbFree(db, zErr);
  74619. zErr = 0;
  74620. sqlite3BtreeEnterAll(db);
  74621. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  74622. if( pTab && IsVirtual(pTab) ){
  74623. pTab = 0;
  74624. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  74625. }
  74626. if( pTab && !HasRowid(pTab) ){
  74627. pTab = 0;
  74628. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  74629. }
  74630. #ifndef SQLITE_OMIT_VIEW
  74631. if( pTab && pTab->pSelect ){
  74632. pTab = 0;
  74633. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  74634. }
  74635. #endif
  74636. if( !pTab ){
  74637. if( pParse->zErrMsg ){
  74638. sqlite3DbFree(db, zErr);
  74639. zErr = pParse->zErrMsg;
  74640. pParse->zErrMsg = 0;
  74641. }
  74642. rc = SQLITE_ERROR;
  74643. sqlite3BtreeLeaveAll(db);
  74644. goto blob_open_out;
  74645. }
  74646. /* Now search pTab for the exact column. */
  74647. for(iCol=0; iCol<pTab->nCol; iCol++) {
  74648. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  74649. break;
  74650. }
  74651. }
  74652. if( iCol==pTab->nCol ){
  74653. sqlite3DbFree(db, zErr);
  74654. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  74655. rc = SQLITE_ERROR;
  74656. sqlite3BtreeLeaveAll(db);
  74657. goto blob_open_out;
  74658. }
  74659. /* If the value is being opened for writing, check that the
  74660. ** column is not indexed, and that it is not part of a foreign key.
  74661. ** It is against the rules to open a column to which either of these
  74662. ** descriptions applies for writing. */
  74663. if( flags ){
  74664. const char *zFault = 0;
  74665. Index *pIdx;
  74666. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74667. if( db->flags&SQLITE_ForeignKeys ){
  74668. /* Check that the column is not part of an FK child key definition. It
  74669. ** is not necessary to check if it is part of a parent key, as parent
  74670. ** key columns must be indexed. The check below will pick up this
  74671. ** case. */
  74672. FKey *pFKey;
  74673. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  74674. int j;
  74675. for(j=0; j<pFKey->nCol; j++){
  74676. if( pFKey->aCol[j].iFrom==iCol ){
  74677. zFault = "foreign key";
  74678. }
  74679. }
  74680. }
  74681. }
  74682. #endif
  74683. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  74684. int j;
  74685. for(j=0; j<pIdx->nKeyCol; j++){
  74686. /* FIXME: Be smarter about indexes that use expressions */
  74687. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  74688. zFault = "indexed";
  74689. }
  74690. }
  74691. }
  74692. if( zFault ){
  74693. sqlite3DbFree(db, zErr);
  74694. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  74695. rc = SQLITE_ERROR;
  74696. sqlite3BtreeLeaveAll(db);
  74697. goto blob_open_out;
  74698. }
  74699. }
  74700. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  74701. assert( pBlob->pStmt || db->mallocFailed );
  74702. if( pBlob->pStmt ){
  74703. Vdbe *v = (Vdbe *)pBlob->pStmt;
  74704. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  74705. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  74706. pTab->pSchema->schema_cookie,
  74707. pTab->pSchema->iGeneration);
  74708. sqlite3VdbeChangeP5(v, 1);
  74709. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  74710. /* Make sure a mutex is held on the table to be accessed */
  74711. sqlite3VdbeUsesBtree(v, iDb);
  74712. /* Configure the OP_TableLock instruction */
  74713. #ifdef SQLITE_OMIT_SHARED_CACHE
  74714. sqlite3VdbeChangeToNoop(v, 1);
  74715. #else
  74716. sqlite3VdbeChangeP1(v, 1, iDb);
  74717. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  74718. sqlite3VdbeChangeP3(v, 1, flags);
  74719. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  74720. #endif
  74721. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  74722. ** parameter of the other to pTab->tnum. */
  74723. sqlite3VdbeChangeToNoop(v, 3 - flags);
  74724. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  74725. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  74726. /* Configure the number of columns. Configure the cursor to
  74727. ** think that the table has one more column than it really
  74728. ** does. An OP_Column to retrieve this imaginary column will
  74729. ** always return an SQL NULL. This is useful because it means
  74730. ** we can invoke OP_Column to fill in the vdbe cursors type
  74731. ** and offset cache without causing any IO.
  74732. */
  74733. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  74734. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  74735. if( !db->mallocFailed ){
  74736. pParse->nVar = 1;
  74737. pParse->nMem = 1;
  74738. pParse->nTab = 1;
  74739. sqlite3VdbeMakeReady(v, pParse);
  74740. }
  74741. }
  74742. pBlob->flags = flags;
  74743. pBlob->iCol = iCol;
  74744. pBlob->db = db;
  74745. sqlite3BtreeLeaveAll(db);
  74746. if( db->mallocFailed ){
  74747. goto blob_open_out;
  74748. }
  74749. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  74750. rc = blobSeekToRow(pBlob, iRow, &zErr);
  74751. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  74752. blob_open_out:
  74753. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  74754. *ppBlob = (sqlite3_blob *)pBlob;
  74755. }else{
  74756. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  74757. sqlite3DbFree(db, pBlob);
  74758. }
  74759. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  74760. sqlite3DbFree(db, zErr);
  74761. sqlite3ParserReset(pParse);
  74762. sqlite3StackFree(db, pParse);
  74763. rc = sqlite3ApiExit(db, rc);
  74764. sqlite3_mutex_leave(db->mutex);
  74765. return rc;
  74766. }
  74767. /*
  74768. ** Close a blob handle that was previously created using
  74769. ** sqlite3_blob_open().
  74770. */
  74771. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
  74772. Incrblob *p = (Incrblob *)pBlob;
  74773. int rc;
  74774. sqlite3 *db;
  74775. if( p ){
  74776. db = p->db;
  74777. sqlite3_mutex_enter(db->mutex);
  74778. rc = sqlite3_finalize(p->pStmt);
  74779. sqlite3DbFree(db, p);
  74780. sqlite3_mutex_leave(db->mutex);
  74781. }else{
  74782. rc = SQLITE_OK;
  74783. }
  74784. return rc;
  74785. }
  74786. /*
  74787. ** Perform a read or write operation on a blob
  74788. */
  74789. static int blobReadWrite(
  74790. sqlite3_blob *pBlob,
  74791. void *z,
  74792. int n,
  74793. int iOffset,
  74794. int (*xCall)(BtCursor*, u32, u32, void*)
  74795. ){
  74796. int rc;
  74797. Incrblob *p = (Incrblob *)pBlob;
  74798. Vdbe *v;
  74799. sqlite3 *db;
  74800. if( p==0 ) return SQLITE_MISUSE_BKPT;
  74801. db = p->db;
  74802. sqlite3_mutex_enter(db->mutex);
  74803. v = (Vdbe*)p->pStmt;
  74804. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  74805. /* Request is out of range. Return a transient error. */
  74806. rc = SQLITE_ERROR;
  74807. }else if( v==0 ){
  74808. /* If there is no statement handle, then the blob-handle has
  74809. ** already been invalidated. Return SQLITE_ABORT in this case.
  74810. */
  74811. rc = SQLITE_ABORT;
  74812. }else{
  74813. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  74814. ** returned, clean-up the statement handle.
  74815. */
  74816. assert( db == v->db );
  74817. sqlite3BtreeEnterCursor(p->pCsr);
  74818. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  74819. sqlite3BtreeLeaveCursor(p->pCsr);
  74820. if( rc==SQLITE_ABORT ){
  74821. sqlite3VdbeFinalize(v);
  74822. p->pStmt = 0;
  74823. }else{
  74824. v->rc = rc;
  74825. }
  74826. }
  74827. sqlite3Error(db, rc);
  74828. rc = sqlite3ApiExit(db, rc);
  74829. sqlite3_mutex_leave(db->mutex);
  74830. return rc;
  74831. }
  74832. /*
  74833. ** Read data from a blob handle.
  74834. */
  74835. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  74836. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  74837. }
  74838. /*
  74839. ** Write data to a blob handle.
  74840. */
  74841. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  74842. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  74843. }
  74844. /*
  74845. ** Query a blob handle for the size of the data.
  74846. **
  74847. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  74848. ** so no mutex is required for access.
  74849. */
  74850. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
  74851. Incrblob *p = (Incrblob *)pBlob;
  74852. return (p && p->pStmt) ? p->nByte : 0;
  74853. }
  74854. /*
  74855. ** Move an existing blob handle to point to a different row of the same
  74856. ** database table.
  74857. **
  74858. ** If an error occurs, or if the specified row does not exist or does not
  74859. ** contain a blob or text value, then an error code is returned and the
  74860. ** database handle error code and message set. If this happens, then all
  74861. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  74862. ** immediately return SQLITE_ABORT.
  74863. */
  74864. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  74865. int rc;
  74866. Incrblob *p = (Incrblob *)pBlob;
  74867. sqlite3 *db;
  74868. if( p==0 ) return SQLITE_MISUSE_BKPT;
  74869. db = p->db;
  74870. sqlite3_mutex_enter(db->mutex);
  74871. if( p->pStmt==0 ){
  74872. /* If there is no statement handle, then the blob-handle has
  74873. ** already been invalidated. Return SQLITE_ABORT in this case.
  74874. */
  74875. rc = SQLITE_ABORT;
  74876. }else{
  74877. char *zErr;
  74878. rc = blobSeekToRow(p, iRow, &zErr);
  74879. if( rc!=SQLITE_OK ){
  74880. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  74881. sqlite3DbFree(db, zErr);
  74882. }
  74883. assert( rc!=SQLITE_SCHEMA );
  74884. }
  74885. rc = sqlite3ApiExit(db, rc);
  74886. assert( rc==SQLITE_OK || p->pStmt==0 );
  74887. sqlite3_mutex_leave(db->mutex);
  74888. return rc;
  74889. }
  74890. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  74891. /************** End of vdbeblob.c ********************************************/
  74892. /************** Begin file vdbesort.c ****************************************/
  74893. /*
  74894. ** 2011-07-09
  74895. **
  74896. ** The author disclaims copyright to this source code. In place of
  74897. ** a legal notice, here is a blessing:
  74898. **
  74899. ** May you do good and not evil.
  74900. ** May you find forgiveness for yourself and forgive others.
  74901. ** May you share freely, never taking more than you give.
  74902. **
  74903. *************************************************************************
  74904. ** This file contains code for the VdbeSorter object, used in concert with
  74905. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  74906. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  74907. ** using indexes and without LIMIT clauses.
  74908. **
  74909. ** The VdbeSorter object implements a multi-threaded external merge sort
  74910. ** algorithm that is efficient even if the number of elements being sorted
  74911. ** exceeds the available memory.
  74912. **
  74913. ** Here is the (internal, non-API) interface between this module and the
  74914. ** rest of the SQLite system:
  74915. **
  74916. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  74917. **
  74918. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  74919. ** object. The row is a binary blob in the
  74920. ** OP_MakeRecord format that contains both
  74921. ** the ORDER BY key columns and result columns
  74922. ** in the case of a SELECT w/ ORDER BY, or
  74923. ** the complete record for an index entry
  74924. ** in the case of a CREATE INDEX.
  74925. **
  74926. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  74927. ** Position the read cursor on the
  74928. ** first sorted element.
  74929. **
  74930. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  74931. ** element.
  74932. **
  74933. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  74934. ** row currently under the read cursor.
  74935. **
  74936. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  74937. ** currently under the read cursor against
  74938. ** another binary blob X and report if
  74939. ** X is strictly less than the read cursor.
  74940. ** Used to enforce uniqueness in a
  74941. ** CREATE UNIQUE INDEX statement.
  74942. **
  74943. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  74944. ** all resources.
  74945. **
  74946. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  74947. ** is like Close() followed by Init() only
  74948. ** much faster.
  74949. **
  74950. ** The interfaces above must be called in a particular order. Write() can
  74951. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  74952. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  74953. **
  74954. ** Init()
  74955. ** for each record: Write()
  74956. ** Rewind()
  74957. ** Rowkey()/Compare()
  74958. ** Next()
  74959. ** Close()
  74960. **
  74961. ** Algorithm:
  74962. **
  74963. ** Records passed to the sorter via calls to Write() are initially held
  74964. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  74965. ** a threshold, when Rewind() is called the set of records is sorted using
  74966. ** an in-memory merge sort. In this case, no temporary files are required
  74967. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  74968. ** directly from main memory.
  74969. **
  74970. ** If the amount of space used to store records in main memory exceeds the
  74971. ** threshold, then the set of records currently in memory are sorted and
  74972. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  74973. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  74974. ** of PMAs may be created by merging existing PMAs together - for example
  74975. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  74976. **
  74977. ** The threshold for the amount of main memory to use before flushing
  74978. ** records to a PMA is roughly the same as the limit configured for the
  74979. ** page-cache of the main database. Specifically, the threshold is set to
  74980. ** the value returned by "PRAGMA main.page_size" multipled by
  74981. ** that returned by "PRAGMA main.cache_size", in bytes.
  74982. **
  74983. ** If the sorter is running in single-threaded mode, then all PMAs generated
  74984. ** are appended to a single temporary file. Or, if the sorter is running in
  74985. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  74986. ** N is the configured number of worker threads. In this case, instead of
  74987. ** sorting the records and writing the PMA to a temporary file itself, the
  74988. ** calling thread usually launches a worker thread to do so. Except, if
  74989. ** there are already N worker threads running, the main thread does the work
  74990. ** itself.
  74991. **
  74992. ** The sorter is running in multi-threaded mode if (a) the library was built
  74993. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  74994. ** than zero, and (b) worker threads have been enabled at runtime by calling
  74995. ** "PRAGMA threads=N" with some value of N greater than 0.
  74996. **
  74997. ** When Rewind() is called, any data remaining in memory is flushed to a
  74998. ** final PMA. So at this point the data is stored in some number of sorted
  74999. ** PMAs within temporary files on disk.
  75000. **
  75001. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  75002. ** sorter is running in single-threaded mode, then these PMAs are merged
  75003. ** incrementally as keys are retreived from the sorter by the VDBE. The
  75004. ** MergeEngine object, described in further detail below, performs this
  75005. ** merge.
  75006. **
  75007. ** Or, if running in multi-threaded mode, then a background thread is
  75008. ** launched to merge the existing PMAs. Once the background thread has
  75009. ** merged T bytes of data into a single sorted PMA, the main thread
  75010. ** begins reading keys from that PMA while the background thread proceeds
  75011. ** with merging the next T bytes of data. And so on.
  75012. **
  75013. ** Parameter T is set to half the value of the memory threshold used
  75014. ** by Write() above to determine when to create a new PMA.
  75015. **
  75016. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  75017. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  75018. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  75019. ** disk are merged together. Then T bytes of data from the second set, and
  75020. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  75021. ** PMAs at a time. This done is to improve locality.
  75022. **
  75023. ** If running in multi-threaded mode and there are more than
  75024. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  75025. ** than one background thread may be created. Specifically, there may be
  75026. ** one background thread for each temporary file on disk, and one background
  75027. ** thread to merge the output of each of the others to a single PMA for
  75028. ** the main thread to read from.
  75029. */
  75030. /* #include "sqliteInt.h" */
  75031. /* #include "vdbeInt.h" */
  75032. /*
  75033. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  75034. ** messages to stderr that may be helpful in understanding the performance
  75035. ** characteristics of the sorter in multi-threaded mode.
  75036. */
  75037. #if 0
  75038. # define SQLITE_DEBUG_SORTER_THREADS 1
  75039. #endif
  75040. /*
  75041. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  75042. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  75043. ** overflows. 512MiB.
  75044. */
  75045. #define SQLITE_MAX_PMASZ (1<<29)
  75046. /*
  75047. ** Private objects used by the sorter
  75048. */
  75049. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  75050. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  75051. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  75052. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  75053. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  75054. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  75055. typedef struct SorterList SorterList; /* In-memory list of records */
  75056. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  75057. /*
  75058. ** A container for a temp file handle and the current amount of data
  75059. ** stored in the file.
  75060. */
  75061. struct SorterFile {
  75062. sqlite3_file *pFd; /* File handle */
  75063. i64 iEof; /* Bytes of data stored in pFd */
  75064. };
  75065. /*
  75066. ** An in-memory list of objects to be sorted.
  75067. **
  75068. ** If aMemory==0 then each object is allocated separately and the objects
  75069. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  75070. ** are stored in the aMemory[] bulk memory, one right after the other, and
  75071. ** are connected using SorterRecord.u.iNext.
  75072. */
  75073. struct SorterList {
  75074. SorterRecord *pList; /* Linked list of records */
  75075. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  75076. int szPMA; /* Size of pList as PMA in bytes */
  75077. };
  75078. /*
  75079. ** The MergeEngine object is used to combine two or more smaller PMAs into
  75080. ** one big PMA using a merge operation. Separate PMAs all need to be
  75081. ** combined into one big PMA in order to be able to step through the sorted
  75082. ** records in order.
  75083. **
  75084. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  75085. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  75086. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  75087. ** For the purposes of the paragraphs below, we assume that the array is
  75088. ** actually N elements in size, where N is the smallest power of 2 greater
  75089. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  75090. ** are treated as if they are empty (always at EOF).
  75091. **
  75092. ** The aTree[] array is also N elements in size. The value of N is stored in
  75093. ** the MergeEngine.nTree variable.
  75094. **
  75095. ** The final (N/2) elements of aTree[] contain the results of comparing
  75096. ** pairs of PMA keys together. Element i contains the result of
  75097. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  75098. ** aTree element is set to the index of it.
  75099. **
  75100. ** For the purposes of this comparison, EOF is considered greater than any
  75101. ** other key value. If the keys are equal (only possible with two EOF
  75102. ** values), it doesn't matter which index is stored.
  75103. **
  75104. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  75105. ** above contains the index of the smallest of each block of 4 PmaReaders
  75106. ** And so on. So that aTree[1] contains the index of the PmaReader that
  75107. ** currently points to the smallest key value. aTree[0] is unused.
  75108. **
  75109. ** Example:
  75110. **
  75111. ** aReadr[0] -> Banana
  75112. ** aReadr[1] -> Feijoa
  75113. ** aReadr[2] -> Elderberry
  75114. ** aReadr[3] -> Currant
  75115. ** aReadr[4] -> Grapefruit
  75116. ** aReadr[5] -> Apple
  75117. ** aReadr[6] -> Durian
  75118. ** aReadr[7] -> EOF
  75119. **
  75120. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  75121. **
  75122. ** The current element is "Apple" (the value of the key indicated by
  75123. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  75124. ** be advanced to the next key in its segment. Say the next key is
  75125. ** "Eggplant":
  75126. **
  75127. ** aReadr[5] -> Eggplant
  75128. **
  75129. ** The contents of aTree[] are updated first by comparing the new PmaReader
  75130. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  75131. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  75132. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  75133. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  75134. ** so the value written into element 1 of the array is 0. As follows:
  75135. **
  75136. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  75137. **
  75138. ** In other words, each time we advance to the next sorter element, log2(N)
  75139. ** key comparison operations are required, where N is the number of segments
  75140. ** being merged (rounded up to the next power of 2).
  75141. */
  75142. struct MergeEngine {
  75143. int nTree; /* Used size of aTree/aReadr (power of 2) */
  75144. SortSubtask *pTask; /* Used by this thread only */
  75145. int *aTree; /* Current state of incremental merge */
  75146. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  75147. };
  75148. /*
  75149. ** This object represents a single thread of control in a sort operation.
  75150. ** Exactly VdbeSorter.nTask instances of this object are allocated
  75151. ** as part of each VdbeSorter object. Instances are never allocated any
  75152. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  75153. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  75154. ** single-threaded operation, there is exactly one instance of this object
  75155. ** and for multi-threaded operation there are two or more instances.
  75156. **
  75157. ** Essentially, this structure contains all those fields of the VdbeSorter
  75158. ** structure for which each thread requires a separate instance. For example,
  75159. ** each thread requries its own UnpackedRecord object to unpack records in
  75160. ** as part of comparison operations.
  75161. **
  75162. ** Before a background thread is launched, variable bDone is set to 0. Then,
  75163. ** right before it exits, the thread itself sets bDone to 1. This is used for
  75164. ** two purposes:
  75165. **
  75166. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  75167. ** attempt to select a SortSubtask for which there is not already an
  75168. ** active background thread (since doing so causes the main thread
  75169. ** to block until it finishes).
  75170. **
  75171. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  75172. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  75173. ** block provoke debugging output.
  75174. **
  75175. ** In both cases, the effects of the main thread seeing (bDone==0) even
  75176. ** after the thread has finished are not dire. So we don't worry about
  75177. ** memory barriers and such here.
  75178. */
  75179. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  75180. struct SortSubtask {
  75181. SQLiteThread *pThread; /* Background thread, if any */
  75182. int bDone; /* Set if thread is finished but not joined */
  75183. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  75184. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  75185. SorterList list; /* List for thread to write to a PMA */
  75186. int nPMA; /* Number of PMAs currently in file */
  75187. SorterCompare xCompare; /* Compare function to use */
  75188. SorterFile file; /* Temp file for level-0 PMAs */
  75189. SorterFile file2; /* Space for other PMAs */
  75190. };
  75191. /*
  75192. ** Main sorter structure. A single instance of this is allocated for each
  75193. ** sorter cursor created by the VDBE.
  75194. **
  75195. ** mxKeysize:
  75196. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  75197. ** this variable is updated so as to be set to the size on disk of the
  75198. ** largest record in the sorter.
  75199. */
  75200. struct VdbeSorter {
  75201. int mnPmaSize; /* Minimum PMA size, in bytes */
  75202. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  75203. int mxKeysize; /* Largest serialized key seen so far */
  75204. int pgsz; /* Main database page size */
  75205. PmaReader *pReader; /* Readr data from here after Rewind() */
  75206. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  75207. sqlite3 *db; /* Database connection */
  75208. KeyInfo *pKeyInfo; /* How to compare records */
  75209. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  75210. SorterList list; /* List of in-memory records */
  75211. int iMemory; /* Offset of free space in list.aMemory */
  75212. int nMemory; /* Size of list.aMemory allocation in bytes */
  75213. u8 bUsePMA; /* True if one or more PMAs created */
  75214. u8 bUseThreads; /* True to use background threads */
  75215. u8 iPrev; /* Previous thread used to flush PMA */
  75216. u8 nTask; /* Size of aTask[] array */
  75217. u8 typeMask;
  75218. SortSubtask aTask[1]; /* One or more subtasks */
  75219. };
  75220. #define SORTER_TYPE_INTEGER 0x01
  75221. #define SORTER_TYPE_TEXT 0x02
  75222. /*
  75223. ** An instance of the following object is used to read records out of a
  75224. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  75225. ** aKey might point into aMap or into aBuffer. If neither of those locations
  75226. ** contain a contiguous representation of the key, then aAlloc is allocated
  75227. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  75228. **
  75229. ** pFd==0 at EOF.
  75230. */
  75231. struct PmaReader {
  75232. i64 iReadOff; /* Current read offset */
  75233. i64 iEof; /* 1 byte past EOF for this PmaReader */
  75234. int nAlloc; /* Bytes of space at aAlloc */
  75235. int nKey; /* Number of bytes in key */
  75236. sqlite3_file *pFd; /* File handle we are reading from */
  75237. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  75238. u8 *aKey; /* Pointer to current key */
  75239. u8 *aBuffer; /* Current read buffer */
  75240. int nBuffer; /* Size of read buffer in bytes */
  75241. u8 *aMap; /* Pointer to mapping of entire file */
  75242. IncrMerger *pIncr; /* Incremental merger */
  75243. };
  75244. /*
  75245. ** Normally, a PmaReader object iterates through an existing PMA stored
  75246. ** within a temp file. However, if the PmaReader.pIncr variable points to
  75247. ** an object of the following type, it may be used to iterate/merge through
  75248. ** multiple PMAs simultaneously.
  75249. **
  75250. ** There are two types of IncrMerger object - single (bUseThread==0) and
  75251. ** multi-threaded (bUseThread==1).
  75252. **
  75253. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  75254. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  75255. ** size. When the IncrMerger is initialized, it reads enough data from
  75256. ** pMerger to populate aFile[0]. It then sets variables within the
  75257. ** corresponding PmaReader object to read from that file and kicks off
  75258. ** a background thread to populate aFile[1] with the next mxSz bytes of
  75259. ** sorted record data from pMerger.
  75260. **
  75261. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  75262. ** background thread has finished populating aFile[1]. It then exchanges
  75263. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  75264. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  75265. ** another background thread to populate the new aFile[1]. And so on, until
  75266. ** the contents of pMerger are exhausted.
  75267. **
  75268. ** A single-threaded IncrMerger does not open any temporary files of its
  75269. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  75270. ** at offset iStartOff of file pTask->file2. And instead of using a
  75271. ** background thread to prepare data for the PmaReader, with a single
  75272. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  75273. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  75274. ** of data.
  75275. */
  75276. struct IncrMerger {
  75277. SortSubtask *pTask; /* Task that owns this merger */
  75278. MergeEngine *pMerger; /* Merge engine thread reads data from */
  75279. i64 iStartOff; /* Offset to start writing file at */
  75280. int mxSz; /* Maximum bytes of data to store */
  75281. int bEof; /* Set to true when merge is finished */
  75282. int bUseThread; /* True to use a bg thread for this object */
  75283. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  75284. };
  75285. /*
  75286. ** An instance of this object is used for writing a PMA.
  75287. **
  75288. ** The PMA is written one record at a time. Each record is of an arbitrary
  75289. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  75290. ** each block is aligned on a page boundary. This object caches writes to
  75291. ** the PMA so that aligned, page-size blocks are written.
  75292. */
  75293. struct PmaWriter {
  75294. int eFWErr; /* Non-zero if in an error state */
  75295. u8 *aBuffer; /* Pointer to write buffer */
  75296. int nBuffer; /* Size of write buffer in bytes */
  75297. int iBufStart; /* First byte of buffer to write */
  75298. int iBufEnd; /* Last byte of buffer to write */
  75299. i64 iWriteOff; /* Offset of start of buffer in file */
  75300. sqlite3_file *pFd; /* File handle to write to */
  75301. };
  75302. /*
  75303. ** This object is the header on a single record while that record is being
  75304. ** held in memory and prior to being written out as part of a PMA.
  75305. **
  75306. ** How the linked list is connected depends on how memory is being managed
  75307. ** by this module. If using a separate allocation for each in-memory record
  75308. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  75309. ** SorterRecord.u.pNext pointers.
  75310. **
  75311. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  75312. ** then while records are being accumulated the list is linked using the
  75313. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  75314. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  75315. ** has finished passing records to the sorter, or when the in-memory buffer
  75316. ** is full, the list is sorted. As part of the sorting process, it is
  75317. ** converted to use the SorterRecord.u.pNext pointers. See function
  75318. ** vdbeSorterSort() for details.
  75319. */
  75320. struct SorterRecord {
  75321. int nVal; /* Size of the record in bytes */
  75322. union {
  75323. SorterRecord *pNext; /* Pointer to next record in list */
  75324. int iNext; /* Offset within aMemory of next record */
  75325. } u;
  75326. /* The data for the record immediately follows this header */
  75327. };
  75328. /* Return a pointer to the buffer containing the record data for SorterRecord
  75329. ** object p. Should be used as if:
  75330. **
  75331. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  75332. */
  75333. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  75334. /* Maximum number of PMAs that a single MergeEngine can merge */
  75335. #define SORTER_MAX_MERGE_COUNT 16
  75336. static int vdbeIncrSwap(IncrMerger*);
  75337. static void vdbeIncrFree(IncrMerger *);
  75338. /*
  75339. ** Free all memory belonging to the PmaReader object passed as the
  75340. ** argument. All structure fields are set to zero before returning.
  75341. */
  75342. static void vdbePmaReaderClear(PmaReader *pReadr){
  75343. sqlite3_free(pReadr->aAlloc);
  75344. sqlite3_free(pReadr->aBuffer);
  75345. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  75346. vdbeIncrFree(pReadr->pIncr);
  75347. memset(pReadr, 0, sizeof(PmaReader));
  75348. }
  75349. /*
  75350. ** Read the next nByte bytes of data from the PMA p.
  75351. ** If successful, set *ppOut to point to a buffer containing the data
  75352. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  75353. ** error code.
  75354. **
  75355. ** The buffer returned in *ppOut is only valid until the
  75356. ** next call to this function.
  75357. */
  75358. static int vdbePmaReadBlob(
  75359. PmaReader *p, /* PmaReader from which to take the blob */
  75360. int nByte, /* Bytes of data to read */
  75361. u8 **ppOut /* OUT: Pointer to buffer containing data */
  75362. ){
  75363. int iBuf; /* Offset within buffer to read from */
  75364. int nAvail; /* Bytes of data available in buffer */
  75365. if( p->aMap ){
  75366. *ppOut = &p->aMap[p->iReadOff];
  75367. p->iReadOff += nByte;
  75368. return SQLITE_OK;
  75369. }
  75370. assert( p->aBuffer );
  75371. /* If there is no more data to be read from the buffer, read the next
  75372. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  75373. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  75374. iBuf = p->iReadOff % p->nBuffer;
  75375. if( iBuf==0 ){
  75376. int nRead; /* Bytes to read from disk */
  75377. int rc; /* sqlite3OsRead() return code */
  75378. /* Determine how many bytes of data to read. */
  75379. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  75380. nRead = p->nBuffer;
  75381. }else{
  75382. nRead = (int)(p->iEof - p->iReadOff);
  75383. }
  75384. assert( nRead>0 );
  75385. /* Readr data from the file. Return early if an error occurs. */
  75386. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  75387. assert( rc!=SQLITE_IOERR_SHORT_READ );
  75388. if( rc!=SQLITE_OK ) return rc;
  75389. }
  75390. nAvail = p->nBuffer - iBuf;
  75391. if( nByte<=nAvail ){
  75392. /* The requested data is available in the in-memory buffer. In this
  75393. ** case there is no need to make a copy of the data, just return a
  75394. ** pointer into the buffer to the caller. */
  75395. *ppOut = &p->aBuffer[iBuf];
  75396. p->iReadOff += nByte;
  75397. }else{
  75398. /* The requested data is not all available in the in-memory buffer.
  75399. ** In this case, allocate space at p->aAlloc[] to copy the requested
  75400. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  75401. int nRem; /* Bytes remaining to copy */
  75402. /* Extend the p->aAlloc[] allocation if required. */
  75403. if( p->nAlloc<nByte ){
  75404. u8 *aNew;
  75405. int nNew = MAX(128, p->nAlloc*2);
  75406. while( nByte>nNew ) nNew = nNew*2;
  75407. aNew = sqlite3Realloc(p->aAlloc, nNew);
  75408. if( !aNew ) return SQLITE_NOMEM;
  75409. p->nAlloc = nNew;
  75410. p->aAlloc = aNew;
  75411. }
  75412. /* Copy as much data as is available in the buffer into the start of
  75413. ** p->aAlloc[]. */
  75414. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  75415. p->iReadOff += nAvail;
  75416. nRem = nByte - nAvail;
  75417. /* The following loop copies up to p->nBuffer bytes per iteration into
  75418. ** the p->aAlloc[] buffer. */
  75419. while( nRem>0 ){
  75420. int rc; /* vdbePmaReadBlob() return code */
  75421. int nCopy; /* Number of bytes to copy */
  75422. u8 *aNext; /* Pointer to buffer to copy data from */
  75423. nCopy = nRem;
  75424. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  75425. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  75426. if( rc!=SQLITE_OK ) return rc;
  75427. assert( aNext!=p->aAlloc );
  75428. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  75429. nRem -= nCopy;
  75430. }
  75431. *ppOut = p->aAlloc;
  75432. }
  75433. return SQLITE_OK;
  75434. }
  75435. /*
  75436. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  75437. ** the value read.
  75438. */
  75439. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  75440. int iBuf;
  75441. if( p->aMap ){
  75442. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  75443. }else{
  75444. iBuf = p->iReadOff % p->nBuffer;
  75445. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  75446. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  75447. }else{
  75448. u8 aVarint[16], *a;
  75449. int i = 0, rc;
  75450. do{
  75451. rc = vdbePmaReadBlob(p, 1, &a);
  75452. if( rc ) return rc;
  75453. aVarint[(i++)&0xf] = a[0];
  75454. }while( (a[0]&0x80)!=0 );
  75455. sqlite3GetVarint(aVarint, pnOut);
  75456. }
  75457. }
  75458. return SQLITE_OK;
  75459. }
  75460. /*
  75461. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  75462. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  75463. ** (because the file is too large or the VFS layer is configured not to use
  75464. ** mmap), return SQLITE_OK and set *pp to NULL.
  75465. **
  75466. ** Or, if an error occurs, return an SQLite error code. The final value of
  75467. ** *pp is undefined in this case.
  75468. */
  75469. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  75470. int rc = SQLITE_OK;
  75471. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  75472. sqlite3_file *pFd = pFile->pFd;
  75473. if( pFd->pMethods->iVersion>=3 ){
  75474. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  75475. testcase( rc!=SQLITE_OK );
  75476. }
  75477. }
  75478. return rc;
  75479. }
  75480. /*
  75481. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  75482. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  75483. ** if successful, or an SQLite error code if an error occurs.
  75484. */
  75485. static int vdbePmaReaderSeek(
  75486. SortSubtask *pTask, /* Task context */
  75487. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  75488. SorterFile *pFile, /* Sorter file to read from */
  75489. i64 iOff /* Offset in pFile */
  75490. ){
  75491. int rc = SQLITE_OK;
  75492. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  75493. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  75494. if( pReadr->aMap ){
  75495. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  75496. pReadr->aMap = 0;
  75497. }
  75498. pReadr->iReadOff = iOff;
  75499. pReadr->iEof = pFile->iEof;
  75500. pReadr->pFd = pFile->pFd;
  75501. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  75502. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  75503. int pgsz = pTask->pSorter->pgsz;
  75504. int iBuf = pReadr->iReadOff % pgsz;
  75505. if( pReadr->aBuffer==0 ){
  75506. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  75507. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  75508. pReadr->nBuffer = pgsz;
  75509. }
  75510. if( rc==SQLITE_OK && iBuf ){
  75511. int nRead = pgsz - iBuf;
  75512. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  75513. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  75514. }
  75515. rc = sqlite3OsRead(
  75516. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  75517. );
  75518. testcase( rc!=SQLITE_OK );
  75519. }
  75520. }
  75521. return rc;
  75522. }
  75523. /*
  75524. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  75525. ** no error occurs, or an SQLite error code if one does.
  75526. */
  75527. static int vdbePmaReaderNext(PmaReader *pReadr){
  75528. int rc = SQLITE_OK; /* Return Code */
  75529. u64 nRec = 0; /* Size of record in bytes */
  75530. if( pReadr->iReadOff>=pReadr->iEof ){
  75531. IncrMerger *pIncr = pReadr->pIncr;
  75532. int bEof = 1;
  75533. if( pIncr ){
  75534. rc = vdbeIncrSwap(pIncr);
  75535. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  75536. rc = vdbePmaReaderSeek(
  75537. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  75538. );
  75539. bEof = 0;
  75540. }
  75541. }
  75542. if( bEof ){
  75543. /* This is an EOF condition */
  75544. vdbePmaReaderClear(pReadr);
  75545. testcase( rc!=SQLITE_OK );
  75546. return rc;
  75547. }
  75548. }
  75549. if( rc==SQLITE_OK ){
  75550. rc = vdbePmaReadVarint(pReadr, &nRec);
  75551. }
  75552. if( rc==SQLITE_OK ){
  75553. pReadr->nKey = (int)nRec;
  75554. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  75555. testcase( rc!=SQLITE_OK );
  75556. }
  75557. return rc;
  75558. }
  75559. /*
  75560. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  75561. ** starting at offset iStart and ending at offset iEof-1. This function
  75562. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  75563. ** PMA is empty).
  75564. **
  75565. ** If the pnByte parameter is NULL, then it is assumed that the file
  75566. ** contains a single PMA, and that that PMA omits the initial length varint.
  75567. */
  75568. static int vdbePmaReaderInit(
  75569. SortSubtask *pTask, /* Task context */
  75570. SorterFile *pFile, /* Sorter file to read from */
  75571. i64 iStart, /* Start offset in pFile */
  75572. PmaReader *pReadr, /* PmaReader to populate */
  75573. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  75574. ){
  75575. int rc;
  75576. assert( pFile->iEof>iStart );
  75577. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  75578. assert( pReadr->aBuffer==0 );
  75579. assert( pReadr->aMap==0 );
  75580. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  75581. if( rc==SQLITE_OK ){
  75582. u64 nByte; /* Size of PMA in bytes */
  75583. rc = vdbePmaReadVarint(pReadr, &nByte);
  75584. pReadr->iEof = pReadr->iReadOff + nByte;
  75585. *pnByte += nByte;
  75586. }
  75587. if( rc==SQLITE_OK ){
  75588. rc = vdbePmaReaderNext(pReadr);
  75589. }
  75590. return rc;
  75591. }
  75592. /*
  75593. ** A version of vdbeSorterCompare() that assumes that it has already been
  75594. ** determined that the first field of key1 is equal to the first field of
  75595. ** key2.
  75596. */
  75597. static int vdbeSorterCompareTail(
  75598. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  75599. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  75600. const void *pKey1, int nKey1, /* Left side of comparison */
  75601. const void *pKey2, int nKey2 /* Right side of comparison */
  75602. ){
  75603. UnpackedRecord *r2 = pTask->pUnpacked;
  75604. if( *pbKey2Cached==0 ){
  75605. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  75606. *pbKey2Cached = 1;
  75607. }
  75608. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  75609. }
  75610. /*
  75611. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  75612. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  75613. ** used by the comparison. Return the result of the comparison.
  75614. **
  75615. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  75616. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  75617. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  75618. ** version of key2 and *pbKey2Cached set to true before returning.
  75619. **
  75620. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  75621. ** to SQLITE_NOMEM.
  75622. */
  75623. static int vdbeSorterCompare(
  75624. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  75625. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  75626. const void *pKey1, int nKey1, /* Left side of comparison */
  75627. const void *pKey2, int nKey2 /* Right side of comparison */
  75628. ){
  75629. UnpackedRecord *r2 = pTask->pUnpacked;
  75630. if( !*pbKey2Cached ){
  75631. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  75632. *pbKey2Cached = 1;
  75633. }
  75634. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  75635. }
  75636. /*
  75637. ** A specially optimized version of vdbeSorterCompare() that assumes that
  75638. ** the first field of each key is a TEXT value and that the collation
  75639. ** sequence to compare them with is BINARY.
  75640. */
  75641. static int vdbeSorterCompareText(
  75642. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  75643. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  75644. const void *pKey1, int nKey1, /* Left side of comparison */
  75645. const void *pKey2, int nKey2 /* Right side of comparison */
  75646. ){
  75647. const u8 * const p1 = (const u8 * const)pKey1;
  75648. const u8 * const p2 = (const u8 * const)pKey2;
  75649. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  75650. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  75651. int n1;
  75652. int n2;
  75653. int res;
  75654. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  75655. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  75656. res = memcmp(v1, v2, MIN(n1, n2));
  75657. if( res==0 ){
  75658. res = n1 - n2;
  75659. }
  75660. if( res==0 ){
  75661. if( pTask->pSorter->pKeyInfo->nField>1 ){
  75662. res = vdbeSorterCompareTail(
  75663. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  75664. );
  75665. }
  75666. }else{
  75667. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  75668. res = res * -1;
  75669. }
  75670. }
  75671. return res;
  75672. }
  75673. /*
  75674. ** A specially optimized version of vdbeSorterCompare() that assumes that
  75675. ** the first field of each key is an INTEGER value.
  75676. */
  75677. static int vdbeSorterCompareInt(
  75678. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  75679. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  75680. const void *pKey1, int nKey1, /* Left side of comparison */
  75681. const void *pKey2, int nKey2 /* Right side of comparison */
  75682. ){
  75683. const u8 * const p1 = (const u8 * const)pKey1;
  75684. const u8 * const p2 = (const u8 * const)pKey2;
  75685. const int s1 = p1[1]; /* Left hand serial type */
  75686. const int s2 = p2[1]; /* Right hand serial type */
  75687. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  75688. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  75689. int res; /* Return value */
  75690. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  75691. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  75692. if( s1>7 && s2>7 ){
  75693. res = s1 - s2;
  75694. }else{
  75695. if( s1==s2 ){
  75696. if( (*v1 ^ *v2) & 0x80 ){
  75697. /* The two values have different signs */
  75698. res = (*v1 & 0x80) ? -1 : +1;
  75699. }else{
  75700. /* The two values have the same sign. Compare using memcmp(). */
  75701. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
  75702. int i;
  75703. res = 0;
  75704. for(i=0; i<aLen[s1]; i++){
  75705. if( (res = v1[i] - v2[i]) ) break;
  75706. }
  75707. }
  75708. }else{
  75709. if( s2>7 ){
  75710. res = +1;
  75711. }else if( s1>7 ){
  75712. res = -1;
  75713. }else{
  75714. res = s1 - s2;
  75715. }
  75716. assert( res!=0 );
  75717. if( res>0 ){
  75718. if( *v1 & 0x80 ) res = -1;
  75719. }else{
  75720. if( *v2 & 0x80 ) res = +1;
  75721. }
  75722. }
  75723. }
  75724. if( res==0 ){
  75725. if( pTask->pSorter->pKeyInfo->nField>1 ){
  75726. res = vdbeSorterCompareTail(
  75727. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  75728. );
  75729. }
  75730. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  75731. res = res * -1;
  75732. }
  75733. return res;
  75734. }
  75735. /*
  75736. ** Initialize the temporary index cursor just opened as a sorter cursor.
  75737. **
  75738. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  75739. ** to determine the number of fields that should be compared from the
  75740. ** records being sorted. However, if the value passed as argument nField
  75741. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  75742. ** is used instead. This is used when sorting records for a CREATE INDEX
  75743. ** statement. In this case, keys are always delivered to the sorter in
  75744. ** order of the primary key, which happens to be make up the final part
  75745. ** of the records being sorted. So if the sort is stable, there is never
  75746. ** any reason to compare PK fields and they can be ignored for a small
  75747. ** performance boost.
  75748. **
  75749. ** The sorter can guarantee a stable sort when running in single-threaded
  75750. ** mode, but not in multi-threaded mode.
  75751. **
  75752. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  75753. */
  75754. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  75755. sqlite3 *db, /* Database connection (for malloc()) */
  75756. int nField, /* Number of key fields in each record */
  75757. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  75758. ){
  75759. int pgsz; /* Page size of main database */
  75760. int i; /* Used to iterate through aTask[] */
  75761. int mxCache; /* Cache size */
  75762. VdbeSorter *pSorter; /* The new sorter */
  75763. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  75764. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  75765. int sz; /* Size of pSorter in bytes */
  75766. int rc = SQLITE_OK;
  75767. #if SQLITE_MAX_WORKER_THREADS==0
  75768. # define nWorker 0
  75769. #else
  75770. int nWorker;
  75771. #endif
  75772. /* Initialize the upper limit on the number of worker threads */
  75773. #if SQLITE_MAX_WORKER_THREADS>0
  75774. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  75775. nWorker = 0;
  75776. }else{
  75777. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  75778. }
  75779. #endif
  75780. /* Do not allow the total number of threads (main thread + all workers)
  75781. ** to exceed the maximum merge count */
  75782. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  75783. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  75784. nWorker = SORTER_MAX_MERGE_COUNT-1;
  75785. }
  75786. #endif
  75787. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  75788. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  75789. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  75790. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  75791. pCsr->pSorter = pSorter;
  75792. if( pSorter==0 ){
  75793. rc = SQLITE_NOMEM;
  75794. }else{
  75795. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  75796. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  75797. pKeyInfo->db = 0;
  75798. if( nField && nWorker==0 ){
  75799. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  75800. pKeyInfo->nField = nField;
  75801. }
  75802. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  75803. pSorter->nTask = nWorker + 1;
  75804. pSorter->iPrev = nWorker-1;
  75805. pSorter->bUseThreads = (pSorter->nTask>1);
  75806. pSorter->db = db;
  75807. for(i=0; i<pSorter->nTask; i++){
  75808. SortSubtask *pTask = &pSorter->aTask[i];
  75809. pTask->pSorter = pSorter;
  75810. }
  75811. if( !sqlite3TempInMemory(db) ){
  75812. u32 szPma = sqlite3GlobalConfig.szPma;
  75813. pSorter->mnPmaSize = szPma * pgsz;
  75814. mxCache = db->aDb[0].pSchema->cache_size;
  75815. if( mxCache<(int)szPma ) mxCache = (int)szPma;
  75816. pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
  75817. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  75818. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  75819. ** large heap allocations.
  75820. */
  75821. if( sqlite3GlobalConfig.pScratch==0 ){
  75822. assert( pSorter->iMemory==0 );
  75823. pSorter->nMemory = pgsz;
  75824. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  75825. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  75826. }
  75827. }
  75828. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  75829. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  75830. ){
  75831. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  75832. }
  75833. }
  75834. return rc;
  75835. }
  75836. #undef nWorker /* Defined at the top of this function */
  75837. /*
  75838. ** Free the list of sorted records starting at pRecord.
  75839. */
  75840. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  75841. SorterRecord *p;
  75842. SorterRecord *pNext;
  75843. for(p=pRecord; p; p=pNext){
  75844. pNext = p->u.pNext;
  75845. sqlite3DbFree(db, p);
  75846. }
  75847. }
  75848. /*
  75849. ** Free all resources owned by the object indicated by argument pTask. All
  75850. ** fields of *pTask are zeroed before returning.
  75851. */
  75852. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  75853. sqlite3DbFree(db, pTask->pUnpacked);
  75854. #if SQLITE_MAX_WORKER_THREADS>0
  75855. /* pTask->list.aMemory can only be non-zero if it was handed memory
  75856. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  75857. if( pTask->list.aMemory ){
  75858. sqlite3_free(pTask->list.aMemory);
  75859. }else
  75860. #endif
  75861. {
  75862. assert( pTask->list.aMemory==0 );
  75863. vdbeSorterRecordFree(0, pTask->list.pList);
  75864. }
  75865. if( pTask->file.pFd ){
  75866. sqlite3OsCloseFree(pTask->file.pFd);
  75867. }
  75868. if( pTask->file2.pFd ){
  75869. sqlite3OsCloseFree(pTask->file2.pFd);
  75870. }
  75871. memset(pTask, 0, sizeof(SortSubtask));
  75872. }
  75873. #ifdef SQLITE_DEBUG_SORTER_THREADS
  75874. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  75875. i64 t;
  75876. int iTask = (pTask - pTask->pSorter->aTask);
  75877. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75878. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  75879. }
  75880. static void vdbeSorterRewindDebug(const char *zEvent){
  75881. i64 t;
  75882. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  75883. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  75884. }
  75885. static void vdbeSorterPopulateDebug(
  75886. SortSubtask *pTask,
  75887. const char *zEvent
  75888. ){
  75889. i64 t;
  75890. int iTask = (pTask - pTask->pSorter->aTask);
  75891. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75892. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  75893. }
  75894. static void vdbeSorterBlockDebug(
  75895. SortSubtask *pTask,
  75896. int bBlocked,
  75897. const char *zEvent
  75898. ){
  75899. if( bBlocked ){
  75900. i64 t;
  75901. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75902. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  75903. }
  75904. }
  75905. #else
  75906. # define vdbeSorterWorkDebug(x,y)
  75907. # define vdbeSorterRewindDebug(y)
  75908. # define vdbeSorterPopulateDebug(x,y)
  75909. # define vdbeSorterBlockDebug(x,y,z)
  75910. #endif
  75911. #if SQLITE_MAX_WORKER_THREADS>0
  75912. /*
  75913. ** Join thread pTask->thread.
  75914. */
  75915. static int vdbeSorterJoinThread(SortSubtask *pTask){
  75916. int rc = SQLITE_OK;
  75917. if( pTask->pThread ){
  75918. #ifdef SQLITE_DEBUG_SORTER_THREADS
  75919. int bDone = pTask->bDone;
  75920. #endif
  75921. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  75922. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  75923. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  75924. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  75925. rc = SQLITE_PTR_TO_INT(pRet);
  75926. assert( pTask->bDone==1 );
  75927. pTask->bDone = 0;
  75928. pTask->pThread = 0;
  75929. }
  75930. return rc;
  75931. }
  75932. /*
  75933. ** Launch a background thread to run xTask(pIn).
  75934. */
  75935. static int vdbeSorterCreateThread(
  75936. SortSubtask *pTask, /* Thread will use this task object */
  75937. void *(*xTask)(void*), /* Routine to run in a separate thread */
  75938. void *pIn /* Argument passed into xTask() */
  75939. ){
  75940. assert( pTask->pThread==0 && pTask->bDone==0 );
  75941. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  75942. }
  75943. /*
  75944. ** Join all outstanding threads launched by SorterWrite() to create
  75945. ** level-0 PMAs.
  75946. */
  75947. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  75948. int rc = rcin;
  75949. int i;
  75950. /* This function is always called by the main user thread.
  75951. **
  75952. ** If this function is being called after SorterRewind() has been called,
  75953. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  75954. ** is currently attempt to join one of the other threads. To avoid a race
  75955. ** condition where this thread also attempts to join the same object, join
  75956. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  75957. for(i=pSorter->nTask-1; i>=0; i--){
  75958. SortSubtask *pTask = &pSorter->aTask[i];
  75959. int rc2 = vdbeSorterJoinThread(pTask);
  75960. if( rc==SQLITE_OK ) rc = rc2;
  75961. }
  75962. return rc;
  75963. }
  75964. #else
  75965. # define vdbeSorterJoinAll(x,rcin) (rcin)
  75966. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  75967. #endif
  75968. /*
  75969. ** Allocate a new MergeEngine object capable of handling up to
  75970. ** nReader PmaReader inputs.
  75971. **
  75972. ** nReader is automatically rounded up to the next power of two.
  75973. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  75974. */
  75975. static MergeEngine *vdbeMergeEngineNew(int nReader){
  75976. int N = 2; /* Smallest power of two >= nReader */
  75977. int nByte; /* Total bytes of space to allocate */
  75978. MergeEngine *pNew; /* Pointer to allocated object to return */
  75979. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  75980. while( N<nReader ) N += N;
  75981. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  75982. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  75983. if( pNew ){
  75984. pNew->nTree = N;
  75985. pNew->pTask = 0;
  75986. pNew->aReadr = (PmaReader*)&pNew[1];
  75987. pNew->aTree = (int*)&pNew->aReadr[N];
  75988. }
  75989. return pNew;
  75990. }
  75991. /*
  75992. ** Free the MergeEngine object passed as the only argument.
  75993. */
  75994. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  75995. int i;
  75996. if( pMerger ){
  75997. for(i=0; i<pMerger->nTree; i++){
  75998. vdbePmaReaderClear(&pMerger->aReadr[i]);
  75999. }
  76000. }
  76001. sqlite3_free(pMerger);
  76002. }
  76003. /*
  76004. ** Free all resources associated with the IncrMerger object indicated by
  76005. ** the first argument.
  76006. */
  76007. static void vdbeIncrFree(IncrMerger *pIncr){
  76008. if( pIncr ){
  76009. #if SQLITE_MAX_WORKER_THREADS>0
  76010. if( pIncr->bUseThread ){
  76011. vdbeSorterJoinThread(pIncr->pTask);
  76012. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  76013. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  76014. }
  76015. #endif
  76016. vdbeMergeEngineFree(pIncr->pMerger);
  76017. sqlite3_free(pIncr);
  76018. }
  76019. }
  76020. /*
  76021. ** Reset a sorting cursor back to its original empty state.
  76022. */
  76023. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  76024. int i;
  76025. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  76026. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  76027. #if SQLITE_MAX_WORKER_THREADS>0
  76028. if( pSorter->pReader ){
  76029. vdbePmaReaderClear(pSorter->pReader);
  76030. sqlite3DbFree(db, pSorter->pReader);
  76031. pSorter->pReader = 0;
  76032. }
  76033. #endif
  76034. vdbeMergeEngineFree(pSorter->pMerger);
  76035. pSorter->pMerger = 0;
  76036. for(i=0; i<pSorter->nTask; i++){
  76037. SortSubtask *pTask = &pSorter->aTask[i];
  76038. vdbeSortSubtaskCleanup(db, pTask);
  76039. pTask->pSorter = pSorter;
  76040. }
  76041. if( pSorter->list.aMemory==0 ){
  76042. vdbeSorterRecordFree(0, pSorter->list.pList);
  76043. }
  76044. pSorter->list.pList = 0;
  76045. pSorter->list.szPMA = 0;
  76046. pSorter->bUsePMA = 0;
  76047. pSorter->iMemory = 0;
  76048. pSorter->mxKeysize = 0;
  76049. sqlite3DbFree(db, pSorter->pUnpacked);
  76050. pSorter->pUnpacked = 0;
  76051. }
  76052. /*
  76053. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  76054. */
  76055. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  76056. VdbeSorter *pSorter = pCsr->pSorter;
  76057. if( pSorter ){
  76058. sqlite3VdbeSorterReset(db, pSorter);
  76059. sqlite3_free(pSorter->list.aMemory);
  76060. sqlite3DbFree(db, pSorter);
  76061. pCsr->pSorter = 0;
  76062. }
  76063. }
  76064. #if SQLITE_MAX_MMAP_SIZE>0
  76065. /*
  76066. ** The first argument is a file-handle open on a temporary file. The file
  76067. ** is guaranteed to be nByte bytes or smaller in size. This function
  76068. ** attempts to extend the file to nByte bytes in size and to ensure that
  76069. ** the VFS has memory mapped it.
  76070. **
  76071. ** Whether or not the file does end up memory mapped of course depends on
  76072. ** the specific VFS implementation.
  76073. */
  76074. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  76075. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  76076. void *p = 0;
  76077. int chunksize = 4*1024;
  76078. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  76079. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  76080. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  76081. sqlite3OsUnfetch(pFd, 0, p);
  76082. }
  76083. }
  76084. #else
  76085. # define vdbeSorterExtendFile(x,y,z)
  76086. #endif
  76087. /*
  76088. ** Allocate space for a file-handle and open a temporary file. If successful,
  76089. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  76090. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  76091. */
  76092. static int vdbeSorterOpenTempFile(
  76093. sqlite3 *db, /* Database handle doing sort */
  76094. i64 nExtend, /* Attempt to extend file to this size */
  76095. sqlite3_file **ppFd
  76096. ){
  76097. int rc;
  76098. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  76099. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  76100. SQLITE_OPEN_TEMP_JOURNAL |
  76101. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  76102. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  76103. );
  76104. if( rc==SQLITE_OK ){
  76105. i64 max = SQLITE_MAX_MMAP_SIZE;
  76106. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  76107. if( nExtend>0 ){
  76108. vdbeSorterExtendFile(db, *ppFd, nExtend);
  76109. }
  76110. }
  76111. return rc;
  76112. }
  76113. /*
  76114. ** If it has not already been allocated, allocate the UnpackedRecord
  76115. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  76116. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  76117. */
  76118. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  76119. if( pTask->pUnpacked==0 ){
  76120. char *pFree;
  76121. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  76122. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  76123. );
  76124. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  76125. if( pFree==0 ) return SQLITE_NOMEM;
  76126. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  76127. pTask->pUnpacked->errCode = 0;
  76128. }
  76129. return SQLITE_OK;
  76130. }
  76131. /*
  76132. ** Merge the two sorted lists p1 and p2 into a single list.
  76133. ** Set *ppOut to the head of the new list.
  76134. */
  76135. static void vdbeSorterMerge(
  76136. SortSubtask *pTask, /* Calling thread context */
  76137. SorterRecord *p1, /* First list to merge */
  76138. SorterRecord *p2, /* Second list to merge */
  76139. SorterRecord **ppOut /* OUT: Head of merged list */
  76140. ){
  76141. SorterRecord *pFinal = 0;
  76142. SorterRecord **pp = &pFinal;
  76143. int bCached = 0;
  76144. while( p1 && p2 ){
  76145. int res;
  76146. res = pTask->xCompare(
  76147. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  76148. );
  76149. if( res<=0 ){
  76150. *pp = p1;
  76151. pp = &p1->u.pNext;
  76152. p1 = p1->u.pNext;
  76153. }else{
  76154. *pp = p2;
  76155. pp = &p2->u.pNext;
  76156. p2 = p2->u.pNext;
  76157. bCached = 0;
  76158. }
  76159. }
  76160. *pp = p1 ? p1 : p2;
  76161. *ppOut = pFinal;
  76162. }
  76163. /*
  76164. ** Return the SorterCompare function to compare values collected by the
  76165. ** sorter object passed as the only argument.
  76166. */
  76167. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  76168. if( p->typeMask==SORTER_TYPE_INTEGER ){
  76169. return vdbeSorterCompareInt;
  76170. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  76171. return vdbeSorterCompareText;
  76172. }
  76173. return vdbeSorterCompare;
  76174. }
  76175. /*
  76176. ** Sort the linked list of records headed at pTask->pList. Return
  76177. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  76178. ** an error occurs.
  76179. */
  76180. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  76181. int i;
  76182. SorterRecord **aSlot;
  76183. SorterRecord *p;
  76184. int rc;
  76185. rc = vdbeSortAllocUnpacked(pTask);
  76186. if( rc!=SQLITE_OK ) return rc;
  76187. p = pList->pList;
  76188. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  76189. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  76190. if( !aSlot ){
  76191. return SQLITE_NOMEM;
  76192. }
  76193. while( p ){
  76194. SorterRecord *pNext;
  76195. if( pList->aMemory ){
  76196. if( (u8*)p==pList->aMemory ){
  76197. pNext = 0;
  76198. }else{
  76199. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  76200. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  76201. }
  76202. }else{
  76203. pNext = p->u.pNext;
  76204. }
  76205. p->u.pNext = 0;
  76206. for(i=0; aSlot[i]; i++){
  76207. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  76208. aSlot[i] = 0;
  76209. }
  76210. aSlot[i] = p;
  76211. p = pNext;
  76212. }
  76213. p = 0;
  76214. for(i=0; i<64; i++){
  76215. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  76216. }
  76217. pList->pList = p;
  76218. sqlite3_free(aSlot);
  76219. assert( pTask->pUnpacked->errCode==SQLITE_OK
  76220. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  76221. );
  76222. return pTask->pUnpacked->errCode;
  76223. }
  76224. /*
  76225. ** Initialize a PMA-writer object.
  76226. */
  76227. static void vdbePmaWriterInit(
  76228. sqlite3_file *pFd, /* File handle to write to */
  76229. PmaWriter *p, /* Object to populate */
  76230. int nBuf, /* Buffer size */
  76231. i64 iStart /* Offset of pFd to begin writing at */
  76232. ){
  76233. memset(p, 0, sizeof(PmaWriter));
  76234. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  76235. if( !p->aBuffer ){
  76236. p->eFWErr = SQLITE_NOMEM;
  76237. }else{
  76238. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  76239. p->iWriteOff = iStart - p->iBufStart;
  76240. p->nBuffer = nBuf;
  76241. p->pFd = pFd;
  76242. }
  76243. }
  76244. /*
  76245. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  76246. ** if successful, or an SQLite error code if an error occurs.
  76247. */
  76248. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  76249. int nRem = nData;
  76250. while( nRem>0 && p->eFWErr==0 ){
  76251. int nCopy = nRem;
  76252. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  76253. nCopy = p->nBuffer - p->iBufEnd;
  76254. }
  76255. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  76256. p->iBufEnd += nCopy;
  76257. if( p->iBufEnd==p->nBuffer ){
  76258. p->eFWErr = sqlite3OsWrite(p->pFd,
  76259. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  76260. p->iWriteOff + p->iBufStart
  76261. );
  76262. p->iBufStart = p->iBufEnd = 0;
  76263. p->iWriteOff += p->nBuffer;
  76264. }
  76265. assert( p->iBufEnd<p->nBuffer );
  76266. nRem -= nCopy;
  76267. }
  76268. }
  76269. /*
  76270. ** Flush any buffered data to disk and clean up the PMA-writer object.
  76271. ** The results of using the PMA-writer after this call are undefined.
  76272. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  76273. ** required. Otherwise, return an SQLite error code.
  76274. **
  76275. ** Before returning, set *piEof to the offset immediately following the
  76276. ** last byte written to the file.
  76277. */
  76278. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  76279. int rc;
  76280. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  76281. p->eFWErr = sqlite3OsWrite(p->pFd,
  76282. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  76283. p->iWriteOff + p->iBufStart
  76284. );
  76285. }
  76286. *piEof = (p->iWriteOff + p->iBufEnd);
  76287. sqlite3_free(p->aBuffer);
  76288. rc = p->eFWErr;
  76289. memset(p, 0, sizeof(PmaWriter));
  76290. return rc;
  76291. }
  76292. /*
  76293. ** Write value iVal encoded as a varint to the PMA. Return
  76294. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  76295. */
  76296. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  76297. int nByte;
  76298. u8 aByte[10];
  76299. nByte = sqlite3PutVarint(aByte, iVal);
  76300. vdbePmaWriteBlob(p, aByte, nByte);
  76301. }
  76302. /*
  76303. ** Write the current contents of in-memory linked-list pList to a level-0
  76304. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  76305. ** successful, or an SQLite error code otherwise.
  76306. **
  76307. ** The format of a PMA is:
  76308. **
  76309. ** * A varint. This varint contains the total number of bytes of content
  76310. ** in the PMA (not including the varint itself).
  76311. **
  76312. ** * One or more records packed end-to-end in order of ascending keys.
  76313. ** Each record consists of a varint followed by a blob of data (the
  76314. ** key). The varint is the number of bytes in the blob of data.
  76315. */
  76316. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  76317. sqlite3 *db = pTask->pSorter->db;
  76318. int rc = SQLITE_OK; /* Return code */
  76319. PmaWriter writer; /* Object used to write to the file */
  76320. #ifdef SQLITE_DEBUG
  76321. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  76322. ** This is used by an assert() statement at the end of this function. */
  76323. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  76324. #endif
  76325. vdbeSorterWorkDebug(pTask, "enter");
  76326. memset(&writer, 0, sizeof(PmaWriter));
  76327. assert( pList->szPMA>0 );
  76328. /* If the first temporary PMA file has not been opened, open it now. */
  76329. if( pTask->file.pFd==0 ){
  76330. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  76331. assert( rc!=SQLITE_OK || pTask->file.pFd );
  76332. assert( pTask->file.iEof==0 );
  76333. assert( pTask->nPMA==0 );
  76334. }
  76335. /* Try to get the file to memory map */
  76336. if( rc==SQLITE_OK ){
  76337. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  76338. }
  76339. /* Sort the list */
  76340. if( rc==SQLITE_OK ){
  76341. rc = vdbeSorterSort(pTask, pList);
  76342. }
  76343. if( rc==SQLITE_OK ){
  76344. SorterRecord *p;
  76345. SorterRecord *pNext = 0;
  76346. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  76347. pTask->file.iEof);
  76348. pTask->nPMA++;
  76349. vdbePmaWriteVarint(&writer, pList->szPMA);
  76350. for(p=pList->pList; p; p=pNext){
  76351. pNext = p->u.pNext;
  76352. vdbePmaWriteVarint(&writer, p->nVal);
  76353. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  76354. if( pList->aMemory==0 ) sqlite3_free(p);
  76355. }
  76356. pList->pList = p;
  76357. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  76358. }
  76359. vdbeSorterWorkDebug(pTask, "exit");
  76360. assert( rc!=SQLITE_OK || pList->pList==0 );
  76361. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  76362. return rc;
  76363. }
  76364. /*
  76365. ** Advance the MergeEngine to its next entry.
  76366. ** Set *pbEof to true there is no next entry because
  76367. ** the MergeEngine has reached the end of all its inputs.
  76368. **
  76369. ** Return SQLITE_OK if successful or an error code if an error occurs.
  76370. */
  76371. static int vdbeMergeEngineStep(
  76372. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  76373. int *pbEof /* Set TRUE at EOF. Set false for more content */
  76374. ){
  76375. int rc;
  76376. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  76377. SortSubtask *pTask = pMerger->pTask;
  76378. /* Advance the current PmaReader */
  76379. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  76380. /* Update contents of aTree[] */
  76381. if( rc==SQLITE_OK ){
  76382. int i; /* Index of aTree[] to recalculate */
  76383. PmaReader *pReadr1; /* First PmaReader to compare */
  76384. PmaReader *pReadr2; /* Second PmaReader to compare */
  76385. int bCached = 0;
  76386. /* Find the first two PmaReaders to compare. The one that was just
  76387. ** advanced (iPrev) and the one next to it in the array. */
  76388. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  76389. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  76390. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  76391. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  76392. int iRes;
  76393. if( pReadr1->pFd==0 ){
  76394. iRes = +1;
  76395. }else if( pReadr2->pFd==0 ){
  76396. iRes = -1;
  76397. }else{
  76398. iRes = pTask->xCompare(pTask, &bCached,
  76399. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  76400. );
  76401. }
  76402. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  76403. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  76404. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  76405. ** pKey2 to point to the record belonging to pReadr2.
  76406. **
  76407. ** Alternatively, if pReadr2 contains the smaller of the two values,
  76408. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  76409. ** was actually called above, then pTask->pUnpacked now contains
  76410. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  76411. ** vdbeSorterCompare() from decoding pReadr2 again.
  76412. **
  76413. ** If the two values were equal, then the value from the oldest
  76414. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  76415. ** is sorted from oldest to newest, so pReadr1 contains older values
  76416. ** than pReadr2 iff (pReadr1<pReadr2). */
  76417. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  76418. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  76419. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  76420. bCached = 0;
  76421. }else{
  76422. if( pReadr1->pFd ) bCached = 0;
  76423. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  76424. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  76425. }
  76426. }
  76427. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  76428. }
  76429. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  76430. }
  76431. #if SQLITE_MAX_WORKER_THREADS>0
  76432. /*
  76433. ** The main routine for background threads that write level-0 PMAs.
  76434. */
  76435. static void *vdbeSorterFlushThread(void *pCtx){
  76436. SortSubtask *pTask = (SortSubtask*)pCtx;
  76437. int rc; /* Return code */
  76438. assert( pTask->bDone==0 );
  76439. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  76440. pTask->bDone = 1;
  76441. return SQLITE_INT_TO_PTR(rc);
  76442. }
  76443. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  76444. /*
  76445. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  76446. ** using a background thread.
  76447. */
  76448. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  76449. #if SQLITE_MAX_WORKER_THREADS==0
  76450. pSorter->bUsePMA = 1;
  76451. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  76452. #else
  76453. int rc = SQLITE_OK;
  76454. int i;
  76455. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  76456. int nWorker = (pSorter->nTask-1);
  76457. /* Set the flag to indicate that at least one PMA has been written.
  76458. ** Or will be, anyhow. */
  76459. pSorter->bUsePMA = 1;
  76460. /* Select a sub-task to sort and flush the current list of in-memory
  76461. ** records to disk. If the sorter is running in multi-threaded mode,
  76462. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  76463. ** the background thread from a sub-tasks previous turn is still running,
  76464. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  76465. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  76466. ** sub-tasks are prefered as they use background threads - the final
  76467. ** sub-task uses the main thread. */
  76468. for(i=0; i<nWorker; i++){
  76469. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  76470. pTask = &pSorter->aTask[iTest];
  76471. if( pTask->bDone ){
  76472. rc = vdbeSorterJoinThread(pTask);
  76473. }
  76474. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  76475. }
  76476. if( rc==SQLITE_OK ){
  76477. if( i==nWorker ){
  76478. /* Use the foreground thread for this operation */
  76479. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  76480. }else{
  76481. /* Launch a background thread for this operation */
  76482. u8 *aMem = pTask->list.aMemory;
  76483. void *pCtx = (void*)pTask;
  76484. assert( pTask->pThread==0 && pTask->bDone==0 );
  76485. assert( pTask->list.pList==0 );
  76486. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  76487. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  76488. pTask->list = pSorter->list;
  76489. pSorter->list.pList = 0;
  76490. pSorter->list.szPMA = 0;
  76491. if( aMem ){
  76492. pSorter->list.aMemory = aMem;
  76493. pSorter->nMemory = sqlite3MallocSize(aMem);
  76494. }else if( pSorter->list.aMemory ){
  76495. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  76496. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  76497. }
  76498. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  76499. }
  76500. }
  76501. return rc;
  76502. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  76503. }
  76504. /*
  76505. ** Add a record to the sorter.
  76506. */
  76507. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  76508. const VdbeCursor *pCsr, /* Sorter cursor */
  76509. Mem *pVal /* Memory cell containing record */
  76510. ){
  76511. VdbeSorter *pSorter = pCsr->pSorter;
  76512. int rc = SQLITE_OK; /* Return Code */
  76513. SorterRecord *pNew; /* New list element */
  76514. int bFlush; /* True to flush contents of memory to PMA */
  76515. int nReq; /* Bytes of memory required */
  76516. int nPMA; /* Bytes of PMA space required */
  76517. int t; /* serial type of first record field */
  76518. getVarint32((const u8*)&pVal->z[1], t);
  76519. if( t>0 && t<10 && t!=7 ){
  76520. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  76521. }else if( t>10 && (t & 0x01) ){
  76522. pSorter->typeMask &= SORTER_TYPE_TEXT;
  76523. }else{
  76524. pSorter->typeMask = 0;
  76525. }
  76526. assert( pSorter );
  76527. /* Figure out whether or not the current contents of memory should be
  76528. ** flushed to a PMA before continuing. If so, do so.
  76529. **
  76530. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  76531. ** flush the contents of memory to a new PMA if (a) at least one value is
  76532. ** already in memory and (b) the new value will not fit in memory.
  76533. **
  76534. ** Or, if using separate allocations for each record, flush the contents
  76535. ** of memory to a PMA if either of the following are true:
  76536. **
  76537. ** * The total memory allocated for the in-memory list is greater
  76538. ** than (page-size * cache-size), or
  76539. **
  76540. ** * The total memory allocated for the in-memory list is greater
  76541. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  76542. */
  76543. nReq = pVal->n + sizeof(SorterRecord);
  76544. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  76545. if( pSorter->mxPmaSize ){
  76546. if( pSorter->list.aMemory ){
  76547. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  76548. }else{
  76549. bFlush = (
  76550. (pSorter->list.szPMA > pSorter->mxPmaSize)
  76551. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  76552. );
  76553. }
  76554. if( bFlush ){
  76555. rc = vdbeSorterFlushPMA(pSorter);
  76556. pSorter->list.szPMA = 0;
  76557. pSorter->iMemory = 0;
  76558. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  76559. }
  76560. }
  76561. pSorter->list.szPMA += nPMA;
  76562. if( nPMA>pSorter->mxKeysize ){
  76563. pSorter->mxKeysize = nPMA;
  76564. }
  76565. if( pSorter->list.aMemory ){
  76566. int nMin = pSorter->iMemory + nReq;
  76567. if( nMin>pSorter->nMemory ){
  76568. u8 *aNew;
  76569. int nNew = pSorter->nMemory * 2;
  76570. while( nNew < nMin ) nNew = nNew*2;
  76571. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  76572. if( nNew < nMin ) nNew = nMin;
  76573. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  76574. if( !aNew ) return SQLITE_NOMEM;
  76575. pSorter->list.pList = (SorterRecord*)(
  76576. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  76577. );
  76578. pSorter->list.aMemory = aNew;
  76579. pSorter->nMemory = nNew;
  76580. }
  76581. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  76582. pSorter->iMemory += ROUND8(nReq);
  76583. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  76584. }else{
  76585. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  76586. if( pNew==0 ){
  76587. return SQLITE_NOMEM;
  76588. }
  76589. pNew->u.pNext = pSorter->list.pList;
  76590. }
  76591. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  76592. pNew->nVal = pVal->n;
  76593. pSorter->list.pList = pNew;
  76594. return rc;
  76595. }
  76596. /*
  76597. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  76598. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  76599. ** except that the number-of-bytes varint is omitted from the start.
  76600. */
  76601. static int vdbeIncrPopulate(IncrMerger *pIncr){
  76602. int rc = SQLITE_OK;
  76603. int rc2;
  76604. i64 iStart = pIncr->iStartOff;
  76605. SorterFile *pOut = &pIncr->aFile[1];
  76606. SortSubtask *pTask = pIncr->pTask;
  76607. MergeEngine *pMerger = pIncr->pMerger;
  76608. PmaWriter writer;
  76609. assert( pIncr->bEof==0 );
  76610. vdbeSorterPopulateDebug(pTask, "enter");
  76611. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  76612. while( rc==SQLITE_OK ){
  76613. int dummy;
  76614. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  76615. int nKey = pReader->nKey;
  76616. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  76617. /* Check if the output file is full or if the input has been exhausted.
  76618. ** In either case exit the loop. */
  76619. if( pReader->pFd==0 ) break;
  76620. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  76621. /* Write the next key to the output. */
  76622. vdbePmaWriteVarint(&writer, nKey);
  76623. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  76624. assert( pIncr->pMerger->pTask==pTask );
  76625. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  76626. }
  76627. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  76628. if( rc==SQLITE_OK ) rc = rc2;
  76629. vdbeSorterPopulateDebug(pTask, "exit");
  76630. return rc;
  76631. }
  76632. #if SQLITE_MAX_WORKER_THREADS>0
  76633. /*
  76634. ** The main routine for background threads that populate aFile[1] of
  76635. ** multi-threaded IncrMerger objects.
  76636. */
  76637. static void *vdbeIncrPopulateThread(void *pCtx){
  76638. IncrMerger *pIncr = (IncrMerger*)pCtx;
  76639. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  76640. pIncr->pTask->bDone = 1;
  76641. return pRet;
  76642. }
  76643. /*
  76644. ** Launch a background thread to populate aFile[1] of pIncr.
  76645. */
  76646. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  76647. void *p = (void*)pIncr;
  76648. assert( pIncr->bUseThread );
  76649. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  76650. }
  76651. #endif
  76652. /*
  76653. ** This function is called when the PmaReader corresponding to pIncr has
  76654. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  76655. ** aFile[0] such that the PmaReader should start rereading it from the
  76656. ** beginning.
  76657. **
  76658. ** For single-threaded objects, this is accomplished by literally reading
  76659. ** keys from pIncr->pMerger and repopulating aFile[0].
  76660. **
  76661. ** For multi-threaded objects, all that is required is to wait until the
  76662. ** background thread is finished (if it is not already) and then swap
  76663. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  76664. ** been exhausted, this function also launches a new background thread
  76665. ** to populate the new aFile[1].
  76666. **
  76667. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  76668. */
  76669. static int vdbeIncrSwap(IncrMerger *pIncr){
  76670. int rc = SQLITE_OK;
  76671. #if SQLITE_MAX_WORKER_THREADS>0
  76672. if( pIncr->bUseThread ){
  76673. rc = vdbeSorterJoinThread(pIncr->pTask);
  76674. if( rc==SQLITE_OK ){
  76675. SorterFile f0 = pIncr->aFile[0];
  76676. pIncr->aFile[0] = pIncr->aFile[1];
  76677. pIncr->aFile[1] = f0;
  76678. }
  76679. if( rc==SQLITE_OK ){
  76680. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  76681. pIncr->bEof = 1;
  76682. }else{
  76683. rc = vdbeIncrBgPopulate(pIncr);
  76684. }
  76685. }
  76686. }else
  76687. #endif
  76688. {
  76689. rc = vdbeIncrPopulate(pIncr);
  76690. pIncr->aFile[0] = pIncr->aFile[1];
  76691. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  76692. pIncr->bEof = 1;
  76693. }
  76694. }
  76695. return rc;
  76696. }
  76697. /*
  76698. ** Allocate and return a new IncrMerger object to read data from pMerger.
  76699. **
  76700. ** If an OOM condition is encountered, return NULL. In this case free the
  76701. ** pMerger argument before returning.
  76702. */
  76703. static int vdbeIncrMergerNew(
  76704. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  76705. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  76706. IncrMerger **ppOut /* Write the new IncrMerger here */
  76707. ){
  76708. int rc = SQLITE_OK;
  76709. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  76710. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  76711. if( pIncr ){
  76712. pIncr->pMerger = pMerger;
  76713. pIncr->pTask = pTask;
  76714. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  76715. pTask->file2.iEof += pIncr->mxSz;
  76716. }else{
  76717. vdbeMergeEngineFree(pMerger);
  76718. rc = SQLITE_NOMEM;
  76719. }
  76720. return rc;
  76721. }
  76722. #if SQLITE_MAX_WORKER_THREADS>0
  76723. /*
  76724. ** Set the "use-threads" flag on object pIncr.
  76725. */
  76726. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  76727. pIncr->bUseThread = 1;
  76728. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  76729. }
  76730. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  76731. /*
  76732. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  76733. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  76734. ** are advanced. This routine merely does the comparison.
  76735. */
  76736. static void vdbeMergeEngineCompare(
  76737. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  76738. int iOut /* Store the result in pMerger->aTree[iOut] */
  76739. ){
  76740. int i1;
  76741. int i2;
  76742. int iRes;
  76743. PmaReader *p1;
  76744. PmaReader *p2;
  76745. assert( iOut<pMerger->nTree && iOut>0 );
  76746. if( iOut>=(pMerger->nTree/2) ){
  76747. i1 = (iOut - pMerger->nTree/2) * 2;
  76748. i2 = i1 + 1;
  76749. }else{
  76750. i1 = pMerger->aTree[iOut*2];
  76751. i2 = pMerger->aTree[iOut*2+1];
  76752. }
  76753. p1 = &pMerger->aReadr[i1];
  76754. p2 = &pMerger->aReadr[i2];
  76755. if( p1->pFd==0 ){
  76756. iRes = i2;
  76757. }else if( p2->pFd==0 ){
  76758. iRes = i1;
  76759. }else{
  76760. SortSubtask *pTask = pMerger->pTask;
  76761. int bCached = 0;
  76762. int res;
  76763. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  76764. res = pTask->xCompare(
  76765. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  76766. );
  76767. if( res<=0 ){
  76768. iRes = i1;
  76769. }else{
  76770. iRes = i2;
  76771. }
  76772. }
  76773. pMerger->aTree[iOut] = iRes;
  76774. }
  76775. /*
  76776. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  76777. ** and vdbePmaReaderIncrMergeInit().
  76778. **
  76779. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  76780. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  76781. ** when there exists one or more separate worker threads.
  76782. */
  76783. #define INCRINIT_NORMAL 0
  76784. #define INCRINIT_TASK 1
  76785. #define INCRINIT_ROOT 2
  76786. /*
  76787. ** Forward reference required as the vdbeIncrMergeInit() and
  76788. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  76789. ** building a merge tree.
  76790. */
  76791. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  76792. /*
  76793. ** Initialize the MergeEngine object passed as the second argument. Once this
  76794. ** function returns, the first key of merged data may be read from the
  76795. ** MergeEngine object in the usual fashion.
  76796. **
  76797. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  76798. ** objects attached to the PmaReader objects that the merger reads from have
  76799. ** already been populated, but that they have not yet populated aFile[0] and
  76800. ** set the PmaReader objects up to read from it. In this case all that is
  76801. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  76802. ** its first key.
  76803. **
  76804. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  76805. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  76806. ** to pMerger.
  76807. **
  76808. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76809. */
  76810. static int vdbeMergeEngineInit(
  76811. SortSubtask *pTask, /* Thread that will run pMerger */
  76812. MergeEngine *pMerger, /* MergeEngine to initialize */
  76813. int eMode /* One of the INCRINIT_XXX constants */
  76814. ){
  76815. int rc = SQLITE_OK; /* Return code */
  76816. int i; /* For looping over PmaReader objects */
  76817. int nTree = pMerger->nTree;
  76818. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  76819. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  76820. /* Verify that the MergeEngine is assigned to a single thread */
  76821. assert( pMerger->pTask==0 );
  76822. pMerger->pTask = pTask;
  76823. for(i=0; i<nTree; i++){
  76824. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  76825. /* PmaReaders should be normally initialized in order, as if they are
  76826. ** reading from the same temp file this makes for more linear file IO.
  76827. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  76828. ** in use it will block the vdbePmaReaderNext() call while it uses
  76829. ** the main thread to fill its buffer. So calling PmaReaderNext()
  76830. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  76831. ** better advantage of multi-processor hardware. */
  76832. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  76833. }else{
  76834. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  76835. }
  76836. if( rc!=SQLITE_OK ) return rc;
  76837. }
  76838. for(i=pMerger->nTree-1; i>0; i--){
  76839. vdbeMergeEngineCompare(pMerger, i);
  76840. }
  76841. return pTask->pUnpacked->errCode;
  76842. }
  76843. /*
  76844. ** The PmaReader passed as the first argument is guaranteed to be an
  76845. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  76846. ** and/or initialize the temp file related fields of the IncrMerge
  76847. ** object at (pReadr->pIncr).
  76848. **
  76849. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  76850. ** in the sub-tree headed by pReadr are also initialized. Data is then
  76851. ** loaded into the buffers belonging to pReadr and it is set to point to
  76852. ** the first key in its range.
  76853. **
  76854. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  76855. ** to be a multi-threaded PmaReader and this function is being called in a
  76856. ** background thread. In this case all PmaReaders in the sub-tree are
  76857. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  76858. ** pReadr is populated. However, pReadr itself is not set up to point
  76859. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  76860. ** that.
  76861. **
  76862. ** The reason this function does not call vdbePmaReaderNext() immediately
  76863. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  76864. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  76865. ** this entire function is being run by thread (pTask->thread), that will
  76866. ** lead to the current background thread attempting to join itself.
  76867. **
  76868. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  76869. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  76870. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  76871. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  76872. ** the current PmaReader set to point to the first key in its range.
  76873. **
  76874. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76875. */
  76876. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  76877. int rc = SQLITE_OK;
  76878. IncrMerger *pIncr = pReadr->pIncr;
  76879. SortSubtask *pTask = pIncr->pTask;
  76880. sqlite3 *db = pTask->pSorter->db;
  76881. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  76882. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  76883. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  76884. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  76885. ** requires two temp files to itself, whereas a single-threaded object
  76886. ** only requires a region of pTask->file2. */
  76887. if( rc==SQLITE_OK ){
  76888. int mxSz = pIncr->mxSz;
  76889. #if SQLITE_MAX_WORKER_THREADS>0
  76890. if( pIncr->bUseThread ){
  76891. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  76892. if( rc==SQLITE_OK ){
  76893. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  76894. }
  76895. }else
  76896. #endif
  76897. /*if( !pIncr->bUseThread )*/{
  76898. if( pTask->file2.pFd==0 ){
  76899. assert( pTask->file2.iEof>0 );
  76900. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  76901. pTask->file2.iEof = 0;
  76902. }
  76903. if( rc==SQLITE_OK ){
  76904. pIncr->aFile[1].pFd = pTask->file2.pFd;
  76905. pIncr->iStartOff = pTask->file2.iEof;
  76906. pTask->file2.iEof += mxSz;
  76907. }
  76908. }
  76909. }
  76910. #if SQLITE_MAX_WORKER_THREADS>0
  76911. if( rc==SQLITE_OK && pIncr->bUseThread ){
  76912. /* Use the current thread to populate aFile[1], even though this
  76913. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  76914. ** then this function is already running in background thread
  76915. ** pIncr->pTask->thread.
  76916. **
  76917. ** If this is the INCRINIT_ROOT object, then it is running in the
  76918. ** main VDBE thread. But that is Ok, as that thread cannot return
  76919. ** control to the VDBE or proceed with anything useful until the
  76920. ** first results are ready from this merger object anyway.
  76921. */
  76922. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  76923. rc = vdbeIncrPopulate(pIncr);
  76924. }
  76925. #endif
  76926. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  76927. rc = vdbePmaReaderNext(pReadr);
  76928. }
  76929. return rc;
  76930. }
  76931. #if SQLITE_MAX_WORKER_THREADS>0
  76932. /*
  76933. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  76934. ** background threads.
  76935. */
  76936. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  76937. PmaReader *pReader = (PmaReader*)pCtx;
  76938. void *pRet = SQLITE_INT_TO_PTR(
  76939. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  76940. );
  76941. pReader->pIncr->pTask->bDone = 1;
  76942. return pRet;
  76943. }
  76944. #endif
  76945. /*
  76946. ** If the PmaReader passed as the first argument is not an incremental-reader
  76947. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  76948. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  76949. ** this routine to initialize the incremental merge.
  76950. **
  76951. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  76952. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  76953. ** Or, if the IncrMerger is single threaded, the same function is called
  76954. ** using the current thread.
  76955. */
  76956. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  76957. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  76958. int rc = SQLITE_OK; /* Return code */
  76959. if( pIncr ){
  76960. #if SQLITE_MAX_WORKER_THREADS>0
  76961. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  76962. if( pIncr->bUseThread ){
  76963. void *pCtx = (void*)pReadr;
  76964. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  76965. }else
  76966. #endif
  76967. {
  76968. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  76969. }
  76970. }
  76971. return rc;
  76972. }
  76973. /*
  76974. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  76975. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  76976. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  76977. ** to NULL and return an SQLite error code.
  76978. **
  76979. ** When this function is called, *piOffset is set to the offset of the
  76980. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  76981. ** set to the offset immediately following the last byte of the last
  76982. ** PMA before returning. If an error does occur, then the final value of
  76983. ** *piOffset is undefined.
  76984. */
  76985. static int vdbeMergeEngineLevel0(
  76986. SortSubtask *pTask, /* Sorter task to read from */
  76987. int nPMA, /* Number of PMAs to read */
  76988. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  76989. MergeEngine **ppOut /* OUT: New merge-engine */
  76990. ){
  76991. MergeEngine *pNew; /* Merge engine to return */
  76992. i64 iOff = *piOffset;
  76993. int i;
  76994. int rc = SQLITE_OK;
  76995. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  76996. if( pNew==0 ) rc = SQLITE_NOMEM;
  76997. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  76998. i64 nDummy;
  76999. PmaReader *pReadr = &pNew->aReadr[i];
  77000. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  77001. iOff = pReadr->iEof;
  77002. }
  77003. if( rc!=SQLITE_OK ){
  77004. vdbeMergeEngineFree(pNew);
  77005. *ppOut = 0;
  77006. }
  77007. *piOffset = iOff;
  77008. return rc;
  77009. }
  77010. /*
  77011. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  77012. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  77013. **
  77014. ** i.e.
  77015. **
  77016. ** nPMA<=16 -> TreeDepth() == 0
  77017. ** nPMA<=256 -> TreeDepth() == 1
  77018. ** nPMA<=65536 -> TreeDepth() == 2
  77019. */
  77020. static int vdbeSorterTreeDepth(int nPMA){
  77021. int nDepth = 0;
  77022. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  77023. while( nDiv < (i64)nPMA ){
  77024. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  77025. nDepth++;
  77026. }
  77027. return nDepth;
  77028. }
  77029. /*
  77030. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  77031. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  77032. ** tree, counting from zero. This function adds pLeaf to the tree.
  77033. **
  77034. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  77035. ** code is returned and pLeaf is freed.
  77036. */
  77037. static int vdbeSorterAddToTree(
  77038. SortSubtask *pTask, /* Task context */
  77039. int nDepth, /* Depth of tree according to TreeDepth() */
  77040. int iSeq, /* Sequence number of leaf within tree */
  77041. MergeEngine *pRoot, /* Root of tree */
  77042. MergeEngine *pLeaf /* Leaf to add to tree */
  77043. ){
  77044. int rc = SQLITE_OK;
  77045. int nDiv = 1;
  77046. int i;
  77047. MergeEngine *p = pRoot;
  77048. IncrMerger *pIncr;
  77049. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  77050. for(i=1; i<nDepth; i++){
  77051. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  77052. }
  77053. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  77054. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  77055. PmaReader *pReadr = &p->aReadr[iIter];
  77056. if( pReadr->pIncr==0 ){
  77057. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  77058. if( pNew==0 ){
  77059. rc = SQLITE_NOMEM;
  77060. }else{
  77061. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  77062. }
  77063. }
  77064. if( rc==SQLITE_OK ){
  77065. p = pReadr->pIncr->pMerger;
  77066. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  77067. }
  77068. }
  77069. if( rc==SQLITE_OK ){
  77070. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  77071. }else{
  77072. vdbeIncrFree(pIncr);
  77073. }
  77074. return rc;
  77075. }
  77076. /*
  77077. ** This function is called as part of a SorterRewind() operation on a sorter
  77078. ** that has already written two or more level-0 PMAs to one or more temp
  77079. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  77080. ** can be used to incrementally merge all PMAs on disk.
  77081. **
  77082. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  77083. ** MergeEngine object at the root of the tree before returning. Or, if an
  77084. ** error occurs, an SQLite error code is returned and the final value
  77085. ** of *ppOut is undefined.
  77086. */
  77087. static int vdbeSorterMergeTreeBuild(
  77088. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  77089. MergeEngine **ppOut /* Write the MergeEngine here */
  77090. ){
  77091. MergeEngine *pMain = 0;
  77092. int rc = SQLITE_OK;
  77093. int iTask;
  77094. #if SQLITE_MAX_WORKER_THREADS>0
  77095. /* If the sorter uses more than one task, then create the top-level
  77096. ** MergeEngine here. This MergeEngine will read data from exactly
  77097. ** one PmaReader per sub-task. */
  77098. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  77099. if( pSorter->nTask>1 ){
  77100. pMain = vdbeMergeEngineNew(pSorter->nTask);
  77101. if( pMain==0 ) rc = SQLITE_NOMEM;
  77102. }
  77103. #endif
  77104. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  77105. SortSubtask *pTask = &pSorter->aTask[iTask];
  77106. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  77107. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  77108. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  77109. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  77110. i64 iReadOff = 0;
  77111. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  77112. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  77113. }else{
  77114. int i;
  77115. int iSeq = 0;
  77116. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  77117. if( pRoot==0 ) rc = SQLITE_NOMEM;
  77118. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  77119. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  77120. int nReader; /* Number of level-0 PMAs to merge */
  77121. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  77122. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  77123. if( rc==SQLITE_OK ){
  77124. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  77125. }
  77126. }
  77127. }
  77128. if( rc==SQLITE_OK ){
  77129. #if SQLITE_MAX_WORKER_THREADS>0
  77130. if( pMain!=0 ){
  77131. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  77132. }else
  77133. #endif
  77134. {
  77135. assert( pMain==0 );
  77136. pMain = pRoot;
  77137. }
  77138. }else{
  77139. vdbeMergeEngineFree(pRoot);
  77140. }
  77141. }
  77142. }
  77143. if( rc!=SQLITE_OK ){
  77144. vdbeMergeEngineFree(pMain);
  77145. pMain = 0;
  77146. }
  77147. *ppOut = pMain;
  77148. return rc;
  77149. }
  77150. /*
  77151. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  77152. ** on a sorter that has written two or more PMAs to temporary files. It sets
  77153. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  77154. ** (for multi-threaded sorters) so that it can be used to iterate through
  77155. ** all records stored in the sorter.
  77156. **
  77157. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  77158. */
  77159. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  77160. int rc; /* Return code */
  77161. SortSubtask *pTask0 = &pSorter->aTask[0];
  77162. MergeEngine *pMain = 0;
  77163. #if SQLITE_MAX_WORKER_THREADS
  77164. sqlite3 *db = pTask0->pSorter->db;
  77165. int i;
  77166. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  77167. for(i=0; i<pSorter->nTask; i++){
  77168. pSorter->aTask[i].xCompare = xCompare;
  77169. }
  77170. #endif
  77171. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  77172. if( rc==SQLITE_OK ){
  77173. #if SQLITE_MAX_WORKER_THREADS
  77174. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  77175. if( pSorter->bUseThreads ){
  77176. int iTask;
  77177. PmaReader *pReadr = 0;
  77178. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  77179. rc = vdbeSortAllocUnpacked(pLast);
  77180. if( rc==SQLITE_OK ){
  77181. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  77182. pSorter->pReader = pReadr;
  77183. if( pReadr==0 ) rc = SQLITE_NOMEM;
  77184. }
  77185. if( rc==SQLITE_OK ){
  77186. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  77187. if( rc==SQLITE_OK ){
  77188. vdbeIncrMergerSetThreads(pReadr->pIncr);
  77189. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  77190. IncrMerger *pIncr;
  77191. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  77192. vdbeIncrMergerSetThreads(pIncr);
  77193. assert( pIncr->pTask!=pLast );
  77194. }
  77195. }
  77196. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  77197. /* Check that:
  77198. **
  77199. ** a) The incremental merge object is configured to use the
  77200. ** right task, and
  77201. ** b) If it is using task (nTask-1), it is configured to run
  77202. ** in single-threaded mode. This is important, as the
  77203. ** root merge (INCRINIT_ROOT) will be using the same task
  77204. ** object.
  77205. */
  77206. PmaReader *p = &pMain->aReadr[iTask];
  77207. assert( p->pIncr==0 || (
  77208. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  77209. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  77210. ));
  77211. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  77212. }
  77213. }
  77214. pMain = 0;
  77215. }
  77216. if( rc==SQLITE_OK ){
  77217. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  77218. }
  77219. }else
  77220. #endif
  77221. {
  77222. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  77223. pSorter->pMerger = pMain;
  77224. pMain = 0;
  77225. }
  77226. }
  77227. if( rc!=SQLITE_OK ){
  77228. vdbeMergeEngineFree(pMain);
  77229. }
  77230. return rc;
  77231. }
  77232. /*
  77233. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  77234. ** this function is called to prepare for iterating through the records
  77235. ** in sorted order.
  77236. */
  77237. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  77238. VdbeSorter *pSorter = pCsr->pSorter;
  77239. int rc = SQLITE_OK; /* Return code */
  77240. assert( pSorter );
  77241. /* If no data has been written to disk, then do not do so now. Instead,
  77242. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  77243. ** from the in-memory list. */
  77244. if( pSorter->bUsePMA==0 ){
  77245. if( pSorter->list.pList ){
  77246. *pbEof = 0;
  77247. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  77248. }else{
  77249. *pbEof = 1;
  77250. }
  77251. return rc;
  77252. }
  77253. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  77254. ** function flushes the contents of memory to disk, it immediately always
  77255. ** creates a new list consisting of a single key immediately afterwards.
  77256. ** So the list is never empty at this point. */
  77257. assert( pSorter->list.pList );
  77258. rc = vdbeSorterFlushPMA(pSorter);
  77259. /* Join all threads */
  77260. rc = vdbeSorterJoinAll(pSorter, rc);
  77261. vdbeSorterRewindDebug("rewind");
  77262. /* Assuming no errors have occurred, set up a merger structure to
  77263. ** incrementally read and merge all remaining PMAs. */
  77264. assert( pSorter->pReader==0 );
  77265. if( rc==SQLITE_OK ){
  77266. rc = vdbeSorterSetupMerge(pSorter);
  77267. *pbEof = 0;
  77268. }
  77269. vdbeSorterRewindDebug("rewinddone");
  77270. return rc;
  77271. }
  77272. /*
  77273. ** Advance to the next element in the sorter.
  77274. */
  77275. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  77276. VdbeSorter *pSorter = pCsr->pSorter;
  77277. int rc; /* Return code */
  77278. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  77279. if( pSorter->bUsePMA ){
  77280. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  77281. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  77282. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  77283. #if SQLITE_MAX_WORKER_THREADS>0
  77284. if( pSorter->bUseThreads ){
  77285. rc = vdbePmaReaderNext(pSorter->pReader);
  77286. *pbEof = (pSorter->pReader->pFd==0);
  77287. }else
  77288. #endif
  77289. /*if( !pSorter->bUseThreads )*/ {
  77290. assert( pSorter->pMerger!=0 );
  77291. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  77292. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  77293. }
  77294. }else{
  77295. SorterRecord *pFree = pSorter->list.pList;
  77296. pSorter->list.pList = pFree->u.pNext;
  77297. pFree->u.pNext = 0;
  77298. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  77299. *pbEof = !pSorter->list.pList;
  77300. rc = SQLITE_OK;
  77301. }
  77302. return rc;
  77303. }
  77304. /*
  77305. ** Return a pointer to a buffer owned by the sorter that contains the
  77306. ** current key.
  77307. */
  77308. static void *vdbeSorterRowkey(
  77309. const VdbeSorter *pSorter, /* Sorter object */
  77310. int *pnKey /* OUT: Size of current key in bytes */
  77311. ){
  77312. void *pKey;
  77313. if( pSorter->bUsePMA ){
  77314. PmaReader *pReader;
  77315. #if SQLITE_MAX_WORKER_THREADS>0
  77316. if( pSorter->bUseThreads ){
  77317. pReader = pSorter->pReader;
  77318. }else
  77319. #endif
  77320. /*if( !pSorter->bUseThreads )*/{
  77321. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  77322. }
  77323. *pnKey = pReader->nKey;
  77324. pKey = pReader->aKey;
  77325. }else{
  77326. *pnKey = pSorter->list.pList->nVal;
  77327. pKey = SRVAL(pSorter->list.pList);
  77328. }
  77329. return pKey;
  77330. }
  77331. /*
  77332. ** Copy the current sorter key into the memory cell pOut.
  77333. */
  77334. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  77335. VdbeSorter *pSorter = pCsr->pSorter;
  77336. void *pKey; int nKey; /* Sorter key to copy into pOut */
  77337. pKey = vdbeSorterRowkey(pSorter, &nKey);
  77338. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  77339. return SQLITE_NOMEM;
  77340. }
  77341. pOut->n = nKey;
  77342. MemSetTypeFlag(pOut, MEM_Blob);
  77343. memcpy(pOut->z, pKey, nKey);
  77344. return SQLITE_OK;
  77345. }
  77346. /*
  77347. ** Compare the key in memory cell pVal with the key that the sorter cursor
  77348. ** passed as the first argument currently points to. For the purposes of
  77349. ** the comparison, ignore the rowid field at the end of each record.
  77350. **
  77351. ** If the sorter cursor key contains any NULL values, consider it to be
  77352. ** less than pVal. Even if pVal also contains NULL values.
  77353. **
  77354. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  77355. ** Otherwise, set *pRes to a negative, zero or positive value if the
  77356. ** key in pVal is smaller than, equal to or larger than the current sorter
  77357. ** key.
  77358. **
  77359. ** This routine forms the core of the OP_SorterCompare opcode, which in
  77360. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  77361. */
  77362. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  77363. const VdbeCursor *pCsr, /* Sorter cursor */
  77364. Mem *pVal, /* Value to compare to current sorter key */
  77365. int nKeyCol, /* Compare this many columns */
  77366. int *pRes /* OUT: Result of comparison */
  77367. ){
  77368. VdbeSorter *pSorter = pCsr->pSorter;
  77369. UnpackedRecord *r2 = pSorter->pUnpacked;
  77370. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  77371. int i;
  77372. void *pKey; int nKey; /* Sorter key to compare pVal with */
  77373. if( r2==0 ){
  77374. char *p;
  77375. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  77376. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  77377. if( r2==0 ) return SQLITE_NOMEM;
  77378. r2->nField = nKeyCol;
  77379. }
  77380. assert( r2->nField==nKeyCol );
  77381. pKey = vdbeSorterRowkey(pSorter, &nKey);
  77382. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  77383. for(i=0; i<nKeyCol; i++){
  77384. if( r2->aMem[i].flags & MEM_Null ){
  77385. *pRes = -1;
  77386. return SQLITE_OK;
  77387. }
  77388. }
  77389. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  77390. return SQLITE_OK;
  77391. }
  77392. /************** End of vdbesort.c ********************************************/
  77393. /************** Begin file journal.c *****************************************/
  77394. /*
  77395. ** 2007 August 22
  77396. **
  77397. ** The author disclaims copyright to this source code. In place of
  77398. ** a legal notice, here is a blessing:
  77399. **
  77400. ** May you do good and not evil.
  77401. ** May you find forgiveness for yourself and forgive others.
  77402. ** May you share freely, never taking more than you give.
  77403. **
  77404. *************************************************************************
  77405. **
  77406. ** This file implements a special kind of sqlite3_file object used
  77407. ** by SQLite to create journal files if the atomic-write optimization
  77408. ** is enabled.
  77409. **
  77410. ** The distinctive characteristic of this sqlite3_file is that the
  77411. ** actual on disk file is created lazily. When the file is created,
  77412. ** the caller specifies a buffer size for an in-memory buffer to
  77413. ** be used to service read() and write() requests. The actual file
  77414. ** on disk is not created or populated until either:
  77415. **
  77416. ** 1) The in-memory representation grows too large for the allocated
  77417. ** buffer, or
  77418. ** 2) The sqlite3JournalCreate() function is called.
  77419. */
  77420. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  77421. /* #include "sqliteInt.h" */
  77422. /*
  77423. ** A JournalFile object is a subclass of sqlite3_file used by
  77424. ** as an open file handle for journal files.
  77425. */
  77426. struct JournalFile {
  77427. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  77428. int nBuf; /* Size of zBuf[] in bytes */
  77429. char *zBuf; /* Space to buffer journal writes */
  77430. int iSize; /* Amount of zBuf[] currently used */
  77431. int flags; /* xOpen flags */
  77432. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  77433. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  77434. const char *zJournal; /* Name of the journal file */
  77435. };
  77436. typedef struct JournalFile JournalFile;
  77437. /*
  77438. ** If it does not already exists, create and populate the on-disk file
  77439. ** for JournalFile p.
  77440. */
  77441. static int createFile(JournalFile *p){
  77442. int rc = SQLITE_OK;
  77443. if( !p->pReal ){
  77444. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  77445. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  77446. if( rc==SQLITE_OK ){
  77447. p->pReal = pReal;
  77448. if( p->iSize>0 ){
  77449. assert(p->iSize<=p->nBuf);
  77450. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  77451. }
  77452. if( rc!=SQLITE_OK ){
  77453. /* If an error occurred while writing to the file, close it before
  77454. ** returning. This way, SQLite uses the in-memory journal data to
  77455. ** roll back changes made to the internal page-cache before this
  77456. ** function was called. */
  77457. sqlite3OsClose(pReal);
  77458. p->pReal = 0;
  77459. }
  77460. }
  77461. }
  77462. return rc;
  77463. }
  77464. /*
  77465. ** Close the file.
  77466. */
  77467. static int jrnlClose(sqlite3_file *pJfd){
  77468. JournalFile *p = (JournalFile *)pJfd;
  77469. if( p->pReal ){
  77470. sqlite3OsClose(p->pReal);
  77471. }
  77472. sqlite3_free(p->zBuf);
  77473. return SQLITE_OK;
  77474. }
  77475. /*
  77476. ** Read data from the file.
  77477. */
  77478. static int jrnlRead(
  77479. sqlite3_file *pJfd, /* The journal file from which to read */
  77480. void *zBuf, /* Put the results here */
  77481. int iAmt, /* Number of bytes to read */
  77482. sqlite_int64 iOfst /* Begin reading at this offset */
  77483. ){
  77484. int rc = SQLITE_OK;
  77485. JournalFile *p = (JournalFile *)pJfd;
  77486. if( p->pReal ){
  77487. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  77488. }else if( (iAmt+iOfst)>p->iSize ){
  77489. rc = SQLITE_IOERR_SHORT_READ;
  77490. }else{
  77491. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  77492. }
  77493. return rc;
  77494. }
  77495. /*
  77496. ** Write data to the file.
  77497. */
  77498. static int jrnlWrite(
  77499. sqlite3_file *pJfd, /* The journal file into which to write */
  77500. const void *zBuf, /* Take data to be written from here */
  77501. int iAmt, /* Number of bytes to write */
  77502. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  77503. ){
  77504. int rc = SQLITE_OK;
  77505. JournalFile *p = (JournalFile *)pJfd;
  77506. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  77507. rc = createFile(p);
  77508. }
  77509. if( rc==SQLITE_OK ){
  77510. if( p->pReal ){
  77511. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  77512. }else{
  77513. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  77514. if( p->iSize<(iOfst+iAmt) ){
  77515. p->iSize = (iOfst+iAmt);
  77516. }
  77517. }
  77518. }
  77519. return rc;
  77520. }
  77521. /*
  77522. ** Truncate the file.
  77523. */
  77524. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  77525. int rc = SQLITE_OK;
  77526. JournalFile *p = (JournalFile *)pJfd;
  77527. if( p->pReal ){
  77528. rc = sqlite3OsTruncate(p->pReal, size);
  77529. }else if( size<p->iSize ){
  77530. p->iSize = size;
  77531. }
  77532. return rc;
  77533. }
  77534. /*
  77535. ** Sync the file.
  77536. */
  77537. static int jrnlSync(sqlite3_file *pJfd, int flags){
  77538. int rc;
  77539. JournalFile *p = (JournalFile *)pJfd;
  77540. if( p->pReal ){
  77541. rc = sqlite3OsSync(p->pReal, flags);
  77542. }else{
  77543. rc = SQLITE_OK;
  77544. }
  77545. return rc;
  77546. }
  77547. /*
  77548. ** Query the size of the file in bytes.
  77549. */
  77550. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  77551. int rc = SQLITE_OK;
  77552. JournalFile *p = (JournalFile *)pJfd;
  77553. if( p->pReal ){
  77554. rc = sqlite3OsFileSize(p->pReal, pSize);
  77555. }else{
  77556. *pSize = (sqlite_int64) p->iSize;
  77557. }
  77558. return rc;
  77559. }
  77560. /*
  77561. ** Table of methods for JournalFile sqlite3_file object.
  77562. */
  77563. static struct sqlite3_io_methods JournalFileMethods = {
  77564. 1, /* iVersion */
  77565. jrnlClose, /* xClose */
  77566. jrnlRead, /* xRead */
  77567. jrnlWrite, /* xWrite */
  77568. jrnlTruncate, /* xTruncate */
  77569. jrnlSync, /* xSync */
  77570. jrnlFileSize, /* xFileSize */
  77571. 0, /* xLock */
  77572. 0, /* xUnlock */
  77573. 0, /* xCheckReservedLock */
  77574. 0, /* xFileControl */
  77575. 0, /* xSectorSize */
  77576. 0, /* xDeviceCharacteristics */
  77577. 0, /* xShmMap */
  77578. 0, /* xShmLock */
  77579. 0, /* xShmBarrier */
  77580. 0 /* xShmUnmap */
  77581. };
  77582. /*
  77583. ** Open a journal file.
  77584. */
  77585. SQLITE_PRIVATE int sqlite3JournalOpen(
  77586. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  77587. const char *zName, /* Name of the journal file */
  77588. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  77589. int flags, /* Opening flags */
  77590. int nBuf /* Bytes buffered before opening the file */
  77591. ){
  77592. JournalFile *p = (JournalFile *)pJfd;
  77593. memset(p, 0, sqlite3JournalSize(pVfs));
  77594. if( nBuf>0 ){
  77595. p->zBuf = sqlite3MallocZero(nBuf);
  77596. if( !p->zBuf ){
  77597. return SQLITE_NOMEM;
  77598. }
  77599. }else{
  77600. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  77601. }
  77602. p->pMethod = &JournalFileMethods;
  77603. p->nBuf = nBuf;
  77604. p->flags = flags;
  77605. p->zJournal = zName;
  77606. p->pVfs = pVfs;
  77607. return SQLITE_OK;
  77608. }
  77609. /*
  77610. ** If the argument p points to a JournalFile structure, and the underlying
  77611. ** file has not yet been created, create it now.
  77612. */
  77613. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  77614. if( p->pMethods!=&JournalFileMethods ){
  77615. return SQLITE_OK;
  77616. }
  77617. return createFile((JournalFile *)p);
  77618. }
  77619. /*
  77620. ** The file-handle passed as the only argument is guaranteed to be an open
  77621. ** file. It may or may not be of class JournalFile. If the file is a
  77622. ** JournalFile, and the underlying file on disk has not yet been opened,
  77623. ** return 0. Otherwise, return 1.
  77624. */
  77625. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  77626. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  77627. }
  77628. /*
  77629. ** Return the number of bytes required to store a JournalFile that uses vfs
  77630. ** pVfs to create the underlying on-disk files.
  77631. */
  77632. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  77633. return (pVfs->szOsFile+sizeof(JournalFile));
  77634. }
  77635. #endif
  77636. /************** End of journal.c *********************************************/
  77637. /************** Begin file memjournal.c **************************************/
  77638. /*
  77639. ** 2008 October 7
  77640. **
  77641. ** The author disclaims copyright to this source code. In place of
  77642. ** a legal notice, here is a blessing:
  77643. **
  77644. ** May you do good and not evil.
  77645. ** May you find forgiveness for yourself and forgive others.
  77646. ** May you share freely, never taking more than you give.
  77647. **
  77648. *************************************************************************
  77649. **
  77650. ** This file contains code use to implement an in-memory rollback journal.
  77651. ** The in-memory rollback journal is used to journal transactions for
  77652. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  77653. */
  77654. /* #include "sqliteInt.h" */
  77655. /* Forward references to internal structures */
  77656. typedef struct MemJournal MemJournal;
  77657. typedef struct FilePoint FilePoint;
  77658. typedef struct FileChunk FileChunk;
  77659. /* Space to hold the rollback journal is allocated in increments of
  77660. ** this many bytes.
  77661. **
  77662. ** The size chosen is a little less than a power of two. That way,
  77663. ** the FileChunk object will have a size that almost exactly fills
  77664. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  77665. ** memory allocators.
  77666. */
  77667. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  77668. /*
  77669. ** The rollback journal is composed of a linked list of these structures.
  77670. */
  77671. struct FileChunk {
  77672. FileChunk *pNext; /* Next chunk in the journal */
  77673. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  77674. };
  77675. /*
  77676. ** An instance of this object serves as a cursor into the rollback journal.
  77677. ** The cursor can be either for reading or writing.
  77678. */
  77679. struct FilePoint {
  77680. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  77681. FileChunk *pChunk; /* Specific chunk into which cursor points */
  77682. };
  77683. /*
  77684. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  77685. ** is an instance of this class.
  77686. */
  77687. struct MemJournal {
  77688. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  77689. FileChunk *pFirst; /* Head of in-memory chunk-list */
  77690. FilePoint endpoint; /* Pointer to the end of the file */
  77691. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  77692. };
  77693. /*
  77694. ** Read data from the in-memory journal file. This is the implementation
  77695. ** of the sqlite3_vfs.xRead method.
  77696. */
  77697. static int memjrnlRead(
  77698. sqlite3_file *pJfd, /* The journal file from which to read */
  77699. void *zBuf, /* Put the results here */
  77700. int iAmt, /* Number of bytes to read */
  77701. sqlite_int64 iOfst /* Begin reading at this offset */
  77702. ){
  77703. MemJournal *p = (MemJournal *)pJfd;
  77704. u8 *zOut = zBuf;
  77705. int nRead = iAmt;
  77706. int iChunkOffset;
  77707. FileChunk *pChunk;
  77708. /* SQLite never tries to read past the end of a rollback journal file */
  77709. assert( iOfst+iAmt<=p->endpoint.iOffset );
  77710. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  77711. sqlite3_int64 iOff = 0;
  77712. for(pChunk=p->pFirst;
  77713. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  77714. pChunk=pChunk->pNext
  77715. ){
  77716. iOff += JOURNAL_CHUNKSIZE;
  77717. }
  77718. }else{
  77719. pChunk = p->readpoint.pChunk;
  77720. }
  77721. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  77722. do {
  77723. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  77724. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  77725. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  77726. zOut += nCopy;
  77727. nRead -= iSpace;
  77728. iChunkOffset = 0;
  77729. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  77730. p->readpoint.iOffset = iOfst+iAmt;
  77731. p->readpoint.pChunk = pChunk;
  77732. return SQLITE_OK;
  77733. }
  77734. /*
  77735. ** Write data to the file.
  77736. */
  77737. static int memjrnlWrite(
  77738. sqlite3_file *pJfd, /* The journal file into which to write */
  77739. const void *zBuf, /* Take data to be written from here */
  77740. int iAmt, /* Number of bytes to write */
  77741. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  77742. ){
  77743. MemJournal *p = (MemJournal *)pJfd;
  77744. int nWrite = iAmt;
  77745. u8 *zWrite = (u8 *)zBuf;
  77746. /* An in-memory journal file should only ever be appended to. Random
  77747. ** access writes are not required by sqlite.
  77748. */
  77749. assert( iOfst==p->endpoint.iOffset );
  77750. UNUSED_PARAMETER(iOfst);
  77751. while( nWrite>0 ){
  77752. FileChunk *pChunk = p->endpoint.pChunk;
  77753. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  77754. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  77755. if( iChunkOffset==0 ){
  77756. /* New chunk is required to extend the file. */
  77757. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  77758. if( !pNew ){
  77759. return SQLITE_IOERR_NOMEM;
  77760. }
  77761. pNew->pNext = 0;
  77762. if( pChunk ){
  77763. assert( p->pFirst );
  77764. pChunk->pNext = pNew;
  77765. }else{
  77766. assert( !p->pFirst );
  77767. p->pFirst = pNew;
  77768. }
  77769. p->endpoint.pChunk = pNew;
  77770. }
  77771. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  77772. zWrite += iSpace;
  77773. nWrite -= iSpace;
  77774. p->endpoint.iOffset += iSpace;
  77775. }
  77776. return SQLITE_OK;
  77777. }
  77778. /*
  77779. ** Truncate the file.
  77780. */
  77781. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  77782. MemJournal *p = (MemJournal *)pJfd;
  77783. FileChunk *pChunk;
  77784. assert(size==0);
  77785. UNUSED_PARAMETER(size);
  77786. pChunk = p->pFirst;
  77787. while( pChunk ){
  77788. FileChunk *pTmp = pChunk;
  77789. pChunk = pChunk->pNext;
  77790. sqlite3_free(pTmp);
  77791. }
  77792. sqlite3MemJournalOpen(pJfd);
  77793. return SQLITE_OK;
  77794. }
  77795. /*
  77796. ** Close the file.
  77797. */
  77798. static int memjrnlClose(sqlite3_file *pJfd){
  77799. memjrnlTruncate(pJfd, 0);
  77800. return SQLITE_OK;
  77801. }
  77802. /*
  77803. ** Sync the file.
  77804. **
  77805. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  77806. ** is never called in a working implementation. This implementation
  77807. ** exists purely as a contingency, in case some malfunction in some other
  77808. ** part of SQLite causes Sync to be called by mistake.
  77809. */
  77810. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  77811. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  77812. return SQLITE_OK;
  77813. }
  77814. /*
  77815. ** Query the size of the file in bytes.
  77816. */
  77817. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  77818. MemJournal *p = (MemJournal *)pJfd;
  77819. *pSize = (sqlite_int64) p->endpoint.iOffset;
  77820. return SQLITE_OK;
  77821. }
  77822. /*
  77823. ** Table of methods for MemJournal sqlite3_file object.
  77824. */
  77825. static const struct sqlite3_io_methods MemJournalMethods = {
  77826. 1, /* iVersion */
  77827. memjrnlClose, /* xClose */
  77828. memjrnlRead, /* xRead */
  77829. memjrnlWrite, /* xWrite */
  77830. memjrnlTruncate, /* xTruncate */
  77831. memjrnlSync, /* xSync */
  77832. memjrnlFileSize, /* xFileSize */
  77833. 0, /* xLock */
  77834. 0, /* xUnlock */
  77835. 0, /* xCheckReservedLock */
  77836. 0, /* xFileControl */
  77837. 0, /* xSectorSize */
  77838. 0, /* xDeviceCharacteristics */
  77839. 0, /* xShmMap */
  77840. 0, /* xShmLock */
  77841. 0, /* xShmBarrier */
  77842. 0, /* xShmUnmap */
  77843. 0, /* xFetch */
  77844. 0 /* xUnfetch */
  77845. };
  77846. /*
  77847. ** Open a journal file.
  77848. */
  77849. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  77850. MemJournal *p = (MemJournal *)pJfd;
  77851. assert( EIGHT_BYTE_ALIGNMENT(p) );
  77852. memset(p, 0, sqlite3MemJournalSize());
  77853. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  77854. }
  77855. /*
  77856. ** Return true if the file-handle passed as an argument is
  77857. ** an in-memory journal
  77858. */
  77859. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  77860. return pJfd->pMethods==&MemJournalMethods;
  77861. }
  77862. /*
  77863. ** Return the number of bytes required to store a MemJournal file descriptor.
  77864. */
  77865. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  77866. return sizeof(MemJournal);
  77867. }
  77868. /************** End of memjournal.c ******************************************/
  77869. /************** Begin file walker.c ******************************************/
  77870. /*
  77871. ** 2008 August 16
  77872. **
  77873. ** The author disclaims copyright to this source code. In place of
  77874. ** a legal notice, here is a blessing:
  77875. **
  77876. ** May you do good and not evil.
  77877. ** May you find forgiveness for yourself and forgive others.
  77878. ** May you share freely, never taking more than you give.
  77879. **
  77880. *************************************************************************
  77881. ** This file contains routines used for walking the parser tree for
  77882. ** an SQL statement.
  77883. */
  77884. /* #include "sqliteInt.h" */
  77885. /* #include <stdlib.h> */
  77886. /* #include <string.h> */
  77887. /*
  77888. ** Walk an expression tree. Invoke the callback once for each node
  77889. ** of the expression, while descending. (In other words, the callback
  77890. ** is invoked before visiting children.)
  77891. **
  77892. ** The return value from the callback should be one of the WRC_*
  77893. ** constants to specify how to proceed with the walk.
  77894. **
  77895. ** WRC_Continue Continue descending down the tree.
  77896. **
  77897. ** WRC_Prune Do not descend into child nodes. But allow
  77898. ** the walk to continue with sibling nodes.
  77899. **
  77900. ** WRC_Abort Do no more callbacks. Unwind the stack and
  77901. ** return the top-level walk call.
  77902. **
  77903. ** The return value from this routine is WRC_Abort to abandon the tree walk
  77904. ** and WRC_Continue to continue.
  77905. */
  77906. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  77907. int rc;
  77908. if( pExpr==0 ) return WRC_Continue;
  77909. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  77910. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  77911. rc = pWalker->xExprCallback(pWalker, pExpr);
  77912. if( rc==WRC_Continue
  77913. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  77914. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  77915. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  77916. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77917. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  77918. }else{
  77919. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  77920. }
  77921. }
  77922. return rc & WRC_Abort;
  77923. }
  77924. /*
  77925. ** Call sqlite3WalkExpr() for every expression in list p or until
  77926. ** an abort request is seen.
  77927. */
  77928. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  77929. int i;
  77930. struct ExprList_item *pItem;
  77931. if( p ){
  77932. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  77933. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  77934. }
  77935. }
  77936. return WRC_Continue;
  77937. }
  77938. /*
  77939. ** Walk all expressions associated with SELECT statement p. Do
  77940. ** not invoke the SELECT callback on p, but do (of course) invoke
  77941. ** any expr callbacks and SELECT callbacks that come from subqueries.
  77942. ** Return WRC_Abort or WRC_Continue.
  77943. */
  77944. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  77945. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  77946. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  77947. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  77948. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  77949. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  77950. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  77951. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  77952. return WRC_Continue;
  77953. }
  77954. /*
  77955. ** Walk the parse trees associated with all subqueries in the
  77956. ** FROM clause of SELECT statement p. Do not invoke the select
  77957. ** callback on p, but do invoke it on each FROM clause subquery
  77958. ** and on any subqueries further down in the tree. Return
  77959. ** WRC_Abort or WRC_Continue;
  77960. */
  77961. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  77962. SrcList *pSrc;
  77963. int i;
  77964. struct SrcList_item *pItem;
  77965. pSrc = p->pSrc;
  77966. if( ALWAYS(pSrc) ){
  77967. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  77968. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  77969. return WRC_Abort;
  77970. }
  77971. if( pItem->fg.isTabFunc
  77972. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  77973. ){
  77974. return WRC_Abort;
  77975. }
  77976. }
  77977. }
  77978. return WRC_Continue;
  77979. }
  77980. /*
  77981. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  77982. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  77983. ** on the compound select chain, p->pPrior.
  77984. **
  77985. ** If it is not NULL, the xSelectCallback() callback is invoked before
  77986. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  77987. ** method, if it is not NULL, is invoked following the walk of the
  77988. ** expressions and FROM clause.
  77989. **
  77990. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  77991. ** there is an abort request.
  77992. **
  77993. ** If the Walker does not have an xSelectCallback() then this routine
  77994. ** is a no-op returning WRC_Continue.
  77995. */
  77996. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  77997. int rc;
  77998. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  77999. return WRC_Continue;
  78000. }
  78001. rc = WRC_Continue;
  78002. pWalker->walkerDepth++;
  78003. while( p ){
  78004. if( pWalker->xSelectCallback ){
  78005. rc = pWalker->xSelectCallback(pWalker, p);
  78006. if( rc ) break;
  78007. }
  78008. if( sqlite3WalkSelectExpr(pWalker, p)
  78009. || sqlite3WalkSelectFrom(pWalker, p)
  78010. ){
  78011. pWalker->walkerDepth--;
  78012. return WRC_Abort;
  78013. }
  78014. if( pWalker->xSelectCallback2 ){
  78015. pWalker->xSelectCallback2(pWalker, p);
  78016. }
  78017. p = p->pPrior;
  78018. }
  78019. pWalker->walkerDepth--;
  78020. return rc & WRC_Abort;
  78021. }
  78022. /************** End of walker.c **********************************************/
  78023. /************** Begin file resolve.c *****************************************/
  78024. /*
  78025. ** 2008 August 18
  78026. **
  78027. ** The author disclaims copyright to this source code. In place of
  78028. ** a legal notice, here is a blessing:
  78029. **
  78030. ** May you do good and not evil.
  78031. ** May you find forgiveness for yourself and forgive others.
  78032. ** May you share freely, never taking more than you give.
  78033. **
  78034. *************************************************************************
  78035. **
  78036. ** This file contains routines used for walking the parser tree and
  78037. ** resolve all identifiers by associating them with a particular
  78038. ** table and column.
  78039. */
  78040. /* #include "sqliteInt.h" */
  78041. /* #include <stdlib.h> */
  78042. /* #include <string.h> */
  78043. /*
  78044. ** Walk the expression tree pExpr and increase the aggregate function
  78045. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  78046. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  78047. ** outer query into an inner subquery.
  78048. **
  78049. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  78050. ** is a helper function - a callback for the tree walker.
  78051. */
  78052. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  78053. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  78054. return WRC_Continue;
  78055. }
  78056. static void incrAggFunctionDepth(Expr *pExpr, int N){
  78057. if( N>0 ){
  78058. Walker w;
  78059. memset(&w, 0, sizeof(w));
  78060. w.xExprCallback = incrAggDepth;
  78061. w.u.n = N;
  78062. sqlite3WalkExpr(&w, pExpr);
  78063. }
  78064. }
  78065. /*
  78066. ** Turn the pExpr expression into an alias for the iCol-th column of the
  78067. ** result set in pEList.
  78068. **
  78069. ** If the reference is followed by a COLLATE operator, then make sure
  78070. ** the COLLATE operator is preserved. For example:
  78071. **
  78072. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  78073. **
  78074. ** Should be transformed into:
  78075. **
  78076. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  78077. **
  78078. ** The nSubquery parameter specifies how many levels of subquery the
  78079. ** alias is removed from the original expression. The usual value is
  78080. ** zero but it might be more if the alias is contained within a subquery
  78081. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  78082. ** structures must be increased by the nSubquery amount.
  78083. */
  78084. static void resolveAlias(
  78085. Parse *pParse, /* Parsing context */
  78086. ExprList *pEList, /* A result set */
  78087. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  78088. Expr *pExpr, /* Transform this into an alias to the result set */
  78089. const char *zType, /* "GROUP" or "ORDER" or "" */
  78090. int nSubquery /* Number of subqueries that the label is moving */
  78091. ){
  78092. Expr *pOrig; /* The iCol-th column of the result set */
  78093. Expr *pDup; /* Copy of pOrig */
  78094. sqlite3 *db; /* The database connection */
  78095. assert( iCol>=0 && iCol<pEList->nExpr );
  78096. pOrig = pEList->a[iCol].pExpr;
  78097. assert( pOrig!=0 );
  78098. db = pParse->db;
  78099. pDup = sqlite3ExprDup(db, pOrig, 0);
  78100. if( pDup==0 ) return;
  78101. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  78102. if( pExpr->op==TK_COLLATE ){
  78103. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  78104. }
  78105. ExprSetProperty(pDup, EP_Alias);
  78106. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  78107. ** prevents ExprDelete() from deleting the Expr structure itself,
  78108. ** allowing it to be repopulated by the memcpy() on the following line.
  78109. ** The pExpr->u.zToken might point into memory that will be freed by the
  78110. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  78111. ** make a copy of the token before doing the sqlite3DbFree().
  78112. */
  78113. ExprSetProperty(pExpr, EP_Static);
  78114. sqlite3ExprDelete(db, pExpr);
  78115. memcpy(pExpr, pDup, sizeof(*pExpr));
  78116. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  78117. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  78118. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  78119. pExpr->flags |= EP_MemToken;
  78120. }
  78121. sqlite3DbFree(db, pDup);
  78122. }
  78123. /*
  78124. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  78125. **
  78126. ** Return FALSE if the USING clause is NULL or if it does not contain
  78127. ** zCol.
  78128. */
  78129. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  78130. if( pUsing ){
  78131. int k;
  78132. for(k=0; k<pUsing->nId; k++){
  78133. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  78134. }
  78135. }
  78136. return 0;
  78137. }
  78138. /*
  78139. ** Subqueries stores the original database, table and column names for their
  78140. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  78141. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  78142. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  78143. ** match anything.
  78144. */
  78145. SQLITE_PRIVATE int sqlite3MatchSpanName(
  78146. const char *zSpan,
  78147. const char *zCol,
  78148. const char *zTab,
  78149. const char *zDb
  78150. ){
  78151. int n;
  78152. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  78153. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  78154. return 0;
  78155. }
  78156. zSpan += n+1;
  78157. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  78158. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  78159. return 0;
  78160. }
  78161. zSpan += n+1;
  78162. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  78163. return 0;
  78164. }
  78165. return 1;
  78166. }
  78167. /*
  78168. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  78169. ** that name in the set of source tables in pSrcList and make the pExpr
  78170. ** expression node refer back to that source column. The following changes
  78171. ** are made to pExpr:
  78172. **
  78173. ** pExpr->iDb Set the index in db->aDb[] of the database X
  78174. ** (even if X is implied).
  78175. ** pExpr->iTable Set to the cursor number for the table obtained
  78176. ** from pSrcList.
  78177. ** pExpr->pTab Points to the Table structure of X.Y (even if
  78178. ** X and/or Y are implied.)
  78179. ** pExpr->iColumn Set to the column number within the table.
  78180. ** pExpr->op Set to TK_COLUMN.
  78181. ** pExpr->pLeft Any expression this points to is deleted
  78182. ** pExpr->pRight Any expression this points to is deleted.
  78183. **
  78184. ** The zDb variable is the name of the database (the "X"). This value may be
  78185. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  78186. ** can be used. The zTable variable is the name of the table (the "Y"). This
  78187. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  78188. ** means that the form of the name is Z and that columns from any table
  78189. ** can be used.
  78190. **
  78191. ** If the name cannot be resolved unambiguously, leave an error message
  78192. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  78193. */
  78194. static int lookupName(
  78195. Parse *pParse, /* The parsing context */
  78196. const char *zDb, /* Name of the database containing table, or NULL */
  78197. const char *zTab, /* Name of table containing column, or NULL */
  78198. const char *zCol, /* Name of the column. */
  78199. NameContext *pNC, /* The name context used to resolve the name */
  78200. Expr *pExpr /* Make this EXPR node point to the selected column */
  78201. ){
  78202. int i, j; /* Loop counters */
  78203. int cnt = 0; /* Number of matching column names */
  78204. int cntTab = 0; /* Number of matching table names */
  78205. int nSubquery = 0; /* How many levels of subquery */
  78206. sqlite3 *db = pParse->db; /* The database connection */
  78207. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  78208. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  78209. NameContext *pTopNC = pNC; /* First namecontext in the list */
  78210. Schema *pSchema = 0; /* Schema of the expression */
  78211. int isTrigger = 0; /* True if resolved to a trigger column */
  78212. Table *pTab = 0; /* Table hold the row */
  78213. Column *pCol; /* A column of pTab */
  78214. assert( pNC ); /* the name context cannot be NULL. */
  78215. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  78216. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  78217. /* Initialize the node to no-match */
  78218. pExpr->iTable = -1;
  78219. pExpr->pTab = 0;
  78220. ExprSetVVAProperty(pExpr, EP_NoReduce);
  78221. /* Translate the schema name in zDb into a pointer to the corresponding
  78222. ** schema. If not found, pSchema will remain NULL and nothing will match
  78223. ** resulting in an appropriate error message toward the end of this routine
  78224. */
  78225. if( zDb ){
  78226. testcase( pNC->ncFlags & NC_PartIdx );
  78227. testcase( pNC->ncFlags & NC_IsCheck );
  78228. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  78229. /* Silently ignore database qualifiers inside CHECK constraints and
  78230. ** partial indices. Do not raise errors because that might break
  78231. ** legacy and because it does not hurt anything to just ignore the
  78232. ** database name. */
  78233. zDb = 0;
  78234. }else{
  78235. for(i=0; i<db->nDb; i++){
  78236. assert( db->aDb[i].zName );
  78237. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  78238. pSchema = db->aDb[i].pSchema;
  78239. break;
  78240. }
  78241. }
  78242. }
  78243. }
  78244. /* Start at the inner-most context and move outward until a match is found */
  78245. while( pNC && cnt==0 ){
  78246. ExprList *pEList;
  78247. SrcList *pSrcList = pNC->pSrcList;
  78248. if( pSrcList ){
  78249. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  78250. pTab = pItem->pTab;
  78251. assert( pTab!=0 && pTab->zName!=0 );
  78252. assert( pTab->nCol>0 );
  78253. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  78254. int hit = 0;
  78255. pEList = pItem->pSelect->pEList;
  78256. for(j=0; j<pEList->nExpr; j++){
  78257. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  78258. cnt++;
  78259. cntTab = 2;
  78260. pMatch = pItem;
  78261. pExpr->iColumn = j;
  78262. hit = 1;
  78263. }
  78264. }
  78265. if( hit || zTab==0 ) continue;
  78266. }
  78267. if( zDb && pTab->pSchema!=pSchema ){
  78268. continue;
  78269. }
  78270. if( zTab ){
  78271. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  78272. assert( zTabName!=0 );
  78273. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  78274. continue;
  78275. }
  78276. }
  78277. if( 0==(cntTab++) ){
  78278. pMatch = pItem;
  78279. }
  78280. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  78281. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  78282. /* If there has been exactly one prior match and this match
  78283. ** is for the right-hand table of a NATURAL JOIN or is in a
  78284. ** USING clause, then skip this match.
  78285. */
  78286. if( cnt==1 ){
  78287. if( pItem->fg.jointype & JT_NATURAL ) continue;
  78288. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  78289. }
  78290. cnt++;
  78291. pMatch = pItem;
  78292. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  78293. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  78294. break;
  78295. }
  78296. }
  78297. }
  78298. if( pMatch ){
  78299. pExpr->iTable = pMatch->iCursor;
  78300. pExpr->pTab = pMatch->pTab;
  78301. /* RIGHT JOIN not (yet) supported */
  78302. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  78303. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  78304. ExprSetProperty(pExpr, EP_CanBeNull);
  78305. }
  78306. pSchema = pExpr->pTab->pSchema;
  78307. }
  78308. } /* if( pSrcList ) */
  78309. #ifndef SQLITE_OMIT_TRIGGER
  78310. /* If we have not already resolved the name, then maybe
  78311. ** it is a new.* or old.* trigger argument reference
  78312. */
  78313. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  78314. int op = pParse->eTriggerOp;
  78315. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  78316. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  78317. pExpr->iTable = 1;
  78318. pTab = pParse->pTriggerTab;
  78319. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  78320. pExpr->iTable = 0;
  78321. pTab = pParse->pTriggerTab;
  78322. }else{
  78323. pTab = 0;
  78324. }
  78325. if( pTab ){
  78326. int iCol;
  78327. pSchema = pTab->pSchema;
  78328. cntTab++;
  78329. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  78330. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  78331. if( iCol==pTab->iPKey ){
  78332. iCol = -1;
  78333. }
  78334. break;
  78335. }
  78336. }
  78337. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  78338. /* IMP: R-51414-32910 */
  78339. /* IMP: R-44911-55124 */
  78340. iCol = -1;
  78341. }
  78342. if( iCol<pTab->nCol ){
  78343. cnt++;
  78344. if( iCol<0 ){
  78345. pExpr->affinity = SQLITE_AFF_INTEGER;
  78346. }else if( pExpr->iTable==0 ){
  78347. testcase( iCol==31 );
  78348. testcase( iCol==32 );
  78349. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  78350. }else{
  78351. testcase( iCol==31 );
  78352. testcase( iCol==32 );
  78353. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  78354. }
  78355. pExpr->iColumn = (i16)iCol;
  78356. pExpr->pTab = pTab;
  78357. isTrigger = 1;
  78358. }
  78359. }
  78360. }
  78361. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  78362. /*
  78363. ** Perhaps the name is a reference to the ROWID
  78364. */
  78365. if( cnt==0
  78366. && cntTab==1
  78367. && pMatch
  78368. && (pNC->ncFlags & NC_IdxExpr)==0
  78369. && sqlite3IsRowid(zCol)
  78370. && VisibleRowid(pMatch->pTab)
  78371. ){
  78372. cnt = 1;
  78373. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  78374. pExpr->affinity = SQLITE_AFF_INTEGER;
  78375. }
  78376. /*
  78377. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  78378. ** might refer to an result-set alias. This happens, for example, when
  78379. ** we are resolving names in the WHERE clause of the following command:
  78380. **
  78381. ** SELECT a+b AS x FROM table WHERE x<10;
  78382. **
  78383. ** In cases like this, replace pExpr with a copy of the expression that
  78384. ** forms the result set entry ("a+b" in the example) and return immediately.
  78385. ** Note that the expression in the result set should have already been
  78386. ** resolved by the time the WHERE clause is resolved.
  78387. **
  78388. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  78389. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  78390. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  78391. ** is supported for backwards compatibility only. Hence, we issue a warning
  78392. ** on sqlite3_log() whenever the capability is used.
  78393. */
  78394. if( (pEList = pNC->pEList)!=0
  78395. && zTab==0
  78396. && cnt==0
  78397. ){
  78398. for(j=0; j<pEList->nExpr; j++){
  78399. char *zAs = pEList->a[j].zName;
  78400. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  78401. Expr *pOrig;
  78402. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  78403. assert( pExpr->x.pList==0 );
  78404. assert( pExpr->x.pSelect==0 );
  78405. pOrig = pEList->a[j].pExpr;
  78406. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  78407. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  78408. return WRC_Abort;
  78409. }
  78410. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  78411. cnt = 1;
  78412. pMatch = 0;
  78413. assert( zTab==0 && zDb==0 );
  78414. goto lookupname_end;
  78415. }
  78416. }
  78417. }
  78418. /* Advance to the next name context. The loop will exit when either
  78419. ** we have a match (cnt>0) or when we run out of name contexts.
  78420. */
  78421. if( cnt==0 ){
  78422. pNC = pNC->pNext;
  78423. nSubquery++;
  78424. }
  78425. }
  78426. /*
  78427. ** If X and Y are NULL (in other words if only the column name Z is
  78428. ** supplied) and the value of Z is enclosed in double-quotes, then
  78429. ** Z is a string literal if it doesn't match any column names. In that
  78430. ** case, we need to return right away and not make any changes to
  78431. ** pExpr.
  78432. **
  78433. ** Because no reference was made to outer contexts, the pNC->nRef
  78434. ** fields are not changed in any context.
  78435. */
  78436. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  78437. pExpr->op = TK_STRING;
  78438. pExpr->pTab = 0;
  78439. return WRC_Prune;
  78440. }
  78441. /*
  78442. ** cnt==0 means there was not match. cnt>1 means there were two or
  78443. ** more matches. Either way, we have an error.
  78444. */
  78445. if( cnt!=1 ){
  78446. const char *zErr;
  78447. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  78448. if( zDb ){
  78449. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  78450. }else if( zTab ){
  78451. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  78452. }else{
  78453. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  78454. }
  78455. pParse->checkSchema = 1;
  78456. pTopNC->nErr++;
  78457. }
  78458. /* If a column from a table in pSrcList is referenced, then record
  78459. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  78460. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  78461. ** column number is greater than the number of bits in the bitmask
  78462. ** then set the high-order bit of the bitmask.
  78463. */
  78464. if( pExpr->iColumn>=0 && pMatch!=0 ){
  78465. int n = pExpr->iColumn;
  78466. testcase( n==BMS-1 );
  78467. if( n>=BMS ){
  78468. n = BMS-1;
  78469. }
  78470. assert( pMatch->iCursor==pExpr->iTable );
  78471. pMatch->colUsed |= ((Bitmask)1)<<n;
  78472. }
  78473. /* Clean up and return
  78474. */
  78475. sqlite3ExprDelete(db, pExpr->pLeft);
  78476. pExpr->pLeft = 0;
  78477. sqlite3ExprDelete(db, pExpr->pRight);
  78478. pExpr->pRight = 0;
  78479. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  78480. lookupname_end:
  78481. if( cnt==1 ){
  78482. assert( pNC!=0 );
  78483. if( !ExprHasProperty(pExpr, EP_Alias) ){
  78484. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  78485. }
  78486. /* Increment the nRef value on all name contexts from TopNC up to
  78487. ** the point where the name matched. */
  78488. for(;;){
  78489. assert( pTopNC!=0 );
  78490. pTopNC->nRef++;
  78491. if( pTopNC==pNC ) break;
  78492. pTopNC = pTopNC->pNext;
  78493. }
  78494. return WRC_Prune;
  78495. } else {
  78496. return WRC_Abort;
  78497. }
  78498. }
  78499. /*
  78500. ** Allocate and return a pointer to an expression to load the column iCol
  78501. ** from datasource iSrc in SrcList pSrc.
  78502. */
  78503. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  78504. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  78505. if( p ){
  78506. struct SrcList_item *pItem = &pSrc->a[iSrc];
  78507. p->pTab = pItem->pTab;
  78508. p->iTable = pItem->iCursor;
  78509. if( p->pTab->iPKey==iCol ){
  78510. p->iColumn = -1;
  78511. }else{
  78512. p->iColumn = (ynVar)iCol;
  78513. testcase( iCol==BMS );
  78514. testcase( iCol==BMS-1 );
  78515. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  78516. }
  78517. ExprSetProperty(p, EP_Resolved);
  78518. }
  78519. return p;
  78520. }
  78521. /*
  78522. ** Report an error that an expression is not valid for some set of
  78523. ** pNC->ncFlags values determined by validMask.
  78524. */
  78525. static void notValid(
  78526. Parse *pParse, /* Leave error message here */
  78527. NameContext *pNC, /* The name context */
  78528. const char *zMsg, /* Type of error */
  78529. int validMask /* Set of contexts for which prohibited */
  78530. ){
  78531. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  78532. if( (pNC->ncFlags & validMask)!=0 ){
  78533. const char *zIn = "partial index WHERE clauses";
  78534. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  78535. #ifndef SQLITE_OMIT_CHECK
  78536. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  78537. #endif
  78538. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  78539. }
  78540. }
  78541. /*
  78542. ** Expression p should encode a floating point value between 1.0 and 0.0.
  78543. ** Return 1024 times this value. Or return -1 if p is not a floating point
  78544. ** value between 1.0 and 0.0.
  78545. */
  78546. static int exprProbability(Expr *p){
  78547. double r = -1.0;
  78548. if( p->op!=TK_FLOAT ) return -1;
  78549. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  78550. assert( r>=0.0 );
  78551. if( r>1.0 ) return -1;
  78552. return (int)(r*134217728.0);
  78553. }
  78554. /*
  78555. ** This routine is callback for sqlite3WalkExpr().
  78556. **
  78557. ** Resolve symbolic names into TK_COLUMN operators for the current
  78558. ** node in the expression tree. Return 0 to continue the search down
  78559. ** the tree or 2 to abort the tree walk.
  78560. **
  78561. ** This routine also does error checking and name resolution for
  78562. ** function names. The operator for aggregate functions is changed
  78563. ** to TK_AGG_FUNCTION.
  78564. */
  78565. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  78566. NameContext *pNC;
  78567. Parse *pParse;
  78568. pNC = pWalker->u.pNC;
  78569. assert( pNC!=0 );
  78570. pParse = pNC->pParse;
  78571. assert( pParse==pWalker->pParse );
  78572. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  78573. ExprSetProperty(pExpr, EP_Resolved);
  78574. #ifndef NDEBUG
  78575. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  78576. SrcList *pSrcList = pNC->pSrcList;
  78577. int i;
  78578. for(i=0; i<pNC->pSrcList->nSrc; i++){
  78579. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  78580. }
  78581. }
  78582. #endif
  78583. switch( pExpr->op ){
  78584. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  78585. /* The special operator TK_ROW means use the rowid for the first
  78586. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  78587. ** clause processing on UPDATE and DELETE statements.
  78588. */
  78589. case TK_ROW: {
  78590. SrcList *pSrcList = pNC->pSrcList;
  78591. struct SrcList_item *pItem;
  78592. assert( pSrcList && pSrcList->nSrc==1 );
  78593. pItem = pSrcList->a;
  78594. pExpr->op = TK_COLUMN;
  78595. pExpr->pTab = pItem->pTab;
  78596. pExpr->iTable = pItem->iCursor;
  78597. pExpr->iColumn = -1;
  78598. pExpr->affinity = SQLITE_AFF_INTEGER;
  78599. break;
  78600. }
  78601. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  78602. && !defined(SQLITE_OMIT_SUBQUERY) */
  78603. /* A lone identifier is the name of a column.
  78604. */
  78605. case TK_ID: {
  78606. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  78607. }
  78608. /* A table name and column name: ID.ID
  78609. ** Or a database, table and column: ID.ID.ID
  78610. */
  78611. case TK_DOT: {
  78612. const char *zColumn;
  78613. const char *zTable;
  78614. const char *zDb;
  78615. Expr *pRight;
  78616. /* if( pSrcList==0 ) break; */
  78617. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  78618. /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
  78619. pRight = pExpr->pRight;
  78620. if( pRight->op==TK_ID ){
  78621. zDb = 0;
  78622. zTable = pExpr->pLeft->u.zToken;
  78623. zColumn = pRight->u.zToken;
  78624. }else{
  78625. assert( pRight->op==TK_DOT );
  78626. zDb = pExpr->pLeft->u.zToken;
  78627. zTable = pRight->pLeft->u.zToken;
  78628. zColumn = pRight->pRight->u.zToken;
  78629. }
  78630. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  78631. }
  78632. /* Resolve function names
  78633. */
  78634. case TK_FUNCTION: {
  78635. ExprList *pList = pExpr->x.pList; /* The argument list */
  78636. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  78637. int no_such_func = 0; /* True if no such function exists */
  78638. int wrong_num_args = 0; /* True if wrong number of arguments */
  78639. int is_agg = 0; /* True if is an aggregate function */
  78640. int auth; /* Authorization to use the function */
  78641. int nId; /* Number of characters in function name */
  78642. const char *zId; /* The function name. */
  78643. FuncDef *pDef; /* Information about the function */
  78644. u8 enc = ENC(pParse->db); /* The database encoding */
  78645. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  78646. notValid(pParse, pNC, "functions", NC_PartIdx);
  78647. zId = pExpr->u.zToken;
  78648. nId = sqlite3Strlen30(zId);
  78649. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  78650. if( pDef==0 ){
  78651. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  78652. if( pDef==0 ){
  78653. no_such_func = 1;
  78654. }else{
  78655. wrong_num_args = 1;
  78656. }
  78657. }else{
  78658. is_agg = pDef->xFunc==0;
  78659. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  78660. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  78661. if( n==2 ){
  78662. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  78663. if( pExpr->iTable<0 ){
  78664. sqlite3ErrorMsg(pParse,
  78665. "second argument to likelihood() must be a "
  78666. "constant between 0.0 and 1.0");
  78667. pNC->nErr++;
  78668. }
  78669. }else{
  78670. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  78671. ** equivalent to likelihood(X, 0.0625).
  78672. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  78673. ** short-hand for likelihood(X,0.0625).
  78674. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  78675. ** for likelihood(X,0.9375).
  78676. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  78677. ** to likelihood(X,0.9375). */
  78678. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  78679. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  78680. }
  78681. }
  78682. #ifndef SQLITE_OMIT_AUTHORIZATION
  78683. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  78684. if( auth!=SQLITE_OK ){
  78685. if( auth==SQLITE_DENY ){
  78686. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  78687. pDef->zName);
  78688. pNC->nErr++;
  78689. }
  78690. pExpr->op = TK_NULL;
  78691. return WRC_Prune;
  78692. }
  78693. #endif
  78694. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  78695. /* For the purposes of the EP_ConstFunc flag, date and time
  78696. ** functions and other functions that change slowly are considered
  78697. ** constant because they are constant for the duration of one query */
  78698. ExprSetProperty(pExpr,EP_ConstFunc);
  78699. }
  78700. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  78701. /* Date/time functions that use 'now', and other functions like
  78702. ** sqlite_version() that might change over time cannot be used
  78703. ** in an index. */
  78704. notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
  78705. }
  78706. }
  78707. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  78708. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  78709. pNC->nErr++;
  78710. is_agg = 0;
  78711. }else if( no_such_func && pParse->db->init.busy==0 ){
  78712. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  78713. pNC->nErr++;
  78714. }else if( wrong_num_args ){
  78715. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  78716. nId, zId);
  78717. pNC->nErr++;
  78718. }
  78719. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  78720. sqlite3WalkExprList(pWalker, pList);
  78721. if( is_agg ){
  78722. NameContext *pNC2 = pNC;
  78723. pExpr->op = TK_AGG_FUNCTION;
  78724. pExpr->op2 = 0;
  78725. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  78726. pExpr->op2++;
  78727. pNC2 = pNC2->pNext;
  78728. }
  78729. assert( pDef!=0 );
  78730. if( pNC2 ){
  78731. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  78732. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  78733. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  78734. }
  78735. pNC->ncFlags |= NC_AllowAgg;
  78736. }
  78737. /* FIX ME: Compute pExpr->affinity based on the expected return
  78738. ** type of the function
  78739. */
  78740. return WRC_Prune;
  78741. }
  78742. #ifndef SQLITE_OMIT_SUBQUERY
  78743. case TK_SELECT:
  78744. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  78745. #endif
  78746. case TK_IN: {
  78747. testcase( pExpr->op==TK_IN );
  78748. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  78749. int nRef = pNC->nRef;
  78750. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  78751. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  78752. assert( pNC->nRef>=nRef );
  78753. if( nRef!=pNC->nRef ){
  78754. ExprSetProperty(pExpr, EP_VarSelect);
  78755. }
  78756. }
  78757. break;
  78758. }
  78759. case TK_VARIABLE: {
  78760. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  78761. break;
  78762. }
  78763. }
  78764. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  78765. }
  78766. /*
  78767. ** pEList is a list of expressions which are really the result set of the
  78768. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  78769. ** This routine checks to see if pE is a simple identifier which corresponds
  78770. ** to the AS-name of one of the terms of the expression list. If it is,
  78771. ** this routine return an integer between 1 and N where N is the number of
  78772. ** elements in pEList, corresponding to the matching entry. If there is
  78773. ** no match, or if pE is not a simple identifier, then this routine
  78774. ** return 0.
  78775. **
  78776. ** pEList has been resolved. pE has not.
  78777. */
  78778. static int resolveAsName(
  78779. Parse *pParse, /* Parsing context for error messages */
  78780. ExprList *pEList, /* List of expressions to scan */
  78781. Expr *pE /* Expression we are trying to match */
  78782. ){
  78783. int i; /* Loop counter */
  78784. UNUSED_PARAMETER(pParse);
  78785. if( pE->op==TK_ID ){
  78786. char *zCol = pE->u.zToken;
  78787. for(i=0; i<pEList->nExpr; i++){
  78788. char *zAs = pEList->a[i].zName;
  78789. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  78790. return i+1;
  78791. }
  78792. }
  78793. }
  78794. return 0;
  78795. }
  78796. /*
  78797. ** pE is a pointer to an expression which is a single term in the
  78798. ** ORDER BY of a compound SELECT. The expression has not been
  78799. ** name resolved.
  78800. **
  78801. ** At the point this routine is called, we already know that the
  78802. ** ORDER BY term is not an integer index into the result set. That
  78803. ** case is handled by the calling routine.
  78804. **
  78805. ** Attempt to match pE against result set columns in the left-most
  78806. ** SELECT statement. Return the index i of the matching column,
  78807. ** as an indication to the caller that it should sort by the i-th column.
  78808. ** The left-most column is 1. In other words, the value returned is the
  78809. ** same integer value that would be used in the SQL statement to indicate
  78810. ** the column.
  78811. **
  78812. ** If there is no match, return 0. Return -1 if an error occurs.
  78813. */
  78814. static int resolveOrderByTermToExprList(
  78815. Parse *pParse, /* Parsing context for error messages */
  78816. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  78817. Expr *pE /* The specific ORDER BY term */
  78818. ){
  78819. int i; /* Loop counter */
  78820. ExprList *pEList; /* The columns of the result set */
  78821. NameContext nc; /* Name context for resolving pE */
  78822. sqlite3 *db; /* Database connection */
  78823. int rc; /* Return code from subprocedures */
  78824. u8 savedSuppErr; /* Saved value of db->suppressErr */
  78825. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  78826. pEList = pSelect->pEList;
  78827. /* Resolve all names in the ORDER BY term expression
  78828. */
  78829. memset(&nc, 0, sizeof(nc));
  78830. nc.pParse = pParse;
  78831. nc.pSrcList = pSelect->pSrc;
  78832. nc.pEList = pEList;
  78833. nc.ncFlags = NC_AllowAgg;
  78834. nc.nErr = 0;
  78835. db = pParse->db;
  78836. savedSuppErr = db->suppressErr;
  78837. db->suppressErr = 1;
  78838. rc = sqlite3ResolveExprNames(&nc, pE);
  78839. db->suppressErr = savedSuppErr;
  78840. if( rc ) return 0;
  78841. /* Try to match the ORDER BY expression against an expression
  78842. ** in the result set. Return an 1-based index of the matching
  78843. ** result-set entry.
  78844. */
  78845. for(i=0; i<pEList->nExpr; i++){
  78846. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  78847. return i+1;
  78848. }
  78849. }
  78850. /* If no match, return 0. */
  78851. return 0;
  78852. }
  78853. /*
  78854. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  78855. */
  78856. static void resolveOutOfRangeError(
  78857. Parse *pParse, /* The error context into which to write the error */
  78858. const char *zType, /* "ORDER" or "GROUP" */
  78859. int i, /* The index (1-based) of the term out of range */
  78860. int mx /* Largest permissible value of i */
  78861. ){
  78862. sqlite3ErrorMsg(pParse,
  78863. "%r %s BY term out of range - should be "
  78864. "between 1 and %d", i, zType, mx);
  78865. }
  78866. /*
  78867. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  78868. ** each term of the ORDER BY clause is a constant integer between 1
  78869. ** and N where N is the number of columns in the compound SELECT.
  78870. **
  78871. ** ORDER BY terms that are already an integer between 1 and N are
  78872. ** unmodified. ORDER BY terms that are integers outside the range of
  78873. ** 1 through N generate an error. ORDER BY terms that are expressions
  78874. ** are matched against result set expressions of compound SELECT
  78875. ** beginning with the left-most SELECT and working toward the right.
  78876. ** At the first match, the ORDER BY expression is transformed into
  78877. ** the integer column number.
  78878. **
  78879. ** Return the number of errors seen.
  78880. */
  78881. static int resolveCompoundOrderBy(
  78882. Parse *pParse, /* Parsing context. Leave error messages here */
  78883. Select *pSelect /* The SELECT statement containing the ORDER BY */
  78884. ){
  78885. int i;
  78886. ExprList *pOrderBy;
  78887. ExprList *pEList;
  78888. sqlite3 *db;
  78889. int moreToDo = 1;
  78890. pOrderBy = pSelect->pOrderBy;
  78891. if( pOrderBy==0 ) return 0;
  78892. db = pParse->db;
  78893. #if SQLITE_MAX_COLUMN
  78894. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  78895. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  78896. return 1;
  78897. }
  78898. #endif
  78899. for(i=0; i<pOrderBy->nExpr; i++){
  78900. pOrderBy->a[i].done = 0;
  78901. }
  78902. pSelect->pNext = 0;
  78903. while( pSelect->pPrior ){
  78904. pSelect->pPrior->pNext = pSelect;
  78905. pSelect = pSelect->pPrior;
  78906. }
  78907. while( pSelect && moreToDo ){
  78908. struct ExprList_item *pItem;
  78909. moreToDo = 0;
  78910. pEList = pSelect->pEList;
  78911. assert( pEList!=0 );
  78912. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  78913. int iCol = -1;
  78914. Expr *pE, *pDup;
  78915. if( pItem->done ) continue;
  78916. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  78917. if( sqlite3ExprIsInteger(pE, &iCol) ){
  78918. if( iCol<=0 || iCol>pEList->nExpr ){
  78919. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  78920. return 1;
  78921. }
  78922. }else{
  78923. iCol = resolveAsName(pParse, pEList, pE);
  78924. if( iCol==0 ){
  78925. pDup = sqlite3ExprDup(db, pE, 0);
  78926. if( !db->mallocFailed ){
  78927. assert(pDup);
  78928. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  78929. }
  78930. sqlite3ExprDelete(db, pDup);
  78931. }
  78932. }
  78933. if( iCol>0 ){
  78934. /* Convert the ORDER BY term into an integer column number iCol,
  78935. ** taking care to preserve the COLLATE clause if it exists */
  78936. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  78937. if( pNew==0 ) return 1;
  78938. pNew->flags |= EP_IntValue;
  78939. pNew->u.iValue = iCol;
  78940. if( pItem->pExpr==pE ){
  78941. pItem->pExpr = pNew;
  78942. }else{
  78943. Expr *pParent = pItem->pExpr;
  78944. assert( pParent->op==TK_COLLATE );
  78945. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  78946. assert( pParent->pLeft==pE );
  78947. pParent->pLeft = pNew;
  78948. }
  78949. sqlite3ExprDelete(db, pE);
  78950. pItem->u.x.iOrderByCol = (u16)iCol;
  78951. pItem->done = 1;
  78952. }else{
  78953. moreToDo = 1;
  78954. }
  78955. }
  78956. pSelect = pSelect->pNext;
  78957. }
  78958. for(i=0; i<pOrderBy->nExpr; i++){
  78959. if( pOrderBy->a[i].done==0 ){
  78960. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  78961. "column in the result set", i+1);
  78962. return 1;
  78963. }
  78964. }
  78965. return 0;
  78966. }
  78967. /*
  78968. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  78969. ** the SELECT statement pSelect. If any term is reference to a
  78970. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  78971. ** field) then convert that term into a copy of the corresponding result set
  78972. ** column.
  78973. **
  78974. ** If any errors are detected, add an error message to pParse and
  78975. ** return non-zero. Return zero if no errors are seen.
  78976. */
  78977. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  78978. Parse *pParse, /* Parsing context. Leave error messages here */
  78979. Select *pSelect, /* The SELECT statement containing the clause */
  78980. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  78981. const char *zType /* "ORDER" or "GROUP" */
  78982. ){
  78983. int i;
  78984. sqlite3 *db = pParse->db;
  78985. ExprList *pEList;
  78986. struct ExprList_item *pItem;
  78987. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  78988. #if SQLITE_MAX_COLUMN
  78989. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  78990. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  78991. return 1;
  78992. }
  78993. #endif
  78994. pEList = pSelect->pEList;
  78995. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  78996. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  78997. if( pItem->u.x.iOrderByCol ){
  78998. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  78999. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  79000. return 1;
  79001. }
  79002. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  79003. zType,0);
  79004. }
  79005. }
  79006. return 0;
  79007. }
  79008. /*
  79009. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  79010. ** The Name context of the SELECT statement is pNC. zType is either
  79011. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  79012. **
  79013. ** This routine resolves each term of the clause into an expression.
  79014. ** If the order-by term is an integer I between 1 and N (where N is the
  79015. ** number of columns in the result set of the SELECT) then the expression
  79016. ** in the resolution is a copy of the I-th result-set expression. If
  79017. ** the order-by term is an identifier that corresponds to the AS-name of
  79018. ** a result-set expression, then the term resolves to a copy of the
  79019. ** result-set expression. Otherwise, the expression is resolved in
  79020. ** the usual way - using sqlite3ResolveExprNames().
  79021. **
  79022. ** This routine returns the number of errors. If errors occur, then
  79023. ** an appropriate error message might be left in pParse. (OOM errors
  79024. ** excepted.)
  79025. */
  79026. static int resolveOrderGroupBy(
  79027. NameContext *pNC, /* The name context of the SELECT statement */
  79028. Select *pSelect, /* The SELECT statement holding pOrderBy */
  79029. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  79030. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  79031. ){
  79032. int i, j; /* Loop counters */
  79033. int iCol; /* Column number */
  79034. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  79035. Parse *pParse; /* Parsing context */
  79036. int nResult; /* Number of terms in the result set */
  79037. if( pOrderBy==0 ) return 0;
  79038. nResult = pSelect->pEList->nExpr;
  79039. pParse = pNC->pParse;
  79040. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  79041. Expr *pE = pItem->pExpr;
  79042. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  79043. if( zType[0]!='G' ){
  79044. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  79045. if( iCol>0 ){
  79046. /* If an AS-name match is found, mark this ORDER BY column as being
  79047. ** a copy of the iCol-th result-set column. The subsequent call to
  79048. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  79049. ** copy of the iCol-th result-set expression. */
  79050. pItem->u.x.iOrderByCol = (u16)iCol;
  79051. continue;
  79052. }
  79053. }
  79054. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  79055. /* The ORDER BY term is an integer constant. Again, set the column
  79056. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  79057. ** order-by term to a copy of the result-set expression */
  79058. if( iCol<1 || iCol>0xffff ){
  79059. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  79060. return 1;
  79061. }
  79062. pItem->u.x.iOrderByCol = (u16)iCol;
  79063. continue;
  79064. }
  79065. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  79066. pItem->u.x.iOrderByCol = 0;
  79067. if( sqlite3ResolveExprNames(pNC, pE) ){
  79068. return 1;
  79069. }
  79070. for(j=0; j<pSelect->pEList->nExpr; j++){
  79071. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  79072. pItem->u.x.iOrderByCol = j+1;
  79073. }
  79074. }
  79075. }
  79076. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  79077. }
  79078. /*
  79079. ** Resolve names in the SELECT statement p and all of its descendants.
  79080. */
  79081. static int resolveSelectStep(Walker *pWalker, Select *p){
  79082. NameContext *pOuterNC; /* Context that contains this SELECT */
  79083. NameContext sNC; /* Name context of this SELECT */
  79084. int isCompound; /* True if p is a compound select */
  79085. int nCompound; /* Number of compound terms processed so far */
  79086. Parse *pParse; /* Parsing context */
  79087. int i; /* Loop counter */
  79088. ExprList *pGroupBy; /* The GROUP BY clause */
  79089. Select *pLeftmost; /* Left-most of SELECT of a compound */
  79090. sqlite3 *db; /* Database connection */
  79091. assert( p!=0 );
  79092. if( p->selFlags & SF_Resolved ){
  79093. return WRC_Prune;
  79094. }
  79095. pOuterNC = pWalker->u.pNC;
  79096. pParse = pWalker->pParse;
  79097. db = pParse->db;
  79098. /* Normally sqlite3SelectExpand() will be called first and will have
  79099. ** already expanded this SELECT. However, if this is a subquery within
  79100. ** an expression, sqlite3ResolveExprNames() will be called without a
  79101. ** prior call to sqlite3SelectExpand(). When that happens, let
  79102. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  79103. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  79104. ** this routine in the correct order.
  79105. */
  79106. if( (p->selFlags & SF_Expanded)==0 ){
  79107. sqlite3SelectPrep(pParse, p, pOuterNC);
  79108. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  79109. }
  79110. isCompound = p->pPrior!=0;
  79111. nCompound = 0;
  79112. pLeftmost = p;
  79113. while( p ){
  79114. assert( (p->selFlags & SF_Expanded)!=0 );
  79115. assert( (p->selFlags & SF_Resolved)==0 );
  79116. p->selFlags |= SF_Resolved;
  79117. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  79118. ** are not allowed to refer to any names, so pass an empty NameContext.
  79119. */
  79120. memset(&sNC, 0, sizeof(sNC));
  79121. sNC.pParse = pParse;
  79122. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  79123. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  79124. return WRC_Abort;
  79125. }
  79126. /* If the SF_Converted flags is set, then this Select object was
  79127. ** was created by the convertCompoundSelectToSubquery() function.
  79128. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  79129. ** as if it were part of the sub-query, not the parent. This block
  79130. ** moves the pOrderBy down to the sub-query. It will be moved back
  79131. ** after the names have been resolved. */
  79132. if( p->selFlags & SF_Converted ){
  79133. Select *pSub = p->pSrc->a[0].pSelect;
  79134. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  79135. assert( pSub->pPrior && pSub->pOrderBy==0 );
  79136. pSub->pOrderBy = p->pOrderBy;
  79137. p->pOrderBy = 0;
  79138. }
  79139. /* Recursively resolve names in all subqueries
  79140. */
  79141. for(i=0; i<p->pSrc->nSrc; i++){
  79142. struct SrcList_item *pItem = &p->pSrc->a[i];
  79143. if( pItem->pSelect ){
  79144. NameContext *pNC; /* Used to iterate name contexts */
  79145. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  79146. const char *zSavedContext = pParse->zAuthContext;
  79147. /* Count the total number of references to pOuterNC and all of its
  79148. ** parent contexts. After resolving references to expressions in
  79149. ** pItem->pSelect, check if this value has changed. If so, then
  79150. ** SELECT statement pItem->pSelect must be correlated. Set the
  79151. ** pItem->fg.isCorrelated flag if this is the case. */
  79152. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  79153. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  79154. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  79155. pParse->zAuthContext = zSavedContext;
  79156. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  79157. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  79158. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  79159. pItem->fg.isCorrelated = (nRef!=0);
  79160. }
  79161. }
  79162. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  79163. ** resolve the result-set expression list.
  79164. */
  79165. sNC.ncFlags = NC_AllowAgg;
  79166. sNC.pSrcList = p->pSrc;
  79167. sNC.pNext = pOuterNC;
  79168. /* Resolve names in the result set. */
  79169. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  79170. /* If there are no aggregate functions in the result-set, and no GROUP BY
  79171. ** expression, do not allow aggregates in any of the other expressions.
  79172. */
  79173. assert( (p->selFlags & SF_Aggregate)==0 );
  79174. pGroupBy = p->pGroupBy;
  79175. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  79176. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  79177. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  79178. }else{
  79179. sNC.ncFlags &= ~NC_AllowAgg;
  79180. }
  79181. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  79182. */
  79183. if( p->pHaving && !pGroupBy ){
  79184. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  79185. return WRC_Abort;
  79186. }
  79187. /* Add the output column list to the name-context before parsing the
  79188. ** other expressions in the SELECT statement. This is so that
  79189. ** expressions in the WHERE clause (etc.) can refer to expressions by
  79190. ** aliases in the result set.
  79191. **
  79192. ** Minor point: If this is the case, then the expression will be
  79193. ** re-evaluated for each reference to it.
  79194. */
  79195. sNC.pEList = p->pEList;
  79196. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  79197. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  79198. /* Resolve names in table-valued-function arguments */
  79199. for(i=0; i<p->pSrc->nSrc; i++){
  79200. struct SrcList_item *pItem = &p->pSrc->a[i];
  79201. if( pItem->fg.isTabFunc
  79202. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  79203. ){
  79204. return WRC_Abort;
  79205. }
  79206. }
  79207. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  79208. ** outer queries
  79209. */
  79210. sNC.pNext = 0;
  79211. sNC.ncFlags |= NC_AllowAgg;
  79212. /* If this is a converted compound query, move the ORDER BY clause from
  79213. ** the sub-query back to the parent query. At this point each term
  79214. ** within the ORDER BY clause has been transformed to an integer value.
  79215. ** These integers will be replaced by copies of the corresponding result
  79216. ** set expressions by the call to resolveOrderGroupBy() below. */
  79217. if( p->selFlags & SF_Converted ){
  79218. Select *pSub = p->pSrc->a[0].pSelect;
  79219. p->pOrderBy = pSub->pOrderBy;
  79220. pSub->pOrderBy = 0;
  79221. }
  79222. /* Process the ORDER BY clause for singleton SELECT statements.
  79223. ** The ORDER BY clause for compounds SELECT statements is handled
  79224. ** below, after all of the result-sets for all of the elements of
  79225. ** the compound have been resolved.
  79226. **
  79227. ** If there is an ORDER BY clause on a term of a compound-select other
  79228. ** than the right-most term, then that is a syntax error. But the error
  79229. ** is not detected until much later, and so we need to go ahead and
  79230. ** resolve those symbols on the incorrect ORDER BY for consistency.
  79231. */
  79232. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  79233. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  79234. ){
  79235. return WRC_Abort;
  79236. }
  79237. if( db->mallocFailed ){
  79238. return WRC_Abort;
  79239. }
  79240. /* Resolve the GROUP BY clause. At the same time, make sure
  79241. ** the GROUP BY clause does not contain aggregate functions.
  79242. */
  79243. if( pGroupBy ){
  79244. struct ExprList_item *pItem;
  79245. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  79246. return WRC_Abort;
  79247. }
  79248. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  79249. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  79250. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  79251. "the GROUP BY clause");
  79252. return WRC_Abort;
  79253. }
  79254. }
  79255. }
  79256. /* If this is part of a compound SELECT, check that it has the right
  79257. ** number of expressions in the select list. */
  79258. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  79259. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  79260. return WRC_Abort;
  79261. }
  79262. /* Advance to the next term of the compound
  79263. */
  79264. p = p->pPrior;
  79265. nCompound++;
  79266. }
  79267. /* Resolve the ORDER BY on a compound SELECT after all terms of
  79268. ** the compound have been resolved.
  79269. */
  79270. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  79271. return WRC_Abort;
  79272. }
  79273. return WRC_Prune;
  79274. }
  79275. /*
  79276. ** This routine walks an expression tree and resolves references to
  79277. ** table columns and result-set columns. At the same time, do error
  79278. ** checking on function usage and set a flag if any aggregate functions
  79279. ** are seen.
  79280. **
  79281. ** To resolve table columns references we look for nodes (or subtrees) of the
  79282. ** form X.Y.Z or Y.Z or just Z where
  79283. **
  79284. ** X: The name of a database. Ex: "main" or "temp" or
  79285. ** the symbolic name assigned to an ATTACH-ed database.
  79286. **
  79287. ** Y: The name of a table in a FROM clause. Or in a trigger
  79288. ** one of the special names "old" or "new".
  79289. **
  79290. ** Z: The name of a column in table Y.
  79291. **
  79292. ** The node at the root of the subtree is modified as follows:
  79293. **
  79294. ** Expr.op Changed to TK_COLUMN
  79295. ** Expr.pTab Points to the Table object for X.Y
  79296. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  79297. ** Expr.iTable The VDBE cursor number for X.Y
  79298. **
  79299. **
  79300. ** To resolve result-set references, look for expression nodes of the
  79301. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  79302. ** size of an AS clause in the result-set of a SELECT. The Z expression
  79303. ** is replaced by a copy of the left-hand side of the result-set expression.
  79304. ** Table-name and function resolution occurs on the substituted expression
  79305. ** tree. For example, in:
  79306. **
  79307. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  79308. **
  79309. ** The "x" term of the order by is replaced by "a+b" to render:
  79310. **
  79311. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  79312. **
  79313. ** Function calls are checked to make sure that the function is
  79314. ** defined and that the correct number of arguments are specified.
  79315. ** If the function is an aggregate function, then the NC_HasAgg flag is
  79316. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  79317. ** If an expression contains aggregate functions then the EP_Agg
  79318. ** property on the expression is set.
  79319. **
  79320. ** An error message is left in pParse if anything is amiss. The number
  79321. ** if errors is returned.
  79322. */
  79323. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  79324. NameContext *pNC, /* Namespace to resolve expressions in. */
  79325. Expr *pExpr /* The expression to be analyzed. */
  79326. ){
  79327. u16 savedHasAgg;
  79328. Walker w;
  79329. if( pExpr==0 ) return 0;
  79330. #if SQLITE_MAX_EXPR_DEPTH>0
  79331. {
  79332. Parse *pParse = pNC->pParse;
  79333. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  79334. return 1;
  79335. }
  79336. pParse->nHeight += pExpr->nHeight;
  79337. }
  79338. #endif
  79339. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  79340. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  79341. memset(&w, 0, sizeof(w));
  79342. w.xExprCallback = resolveExprStep;
  79343. w.xSelectCallback = resolveSelectStep;
  79344. w.pParse = pNC->pParse;
  79345. w.u.pNC = pNC;
  79346. sqlite3WalkExpr(&w, pExpr);
  79347. #if SQLITE_MAX_EXPR_DEPTH>0
  79348. pNC->pParse->nHeight -= pExpr->nHeight;
  79349. #endif
  79350. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  79351. ExprSetProperty(pExpr, EP_Error);
  79352. }
  79353. if( pNC->ncFlags & NC_HasAgg ){
  79354. ExprSetProperty(pExpr, EP_Agg);
  79355. }
  79356. pNC->ncFlags |= savedHasAgg;
  79357. return ExprHasProperty(pExpr, EP_Error);
  79358. }
  79359. /*
  79360. ** Resolve all names for all expression in an expression list. This is
  79361. ** just like sqlite3ResolveExprNames() except that it works for an expression
  79362. ** list rather than a single expression.
  79363. */
  79364. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  79365. NameContext *pNC, /* Namespace to resolve expressions in. */
  79366. ExprList *pList /* The expression list to be analyzed. */
  79367. ){
  79368. int i;
  79369. assert( pList!=0 );
  79370. for(i=0; i<pList->nExpr; i++){
  79371. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  79372. }
  79373. return WRC_Continue;
  79374. }
  79375. /*
  79376. ** Resolve all names in all expressions of a SELECT and in all
  79377. ** decendents of the SELECT, including compounds off of p->pPrior,
  79378. ** subqueries in expressions, and subqueries used as FROM clause
  79379. ** terms.
  79380. **
  79381. ** See sqlite3ResolveExprNames() for a description of the kinds of
  79382. ** transformations that occur.
  79383. **
  79384. ** All SELECT statements should have been expanded using
  79385. ** sqlite3SelectExpand() prior to invoking this routine.
  79386. */
  79387. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  79388. Parse *pParse, /* The parser context */
  79389. Select *p, /* The SELECT statement being coded. */
  79390. NameContext *pOuterNC /* Name context for parent SELECT statement */
  79391. ){
  79392. Walker w;
  79393. assert( p!=0 );
  79394. memset(&w, 0, sizeof(w));
  79395. w.xExprCallback = resolveExprStep;
  79396. w.xSelectCallback = resolveSelectStep;
  79397. w.pParse = pParse;
  79398. w.u.pNC = pOuterNC;
  79399. sqlite3WalkSelect(&w, p);
  79400. }
  79401. /*
  79402. ** Resolve names in expressions that can only reference a single table:
  79403. **
  79404. ** * CHECK constraints
  79405. ** * WHERE clauses on partial indices
  79406. **
  79407. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  79408. ** is set to -1 and the Expr.iColumn value is set to the column number.
  79409. **
  79410. ** Any errors cause an error message to be set in pParse.
  79411. */
  79412. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  79413. Parse *pParse, /* Parsing context */
  79414. Table *pTab, /* The table being referenced */
  79415. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  79416. Expr *pExpr, /* Expression to resolve. May be NULL. */
  79417. ExprList *pList /* Expression list to resolve. May be NUL. */
  79418. ){
  79419. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  79420. NameContext sNC; /* Name context for pParse->pNewTable */
  79421. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  79422. memset(&sNC, 0, sizeof(sNC));
  79423. memset(&sSrc, 0, sizeof(sSrc));
  79424. sSrc.nSrc = 1;
  79425. sSrc.a[0].zName = pTab->zName;
  79426. sSrc.a[0].pTab = pTab;
  79427. sSrc.a[0].iCursor = -1;
  79428. sNC.pParse = pParse;
  79429. sNC.pSrcList = &sSrc;
  79430. sNC.ncFlags = type;
  79431. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  79432. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  79433. }
  79434. /************** End of resolve.c *********************************************/
  79435. /************** Begin file expr.c ********************************************/
  79436. /*
  79437. ** 2001 September 15
  79438. **
  79439. ** The author disclaims copyright to this source code. In place of
  79440. ** a legal notice, here is a blessing:
  79441. **
  79442. ** May you do good and not evil.
  79443. ** May you find forgiveness for yourself and forgive others.
  79444. ** May you share freely, never taking more than you give.
  79445. **
  79446. *************************************************************************
  79447. ** This file contains routines used for analyzing expressions and
  79448. ** for generating VDBE code that evaluates expressions in SQLite.
  79449. */
  79450. /* #include "sqliteInt.h" */
  79451. /*
  79452. ** Return the 'affinity' of the expression pExpr if any.
  79453. **
  79454. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  79455. ** or a sub-select with a column as the return value, then the
  79456. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  79457. ** indicating no affinity for the expression.
  79458. **
  79459. ** i.e. the WHERE clause expressions in the following statements all
  79460. ** have an affinity:
  79461. **
  79462. ** CREATE TABLE t1(a);
  79463. ** SELECT * FROM t1 WHERE a;
  79464. ** SELECT a AS b FROM t1 WHERE b;
  79465. ** SELECT * FROM t1 WHERE (select a from t1);
  79466. */
  79467. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  79468. int op;
  79469. pExpr = sqlite3ExprSkipCollate(pExpr);
  79470. if( pExpr->flags & EP_Generic ) return 0;
  79471. op = pExpr->op;
  79472. if( op==TK_SELECT ){
  79473. assert( pExpr->flags&EP_xIsSelect );
  79474. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  79475. }
  79476. #ifndef SQLITE_OMIT_CAST
  79477. if( op==TK_CAST ){
  79478. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79479. return sqlite3AffinityType(pExpr->u.zToken, 0);
  79480. }
  79481. #endif
  79482. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  79483. && pExpr->pTab!=0
  79484. ){
  79485. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  79486. ** a TK_COLUMN but was previously evaluated and cached in a register */
  79487. int j = pExpr->iColumn;
  79488. if( j<0 ) return SQLITE_AFF_INTEGER;
  79489. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  79490. return pExpr->pTab->aCol[j].affinity;
  79491. }
  79492. return pExpr->affinity;
  79493. }
  79494. /*
  79495. ** Set the collating sequence for expression pExpr to be the collating
  79496. ** sequence named by pToken. Return a pointer to a new Expr node that
  79497. ** implements the COLLATE operator.
  79498. **
  79499. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  79500. ** and the pExpr parameter is returned unchanged.
  79501. */
  79502. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  79503. Parse *pParse, /* Parsing context */
  79504. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  79505. const Token *pCollName, /* Name of collating sequence */
  79506. int dequote /* True to dequote pCollName */
  79507. ){
  79508. if( pCollName->n>0 ){
  79509. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  79510. if( pNew ){
  79511. pNew->pLeft = pExpr;
  79512. pNew->flags |= EP_Collate|EP_Skip;
  79513. pExpr = pNew;
  79514. }
  79515. }
  79516. return pExpr;
  79517. }
  79518. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  79519. Token s;
  79520. assert( zC!=0 );
  79521. s.z = zC;
  79522. s.n = sqlite3Strlen30(s.z);
  79523. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  79524. }
  79525. /*
  79526. ** Skip over any TK_COLLATE operators and any unlikely()
  79527. ** or likelihood() function at the root of an expression.
  79528. */
  79529. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  79530. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  79531. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  79532. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79533. assert( pExpr->x.pList->nExpr>0 );
  79534. assert( pExpr->op==TK_FUNCTION );
  79535. pExpr = pExpr->x.pList->a[0].pExpr;
  79536. }else{
  79537. assert( pExpr->op==TK_COLLATE );
  79538. pExpr = pExpr->pLeft;
  79539. }
  79540. }
  79541. return pExpr;
  79542. }
  79543. /*
  79544. ** Return the collation sequence for the expression pExpr. If
  79545. ** there is no defined collating sequence, return NULL.
  79546. **
  79547. ** The collating sequence might be determined by a COLLATE operator
  79548. ** or by the presence of a column with a defined collating sequence.
  79549. ** COLLATE operators take first precedence. Left operands take
  79550. ** precedence over right operands.
  79551. */
  79552. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  79553. sqlite3 *db = pParse->db;
  79554. CollSeq *pColl = 0;
  79555. Expr *p = pExpr;
  79556. while( p ){
  79557. int op = p->op;
  79558. if( p->flags & EP_Generic ) break;
  79559. if( op==TK_CAST || op==TK_UPLUS ){
  79560. p = p->pLeft;
  79561. continue;
  79562. }
  79563. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  79564. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  79565. break;
  79566. }
  79567. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  79568. || op==TK_REGISTER || op==TK_TRIGGER)
  79569. && p->pTab!=0
  79570. ){
  79571. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  79572. ** a TK_COLUMN but was previously evaluated and cached in a register */
  79573. int j = p->iColumn;
  79574. if( j>=0 ){
  79575. const char *zColl = p->pTab->aCol[j].zColl;
  79576. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  79577. }
  79578. break;
  79579. }
  79580. if( p->flags & EP_Collate ){
  79581. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  79582. p = p->pLeft;
  79583. }else{
  79584. Expr *pNext = p->pRight;
  79585. /* The Expr.x union is never used at the same time as Expr.pRight */
  79586. assert( p->x.pList==0 || p->pRight==0 );
  79587. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  79588. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  79589. ** least one EP_Collate. Thus the following two ALWAYS. */
  79590. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  79591. int i;
  79592. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  79593. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  79594. pNext = p->x.pList->a[i].pExpr;
  79595. break;
  79596. }
  79597. }
  79598. }
  79599. p = pNext;
  79600. }
  79601. }else{
  79602. break;
  79603. }
  79604. }
  79605. if( sqlite3CheckCollSeq(pParse, pColl) ){
  79606. pColl = 0;
  79607. }
  79608. return pColl;
  79609. }
  79610. /*
  79611. ** pExpr is an operand of a comparison operator. aff2 is the
  79612. ** type affinity of the other operand. This routine returns the
  79613. ** type affinity that should be used for the comparison operator.
  79614. */
  79615. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  79616. char aff1 = sqlite3ExprAffinity(pExpr);
  79617. if( aff1 && aff2 ){
  79618. /* Both sides of the comparison are columns. If one has numeric
  79619. ** affinity, use that. Otherwise use no affinity.
  79620. */
  79621. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  79622. return SQLITE_AFF_NUMERIC;
  79623. }else{
  79624. return SQLITE_AFF_BLOB;
  79625. }
  79626. }else if( !aff1 && !aff2 ){
  79627. /* Neither side of the comparison is a column. Compare the
  79628. ** results directly.
  79629. */
  79630. return SQLITE_AFF_BLOB;
  79631. }else{
  79632. /* One side is a column, the other is not. Use the columns affinity. */
  79633. assert( aff1==0 || aff2==0 );
  79634. return (aff1 + aff2);
  79635. }
  79636. }
  79637. /*
  79638. ** pExpr is a comparison operator. Return the type affinity that should
  79639. ** be applied to both operands prior to doing the comparison.
  79640. */
  79641. static char comparisonAffinity(Expr *pExpr){
  79642. char aff;
  79643. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  79644. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  79645. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  79646. assert( pExpr->pLeft );
  79647. aff = sqlite3ExprAffinity(pExpr->pLeft);
  79648. if( pExpr->pRight ){
  79649. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  79650. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  79651. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  79652. }else if( !aff ){
  79653. aff = SQLITE_AFF_BLOB;
  79654. }
  79655. return aff;
  79656. }
  79657. /*
  79658. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  79659. ** idx_affinity is the affinity of an indexed column. Return true
  79660. ** if the index with affinity idx_affinity may be used to implement
  79661. ** the comparison in pExpr.
  79662. */
  79663. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  79664. char aff = comparisonAffinity(pExpr);
  79665. switch( aff ){
  79666. case SQLITE_AFF_BLOB:
  79667. return 1;
  79668. case SQLITE_AFF_TEXT:
  79669. return idx_affinity==SQLITE_AFF_TEXT;
  79670. default:
  79671. return sqlite3IsNumericAffinity(idx_affinity);
  79672. }
  79673. }
  79674. /*
  79675. ** Return the P5 value that should be used for a binary comparison
  79676. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  79677. */
  79678. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  79679. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  79680. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  79681. return aff;
  79682. }
  79683. /*
  79684. ** Return a pointer to the collation sequence that should be used by
  79685. ** a binary comparison operator comparing pLeft and pRight.
  79686. **
  79687. ** If the left hand expression has a collating sequence type, then it is
  79688. ** used. Otherwise the collation sequence for the right hand expression
  79689. ** is used, or the default (BINARY) if neither expression has a collating
  79690. ** type.
  79691. **
  79692. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  79693. ** it is not considered.
  79694. */
  79695. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  79696. Parse *pParse,
  79697. Expr *pLeft,
  79698. Expr *pRight
  79699. ){
  79700. CollSeq *pColl;
  79701. assert( pLeft );
  79702. if( pLeft->flags & EP_Collate ){
  79703. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  79704. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  79705. pColl = sqlite3ExprCollSeq(pParse, pRight);
  79706. }else{
  79707. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  79708. if( !pColl ){
  79709. pColl = sqlite3ExprCollSeq(pParse, pRight);
  79710. }
  79711. }
  79712. return pColl;
  79713. }
  79714. /*
  79715. ** Generate code for a comparison operator.
  79716. */
  79717. static int codeCompare(
  79718. Parse *pParse, /* The parsing (and code generating) context */
  79719. Expr *pLeft, /* The left operand */
  79720. Expr *pRight, /* The right operand */
  79721. int opcode, /* The comparison opcode */
  79722. int in1, int in2, /* Register holding operands */
  79723. int dest, /* Jump here if true. */
  79724. int jumpIfNull /* If true, jump if either operand is NULL */
  79725. ){
  79726. int p5;
  79727. int addr;
  79728. CollSeq *p4;
  79729. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  79730. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  79731. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  79732. (void*)p4, P4_COLLSEQ);
  79733. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  79734. return addr;
  79735. }
  79736. #if SQLITE_MAX_EXPR_DEPTH>0
  79737. /*
  79738. ** Check that argument nHeight is less than or equal to the maximum
  79739. ** expression depth allowed. If it is not, leave an error message in
  79740. ** pParse.
  79741. */
  79742. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  79743. int rc = SQLITE_OK;
  79744. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  79745. if( nHeight>mxHeight ){
  79746. sqlite3ErrorMsg(pParse,
  79747. "Expression tree is too large (maximum depth %d)", mxHeight
  79748. );
  79749. rc = SQLITE_ERROR;
  79750. }
  79751. return rc;
  79752. }
  79753. /* The following three functions, heightOfExpr(), heightOfExprList()
  79754. ** and heightOfSelect(), are used to determine the maximum height
  79755. ** of any expression tree referenced by the structure passed as the
  79756. ** first argument.
  79757. **
  79758. ** If this maximum height is greater than the current value pointed
  79759. ** to by pnHeight, the second parameter, then set *pnHeight to that
  79760. ** value.
  79761. */
  79762. static void heightOfExpr(Expr *p, int *pnHeight){
  79763. if( p ){
  79764. if( p->nHeight>*pnHeight ){
  79765. *pnHeight = p->nHeight;
  79766. }
  79767. }
  79768. }
  79769. static void heightOfExprList(ExprList *p, int *pnHeight){
  79770. if( p ){
  79771. int i;
  79772. for(i=0; i<p->nExpr; i++){
  79773. heightOfExpr(p->a[i].pExpr, pnHeight);
  79774. }
  79775. }
  79776. }
  79777. static void heightOfSelect(Select *p, int *pnHeight){
  79778. if( p ){
  79779. heightOfExpr(p->pWhere, pnHeight);
  79780. heightOfExpr(p->pHaving, pnHeight);
  79781. heightOfExpr(p->pLimit, pnHeight);
  79782. heightOfExpr(p->pOffset, pnHeight);
  79783. heightOfExprList(p->pEList, pnHeight);
  79784. heightOfExprList(p->pGroupBy, pnHeight);
  79785. heightOfExprList(p->pOrderBy, pnHeight);
  79786. heightOfSelect(p->pPrior, pnHeight);
  79787. }
  79788. }
  79789. /*
  79790. ** Set the Expr.nHeight variable in the structure passed as an
  79791. ** argument. An expression with no children, Expr.pList or
  79792. ** Expr.pSelect member has a height of 1. Any other expression
  79793. ** has a height equal to the maximum height of any other
  79794. ** referenced Expr plus one.
  79795. **
  79796. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  79797. ** if appropriate.
  79798. */
  79799. static void exprSetHeight(Expr *p){
  79800. int nHeight = 0;
  79801. heightOfExpr(p->pLeft, &nHeight);
  79802. heightOfExpr(p->pRight, &nHeight);
  79803. if( ExprHasProperty(p, EP_xIsSelect) ){
  79804. heightOfSelect(p->x.pSelect, &nHeight);
  79805. }else if( p->x.pList ){
  79806. heightOfExprList(p->x.pList, &nHeight);
  79807. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  79808. }
  79809. p->nHeight = nHeight + 1;
  79810. }
  79811. /*
  79812. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  79813. ** the height is greater than the maximum allowed expression depth,
  79814. ** leave an error in pParse.
  79815. **
  79816. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  79817. ** Expr.flags.
  79818. */
  79819. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  79820. if( pParse->nErr ) return;
  79821. exprSetHeight(p);
  79822. sqlite3ExprCheckHeight(pParse, p->nHeight);
  79823. }
  79824. /*
  79825. ** Return the maximum height of any expression tree referenced
  79826. ** by the select statement passed as an argument.
  79827. */
  79828. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  79829. int nHeight = 0;
  79830. heightOfSelect(p, &nHeight);
  79831. return nHeight;
  79832. }
  79833. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  79834. /*
  79835. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  79836. ** Expr.flags.
  79837. */
  79838. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  79839. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  79840. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  79841. }
  79842. }
  79843. #define exprSetHeight(y)
  79844. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  79845. /*
  79846. ** This routine is the core allocator for Expr nodes.
  79847. **
  79848. ** Construct a new expression node and return a pointer to it. Memory
  79849. ** for this node and for the pToken argument is a single allocation
  79850. ** obtained from sqlite3DbMalloc(). The calling function
  79851. ** is responsible for making sure the node eventually gets freed.
  79852. **
  79853. ** If dequote is true, then the token (if it exists) is dequoted.
  79854. ** If dequote is false, no dequoting is performed. The deQuote
  79855. ** parameter is ignored if pToken is NULL or if the token does not
  79856. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  79857. ** then the EP_DblQuoted flag is set on the expression node.
  79858. **
  79859. ** Special case: If op==TK_INTEGER and pToken points to a string that
  79860. ** can be translated into a 32-bit integer, then the token is not
  79861. ** stored in u.zToken. Instead, the integer values is written
  79862. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  79863. ** is allocated to hold the integer text and the dequote flag is ignored.
  79864. */
  79865. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  79866. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  79867. int op, /* Expression opcode */
  79868. const Token *pToken, /* Token argument. Might be NULL */
  79869. int dequote /* True to dequote */
  79870. ){
  79871. Expr *pNew;
  79872. int nExtra = 0;
  79873. int iValue = 0;
  79874. if( pToken ){
  79875. if( op!=TK_INTEGER || pToken->z==0
  79876. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  79877. nExtra = pToken->n+1;
  79878. assert( iValue>=0 );
  79879. }
  79880. }
  79881. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  79882. if( pNew ){
  79883. pNew->op = (u8)op;
  79884. pNew->iAgg = -1;
  79885. if( pToken ){
  79886. if( nExtra==0 ){
  79887. pNew->flags |= EP_IntValue;
  79888. pNew->u.iValue = iValue;
  79889. }else{
  79890. int c;
  79891. pNew->u.zToken = (char*)&pNew[1];
  79892. assert( pToken->z!=0 || pToken->n==0 );
  79893. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  79894. pNew->u.zToken[pToken->n] = 0;
  79895. if( dequote && nExtra>=3
  79896. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  79897. sqlite3Dequote(pNew->u.zToken);
  79898. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  79899. }
  79900. }
  79901. }
  79902. #if SQLITE_MAX_EXPR_DEPTH>0
  79903. pNew->nHeight = 1;
  79904. #endif
  79905. }
  79906. return pNew;
  79907. }
  79908. /*
  79909. ** Allocate a new expression node from a zero-terminated token that has
  79910. ** already been dequoted.
  79911. */
  79912. SQLITE_PRIVATE Expr *sqlite3Expr(
  79913. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  79914. int op, /* Expression opcode */
  79915. const char *zToken /* Token argument. Might be NULL */
  79916. ){
  79917. Token x;
  79918. x.z = zToken;
  79919. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  79920. return sqlite3ExprAlloc(db, op, &x, 0);
  79921. }
  79922. /*
  79923. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  79924. **
  79925. ** If pRoot==NULL that means that a memory allocation error has occurred.
  79926. ** In that case, delete the subtrees pLeft and pRight.
  79927. */
  79928. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  79929. sqlite3 *db,
  79930. Expr *pRoot,
  79931. Expr *pLeft,
  79932. Expr *pRight
  79933. ){
  79934. if( pRoot==0 ){
  79935. assert( db->mallocFailed );
  79936. sqlite3ExprDelete(db, pLeft);
  79937. sqlite3ExprDelete(db, pRight);
  79938. }else{
  79939. if( pRight ){
  79940. pRoot->pRight = pRight;
  79941. pRoot->flags |= EP_Propagate & pRight->flags;
  79942. }
  79943. if( pLeft ){
  79944. pRoot->pLeft = pLeft;
  79945. pRoot->flags |= EP_Propagate & pLeft->flags;
  79946. }
  79947. exprSetHeight(pRoot);
  79948. }
  79949. }
  79950. /*
  79951. ** Allocate an Expr node which joins as many as two subtrees.
  79952. **
  79953. ** One or both of the subtrees can be NULL. Return a pointer to the new
  79954. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  79955. ** free the subtrees and return NULL.
  79956. */
  79957. SQLITE_PRIVATE Expr *sqlite3PExpr(
  79958. Parse *pParse, /* Parsing context */
  79959. int op, /* Expression opcode */
  79960. Expr *pLeft, /* Left operand */
  79961. Expr *pRight, /* Right operand */
  79962. const Token *pToken /* Argument token */
  79963. ){
  79964. Expr *p;
  79965. if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
  79966. /* Take advantage of short-circuit false optimization for AND */
  79967. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  79968. }else{
  79969. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  79970. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  79971. }
  79972. if( p ) {
  79973. sqlite3ExprCheckHeight(pParse, p->nHeight);
  79974. }
  79975. return p;
  79976. }
  79977. /*
  79978. ** If the expression is always either TRUE or FALSE (respectively),
  79979. ** then return 1. If one cannot determine the truth value of the
  79980. ** expression at compile-time return 0.
  79981. **
  79982. ** This is an optimization. If is OK to return 0 here even if
  79983. ** the expression really is always false or false (a false negative).
  79984. ** But it is a bug to return 1 if the expression might have different
  79985. ** boolean values in different circumstances (a false positive.)
  79986. **
  79987. ** Note that if the expression is part of conditional for a
  79988. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  79989. ** is it true or false, so always return 0.
  79990. */
  79991. static int exprAlwaysTrue(Expr *p){
  79992. int v = 0;
  79993. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  79994. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  79995. return v!=0;
  79996. }
  79997. static int exprAlwaysFalse(Expr *p){
  79998. int v = 0;
  79999. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  80000. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  80001. return v==0;
  80002. }
  80003. /*
  80004. ** Join two expressions using an AND operator. If either expression is
  80005. ** NULL, then just return the other expression.
  80006. **
  80007. ** If one side or the other of the AND is known to be false, then instead
  80008. ** of returning an AND expression, just return a constant expression with
  80009. ** a value of false.
  80010. */
  80011. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  80012. if( pLeft==0 ){
  80013. return pRight;
  80014. }else if( pRight==0 ){
  80015. return pLeft;
  80016. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  80017. sqlite3ExprDelete(db, pLeft);
  80018. sqlite3ExprDelete(db, pRight);
  80019. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  80020. }else{
  80021. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  80022. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  80023. return pNew;
  80024. }
  80025. }
  80026. /*
  80027. ** Construct a new expression node for a function with multiple
  80028. ** arguments.
  80029. */
  80030. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  80031. Expr *pNew;
  80032. sqlite3 *db = pParse->db;
  80033. assert( pToken );
  80034. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  80035. if( pNew==0 ){
  80036. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  80037. return 0;
  80038. }
  80039. pNew->x.pList = pList;
  80040. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  80041. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  80042. return pNew;
  80043. }
  80044. /*
  80045. ** Assign a variable number to an expression that encodes a wildcard
  80046. ** in the original SQL statement.
  80047. **
  80048. ** Wildcards consisting of a single "?" are assigned the next sequential
  80049. ** variable number.
  80050. **
  80051. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  80052. ** sure "nnn" is not too be to avoid a denial of service attack when
  80053. ** the SQL statement comes from an external source.
  80054. **
  80055. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  80056. ** as the previous instance of the same wildcard. Or if this is the first
  80057. ** instance of the wildcard, the next sequential variable number is
  80058. ** assigned.
  80059. */
  80060. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  80061. sqlite3 *db = pParse->db;
  80062. const char *z;
  80063. if( pExpr==0 ) return;
  80064. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  80065. z = pExpr->u.zToken;
  80066. assert( z!=0 );
  80067. assert( z[0]!=0 );
  80068. if( z[1]==0 ){
  80069. /* Wildcard of the form "?". Assign the next variable number */
  80070. assert( z[0]=='?' );
  80071. pExpr->iColumn = (ynVar)(++pParse->nVar);
  80072. }else{
  80073. ynVar x = 0;
  80074. u32 n = sqlite3Strlen30(z);
  80075. if( z[0]=='?' ){
  80076. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  80077. ** use it as the variable number */
  80078. i64 i;
  80079. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  80080. pExpr->iColumn = x = (ynVar)i;
  80081. testcase( i==0 );
  80082. testcase( i==1 );
  80083. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  80084. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  80085. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  80086. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  80087. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  80088. x = 0;
  80089. }
  80090. if( i>pParse->nVar ){
  80091. pParse->nVar = (int)i;
  80092. }
  80093. }else{
  80094. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  80095. ** number as the prior appearance of the same name, or if the name
  80096. ** has never appeared before, reuse the same variable number
  80097. */
  80098. ynVar i;
  80099. for(i=0; i<pParse->nzVar; i++){
  80100. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  80101. pExpr->iColumn = x = (ynVar)i+1;
  80102. break;
  80103. }
  80104. }
  80105. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  80106. }
  80107. if( x>0 ){
  80108. if( x>pParse->nzVar ){
  80109. char **a;
  80110. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  80111. if( a==0 ) return; /* Error reported through db->mallocFailed */
  80112. pParse->azVar = a;
  80113. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  80114. pParse->nzVar = x;
  80115. }
  80116. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  80117. sqlite3DbFree(db, pParse->azVar[x-1]);
  80118. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  80119. }
  80120. }
  80121. }
  80122. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  80123. sqlite3ErrorMsg(pParse, "too many SQL variables");
  80124. }
  80125. }
  80126. /*
  80127. ** Recursively delete an expression tree.
  80128. */
  80129. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  80130. if( p==0 ) return;
  80131. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  80132. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  80133. if( !ExprHasProperty(p, EP_TokenOnly) ){
  80134. /* The Expr.x union is never used at the same time as Expr.pRight */
  80135. assert( p->x.pList==0 || p->pRight==0 );
  80136. sqlite3ExprDelete(db, p->pLeft);
  80137. sqlite3ExprDelete(db, p->pRight);
  80138. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  80139. if( ExprHasProperty(p, EP_xIsSelect) ){
  80140. sqlite3SelectDelete(db, p->x.pSelect);
  80141. }else{
  80142. sqlite3ExprListDelete(db, p->x.pList);
  80143. }
  80144. }
  80145. if( !ExprHasProperty(p, EP_Static) ){
  80146. sqlite3DbFree(db, p);
  80147. }
  80148. }
  80149. /*
  80150. ** Return the number of bytes allocated for the expression structure
  80151. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  80152. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  80153. */
  80154. static int exprStructSize(Expr *p){
  80155. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  80156. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  80157. return EXPR_FULLSIZE;
  80158. }
  80159. /*
  80160. ** The dupedExpr*Size() routines each return the number of bytes required
  80161. ** to store a copy of an expression or expression tree. They differ in
  80162. ** how much of the tree is measured.
  80163. **
  80164. ** dupedExprStructSize() Size of only the Expr structure
  80165. ** dupedExprNodeSize() Size of Expr + space for token
  80166. ** dupedExprSize() Expr + token + subtree components
  80167. **
  80168. ***************************************************************************
  80169. **
  80170. ** The dupedExprStructSize() function returns two values OR-ed together:
  80171. ** (1) the space required for a copy of the Expr structure only and
  80172. ** (2) the EP_xxx flags that indicate what the structure size should be.
  80173. ** The return values is always one of:
  80174. **
  80175. ** EXPR_FULLSIZE
  80176. ** EXPR_REDUCEDSIZE | EP_Reduced
  80177. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  80178. **
  80179. ** The size of the structure can be found by masking the return value
  80180. ** of this routine with 0xfff. The flags can be found by masking the
  80181. ** return value with EP_Reduced|EP_TokenOnly.
  80182. **
  80183. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  80184. ** (unreduced) Expr objects as they or originally constructed by the parser.
  80185. ** During expression analysis, extra information is computed and moved into
  80186. ** later parts of teh Expr object and that extra information might get chopped
  80187. ** off if the expression is reduced. Note also that it does not work to
  80188. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  80189. ** to reduce a pristine expression tree from the parser. The implementation
  80190. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  80191. ** to enforce this constraint.
  80192. */
  80193. static int dupedExprStructSize(Expr *p, int flags){
  80194. int nSize;
  80195. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  80196. assert( EXPR_FULLSIZE<=0xfff );
  80197. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  80198. if( 0==(flags&EXPRDUP_REDUCE) ){
  80199. nSize = EXPR_FULLSIZE;
  80200. }else{
  80201. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  80202. assert( !ExprHasProperty(p, EP_FromJoin) );
  80203. assert( !ExprHasProperty(p, EP_MemToken) );
  80204. assert( !ExprHasProperty(p, EP_NoReduce) );
  80205. if( p->pLeft || p->x.pList ){
  80206. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  80207. }else{
  80208. assert( p->pRight==0 );
  80209. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  80210. }
  80211. }
  80212. return nSize;
  80213. }
  80214. /*
  80215. ** This function returns the space in bytes required to store the copy
  80216. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  80217. ** string is defined.)
  80218. */
  80219. static int dupedExprNodeSize(Expr *p, int flags){
  80220. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  80221. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  80222. nByte += sqlite3Strlen30(p->u.zToken)+1;
  80223. }
  80224. return ROUND8(nByte);
  80225. }
  80226. /*
  80227. ** Return the number of bytes required to create a duplicate of the
  80228. ** expression passed as the first argument. The second argument is a
  80229. ** mask containing EXPRDUP_XXX flags.
  80230. **
  80231. ** The value returned includes space to create a copy of the Expr struct
  80232. ** itself and the buffer referred to by Expr.u.zToken, if any.
  80233. **
  80234. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  80235. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  80236. ** and Expr.pRight variables (but not for any structures pointed to or
  80237. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  80238. */
  80239. static int dupedExprSize(Expr *p, int flags){
  80240. int nByte = 0;
  80241. if( p ){
  80242. nByte = dupedExprNodeSize(p, flags);
  80243. if( flags&EXPRDUP_REDUCE ){
  80244. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  80245. }
  80246. }
  80247. return nByte;
  80248. }
  80249. /*
  80250. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  80251. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  80252. ** to store the copy of expression p, the copies of p->u.zToken
  80253. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  80254. ** if any. Before returning, *pzBuffer is set to the first byte past the
  80255. ** portion of the buffer copied into by this function.
  80256. */
  80257. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  80258. Expr *pNew = 0; /* Value to return */
  80259. if( p ){
  80260. const int isReduced = (flags&EXPRDUP_REDUCE);
  80261. u8 *zAlloc;
  80262. u32 staticFlag = 0;
  80263. assert( pzBuffer==0 || isReduced );
  80264. /* Figure out where to write the new Expr structure. */
  80265. if( pzBuffer ){
  80266. zAlloc = *pzBuffer;
  80267. staticFlag = EP_Static;
  80268. }else{
  80269. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  80270. }
  80271. pNew = (Expr *)zAlloc;
  80272. if( pNew ){
  80273. /* Set nNewSize to the size allocated for the structure pointed to
  80274. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  80275. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  80276. ** by the copy of the p->u.zToken string (if any).
  80277. */
  80278. const unsigned nStructSize = dupedExprStructSize(p, flags);
  80279. const int nNewSize = nStructSize & 0xfff;
  80280. int nToken;
  80281. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  80282. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  80283. }else{
  80284. nToken = 0;
  80285. }
  80286. if( isReduced ){
  80287. assert( ExprHasProperty(p, EP_Reduced)==0 );
  80288. memcpy(zAlloc, p, nNewSize);
  80289. }else{
  80290. int nSize = exprStructSize(p);
  80291. memcpy(zAlloc, p, nSize);
  80292. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  80293. }
  80294. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  80295. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  80296. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  80297. pNew->flags |= staticFlag;
  80298. /* Copy the p->u.zToken string, if any. */
  80299. if( nToken ){
  80300. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  80301. memcpy(zToken, p->u.zToken, nToken);
  80302. }
  80303. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  80304. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  80305. if( ExprHasProperty(p, EP_xIsSelect) ){
  80306. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  80307. }else{
  80308. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  80309. }
  80310. }
  80311. /* Fill in pNew->pLeft and pNew->pRight. */
  80312. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  80313. zAlloc += dupedExprNodeSize(p, flags);
  80314. if( ExprHasProperty(pNew, EP_Reduced) ){
  80315. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  80316. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  80317. }
  80318. if( pzBuffer ){
  80319. *pzBuffer = zAlloc;
  80320. }
  80321. }else{
  80322. if( !ExprHasProperty(p, EP_TokenOnly) ){
  80323. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  80324. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  80325. }
  80326. }
  80327. }
  80328. }
  80329. return pNew;
  80330. }
  80331. /*
  80332. ** Create and return a deep copy of the object passed as the second
  80333. ** argument. If an OOM condition is encountered, NULL is returned
  80334. ** and the db->mallocFailed flag set.
  80335. */
  80336. #ifndef SQLITE_OMIT_CTE
  80337. static With *withDup(sqlite3 *db, With *p){
  80338. With *pRet = 0;
  80339. if( p ){
  80340. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  80341. pRet = sqlite3DbMallocZero(db, nByte);
  80342. if( pRet ){
  80343. int i;
  80344. pRet->nCte = p->nCte;
  80345. for(i=0; i<p->nCte; i++){
  80346. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  80347. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  80348. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  80349. }
  80350. }
  80351. }
  80352. return pRet;
  80353. }
  80354. #else
  80355. # define withDup(x,y) 0
  80356. #endif
  80357. /*
  80358. ** The following group of routines make deep copies of expressions,
  80359. ** expression lists, ID lists, and select statements. The copies can
  80360. ** be deleted (by being passed to their respective ...Delete() routines)
  80361. ** without effecting the originals.
  80362. **
  80363. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  80364. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  80365. ** by subsequent calls to sqlite*ListAppend() routines.
  80366. **
  80367. ** Any tables that the SrcList might point to are not duplicated.
  80368. **
  80369. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  80370. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  80371. ** truncated version of the usual Expr structure that will be stored as
  80372. ** part of the in-memory representation of the database schema.
  80373. */
  80374. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  80375. return exprDup(db, p, flags, 0);
  80376. }
  80377. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  80378. ExprList *pNew;
  80379. struct ExprList_item *pItem, *pOldItem;
  80380. int i;
  80381. if( p==0 ) return 0;
  80382. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  80383. if( pNew==0 ) return 0;
  80384. pNew->nExpr = i = p->nExpr;
  80385. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  80386. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  80387. if( pItem==0 ){
  80388. sqlite3DbFree(db, pNew);
  80389. return 0;
  80390. }
  80391. pOldItem = p->a;
  80392. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  80393. Expr *pOldExpr = pOldItem->pExpr;
  80394. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  80395. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  80396. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  80397. pItem->sortOrder = pOldItem->sortOrder;
  80398. pItem->done = 0;
  80399. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  80400. pItem->u = pOldItem->u;
  80401. }
  80402. return pNew;
  80403. }
  80404. /*
  80405. ** If cursors, triggers, views and subqueries are all omitted from
  80406. ** the build, then none of the following routines, except for
  80407. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  80408. ** called with a NULL argument.
  80409. */
  80410. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  80411. || !defined(SQLITE_OMIT_SUBQUERY)
  80412. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  80413. SrcList *pNew;
  80414. int i;
  80415. int nByte;
  80416. if( p==0 ) return 0;
  80417. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  80418. pNew = sqlite3DbMallocRaw(db, nByte );
  80419. if( pNew==0 ) return 0;
  80420. pNew->nSrc = pNew->nAlloc = p->nSrc;
  80421. for(i=0; i<p->nSrc; i++){
  80422. struct SrcList_item *pNewItem = &pNew->a[i];
  80423. struct SrcList_item *pOldItem = &p->a[i];
  80424. Table *pTab;
  80425. pNewItem->pSchema = pOldItem->pSchema;
  80426. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  80427. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  80428. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  80429. pNewItem->fg = pOldItem->fg;
  80430. pNewItem->iCursor = pOldItem->iCursor;
  80431. pNewItem->addrFillSub = pOldItem->addrFillSub;
  80432. pNewItem->regReturn = pOldItem->regReturn;
  80433. if( pNewItem->fg.isIndexedBy ){
  80434. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  80435. }
  80436. pNewItem->pIBIndex = pOldItem->pIBIndex;
  80437. if( pNewItem->fg.isTabFunc ){
  80438. pNewItem->u1.pFuncArg =
  80439. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  80440. }
  80441. pTab = pNewItem->pTab = pOldItem->pTab;
  80442. if( pTab ){
  80443. pTab->nRef++;
  80444. }
  80445. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  80446. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  80447. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  80448. pNewItem->colUsed = pOldItem->colUsed;
  80449. }
  80450. return pNew;
  80451. }
  80452. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  80453. IdList *pNew;
  80454. int i;
  80455. if( p==0 ) return 0;
  80456. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  80457. if( pNew==0 ) return 0;
  80458. pNew->nId = p->nId;
  80459. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  80460. if( pNew->a==0 ){
  80461. sqlite3DbFree(db, pNew);
  80462. return 0;
  80463. }
  80464. /* Note that because the size of the allocation for p->a[] is not
  80465. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  80466. ** on the duplicate created by this function. */
  80467. for(i=0; i<p->nId; i++){
  80468. struct IdList_item *pNewItem = &pNew->a[i];
  80469. struct IdList_item *pOldItem = &p->a[i];
  80470. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  80471. pNewItem->idx = pOldItem->idx;
  80472. }
  80473. return pNew;
  80474. }
  80475. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  80476. Select *pNew, *pPrior;
  80477. if( p==0 ) return 0;
  80478. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  80479. if( pNew==0 ) return 0;
  80480. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  80481. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  80482. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  80483. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  80484. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  80485. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  80486. pNew->op = p->op;
  80487. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  80488. if( pPrior ) pPrior->pNext = pNew;
  80489. pNew->pNext = 0;
  80490. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  80491. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  80492. pNew->iLimit = 0;
  80493. pNew->iOffset = 0;
  80494. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  80495. pNew->addrOpenEphm[0] = -1;
  80496. pNew->addrOpenEphm[1] = -1;
  80497. pNew->nSelectRow = p->nSelectRow;
  80498. pNew->pWith = withDup(db, p->pWith);
  80499. sqlite3SelectSetName(pNew, p->zSelName);
  80500. return pNew;
  80501. }
  80502. #else
  80503. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  80504. assert( p==0 );
  80505. return 0;
  80506. }
  80507. #endif
  80508. /*
  80509. ** Add a new element to the end of an expression list. If pList is
  80510. ** initially NULL, then create a new expression list.
  80511. **
  80512. ** If a memory allocation error occurs, the entire list is freed and
  80513. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  80514. ** that the new entry was successfully appended.
  80515. */
  80516. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  80517. Parse *pParse, /* Parsing context */
  80518. ExprList *pList, /* List to which to append. Might be NULL */
  80519. Expr *pExpr /* Expression to be appended. Might be NULL */
  80520. ){
  80521. sqlite3 *db = pParse->db;
  80522. if( pList==0 ){
  80523. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  80524. if( pList==0 ){
  80525. goto no_mem;
  80526. }
  80527. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  80528. if( pList->a==0 ) goto no_mem;
  80529. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  80530. struct ExprList_item *a;
  80531. assert( pList->nExpr>0 );
  80532. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  80533. if( a==0 ){
  80534. goto no_mem;
  80535. }
  80536. pList->a = a;
  80537. }
  80538. assert( pList->a!=0 );
  80539. if( 1 ){
  80540. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  80541. memset(pItem, 0, sizeof(*pItem));
  80542. pItem->pExpr = pExpr;
  80543. }
  80544. return pList;
  80545. no_mem:
  80546. /* Avoid leaking memory if malloc has failed. */
  80547. sqlite3ExprDelete(db, pExpr);
  80548. sqlite3ExprListDelete(db, pList);
  80549. return 0;
  80550. }
  80551. /*
  80552. ** Set the sort order for the last element on the given ExprList.
  80553. */
  80554. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  80555. if( p==0 ) return;
  80556. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  80557. assert( p->nExpr>0 );
  80558. if( iSortOrder<0 ){
  80559. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  80560. return;
  80561. }
  80562. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  80563. }
  80564. /*
  80565. ** Set the ExprList.a[].zName element of the most recently added item
  80566. ** on the expression list.
  80567. **
  80568. ** pList might be NULL following an OOM error. But pName should never be
  80569. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  80570. ** is set.
  80571. */
  80572. SQLITE_PRIVATE void sqlite3ExprListSetName(
  80573. Parse *pParse, /* Parsing context */
  80574. ExprList *pList, /* List to which to add the span. */
  80575. Token *pName, /* Name to be added */
  80576. int dequote /* True to cause the name to be dequoted */
  80577. ){
  80578. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  80579. if( pList ){
  80580. struct ExprList_item *pItem;
  80581. assert( pList->nExpr>0 );
  80582. pItem = &pList->a[pList->nExpr-1];
  80583. assert( pItem->zName==0 );
  80584. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  80585. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  80586. }
  80587. }
  80588. /*
  80589. ** Set the ExprList.a[].zSpan element of the most recently added item
  80590. ** on the expression list.
  80591. **
  80592. ** pList might be NULL following an OOM error. But pSpan should never be
  80593. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  80594. ** is set.
  80595. */
  80596. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  80597. Parse *pParse, /* Parsing context */
  80598. ExprList *pList, /* List to which to add the span. */
  80599. ExprSpan *pSpan /* The span to be added */
  80600. ){
  80601. sqlite3 *db = pParse->db;
  80602. assert( pList!=0 || db->mallocFailed!=0 );
  80603. if( pList ){
  80604. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  80605. assert( pList->nExpr>0 );
  80606. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  80607. sqlite3DbFree(db, pItem->zSpan);
  80608. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  80609. (int)(pSpan->zEnd - pSpan->zStart));
  80610. }
  80611. }
  80612. /*
  80613. ** If the expression list pEList contains more than iLimit elements,
  80614. ** leave an error message in pParse.
  80615. */
  80616. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  80617. Parse *pParse,
  80618. ExprList *pEList,
  80619. const char *zObject
  80620. ){
  80621. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  80622. testcase( pEList && pEList->nExpr==mx );
  80623. testcase( pEList && pEList->nExpr==mx+1 );
  80624. if( pEList && pEList->nExpr>mx ){
  80625. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  80626. }
  80627. }
  80628. /*
  80629. ** Delete an entire expression list.
  80630. */
  80631. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  80632. int i;
  80633. struct ExprList_item *pItem;
  80634. if( pList==0 ) return;
  80635. assert( pList->a!=0 || pList->nExpr==0 );
  80636. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  80637. sqlite3ExprDelete(db, pItem->pExpr);
  80638. sqlite3DbFree(db, pItem->zName);
  80639. sqlite3DbFree(db, pItem->zSpan);
  80640. }
  80641. sqlite3DbFree(db, pList->a);
  80642. sqlite3DbFree(db, pList);
  80643. }
  80644. /*
  80645. ** Return the bitwise-OR of all Expr.flags fields in the given
  80646. ** ExprList.
  80647. */
  80648. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  80649. int i;
  80650. u32 m = 0;
  80651. if( pList ){
  80652. for(i=0; i<pList->nExpr; i++){
  80653. Expr *pExpr = pList->a[i].pExpr;
  80654. if( ALWAYS(pExpr) ) m |= pExpr->flags;
  80655. }
  80656. }
  80657. return m;
  80658. }
  80659. /*
  80660. ** These routines are Walker callbacks used to check expressions to
  80661. ** see if they are "constant" for some definition of constant. The
  80662. ** Walker.eCode value determines the type of "constant" we are looking
  80663. ** for.
  80664. **
  80665. ** These callback routines are used to implement the following:
  80666. **
  80667. ** sqlite3ExprIsConstant() pWalker->eCode==1
  80668. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  80669. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  80670. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  80671. **
  80672. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  80673. ** is found to not be a constant.
  80674. **
  80675. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  80676. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  80677. ** an existing schema and 4 when processing a new statement. A bound
  80678. ** parameter raises an error for new statements, but is silently converted
  80679. ** to NULL for existing schemas. This allows sqlite_master tables that
  80680. ** contain a bound parameter because they were generated by older versions
  80681. ** of SQLite to be parsed by newer versions of SQLite without raising a
  80682. ** malformed schema error.
  80683. */
  80684. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  80685. /* If pWalker->eCode is 2 then any term of the expression that comes from
  80686. ** the ON or USING clauses of a left join disqualifies the expression
  80687. ** from being considered constant. */
  80688. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  80689. pWalker->eCode = 0;
  80690. return WRC_Abort;
  80691. }
  80692. switch( pExpr->op ){
  80693. /* Consider functions to be constant if all their arguments are constant
  80694. ** and either pWalker->eCode==4 or 5 or the function has the
  80695. ** SQLITE_FUNC_CONST flag. */
  80696. case TK_FUNCTION:
  80697. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  80698. return WRC_Continue;
  80699. }else{
  80700. pWalker->eCode = 0;
  80701. return WRC_Abort;
  80702. }
  80703. case TK_ID:
  80704. case TK_COLUMN:
  80705. case TK_AGG_FUNCTION:
  80706. case TK_AGG_COLUMN:
  80707. testcase( pExpr->op==TK_ID );
  80708. testcase( pExpr->op==TK_COLUMN );
  80709. testcase( pExpr->op==TK_AGG_FUNCTION );
  80710. testcase( pExpr->op==TK_AGG_COLUMN );
  80711. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  80712. return WRC_Continue;
  80713. }else{
  80714. pWalker->eCode = 0;
  80715. return WRC_Abort;
  80716. }
  80717. case TK_VARIABLE:
  80718. if( pWalker->eCode==5 ){
  80719. /* Silently convert bound parameters that appear inside of CREATE
  80720. ** statements into a NULL when parsing the CREATE statement text out
  80721. ** of the sqlite_master table */
  80722. pExpr->op = TK_NULL;
  80723. }else if( pWalker->eCode==4 ){
  80724. /* A bound parameter in a CREATE statement that originates from
  80725. ** sqlite3_prepare() causes an error */
  80726. pWalker->eCode = 0;
  80727. return WRC_Abort;
  80728. }
  80729. /* Fall through */
  80730. default:
  80731. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  80732. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  80733. return WRC_Continue;
  80734. }
  80735. }
  80736. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  80737. UNUSED_PARAMETER(NotUsed);
  80738. pWalker->eCode = 0;
  80739. return WRC_Abort;
  80740. }
  80741. static int exprIsConst(Expr *p, int initFlag, int iCur){
  80742. Walker w;
  80743. memset(&w, 0, sizeof(w));
  80744. w.eCode = initFlag;
  80745. w.xExprCallback = exprNodeIsConstant;
  80746. w.xSelectCallback = selectNodeIsConstant;
  80747. w.u.iCur = iCur;
  80748. sqlite3WalkExpr(&w, p);
  80749. return w.eCode;
  80750. }
  80751. /*
  80752. ** Walk an expression tree. Return non-zero if the expression is constant
  80753. ** and 0 if it involves variables or function calls.
  80754. **
  80755. ** For the purposes of this function, a double-quoted string (ex: "abc")
  80756. ** is considered a variable but a single-quoted string (ex: 'abc') is
  80757. ** a constant.
  80758. */
  80759. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  80760. return exprIsConst(p, 1, 0);
  80761. }
  80762. /*
  80763. ** Walk an expression tree. Return non-zero if the expression is constant
  80764. ** that does no originate from the ON or USING clauses of a join.
  80765. ** Return 0 if it involves variables or function calls or terms from
  80766. ** an ON or USING clause.
  80767. */
  80768. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  80769. return exprIsConst(p, 2, 0);
  80770. }
  80771. /*
  80772. ** Walk an expression tree. Return non-zero if the expression is constant
  80773. ** for any single row of the table with cursor iCur. In other words, the
  80774. ** expression must not refer to any non-deterministic function nor any
  80775. ** table other than iCur.
  80776. */
  80777. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  80778. return exprIsConst(p, 3, iCur);
  80779. }
  80780. /*
  80781. ** Walk an expression tree. Return non-zero if the expression is constant
  80782. ** or a function call with constant arguments. Return and 0 if there
  80783. ** are any variables.
  80784. **
  80785. ** For the purposes of this function, a double-quoted string (ex: "abc")
  80786. ** is considered a variable but a single-quoted string (ex: 'abc') is
  80787. ** a constant.
  80788. */
  80789. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  80790. assert( isInit==0 || isInit==1 );
  80791. return exprIsConst(p, 4+isInit, 0);
  80792. }
  80793. /*
  80794. ** If the expression p codes a constant integer that is small enough
  80795. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  80796. ** in *pValue. If the expression is not an integer or if it is too big
  80797. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  80798. */
  80799. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  80800. int rc = 0;
  80801. /* If an expression is an integer literal that fits in a signed 32-bit
  80802. ** integer, then the EP_IntValue flag will have already been set */
  80803. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  80804. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  80805. if( p->flags & EP_IntValue ){
  80806. *pValue = p->u.iValue;
  80807. return 1;
  80808. }
  80809. switch( p->op ){
  80810. case TK_UPLUS: {
  80811. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  80812. break;
  80813. }
  80814. case TK_UMINUS: {
  80815. int v;
  80816. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  80817. assert( v!=(-2147483647-1) );
  80818. *pValue = -v;
  80819. rc = 1;
  80820. }
  80821. break;
  80822. }
  80823. default: break;
  80824. }
  80825. return rc;
  80826. }
  80827. /*
  80828. ** Return FALSE if there is no chance that the expression can be NULL.
  80829. **
  80830. ** If the expression might be NULL or if the expression is too complex
  80831. ** to tell return TRUE.
  80832. **
  80833. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  80834. ** when we know that a value cannot be NULL. Hence, a false positive
  80835. ** (returning TRUE when in fact the expression can never be NULL) might
  80836. ** be a small performance hit but is otherwise harmless. On the other
  80837. ** hand, a false negative (returning FALSE when the result could be NULL)
  80838. ** will likely result in an incorrect answer. So when in doubt, return
  80839. ** TRUE.
  80840. */
  80841. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  80842. u8 op;
  80843. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  80844. op = p->op;
  80845. if( op==TK_REGISTER ) op = p->op2;
  80846. switch( op ){
  80847. case TK_INTEGER:
  80848. case TK_STRING:
  80849. case TK_FLOAT:
  80850. case TK_BLOB:
  80851. return 0;
  80852. case TK_COLUMN:
  80853. assert( p->pTab!=0 );
  80854. return ExprHasProperty(p, EP_CanBeNull) ||
  80855. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  80856. default:
  80857. return 1;
  80858. }
  80859. }
  80860. /*
  80861. ** Return TRUE if the given expression is a constant which would be
  80862. ** unchanged by OP_Affinity with the affinity given in the second
  80863. ** argument.
  80864. **
  80865. ** This routine is used to determine if the OP_Affinity operation
  80866. ** can be omitted. When in doubt return FALSE. A false negative
  80867. ** is harmless. A false positive, however, can result in the wrong
  80868. ** answer.
  80869. */
  80870. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  80871. u8 op;
  80872. if( aff==SQLITE_AFF_BLOB ) return 1;
  80873. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  80874. op = p->op;
  80875. if( op==TK_REGISTER ) op = p->op2;
  80876. switch( op ){
  80877. case TK_INTEGER: {
  80878. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  80879. }
  80880. case TK_FLOAT: {
  80881. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  80882. }
  80883. case TK_STRING: {
  80884. return aff==SQLITE_AFF_TEXT;
  80885. }
  80886. case TK_BLOB: {
  80887. return 1;
  80888. }
  80889. case TK_COLUMN: {
  80890. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  80891. return p->iColumn<0
  80892. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  80893. }
  80894. default: {
  80895. return 0;
  80896. }
  80897. }
  80898. }
  80899. /*
  80900. ** Return TRUE if the given string is a row-id column name.
  80901. */
  80902. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  80903. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  80904. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  80905. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  80906. return 0;
  80907. }
  80908. /*
  80909. ** Return true if we are able to the IN operator optimization on a
  80910. ** query of the form
  80911. **
  80912. ** x IN (SELECT ...)
  80913. **
  80914. ** Where the SELECT... clause is as specified by the parameter to this
  80915. ** routine.
  80916. **
  80917. ** The Select object passed in has already been preprocessed and no
  80918. ** errors have been found.
  80919. */
  80920. #ifndef SQLITE_OMIT_SUBQUERY
  80921. static int isCandidateForInOpt(Select *p){
  80922. SrcList *pSrc;
  80923. ExprList *pEList;
  80924. Table *pTab;
  80925. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  80926. if( p->pPrior ) return 0; /* Not a compound SELECT */
  80927. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  80928. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  80929. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  80930. return 0; /* No DISTINCT keyword and no aggregate functions */
  80931. }
  80932. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  80933. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  80934. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  80935. if( p->pWhere ) return 0; /* Has no WHERE clause */
  80936. pSrc = p->pSrc;
  80937. assert( pSrc!=0 );
  80938. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  80939. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  80940. pTab = pSrc->a[0].pTab;
  80941. if( NEVER(pTab==0) ) return 0;
  80942. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  80943. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  80944. pEList = p->pEList;
  80945. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  80946. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  80947. return 1;
  80948. }
  80949. #endif /* SQLITE_OMIT_SUBQUERY */
  80950. /*
  80951. ** Code an OP_Once instruction and allocate space for its flag. Return the
  80952. ** address of the new instruction.
  80953. */
  80954. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  80955. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  80956. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  80957. }
  80958. /*
  80959. ** Generate code that checks the left-most column of index table iCur to see if
  80960. ** it contains any NULL entries. Cause the register at regHasNull to be set
  80961. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  80962. ** to be set to NULL if iCur contains one or more NULL values.
  80963. */
  80964. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  80965. int addr1;
  80966. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  80967. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  80968. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  80969. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  80970. VdbeComment((v, "first_entry_in(%d)", iCur));
  80971. sqlite3VdbeJumpHere(v, addr1);
  80972. }
  80973. #ifndef SQLITE_OMIT_SUBQUERY
  80974. /*
  80975. ** The argument is an IN operator with a list (not a subquery) on the
  80976. ** right-hand side. Return TRUE if that list is constant.
  80977. */
  80978. static int sqlite3InRhsIsConstant(Expr *pIn){
  80979. Expr *pLHS;
  80980. int res;
  80981. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  80982. pLHS = pIn->pLeft;
  80983. pIn->pLeft = 0;
  80984. res = sqlite3ExprIsConstant(pIn);
  80985. pIn->pLeft = pLHS;
  80986. return res;
  80987. }
  80988. #endif
  80989. /*
  80990. ** This function is used by the implementation of the IN (...) operator.
  80991. ** The pX parameter is the expression on the RHS of the IN operator, which
  80992. ** might be either a list of expressions or a subquery.
  80993. **
  80994. ** The job of this routine is to find or create a b-tree object that can
  80995. ** be used either to test for membership in the RHS set or to iterate through
  80996. ** all members of the RHS set, skipping duplicates.
  80997. **
  80998. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  80999. ** and pX->iTable is set to the index of that cursor.
  81000. **
  81001. ** The returned value of this function indicates the b-tree type, as follows:
  81002. **
  81003. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  81004. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  81005. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  81006. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  81007. ** populated epheremal table.
  81008. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  81009. ** implemented as a sequence of comparisons.
  81010. **
  81011. ** An existing b-tree might be used if the RHS expression pX is a simple
  81012. ** subquery such as:
  81013. **
  81014. ** SELECT <column> FROM <table>
  81015. **
  81016. ** If the RHS of the IN operator is a list or a more complex subquery, then
  81017. ** an ephemeral table might need to be generated from the RHS and then
  81018. ** pX->iTable made to point to the ephemeral table instead of an
  81019. ** existing table.
  81020. **
  81021. ** The inFlags parameter must contain exactly one of the bits
  81022. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  81023. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  81024. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  81025. ** IN index will be used to loop over all values of the RHS of the
  81026. ** IN operator.
  81027. **
  81028. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  81029. ** through the set members) then the b-tree must not contain duplicates.
  81030. ** An epheremal table must be used unless the selected <column> is guaranteed
  81031. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  81032. ** has a UNIQUE constraint or UNIQUE index.
  81033. **
  81034. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  81035. ** for fast set membership tests) then an epheremal table must
  81036. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  81037. ** be found with <column> as its left-most column.
  81038. **
  81039. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  81040. ** if the RHS of the IN operator is a list (not a subquery) then this
  81041. ** routine might decide that creating an ephemeral b-tree for membership
  81042. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  81043. ** calling routine should implement the IN operator using a sequence
  81044. ** of Eq or Ne comparison operations.
  81045. **
  81046. ** When the b-tree is being used for membership tests, the calling function
  81047. ** might need to know whether or not the RHS side of the IN operator
  81048. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  81049. ** if there is any chance that the (...) might contain a NULL value at
  81050. ** runtime, then a register is allocated and the register number written
  81051. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  81052. ** NULL value, then *prRhsHasNull is left unchanged.
  81053. **
  81054. ** If a register is allocated and its location stored in *prRhsHasNull, then
  81055. ** the value in that register will be NULL if the b-tree contains one or more
  81056. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  81057. ** NULL values.
  81058. */
  81059. #ifndef SQLITE_OMIT_SUBQUERY
  81060. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  81061. Select *p; /* SELECT to the right of IN operator */
  81062. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  81063. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  81064. int mustBeUnique; /* True if RHS must be unique */
  81065. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  81066. assert( pX->op==TK_IN );
  81067. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  81068. /* Check to see if an existing table or index can be used to
  81069. ** satisfy the query. This is preferable to generating a new
  81070. ** ephemeral table.
  81071. */
  81072. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  81073. if( pParse->nErr==0 && isCandidateForInOpt(p) ){
  81074. sqlite3 *db = pParse->db; /* Database connection */
  81075. Table *pTab; /* Table <table>. */
  81076. Expr *pExpr; /* Expression <column> */
  81077. i16 iCol; /* Index of column <column> */
  81078. i16 iDb; /* Database idx for pTab */
  81079. assert( p ); /* Because of isCandidateForInOpt(p) */
  81080. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  81081. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  81082. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  81083. pTab = p->pSrc->a[0].pTab;
  81084. pExpr = p->pEList->a[0].pExpr;
  81085. iCol = (i16)pExpr->iColumn;
  81086. /* Code an OP_Transaction and OP_TableLock for <table>. */
  81087. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81088. sqlite3CodeVerifySchema(pParse, iDb);
  81089. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  81090. /* This function is only called from two places. In both cases the vdbe
  81091. ** has already been allocated. So assume sqlite3GetVdbe() is always
  81092. ** successful here.
  81093. */
  81094. assert(v);
  81095. if( iCol<0 ){
  81096. int iAddr = sqlite3CodeOnce(pParse);
  81097. VdbeCoverage(v);
  81098. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  81099. eType = IN_INDEX_ROWID;
  81100. sqlite3VdbeJumpHere(v, iAddr);
  81101. }else{
  81102. Index *pIdx; /* Iterator variable */
  81103. /* The collation sequence used by the comparison. If an index is to
  81104. ** be used in place of a temp-table, it must be ordered according
  81105. ** to this collation sequence. */
  81106. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  81107. /* Check that the affinity that will be used to perform the
  81108. ** comparison is the same as the affinity of the column. If
  81109. ** it is not, it is not possible to use any index.
  81110. */
  81111. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  81112. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  81113. if( (pIdx->aiColumn[0]==iCol)
  81114. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  81115. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  81116. ){
  81117. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  81118. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  81119. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  81120. VdbeComment((v, "%s", pIdx->zName));
  81121. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  81122. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  81123. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  81124. *prRhsHasNull = ++pParse->nMem;
  81125. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  81126. }
  81127. sqlite3VdbeJumpHere(v, iAddr);
  81128. }
  81129. }
  81130. }
  81131. }
  81132. /* If no preexisting index is available for the IN clause
  81133. ** and IN_INDEX_NOOP is an allowed reply
  81134. ** and the RHS of the IN operator is a list, not a subquery
  81135. ** and the RHS is not contant or has two or fewer terms,
  81136. ** then it is not worth creating an ephemeral table to evaluate
  81137. ** the IN operator so return IN_INDEX_NOOP.
  81138. */
  81139. if( eType==0
  81140. && (inFlags & IN_INDEX_NOOP_OK)
  81141. && !ExprHasProperty(pX, EP_xIsSelect)
  81142. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  81143. ){
  81144. eType = IN_INDEX_NOOP;
  81145. }
  81146. if( eType==0 ){
  81147. /* Could not find an existing table or index to use as the RHS b-tree.
  81148. ** We will have to generate an ephemeral table to do the job.
  81149. */
  81150. u32 savedNQueryLoop = pParse->nQueryLoop;
  81151. int rMayHaveNull = 0;
  81152. eType = IN_INDEX_EPH;
  81153. if( inFlags & IN_INDEX_LOOP ){
  81154. pParse->nQueryLoop = 0;
  81155. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  81156. eType = IN_INDEX_ROWID;
  81157. }
  81158. }else if( prRhsHasNull ){
  81159. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  81160. }
  81161. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  81162. pParse->nQueryLoop = savedNQueryLoop;
  81163. }else{
  81164. pX->iTable = iTab;
  81165. }
  81166. return eType;
  81167. }
  81168. #endif
  81169. /*
  81170. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  81171. ** or IN operators. Examples:
  81172. **
  81173. ** (SELECT a FROM b) -- subquery
  81174. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  81175. ** x IN (4,5,11) -- IN operator with list on right-hand side
  81176. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  81177. **
  81178. ** The pExpr parameter describes the expression that contains the IN
  81179. ** operator or subquery.
  81180. **
  81181. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  81182. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  81183. ** to some integer key column of a table B-Tree. In this case, use an
  81184. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  81185. ** (slower) variable length keys B-Tree.
  81186. **
  81187. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  81188. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  81189. ** All this routine does is initialize the register given by rMayHaveNull
  81190. ** to NULL. Calling routines will take care of changing this register
  81191. ** value to non-NULL if the RHS is NULL-free.
  81192. **
  81193. ** For a SELECT or EXISTS operator, return the register that holds the
  81194. ** result. For IN operators or if an error occurs, the return value is 0.
  81195. */
  81196. #ifndef SQLITE_OMIT_SUBQUERY
  81197. SQLITE_PRIVATE int sqlite3CodeSubselect(
  81198. Parse *pParse, /* Parsing context */
  81199. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  81200. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  81201. int isRowid /* If true, LHS of IN operator is a rowid */
  81202. ){
  81203. int jmpIfDynamic = -1; /* One-time test address */
  81204. int rReg = 0; /* Register storing resulting */
  81205. Vdbe *v = sqlite3GetVdbe(pParse);
  81206. if( NEVER(v==0) ) return 0;
  81207. sqlite3ExprCachePush(pParse);
  81208. /* This code must be run in its entirety every time it is encountered
  81209. ** if any of the following is true:
  81210. **
  81211. ** * The right-hand side is a correlated subquery
  81212. ** * The right-hand side is an expression list containing variables
  81213. ** * We are inside a trigger
  81214. **
  81215. ** If all of the above are false, then we can run this code just once
  81216. ** save the results, and reuse the same result on subsequent invocations.
  81217. */
  81218. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  81219. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  81220. }
  81221. #ifndef SQLITE_OMIT_EXPLAIN
  81222. if( pParse->explain==2 ){
  81223. char *zMsg = sqlite3MPrintf(
  81224. pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
  81225. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  81226. );
  81227. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  81228. }
  81229. #endif
  81230. switch( pExpr->op ){
  81231. case TK_IN: {
  81232. char affinity; /* Affinity of the LHS of the IN */
  81233. int addr; /* Address of OP_OpenEphemeral instruction */
  81234. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  81235. KeyInfo *pKeyInfo = 0; /* Key information */
  81236. affinity = sqlite3ExprAffinity(pLeft);
  81237. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  81238. ** expression it is handled the same way. An ephemeral table is
  81239. ** filled with single-field index keys representing the results
  81240. ** from the SELECT or the <exprlist>.
  81241. **
  81242. ** If the 'x' expression is a column value, or the SELECT...
  81243. ** statement returns a column value, then the affinity of that
  81244. ** column is used to build the index keys. If both 'x' and the
  81245. ** SELECT... statement are columns, then numeric affinity is used
  81246. ** if either column has NUMERIC or INTEGER affinity. If neither
  81247. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  81248. ** is used.
  81249. */
  81250. pExpr->iTable = pParse->nTab++;
  81251. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  81252. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  81253. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  81254. /* Case 1: expr IN (SELECT ...)
  81255. **
  81256. ** Generate code to write the results of the select into the temporary
  81257. ** table allocated and opened above.
  81258. */
  81259. Select *pSelect = pExpr->x.pSelect;
  81260. SelectDest dest;
  81261. ExprList *pEList;
  81262. assert( !isRowid );
  81263. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  81264. dest.affSdst = (u8)affinity;
  81265. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  81266. pSelect->iLimit = 0;
  81267. testcase( pSelect->selFlags & SF_Distinct );
  81268. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  81269. if( sqlite3Select(pParse, pSelect, &dest) ){
  81270. sqlite3KeyInfoUnref(pKeyInfo);
  81271. return 0;
  81272. }
  81273. pEList = pSelect->pEList;
  81274. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  81275. assert( pEList!=0 );
  81276. assert( pEList->nExpr>0 );
  81277. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  81278. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  81279. pEList->a[0].pExpr);
  81280. }else if( ALWAYS(pExpr->x.pList!=0) ){
  81281. /* Case 2: expr IN (exprlist)
  81282. **
  81283. ** For each expression, build an index key from the evaluation and
  81284. ** store it in the temporary table. If <expr> is a column, then use
  81285. ** that columns affinity when building index keys. If <expr> is not
  81286. ** a column, use numeric affinity.
  81287. */
  81288. int i;
  81289. ExprList *pList = pExpr->x.pList;
  81290. struct ExprList_item *pItem;
  81291. int r1, r2, r3;
  81292. if( !affinity ){
  81293. affinity = SQLITE_AFF_BLOB;
  81294. }
  81295. if( pKeyInfo ){
  81296. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  81297. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  81298. }
  81299. /* Loop through each expression in <exprlist>. */
  81300. r1 = sqlite3GetTempReg(pParse);
  81301. r2 = sqlite3GetTempReg(pParse);
  81302. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  81303. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  81304. Expr *pE2 = pItem->pExpr;
  81305. int iValToIns;
  81306. /* If the expression is not constant then we will need to
  81307. ** disable the test that was generated above that makes sure
  81308. ** this code only executes once. Because for a non-constant
  81309. ** expression we need to rerun this code each time.
  81310. */
  81311. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  81312. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  81313. jmpIfDynamic = -1;
  81314. }
  81315. /* Evaluate the expression and insert it into the temp table */
  81316. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  81317. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  81318. }else{
  81319. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  81320. if( isRowid ){
  81321. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  81322. sqlite3VdbeCurrentAddr(v)+2);
  81323. VdbeCoverage(v);
  81324. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  81325. }else{
  81326. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  81327. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  81328. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  81329. }
  81330. }
  81331. }
  81332. sqlite3ReleaseTempReg(pParse, r1);
  81333. sqlite3ReleaseTempReg(pParse, r2);
  81334. }
  81335. if( pKeyInfo ){
  81336. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  81337. }
  81338. break;
  81339. }
  81340. case TK_EXISTS:
  81341. case TK_SELECT:
  81342. default: {
  81343. /* If this has to be a scalar SELECT. Generate code to put the
  81344. ** value of this select in a memory cell and record the number
  81345. ** of the memory cell in iColumn. If this is an EXISTS, write
  81346. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  81347. ** and record that memory cell in iColumn.
  81348. */
  81349. Select *pSel; /* SELECT statement to encode */
  81350. SelectDest dest; /* How to deal with SELECt result */
  81351. testcase( pExpr->op==TK_EXISTS );
  81352. testcase( pExpr->op==TK_SELECT );
  81353. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  81354. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  81355. pSel = pExpr->x.pSelect;
  81356. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  81357. if( pExpr->op==TK_SELECT ){
  81358. dest.eDest = SRT_Mem;
  81359. dest.iSdst = dest.iSDParm;
  81360. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  81361. VdbeComment((v, "Init subquery result"));
  81362. }else{
  81363. dest.eDest = SRT_Exists;
  81364. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  81365. VdbeComment((v, "Init EXISTS result"));
  81366. }
  81367. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  81368. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  81369. &sqlite3IntTokens[1]);
  81370. pSel->iLimit = 0;
  81371. pSel->selFlags &= ~SF_MultiValue;
  81372. if( sqlite3Select(pParse, pSel, &dest) ){
  81373. return 0;
  81374. }
  81375. rReg = dest.iSDParm;
  81376. ExprSetVVAProperty(pExpr, EP_NoReduce);
  81377. break;
  81378. }
  81379. }
  81380. if( rHasNullFlag ){
  81381. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  81382. }
  81383. if( jmpIfDynamic>=0 ){
  81384. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  81385. }
  81386. sqlite3ExprCachePop(pParse);
  81387. return rReg;
  81388. }
  81389. #endif /* SQLITE_OMIT_SUBQUERY */
  81390. #ifndef SQLITE_OMIT_SUBQUERY
  81391. /*
  81392. ** Generate code for an IN expression.
  81393. **
  81394. ** x IN (SELECT ...)
  81395. ** x IN (value, value, ...)
  81396. **
  81397. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  81398. ** is an array of zero or more values. The expression is true if the LHS is
  81399. ** contained within the RHS. The value of the expression is unknown (NULL)
  81400. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  81401. ** RHS contains one or more NULL values.
  81402. **
  81403. ** This routine generates code that jumps to destIfFalse if the LHS is not
  81404. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  81405. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  81406. ** within the RHS then fall through.
  81407. */
  81408. static void sqlite3ExprCodeIN(
  81409. Parse *pParse, /* Parsing and code generating context */
  81410. Expr *pExpr, /* The IN expression */
  81411. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  81412. int destIfNull /* Jump here if the results are unknown due to NULLs */
  81413. ){
  81414. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  81415. char affinity; /* Comparison affinity to use */
  81416. int eType; /* Type of the RHS */
  81417. int r1; /* Temporary use register */
  81418. Vdbe *v; /* Statement under construction */
  81419. /* Compute the RHS. After this step, the table with cursor
  81420. ** pExpr->iTable will contains the values that make up the RHS.
  81421. */
  81422. v = pParse->pVdbe;
  81423. assert( v!=0 ); /* OOM detected prior to this routine */
  81424. VdbeNoopComment((v, "begin IN expr"));
  81425. eType = sqlite3FindInIndex(pParse, pExpr,
  81426. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  81427. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  81428. /* Figure out the affinity to use to create a key from the results
  81429. ** of the expression. affinityStr stores a static string suitable for
  81430. ** P4 of OP_MakeRecord.
  81431. */
  81432. affinity = comparisonAffinity(pExpr);
  81433. /* Code the LHS, the <expr> from "<expr> IN (...)".
  81434. */
  81435. sqlite3ExprCachePush(pParse);
  81436. r1 = sqlite3GetTempReg(pParse);
  81437. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  81438. /* If sqlite3FindInIndex() did not find or create an index that is
  81439. ** suitable for evaluating the IN operator, then evaluate using a
  81440. ** sequence of comparisons.
  81441. */
  81442. if( eType==IN_INDEX_NOOP ){
  81443. ExprList *pList = pExpr->x.pList;
  81444. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  81445. int labelOk = sqlite3VdbeMakeLabel(v);
  81446. int r2, regToFree;
  81447. int regCkNull = 0;
  81448. int ii;
  81449. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81450. if( destIfNull!=destIfFalse ){
  81451. regCkNull = sqlite3GetTempReg(pParse);
  81452. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  81453. }
  81454. for(ii=0; ii<pList->nExpr; ii++){
  81455. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  81456. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  81457. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  81458. }
  81459. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  81460. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  81461. (void*)pColl, P4_COLLSEQ);
  81462. VdbeCoverageIf(v, ii<pList->nExpr-1);
  81463. VdbeCoverageIf(v, ii==pList->nExpr-1);
  81464. sqlite3VdbeChangeP5(v, affinity);
  81465. }else{
  81466. assert( destIfNull==destIfFalse );
  81467. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  81468. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  81469. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  81470. }
  81471. sqlite3ReleaseTempReg(pParse, regToFree);
  81472. }
  81473. if( regCkNull ){
  81474. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  81475. sqlite3VdbeGoto(v, destIfFalse);
  81476. }
  81477. sqlite3VdbeResolveLabel(v, labelOk);
  81478. sqlite3ReleaseTempReg(pParse, regCkNull);
  81479. }else{
  81480. /* If the LHS is NULL, then the result is either false or NULL depending
  81481. ** on whether the RHS is empty or not, respectively.
  81482. */
  81483. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  81484. if( destIfNull==destIfFalse ){
  81485. /* Shortcut for the common case where the false and NULL outcomes are
  81486. ** the same. */
  81487. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  81488. }else{
  81489. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  81490. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  81491. VdbeCoverage(v);
  81492. sqlite3VdbeGoto(v, destIfNull);
  81493. sqlite3VdbeJumpHere(v, addr1);
  81494. }
  81495. }
  81496. if( eType==IN_INDEX_ROWID ){
  81497. /* In this case, the RHS is the ROWID of table b-tree
  81498. */
  81499. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  81500. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  81501. VdbeCoverage(v);
  81502. }else{
  81503. /* In this case, the RHS is an index b-tree.
  81504. */
  81505. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  81506. /* If the set membership test fails, then the result of the
  81507. ** "x IN (...)" expression must be either 0 or NULL. If the set
  81508. ** contains no NULL values, then the result is 0. If the set
  81509. ** contains one or more NULL values, then the result of the
  81510. ** expression is also NULL.
  81511. */
  81512. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  81513. if( rRhsHasNull==0 ){
  81514. /* This branch runs if it is known at compile time that the RHS
  81515. ** cannot contain NULL values. This happens as the result
  81516. ** of a "NOT NULL" constraint in the database schema.
  81517. **
  81518. ** Also run this branch if NULL is equivalent to FALSE
  81519. ** for this particular IN operator.
  81520. */
  81521. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  81522. VdbeCoverage(v);
  81523. }else{
  81524. /* In this branch, the RHS of the IN might contain a NULL and
  81525. ** the presence of a NULL on the RHS makes a difference in the
  81526. ** outcome.
  81527. */
  81528. int addr1;
  81529. /* First check to see if the LHS is contained in the RHS. If so,
  81530. ** then the answer is TRUE the presence of NULLs in the RHS does
  81531. ** not matter. If the LHS is not contained in the RHS, then the
  81532. ** answer is NULL if the RHS contains NULLs and the answer is
  81533. ** FALSE if the RHS is NULL-free.
  81534. */
  81535. addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  81536. VdbeCoverage(v);
  81537. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  81538. VdbeCoverage(v);
  81539. sqlite3VdbeGoto(v, destIfFalse);
  81540. sqlite3VdbeJumpHere(v, addr1);
  81541. }
  81542. }
  81543. }
  81544. sqlite3ReleaseTempReg(pParse, r1);
  81545. sqlite3ExprCachePop(pParse);
  81546. VdbeComment((v, "end IN expr"));
  81547. }
  81548. #endif /* SQLITE_OMIT_SUBQUERY */
  81549. #ifndef SQLITE_OMIT_FLOATING_POINT
  81550. /*
  81551. ** Generate an instruction that will put the floating point
  81552. ** value described by z[0..n-1] into register iMem.
  81553. **
  81554. ** The z[] string will probably not be zero-terminated. But the
  81555. ** z[n] character is guaranteed to be something that does not look
  81556. ** like the continuation of the number.
  81557. */
  81558. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  81559. if( ALWAYS(z!=0) ){
  81560. double value;
  81561. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  81562. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  81563. if( negateFlag ) value = -value;
  81564. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  81565. }
  81566. }
  81567. #endif
  81568. /*
  81569. ** Generate an instruction that will put the integer describe by
  81570. ** text z[0..n-1] into register iMem.
  81571. **
  81572. ** Expr.u.zToken is always UTF8 and zero-terminated.
  81573. */
  81574. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  81575. Vdbe *v = pParse->pVdbe;
  81576. if( pExpr->flags & EP_IntValue ){
  81577. int i = pExpr->u.iValue;
  81578. assert( i>=0 );
  81579. if( negFlag ) i = -i;
  81580. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  81581. }else{
  81582. int c;
  81583. i64 value;
  81584. const char *z = pExpr->u.zToken;
  81585. assert( z!=0 );
  81586. c = sqlite3DecOrHexToI64(z, &value);
  81587. if( c==0 || (c==2 && negFlag) ){
  81588. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  81589. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  81590. }else{
  81591. #ifdef SQLITE_OMIT_FLOATING_POINT
  81592. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  81593. #else
  81594. #ifndef SQLITE_OMIT_HEX_INTEGER
  81595. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  81596. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  81597. }else
  81598. #endif
  81599. {
  81600. codeReal(v, z, negFlag, iMem);
  81601. }
  81602. #endif
  81603. }
  81604. }
  81605. }
  81606. /*
  81607. ** Clear a cache entry.
  81608. */
  81609. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  81610. if( p->tempReg ){
  81611. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  81612. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  81613. }
  81614. p->tempReg = 0;
  81615. }
  81616. }
  81617. /*
  81618. ** Record in the column cache that a particular column from a
  81619. ** particular table is stored in a particular register.
  81620. */
  81621. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  81622. int i;
  81623. int minLru;
  81624. int idxLru;
  81625. struct yColCache *p;
  81626. /* Unless an error has occurred, register numbers are always positive. */
  81627. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  81628. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  81629. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  81630. ** for testing only - to verify that SQLite always gets the same answer
  81631. ** with and without the column cache.
  81632. */
  81633. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  81634. /* First replace any existing entry.
  81635. **
  81636. ** Actually, the way the column cache is currently used, we are guaranteed
  81637. ** that the object will never already be in cache. Verify this guarantee.
  81638. */
  81639. #ifndef NDEBUG
  81640. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81641. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  81642. }
  81643. #endif
  81644. /* Find an empty slot and replace it */
  81645. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81646. if( p->iReg==0 ){
  81647. p->iLevel = pParse->iCacheLevel;
  81648. p->iTable = iTab;
  81649. p->iColumn = iCol;
  81650. p->iReg = iReg;
  81651. p->tempReg = 0;
  81652. p->lru = pParse->iCacheCnt++;
  81653. return;
  81654. }
  81655. }
  81656. /* Replace the last recently used */
  81657. minLru = 0x7fffffff;
  81658. idxLru = -1;
  81659. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81660. if( p->lru<minLru ){
  81661. idxLru = i;
  81662. minLru = p->lru;
  81663. }
  81664. }
  81665. if( ALWAYS(idxLru>=0) ){
  81666. p = &pParse->aColCache[idxLru];
  81667. p->iLevel = pParse->iCacheLevel;
  81668. p->iTable = iTab;
  81669. p->iColumn = iCol;
  81670. p->iReg = iReg;
  81671. p->tempReg = 0;
  81672. p->lru = pParse->iCacheCnt++;
  81673. return;
  81674. }
  81675. }
  81676. /*
  81677. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  81678. ** Purge the range of registers from the column cache.
  81679. */
  81680. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  81681. int i;
  81682. int iLast = iReg + nReg - 1;
  81683. struct yColCache *p;
  81684. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81685. int r = p->iReg;
  81686. if( r>=iReg && r<=iLast ){
  81687. cacheEntryClear(pParse, p);
  81688. p->iReg = 0;
  81689. }
  81690. }
  81691. }
  81692. /*
  81693. ** Remember the current column cache context. Any new entries added
  81694. ** added to the column cache after this call are removed when the
  81695. ** corresponding pop occurs.
  81696. */
  81697. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  81698. pParse->iCacheLevel++;
  81699. #ifdef SQLITE_DEBUG
  81700. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  81701. printf("PUSH to %d\n", pParse->iCacheLevel);
  81702. }
  81703. #endif
  81704. }
  81705. /*
  81706. ** Remove from the column cache any entries that were added since the
  81707. ** the previous sqlite3ExprCachePush operation. In other words, restore
  81708. ** the cache to the state it was in prior the most recent Push.
  81709. */
  81710. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  81711. int i;
  81712. struct yColCache *p;
  81713. assert( pParse->iCacheLevel>=1 );
  81714. pParse->iCacheLevel--;
  81715. #ifdef SQLITE_DEBUG
  81716. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  81717. printf("POP to %d\n", pParse->iCacheLevel);
  81718. }
  81719. #endif
  81720. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81721. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  81722. cacheEntryClear(pParse, p);
  81723. p->iReg = 0;
  81724. }
  81725. }
  81726. }
  81727. /*
  81728. ** When a cached column is reused, make sure that its register is
  81729. ** no longer available as a temp register. ticket #3879: that same
  81730. ** register might be in the cache in multiple places, so be sure to
  81731. ** get them all.
  81732. */
  81733. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  81734. int i;
  81735. struct yColCache *p;
  81736. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81737. if( p->iReg==iReg ){
  81738. p->tempReg = 0;
  81739. }
  81740. }
  81741. }
  81742. /* Generate code that will load into register regOut a value that is
  81743. ** appropriate for the iIdxCol-th column of index pIdx.
  81744. */
  81745. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  81746. Parse *pParse, /* The parsing context */
  81747. Index *pIdx, /* The index whose column is to be loaded */
  81748. int iTabCur, /* Cursor pointing to a table row */
  81749. int iIdxCol, /* The column of the index to be loaded */
  81750. int regOut /* Store the index column value in this register */
  81751. ){
  81752. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  81753. if( iTabCol==XN_EXPR ){
  81754. assert( pIdx->aColExpr );
  81755. assert( pIdx->aColExpr->nExpr>iIdxCol );
  81756. pParse->iSelfTab = iTabCur;
  81757. sqlite3ExprCode(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  81758. }else{
  81759. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  81760. iTabCol, regOut);
  81761. }
  81762. }
  81763. /*
  81764. ** Generate code to extract the value of the iCol-th column of a table.
  81765. */
  81766. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  81767. Vdbe *v, /* The VDBE under construction */
  81768. Table *pTab, /* The table containing the value */
  81769. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  81770. int iCol, /* Index of the column to extract */
  81771. int regOut /* Extract the value into this register */
  81772. ){
  81773. if( iCol<0 || iCol==pTab->iPKey ){
  81774. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  81775. }else{
  81776. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  81777. int x = iCol;
  81778. if( !HasRowid(pTab) ){
  81779. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  81780. }
  81781. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  81782. }
  81783. if( iCol>=0 ){
  81784. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  81785. }
  81786. }
  81787. /*
  81788. ** Generate code that will extract the iColumn-th column from
  81789. ** table pTab and store the column value in a register. An effort
  81790. ** is made to store the column value in register iReg, but this is
  81791. ** not guaranteed. The location of the column value is returned.
  81792. **
  81793. ** There must be an open cursor to pTab in iTable when this routine
  81794. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  81795. */
  81796. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  81797. Parse *pParse, /* Parsing and code generating context */
  81798. Table *pTab, /* Description of the table we are reading from */
  81799. int iColumn, /* Index of the table column */
  81800. int iTable, /* The cursor pointing to the table */
  81801. int iReg, /* Store results here */
  81802. u8 p5 /* P5 value for OP_Column */
  81803. ){
  81804. Vdbe *v = pParse->pVdbe;
  81805. int i;
  81806. struct yColCache *p;
  81807. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81808. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  81809. p->lru = pParse->iCacheCnt++;
  81810. sqlite3ExprCachePinRegister(pParse, p->iReg);
  81811. return p->iReg;
  81812. }
  81813. }
  81814. assert( v!=0 );
  81815. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  81816. if( p5 ){
  81817. sqlite3VdbeChangeP5(v, p5);
  81818. }else{
  81819. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  81820. }
  81821. return iReg;
  81822. }
  81823. /*
  81824. ** Clear all column cache entries.
  81825. */
  81826. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  81827. int i;
  81828. struct yColCache *p;
  81829. #if SQLITE_DEBUG
  81830. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  81831. printf("CLEAR\n");
  81832. }
  81833. #endif
  81834. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81835. if( p->iReg ){
  81836. cacheEntryClear(pParse, p);
  81837. p->iReg = 0;
  81838. }
  81839. }
  81840. }
  81841. /*
  81842. ** Record the fact that an affinity change has occurred on iCount
  81843. ** registers starting with iStart.
  81844. */
  81845. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  81846. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  81847. }
  81848. /*
  81849. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  81850. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  81851. */
  81852. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  81853. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  81854. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  81855. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  81856. }
  81857. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  81858. /*
  81859. ** Return true if any register in the range iFrom..iTo (inclusive)
  81860. ** is used as part of the column cache.
  81861. **
  81862. ** This routine is used within assert() and testcase() macros only
  81863. ** and does not appear in a normal build.
  81864. */
  81865. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  81866. int i;
  81867. struct yColCache *p;
  81868. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81869. int r = p->iReg;
  81870. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  81871. }
  81872. return 0;
  81873. }
  81874. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  81875. /*
  81876. ** Convert an expression node to a TK_REGISTER
  81877. */
  81878. static void exprToRegister(Expr *p, int iReg){
  81879. p->op2 = p->op;
  81880. p->op = TK_REGISTER;
  81881. p->iTable = iReg;
  81882. ExprClearProperty(p, EP_Skip);
  81883. }
  81884. /*
  81885. ** Generate code into the current Vdbe to evaluate the given
  81886. ** expression. Attempt to store the results in register "target".
  81887. ** Return the register where results are stored.
  81888. **
  81889. ** With this routine, there is no guarantee that results will
  81890. ** be stored in target. The result might be stored in some other
  81891. ** register if it is convenient to do so. The calling function
  81892. ** must check the return code and move the results to the desired
  81893. ** register.
  81894. */
  81895. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  81896. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  81897. int op; /* The opcode being coded */
  81898. int inReg = target; /* Results stored in register inReg */
  81899. int regFree1 = 0; /* If non-zero free this temporary register */
  81900. int regFree2 = 0; /* If non-zero free this temporary register */
  81901. int r1, r2, r3, r4; /* Various register numbers */
  81902. sqlite3 *db = pParse->db; /* The database connection */
  81903. Expr tempX; /* Temporary expression node */
  81904. assert( target>0 && target<=pParse->nMem );
  81905. if( v==0 ){
  81906. assert( pParse->db->mallocFailed );
  81907. return 0;
  81908. }
  81909. if( pExpr==0 ){
  81910. op = TK_NULL;
  81911. }else{
  81912. op = pExpr->op;
  81913. }
  81914. switch( op ){
  81915. case TK_AGG_COLUMN: {
  81916. AggInfo *pAggInfo = pExpr->pAggInfo;
  81917. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  81918. if( !pAggInfo->directMode ){
  81919. assert( pCol->iMem>0 );
  81920. inReg = pCol->iMem;
  81921. break;
  81922. }else if( pAggInfo->useSortingIdx ){
  81923. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  81924. pCol->iSorterColumn, target);
  81925. break;
  81926. }
  81927. /* Otherwise, fall thru into the TK_COLUMN case */
  81928. }
  81929. case TK_COLUMN: {
  81930. int iTab = pExpr->iTable;
  81931. if( iTab<0 ){
  81932. if( pParse->ckBase>0 ){
  81933. /* Generating CHECK constraints or inserting into partial index */
  81934. inReg = pExpr->iColumn + pParse->ckBase;
  81935. break;
  81936. }else{
  81937. /* Coding an expression that is part of an index where column names
  81938. ** in the index refer to the table to which the index belongs */
  81939. iTab = pParse->iSelfTab;
  81940. }
  81941. }
  81942. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  81943. pExpr->iColumn, iTab, target,
  81944. pExpr->op2);
  81945. break;
  81946. }
  81947. case TK_INTEGER: {
  81948. codeInteger(pParse, pExpr, 0, target);
  81949. break;
  81950. }
  81951. #ifndef SQLITE_OMIT_FLOATING_POINT
  81952. case TK_FLOAT: {
  81953. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81954. codeReal(v, pExpr->u.zToken, 0, target);
  81955. break;
  81956. }
  81957. #endif
  81958. case TK_STRING: {
  81959. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81960. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  81961. break;
  81962. }
  81963. case TK_NULL: {
  81964. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  81965. break;
  81966. }
  81967. #ifndef SQLITE_OMIT_BLOB_LITERAL
  81968. case TK_BLOB: {
  81969. int n;
  81970. const char *z;
  81971. char *zBlob;
  81972. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81973. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  81974. assert( pExpr->u.zToken[1]=='\'' );
  81975. z = &pExpr->u.zToken[2];
  81976. n = sqlite3Strlen30(z) - 1;
  81977. assert( z[n]=='\'' );
  81978. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  81979. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  81980. break;
  81981. }
  81982. #endif
  81983. case TK_VARIABLE: {
  81984. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81985. assert( pExpr->u.zToken!=0 );
  81986. assert( pExpr->u.zToken[0]!=0 );
  81987. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  81988. if( pExpr->u.zToken[1]!=0 ){
  81989. assert( pExpr->u.zToken[0]=='?'
  81990. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  81991. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  81992. }
  81993. break;
  81994. }
  81995. case TK_REGISTER: {
  81996. inReg = pExpr->iTable;
  81997. break;
  81998. }
  81999. #ifndef SQLITE_OMIT_CAST
  82000. case TK_CAST: {
  82001. /* Expressions of the form: CAST(pLeft AS token) */
  82002. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  82003. if( inReg!=target ){
  82004. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  82005. inReg = target;
  82006. }
  82007. sqlite3VdbeAddOp2(v, OP_Cast, target,
  82008. sqlite3AffinityType(pExpr->u.zToken, 0));
  82009. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  82010. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  82011. break;
  82012. }
  82013. #endif /* SQLITE_OMIT_CAST */
  82014. case TK_LT:
  82015. case TK_LE:
  82016. case TK_GT:
  82017. case TK_GE:
  82018. case TK_NE:
  82019. case TK_EQ: {
  82020. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82021. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82022. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82023. r1, r2, inReg, SQLITE_STOREP2);
  82024. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  82025. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  82026. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  82027. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  82028. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  82029. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  82030. testcase( regFree1==0 );
  82031. testcase( regFree2==0 );
  82032. break;
  82033. }
  82034. case TK_IS:
  82035. case TK_ISNOT: {
  82036. testcase( op==TK_IS );
  82037. testcase( op==TK_ISNOT );
  82038. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82039. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82040. op = (op==TK_IS) ? TK_EQ : TK_NE;
  82041. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82042. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  82043. VdbeCoverageIf(v, op==TK_EQ);
  82044. VdbeCoverageIf(v, op==TK_NE);
  82045. testcase( regFree1==0 );
  82046. testcase( regFree2==0 );
  82047. break;
  82048. }
  82049. case TK_AND:
  82050. case TK_OR:
  82051. case TK_PLUS:
  82052. case TK_STAR:
  82053. case TK_MINUS:
  82054. case TK_REM:
  82055. case TK_BITAND:
  82056. case TK_BITOR:
  82057. case TK_SLASH:
  82058. case TK_LSHIFT:
  82059. case TK_RSHIFT:
  82060. case TK_CONCAT: {
  82061. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  82062. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  82063. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  82064. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  82065. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  82066. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  82067. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  82068. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  82069. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  82070. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  82071. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  82072. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82073. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82074. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  82075. testcase( regFree1==0 );
  82076. testcase( regFree2==0 );
  82077. break;
  82078. }
  82079. case TK_UMINUS: {
  82080. Expr *pLeft = pExpr->pLeft;
  82081. assert( pLeft );
  82082. if( pLeft->op==TK_INTEGER ){
  82083. codeInteger(pParse, pLeft, 1, target);
  82084. #ifndef SQLITE_OMIT_FLOATING_POINT
  82085. }else if( pLeft->op==TK_FLOAT ){
  82086. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82087. codeReal(v, pLeft->u.zToken, 1, target);
  82088. #endif
  82089. }else{
  82090. tempX.op = TK_INTEGER;
  82091. tempX.flags = EP_IntValue|EP_TokenOnly;
  82092. tempX.u.iValue = 0;
  82093. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  82094. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  82095. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  82096. testcase( regFree2==0 );
  82097. }
  82098. inReg = target;
  82099. break;
  82100. }
  82101. case TK_BITNOT:
  82102. case TK_NOT: {
  82103. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  82104. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  82105. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82106. testcase( regFree1==0 );
  82107. inReg = target;
  82108. sqlite3VdbeAddOp2(v, op, r1, inReg);
  82109. break;
  82110. }
  82111. case TK_ISNULL:
  82112. case TK_NOTNULL: {
  82113. int addr;
  82114. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  82115. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  82116. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  82117. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82118. testcase( regFree1==0 );
  82119. addr = sqlite3VdbeAddOp1(v, op, r1);
  82120. VdbeCoverageIf(v, op==TK_ISNULL);
  82121. VdbeCoverageIf(v, op==TK_NOTNULL);
  82122. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  82123. sqlite3VdbeJumpHere(v, addr);
  82124. break;
  82125. }
  82126. case TK_AGG_FUNCTION: {
  82127. AggInfo *pInfo = pExpr->pAggInfo;
  82128. if( pInfo==0 ){
  82129. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82130. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  82131. }else{
  82132. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  82133. }
  82134. break;
  82135. }
  82136. case TK_FUNCTION: {
  82137. ExprList *pFarg; /* List of function arguments */
  82138. int nFarg; /* Number of function arguments */
  82139. FuncDef *pDef; /* The function definition object */
  82140. int nId; /* Length of the function name in bytes */
  82141. const char *zId; /* The function name */
  82142. u32 constMask = 0; /* Mask of function arguments that are constant */
  82143. int i; /* Loop counter */
  82144. u8 enc = ENC(db); /* The text encoding used by this database */
  82145. CollSeq *pColl = 0; /* A collating sequence */
  82146. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  82147. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  82148. pFarg = 0;
  82149. }else{
  82150. pFarg = pExpr->x.pList;
  82151. }
  82152. nFarg = pFarg ? pFarg->nExpr : 0;
  82153. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82154. zId = pExpr->u.zToken;
  82155. nId = sqlite3Strlen30(zId);
  82156. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  82157. if( pDef==0 || pDef->xFunc==0 ){
  82158. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  82159. break;
  82160. }
  82161. /* Attempt a direct implementation of the built-in COALESCE() and
  82162. ** IFNULL() functions. This avoids unnecessary evaluation of
  82163. ** arguments past the first non-NULL argument.
  82164. */
  82165. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  82166. int endCoalesce = sqlite3VdbeMakeLabel(v);
  82167. assert( nFarg>=2 );
  82168. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  82169. for(i=1; i<nFarg; i++){
  82170. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  82171. VdbeCoverage(v);
  82172. sqlite3ExprCacheRemove(pParse, target, 1);
  82173. sqlite3ExprCachePush(pParse);
  82174. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  82175. sqlite3ExprCachePop(pParse);
  82176. }
  82177. sqlite3VdbeResolveLabel(v, endCoalesce);
  82178. break;
  82179. }
  82180. /* The UNLIKELY() function is a no-op. The result is the value
  82181. ** of the first argument.
  82182. */
  82183. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  82184. assert( nFarg>=1 );
  82185. inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  82186. break;
  82187. }
  82188. for(i=0; i<nFarg; i++){
  82189. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  82190. testcase( i==31 );
  82191. constMask |= MASKBIT32(i);
  82192. }
  82193. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  82194. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  82195. }
  82196. }
  82197. if( pFarg ){
  82198. if( constMask ){
  82199. r1 = pParse->nMem+1;
  82200. pParse->nMem += nFarg;
  82201. }else{
  82202. r1 = sqlite3GetTempRange(pParse, nFarg);
  82203. }
  82204. /* For length() and typeof() functions with a column argument,
  82205. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  82206. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  82207. ** loading.
  82208. */
  82209. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  82210. u8 exprOp;
  82211. assert( nFarg==1 );
  82212. assert( pFarg->a[0].pExpr!=0 );
  82213. exprOp = pFarg->a[0].pExpr->op;
  82214. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  82215. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  82216. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  82217. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  82218. pFarg->a[0].pExpr->op2 =
  82219. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  82220. }
  82221. }
  82222. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  82223. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  82224. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  82225. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  82226. }else{
  82227. r1 = 0;
  82228. }
  82229. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82230. /* Possibly overload the function if the first argument is
  82231. ** a virtual table column.
  82232. **
  82233. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  82234. ** second argument, not the first, as the argument to test to
  82235. ** see if it is a column in a virtual table. This is done because
  82236. ** the left operand of infix functions (the operand we want to
  82237. ** control overloading) ends up as the second argument to the
  82238. ** function. The expression "A glob B" is equivalent to
  82239. ** "glob(B,A). We want to use the A in "A glob B" to test
  82240. ** for function overloading. But we use the B term in "glob(B,A)".
  82241. */
  82242. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  82243. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  82244. }else if( nFarg>0 ){
  82245. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  82246. }
  82247. #endif
  82248. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  82249. if( !pColl ) pColl = db->pDfltColl;
  82250. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  82251. }
  82252. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  82253. (char*)pDef, P4_FUNCDEF);
  82254. sqlite3VdbeChangeP5(v, (u8)nFarg);
  82255. if( nFarg && constMask==0 ){
  82256. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  82257. }
  82258. break;
  82259. }
  82260. #ifndef SQLITE_OMIT_SUBQUERY
  82261. case TK_EXISTS:
  82262. case TK_SELECT: {
  82263. testcase( op==TK_EXISTS );
  82264. testcase( op==TK_SELECT );
  82265. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  82266. break;
  82267. }
  82268. case TK_IN: {
  82269. int destIfFalse = sqlite3VdbeMakeLabel(v);
  82270. int destIfNull = sqlite3VdbeMakeLabel(v);
  82271. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  82272. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  82273. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  82274. sqlite3VdbeResolveLabel(v, destIfFalse);
  82275. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  82276. sqlite3VdbeResolveLabel(v, destIfNull);
  82277. break;
  82278. }
  82279. #endif /* SQLITE_OMIT_SUBQUERY */
  82280. /*
  82281. ** x BETWEEN y AND z
  82282. **
  82283. ** This is equivalent to
  82284. **
  82285. ** x>=y AND x<=z
  82286. **
  82287. ** X is stored in pExpr->pLeft.
  82288. ** Y is stored in pExpr->pList->a[0].pExpr.
  82289. ** Z is stored in pExpr->pList->a[1].pExpr.
  82290. */
  82291. case TK_BETWEEN: {
  82292. Expr *pLeft = pExpr->pLeft;
  82293. struct ExprList_item *pLItem = pExpr->x.pList->a;
  82294. Expr *pRight = pLItem->pExpr;
  82295. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  82296. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  82297. testcase( regFree1==0 );
  82298. testcase( regFree2==0 );
  82299. r3 = sqlite3GetTempReg(pParse);
  82300. r4 = sqlite3GetTempReg(pParse);
  82301. codeCompare(pParse, pLeft, pRight, OP_Ge,
  82302. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  82303. pLItem++;
  82304. pRight = pLItem->pExpr;
  82305. sqlite3ReleaseTempReg(pParse, regFree2);
  82306. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  82307. testcase( regFree2==0 );
  82308. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  82309. VdbeCoverage(v);
  82310. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  82311. sqlite3ReleaseTempReg(pParse, r3);
  82312. sqlite3ReleaseTempReg(pParse, r4);
  82313. break;
  82314. }
  82315. case TK_COLLATE:
  82316. case TK_UPLUS: {
  82317. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  82318. break;
  82319. }
  82320. case TK_TRIGGER: {
  82321. /* If the opcode is TK_TRIGGER, then the expression is a reference
  82322. ** to a column in the new.* or old.* pseudo-tables available to
  82323. ** trigger programs. In this case Expr.iTable is set to 1 for the
  82324. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  82325. ** is set to the column of the pseudo-table to read, or to -1 to
  82326. ** read the rowid field.
  82327. **
  82328. ** The expression is implemented using an OP_Param opcode. The p1
  82329. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  82330. ** to reference another column of the old.* pseudo-table, where
  82331. ** i is the index of the column. For a new.rowid reference, p1 is
  82332. ** set to (n+1), where n is the number of columns in each pseudo-table.
  82333. ** For a reference to any other column in the new.* pseudo-table, p1
  82334. ** is set to (n+2+i), where n and i are as defined previously. For
  82335. ** example, if the table on which triggers are being fired is
  82336. ** declared as:
  82337. **
  82338. ** CREATE TABLE t1(a, b);
  82339. **
  82340. ** Then p1 is interpreted as follows:
  82341. **
  82342. ** p1==0 -> old.rowid p1==3 -> new.rowid
  82343. ** p1==1 -> old.a p1==4 -> new.a
  82344. ** p1==2 -> old.b p1==5 -> new.b
  82345. */
  82346. Table *pTab = pExpr->pTab;
  82347. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  82348. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  82349. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  82350. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  82351. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  82352. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  82353. VdbeComment((v, "%s.%s -> $%d",
  82354. (pExpr->iTable ? "new" : "old"),
  82355. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  82356. target
  82357. ));
  82358. #ifndef SQLITE_OMIT_FLOATING_POINT
  82359. /* If the column has REAL affinity, it may currently be stored as an
  82360. ** integer. Use OP_RealAffinity to make sure it is really real.
  82361. **
  82362. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  82363. ** floating point when extracting it from the record. */
  82364. if( pExpr->iColumn>=0
  82365. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  82366. ){
  82367. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  82368. }
  82369. #endif
  82370. break;
  82371. }
  82372. /*
  82373. ** Form A:
  82374. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  82375. **
  82376. ** Form B:
  82377. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  82378. **
  82379. ** Form A is can be transformed into the equivalent form B as follows:
  82380. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  82381. ** WHEN x=eN THEN rN ELSE y END
  82382. **
  82383. ** X (if it exists) is in pExpr->pLeft.
  82384. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  82385. ** odd. The Y is also optional. If the number of elements in x.pList
  82386. ** is even, then Y is omitted and the "otherwise" result is NULL.
  82387. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  82388. **
  82389. ** The result of the expression is the Ri for the first matching Ei,
  82390. ** or if there is no matching Ei, the ELSE term Y, or if there is
  82391. ** no ELSE term, NULL.
  82392. */
  82393. default: assert( op==TK_CASE ); {
  82394. int endLabel; /* GOTO label for end of CASE stmt */
  82395. int nextCase; /* GOTO label for next WHEN clause */
  82396. int nExpr; /* 2x number of WHEN terms */
  82397. int i; /* Loop counter */
  82398. ExprList *pEList; /* List of WHEN terms */
  82399. struct ExprList_item *aListelem; /* Array of WHEN terms */
  82400. Expr opCompare; /* The X==Ei expression */
  82401. Expr *pX; /* The X expression */
  82402. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  82403. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  82404. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  82405. assert(pExpr->x.pList->nExpr > 0);
  82406. pEList = pExpr->x.pList;
  82407. aListelem = pEList->a;
  82408. nExpr = pEList->nExpr;
  82409. endLabel = sqlite3VdbeMakeLabel(v);
  82410. if( (pX = pExpr->pLeft)!=0 ){
  82411. tempX = *pX;
  82412. testcase( pX->op==TK_COLUMN );
  82413. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  82414. testcase( regFree1==0 );
  82415. opCompare.op = TK_EQ;
  82416. opCompare.pLeft = &tempX;
  82417. pTest = &opCompare;
  82418. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  82419. ** The value in regFree1 might get SCopy-ed into the file result.
  82420. ** So make sure that the regFree1 register is not reused for other
  82421. ** purposes and possibly overwritten. */
  82422. regFree1 = 0;
  82423. }
  82424. for(i=0; i<nExpr-1; i=i+2){
  82425. sqlite3ExprCachePush(pParse);
  82426. if( pX ){
  82427. assert( pTest!=0 );
  82428. opCompare.pRight = aListelem[i].pExpr;
  82429. }else{
  82430. pTest = aListelem[i].pExpr;
  82431. }
  82432. nextCase = sqlite3VdbeMakeLabel(v);
  82433. testcase( pTest->op==TK_COLUMN );
  82434. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  82435. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  82436. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  82437. sqlite3VdbeGoto(v, endLabel);
  82438. sqlite3ExprCachePop(pParse);
  82439. sqlite3VdbeResolveLabel(v, nextCase);
  82440. }
  82441. if( (nExpr&1)!=0 ){
  82442. sqlite3ExprCachePush(pParse);
  82443. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  82444. sqlite3ExprCachePop(pParse);
  82445. }else{
  82446. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  82447. }
  82448. assert( db->mallocFailed || pParse->nErr>0
  82449. || pParse->iCacheLevel==iCacheLevel );
  82450. sqlite3VdbeResolveLabel(v, endLabel);
  82451. break;
  82452. }
  82453. #ifndef SQLITE_OMIT_TRIGGER
  82454. case TK_RAISE: {
  82455. assert( pExpr->affinity==OE_Rollback
  82456. || pExpr->affinity==OE_Abort
  82457. || pExpr->affinity==OE_Fail
  82458. || pExpr->affinity==OE_Ignore
  82459. );
  82460. if( !pParse->pTriggerTab ){
  82461. sqlite3ErrorMsg(pParse,
  82462. "RAISE() may only be used within a trigger-program");
  82463. return 0;
  82464. }
  82465. if( pExpr->affinity==OE_Abort ){
  82466. sqlite3MayAbort(pParse);
  82467. }
  82468. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82469. if( pExpr->affinity==OE_Ignore ){
  82470. sqlite3VdbeAddOp4(
  82471. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  82472. VdbeCoverage(v);
  82473. }else{
  82474. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  82475. pExpr->affinity, pExpr->u.zToken, 0, 0);
  82476. }
  82477. break;
  82478. }
  82479. #endif
  82480. }
  82481. sqlite3ReleaseTempReg(pParse, regFree1);
  82482. sqlite3ReleaseTempReg(pParse, regFree2);
  82483. return inReg;
  82484. }
  82485. /*
  82486. ** Factor out the code of the given expression to initialization time.
  82487. */
  82488. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  82489. Parse *pParse, /* Parsing context */
  82490. Expr *pExpr, /* The expression to code when the VDBE initializes */
  82491. int regDest, /* Store the value in this register */
  82492. u8 reusable /* True if this expression is reusable */
  82493. ){
  82494. ExprList *p;
  82495. assert( ConstFactorOk(pParse) );
  82496. p = pParse->pConstExpr;
  82497. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  82498. p = sqlite3ExprListAppend(pParse, p, pExpr);
  82499. if( p ){
  82500. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  82501. pItem->u.iConstExprReg = regDest;
  82502. pItem->reusable = reusable;
  82503. }
  82504. pParse->pConstExpr = p;
  82505. }
  82506. /*
  82507. ** Generate code to evaluate an expression and store the results
  82508. ** into a register. Return the register number where the results
  82509. ** are stored.
  82510. **
  82511. ** If the register is a temporary register that can be deallocated,
  82512. ** then write its number into *pReg. If the result register is not
  82513. ** a temporary, then set *pReg to zero.
  82514. **
  82515. ** If pExpr is a constant, then this routine might generate this
  82516. ** code to fill the register in the initialization section of the
  82517. ** VDBE program, in order to factor it out of the evaluation loop.
  82518. */
  82519. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  82520. int r2;
  82521. pExpr = sqlite3ExprSkipCollate(pExpr);
  82522. if( ConstFactorOk(pParse)
  82523. && pExpr->op!=TK_REGISTER
  82524. && sqlite3ExprIsConstantNotJoin(pExpr)
  82525. ){
  82526. ExprList *p = pParse->pConstExpr;
  82527. int i;
  82528. *pReg = 0;
  82529. if( p ){
  82530. struct ExprList_item *pItem;
  82531. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  82532. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  82533. return pItem->u.iConstExprReg;
  82534. }
  82535. }
  82536. }
  82537. r2 = ++pParse->nMem;
  82538. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  82539. }else{
  82540. int r1 = sqlite3GetTempReg(pParse);
  82541. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  82542. if( r2==r1 ){
  82543. *pReg = r1;
  82544. }else{
  82545. sqlite3ReleaseTempReg(pParse, r1);
  82546. *pReg = 0;
  82547. }
  82548. }
  82549. return r2;
  82550. }
  82551. /*
  82552. ** Generate code that will evaluate expression pExpr and store the
  82553. ** results in register target. The results are guaranteed to appear
  82554. ** in register target.
  82555. */
  82556. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  82557. int inReg;
  82558. assert( target>0 && target<=pParse->nMem );
  82559. if( pExpr && pExpr->op==TK_REGISTER ){
  82560. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  82561. }else{
  82562. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  82563. assert( pParse->pVdbe || pParse->db->mallocFailed );
  82564. if( inReg!=target && pParse->pVdbe ){
  82565. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  82566. }
  82567. }
  82568. }
  82569. /*
  82570. ** Generate code that will evaluate expression pExpr and store the
  82571. ** results in register target. The results are guaranteed to appear
  82572. ** in register target. If the expression is constant, then this routine
  82573. ** might choose to code the expression at initialization time.
  82574. */
  82575. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  82576. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  82577. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  82578. }else{
  82579. sqlite3ExprCode(pParse, pExpr, target);
  82580. }
  82581. }
  82582. /*
  82583. ** Generate code that evaluates the given expression and puts the result
  82584. ** in register target.
  82585. **
  82586. ** Also make a copy of the expression results into another "cache" register
  82587. ** and modify the expression so that the next time it is evaluated,
  82588. ** the result is a copy of the cache register.
  82589. **
  82590. ** This routine is used for expressions that are used multiple
  82591. ** times. They are evaluated once and the results of the expression
  82592. ** are reused.
  82593. */
  82594. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  82595. Vdbe *v = pParse->pVdbe;
  82596. int iMem;
  82597. assert( target>0 );
  82598. assert( pExpr->op!=TK_REGISTER );
  82599. sqlite3ExprCode(pParse, pExpr, target);
  82600. iMem = ++pParse->nMem;
  82601. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  82602. exprToRegister(pExpr, iMem);
  82603. }
  82604. /*
  82605. ** Generate code that pushes the value of every element of the given
  82606. ** expression list into a sequence of registers beginning at target.
  82607. **
  82608. ** Return the number of elements evaluated.
  82609. **
  82610. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  82611. ** filled using OP_SCopy. OP_Copy must be used instead.
  82612. **
  82613. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  82614. ** factored out into initialization code.
  82615. */
  82616. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  82617. Parse *pParse, /* Parsing context */
  82618. ExprList *pList, /* The expression list to be coded */
  82619. int target, /* Where to write results */
  82620. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  82621. u8 flags /* SQLITE_ECEL_* flags */
  82622. ){
  82623. struct ExprList_item *pItem;
  82624. int i, j, n;
  82625. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  82626. Vdbe *v = pParse->pVdbe;
  82627. assert( pList!=0 );
  82628. assert( target>0 );
  82629. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  82630. n = pList->nExpr;
  82631. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  82632. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  82633. Expr *pExpr = pItem->pExpr;
  82634. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
  82635. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  82636. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  82637. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  82638. }else{
  82639. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  82640. if( inReg!=target+i ){
  82641. VdbeOp *pOp;
  82642. if( copyOp==OP_Copy
  82643. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  82644. && pOp->p1+pOp->p3+1==inReg
  82645. && pOp->p2+pOp->p3+1==target+i
  82646. ){
  82647. pOp->p3++;
  82648. }else{
  82649. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  82650. }
  82651. }
  82652. }
  82653. }
  82654. return n;
  82655. }
  82656. /*
  82657. ** Generate code for a BETWEEN operator.
  82658. **
  82659. ** x BETWEEN y AND z
  82660. **
  82661. ** The above is equivalent to
  82662. **
  82663. ** x>=y AND x<=z
  82664. **
  82665. ** Code it as such, taking care to do the common subexpression
  82666. ** elimination of x.
  82667. */
  82668. static void exprCodeBetween(
  82669. Parse *pParse, /* Parsing and code generating context */
  82670. Expr *pExpr, /* The BETWEEN expression */
  82671. int dest, /* Jump here if the jump is taken */
  82672. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  82673. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  82674. ){
  82675. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  82676. Expr compLeft; /* The x>=y term */
  82677. Expr compRight; /* The x<=z term */
  82678. Expr exprX; /* The x subexpression */
  82679. int regFree1 = 0; /* Temporary use register */
  82680. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  82681. exprX = *pExpr->pLeft;
  82682. exprAnd.op = TK_AND;
  82683. exprAnd.pLeft = &compLeft;
  82684. exprAnd.pRight = &compRight;
  82685. compLeft.op = TK_GE;
  82686. compLeft.pLeft = &exprX;
  82687. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  82688. compRight.op = TK_LE;
  82689. compRight.pLeft = &exprX;
  82690. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  82691. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  82692. if( jumpIfTrue ){
  82693. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  82694. }else{
  82695. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  82696. }
  82697. sqlite3ReleaseTempReg(pParse, regFree1);
  82698. /* Ensure adequate test coverage */
  82699. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  82700. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  82701. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  82702. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  82703. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  82704. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  82705. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  82706. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  82707. }
  82708. /*
  82709. ** Generate code for a boolean expression such that a jump is made
  82710. ** to the label "dest" if the expression is true but execution
  82711. ** continues straight thru if the expression is false.
  82712. **
  82713. ** If the expression evaluates to NULL (neither true nor false), then
  82714. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  82715. **
  82716. ** This code depends on the fact that certain token values (ex: TK_EQ)
  82717. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  82718. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  82719. ** the make process cause these values to align. Assert()s in the code
  82720. ** below verify that the numbers are aligned correctly.
  82721. */
  82722. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  82723. Vdbe *v = pParse->pVdbe;
  82724. int op = 0;
  82725. int regFree1 = 0;
  82726. int regFree2 = 0;
  82727. int r1, r2;
  82728. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  82729. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  82730. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  82731. op = pExpr->op;
  82732. switch( op ){
  82733. case TK_AND: {
  82734. int d2 = sqlite3VdbeMakeLabel(v);
  82735. testcase( jumpIfNull==0 );
  82736. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  82737. sqlite3ExprCachePush(pParse);
  82738. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  82739. sqlite3VdbeResolveLabel(v, d2);
  82740. sqlite3ExprCachePop(pParse);
  82741. break;
  82742. }
  82743. case TK_OR: {
  82744. testcase( jumpIfNull==0 );
  82745. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  82746. sqlite3ExprCachePush(pParse);
  82747. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  82748. sqlite3ExprCachePop(pParse);
  82749. break;
  82750. }
  82751. case TK_NOT: {
  82752. testcase( jumpIfNull==0 );
  82753. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  82754. break;
  82755. }
  82756. case TK_LT:
  82757. case TK_LE:
  82758. case TK_GT:
  82759. case TK_GE:
  82760. case TK_NE:
  82761. case TK_EQ: {
  82762. testcase( jumpIfNull==0 );
  82763. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82764. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82765. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82766. r1, r2, dest, jumpIfNull);
  82767. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  82768. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  82769. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  82770. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  82771. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  82772. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  82773. testcase( regFree1==0 );
  82774. testcase( regFree2==0 );
  82775. break;
  82776. }
  82777. case TK_IS:
  82778. case TK_ISNOT: {
  82779. testcase( op==TK_IS );
  82780. testcase( op==TK_ISNOT );
  82781. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82782. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82783. op = (op==TK_IS) ? TK_EQ : TK_NE;
  82784. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82785. r1, r2, dest, SQLITE_NULLEQ);
  82786. VdbeCoverageIf(v, op==TK_EQ);
  82787. VdbeCoverageIf(v, op==TK_NE);
  82788. testcase( regFree1==0 );
  82789. testcase( regFree2==0 );
  82790. break;
  82791. }
  82792. case TK_ISNULL:
  82793. case TK_NOTNULL: {
  82794. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  82795. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  82796. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82797. sqlite3VdbeAddOp2(v, op, r1, dest);
  82798. VdbeCoverageIf(v, op==TK_ISNULL);
  82799. VdbeCoverageIf(v, op==TK_NOTNULL);
  82800. testcase( regFree1==0 );
  82801. break;
  82802. }
  82803. case TK_BETWEEN: {
  82804. testcase( jumpIfNull==0 );
  82805. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  82806. break;
  82807. }
  82808. #ifndef SQLITE_OMIT_SUBQUERY
  82809. case TK_IN: {
  82810. int destIfFalse = sqlite3VdbeMakeLabel(v);
  82811. int destIfNull = jumpIfNull ? dest : destIfFalse;
  82812. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  82813. sqlite3VdbeGoto(v, dest);
  82814. sqlite3VdbeResolveLabel(v, destIfFalse);
  82815. break;
  82816. }
  82817. #endif
  82818. default: {
  82819. if( exprAlwaysTrue(pExpr) ){
  82820. sqlite3VdbeGoto(v, dest);
  82821. }else if( exprAlwaysFalse(pExpr) ){
  82822. /* No-op */
  82823. }else{
  82824. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  82825. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  82826. VdbeCoverage(v);
  82827. testcase( regFree1==0 );
  82828. testcase( jumpIfNull==0 );
  82829. }
  82830. break;
  82831. }
  82832. }
  82833. sqlite3ReleaseTempReg(pParse, regFree1);
  82834. sqlite3ReleaseTempReg(pParse, regFree2);
  82835. }
  82836. /*
  82837. ** Generate code for a boolean expression such that a jump is made
  82838. ** to the label "dest" if the expression is false but execution
  82839. ** continues straight thru if the expression is true.
  82840. **
  82841. ** If the expression evaluates to NULL (neither true nor false) then
  82842. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  82843. ** is 0.
  82844. */
  82845. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  82846. Vdbe *v = pParse->pVdbe;
  82847. int op = 0;
  82848. int regFree1 = 0;
  82849. int regFree2 = 0;
  82850. int r1, r2;
  82851. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  82852. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  82853. if( pExpr==0 ) return;
  82854. /* The value of pExpr->op and op are related as follows:
  82855. **
  82856. ** pExpr->op op
  82857. ** --------- ----------
  82858. ** TK_ISNULL OP_NotNull
  82859. ** TK_NOTNULL OP_IsNull
  82860. ** TK_NE OP_Eq
  82861. ** TK_EQ OP_Ne
  82862. ** TK_GT OP_Le
  82863. ** TK_LE OP_Gt
  82864. ** TK_GE OP_Lt
  82865. ** TK_LT OP_Ge
  82866. **
  82867. ** For other values of pExpr->op, op is undefined and unused.
  82868. ** The value of TK_ and OP_ constants are arranged such that we
  82869. ** can compute the mapping above using the following expression.
  82870. ** Assert()s verify that the computation is correct.
  82871. */
  82872. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  82873. /* Verify correct alignment of TK_ and OP_ constants
  82874. */
  82875. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  82876. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  82877. assert( pExpr->op!=TK_NE || op==OP_Eq );
  82878. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  82879. assert( pExpr->op!=TK_LT || op==OP_Ge );
  82880. assert( pExpr->op!=TK_LE || op==OP_Gt );
  82881. assert( pExpr->op!=TK_GT || op==OP_Le );
  82882. assert( pExpr->op!=TK_GE || op==OP_Lt );
  82883. switch( pExpr->op ){
  82884. case TK_AND: {
  82885. testcase( jumpIfNull==0 );
  82886. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  82887. sqlite3ExprCachePush(pParse);
  82888. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  82889. sqlite3ExprCachePop(pParse);
  82890. break;
  82891. }
  82892. case TK_OR: {
  82893. int d2 = sqlite3VdbeMakeLabel(v);
  82894. testcase( jumpIfNull==0 );
  82895. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  82896. sqlite3ExprCachePush(pParse);
  82897. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  82898. sqlite3VdbeResolveLabel(v, d2);
  82899. sqlite3ExprCachePop(pParse);
  82900. break;
  82901. }
  82902. case TK_NOT: {
  82903. testcase( jumpIfNull==0 );
  82904. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  82905. break;
  82906. }
  82907. case TK_LT:
  82908. case TK_LE:
  82909. case TK_GT:
  82910. case TK_GE:
  82911. case TK_NE:
  82912. case TK_EQ: {
  82913. testcase( jumpIfNull==0 );
  82914. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82915. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82916. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82917. r1, r2, dest, jumpIfNull);
  82918. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  82919. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  82920. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  82921. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  82922. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  82923. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  82924. testcase( regFree1==0 );
  82925. testcase( regFree2==0 );
  82926. break;
  82927. }
  82928. case TK_IS:
  82929. case TK_ISNOT: {
  82930. testcase( pExpr->op==TK_IS );
  82931. testcase( pExpr->op==TK_ISNOT );
  82932. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82933. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82934. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  82935. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82936. r1, r2, dest, SQLITE_NULLEQ);
  82937. VdbeCoverageIf(v, op==TK_EQ);
  82938. VdbeCoverageIf(v, op==TK_NE);
  82939. testcase( regFree1==0 );
  82940. testcase( regFree2==0 );
  82941. break;
  82942. }
  82943. case TK_ISNULL:
  82944. case TK_NOTNULL: {
  82945. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82946. sqlite3VdbeAddOp2(v, op, r1, dest);
  82947. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  82948. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  82949. testcase( regFree1==0 );
  82950. break;
  82951. }
  82952. case TK_BETWEEN: {
  82953. testcase( jumpIfNull==0 );
  82954. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  82955. break;
  82956. }
  82957. #ifndef SQLITE_OMIT_SUBQUERY
  82958. case TK_IN: {
  82959. if( jumpIfNull ){
  82960. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  82961. }else{
  82962. int destIfNull = sqlite3VdbeMakeLabel(v);
  82963. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  82964. sqlite3VdbeResolveLabel(v, destIfNull);
  82965. }
  82966. break;
  82967. }
  82968. #endif
  82969. default: {
  82970. if( exprAlwaysFalse(pExpr) ){
  82971. sqlite3VdbeGoto(v, dest);
  82972. }else if( exprAlwaysTrue(pExpr) ){
  82973. /* no-op */
  82974. }else{
  82975. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  82976. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  82977. VdbeCoverage(v);
  82978. testcase( regFree1==0 );
  82979. testcase( jumpIfNull==0 );
  82980. }
  82981. break;
  82982. }
  82983. }
  82984. sqlite3ReleaseTempReg(pParse, regFree1);
  82985. sqlite3ReleaseTempReg(pParse, regFree2);
  82986. }
  82987. /*
  82988. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  82989. ** code generation, and that copy is deleted after code generation. This
  82990. ** ensures that the original pExpr is unchanged.
  82991. */
  82992. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  82993. sqlite3 *db = pParse->db;
  82994. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  82995. if( db->mallocFailed==0 ){
  82996. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  82997. }
  82998. sqlite3ExprDelete(db, pCopy);
  82999. }
  83000. /*
  83001. ** Do a deep comparison of two expression trees. Return 0 if the two
  83002. ** expressions are completely identical. Return 1 if they differ only
  83003. ** by a COLLATE operator at the top level. Return 2 if there are differences
  83004. ** other than the top-level COLLATE operator.
  83005. **
  83006. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  83007. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  83008. **
  83009. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  83010. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  83011. **
  83012. ** Sometimes this routine will return 2 even if the two expressions
  83013. ** really are equivalent. If we cannot prove that the expressions are
  83014. ** identical, we return 2 just to be safe. So if this routine
  83015. ** returns 2, then you do not really know for certain if the two
  83016. ** expressions are the same. But if you get a 0 or 1 return, then you
  83017. ** can be sure the expressions are the same. In the places where
  83018. ** this routine is used, it does not hurt to get an extra 2 - that
  83019. ** just might result in some slightly slower code. But returning
  83020. ** an incorrect 0 or 1 could lead to a malfunction.
  83021. */
  83022. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  83023. u32 combinedFlags;
  83024. if( pA==0 || pB==0 ){
  83025. return pB==pA ? 0 : 2;
  83026. }
  83027. combinedFlags = pA->flags | pB->flags;
  83028. if( combinedFlags & EP_IntValue ){
  83029. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  83030. return 0;
  83031. }
  83032. return 2;
  83033. }
  83034. if( pA->op!=pB->op ){
  83035. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  83036. return 1;
  83037. }
  83038. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  83039. return 1;
  83040. }
  83041. return 2;
  83042. }
  83043. if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  83044. if( pA->op==TK_FUNCTION ){
  83045. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  83046. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  83047. return pA->op==TK_COLLATE ? 1 : 2;
  83048. }
  83049. }
  83050. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  83051. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  83052. if( combinedFlags & EP_xIsSelect ) return 2;
  83053. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  83054. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  83055. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  83056. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  83057. if( pA->iColumn!=pB->iColumn ) return 2;
  83058. if( pA->iTable!=pB->iTable
  83059. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  83060. }
  83061. }
  83062. return 0;
  83063. }
  83064. /*
  83065. ** Compare two ExprList objects. Return 0 if they are identical and
  83066. ** non-zero if they differ in any way.
  83067. **
  83068. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  83069. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  83070. **
  83071. ** This routine might return non-zero for equivalent ExprLists. The
  83072. ** only consequence will be disabled optimizations. But this routine
  83073. ** must never return 0 if the two ExprList objects are different, or
  83074. ** a malfunction will result.
  83075. **
  83076. ** Two NULL pointers are considered to be the same. But a NULL pointer
  83077. ** always differs from a non-NULL pointer.
  83078. */
  83079. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  83080. int i;
  83081. if( pA==0 && pB==0 ) return 0;
  83082. if( pA==0 || pB==0 ) return 1;
  83083. if( pA->nExpr!=pB->nExpr ) return 1;
  83084. for(i=0; i<pA->nExpr; i++){
  83085. Expr *pExprA = pA->a[i].pExpr;
  83086. Expr *pExprB = pB->a[i].pExpr;
  83087. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  83088. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  83089. }
  83090. return 0;
  83091. }
  83092. /*
  83093. ** Return true if we can prove the pE2 will always be true if pE1 is
  83094. ** true. Return false if we cannot complete the proof or if pE2 might
  83095. ** be false. Examples:
  83096. **
  83097. ** pE1: x==5 pE2: x==5 Result: true
  83098. ** pE1: x>0 pE2: x==5 Result: false
  83099. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  83100. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  83101. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  83102. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  83103. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  83104. **
  83105. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  83106. ** Expr.iTable<0 then assume a table number given by iTab.
  83107. **
  83108. ** When in doubt, return false. Returning true might give a performance
  83109. ** improvement. Returning false might cause a performance reduction, but
  83110. ** it will always give the correct answer and is hence always safe.
  83111. */
  83112. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  83113. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  83114. return 1;
  83115. }
  83116. if( pE2->op==TK_OR
  83117. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  83118. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  83119. ){
  83120. return 1;
  83121. }
  83122. if( pE2->op==TK_NOTNULL
  83123. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  83124. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  83125. ){
  83126. return 1;
  83127. }
  83128. return 0;
  83129. }
  83130. /*
  83131. ** An instance of the following structure is used by the tree walker
  83132. ** to count references to table columns in the arguments of an
  83133. ** aggregate function, in order to implement the
  83134. ** sqlite3FunctionThisSrc() routine.
  83135. */
  83136. struct SrcCount {
  83137. SrcList *pSrc; /* One particular FROM clause in a nested query */
  83138. int nThis; /* Number of references to columns in pSrcList */
  83139. int nOther; /* Number of references to columns in other FROM clauses */
  83140. };
  83141. /*
  83142. ** Count the number of references to columns.
  83143. */
  83144. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  83145. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  83146. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  83147. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  83148. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  83149. ** NEVER() will need to be removed. */
  83150. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  83151. int i;
  83152. struct SrcCount *p = pWalker->u.pSrcCount;
  83153. SrcList *pSrc = p->pSrc;
  83154. int nSrc = pSrc ? pSrc->nSrc : 0;
  83155. for(i=0; i<nSrc; i++){
  83156. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  83157. }
  83158. if( i<nSrc ){
  83159. p->nThis++;
  83160. }else{
  83161. p->nOther++;
  83162. }
  83163. }
  83164. return WRC_Continue;
  83165. }
  83166. /*
  83167. ** Determine if any of the arguments to the pExpr Function reference
  83168. ** pSrcList. Return true if they do. Also return true if the function
  83169. ** has no arguments or has only constant arguments. Return false if pExpr
  83170. ** references columns but not columns of tables found in pSrcList.
  83171. */
  83172. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  83173. Walker w;
  83174. struct SrcCount cnt;
  83175. assert( pExpr->op==TK_AGG_FUNCTION );
  83176. memset(&w, 0, sizeof(w));
  83177. w.xExprCallback = exprSrcCount;
  83178. w.u.pSrcCount = &cnt;
  83179. cnt.pSrc = pSrcList;
  83180. cnt.nThis = 0;
  83181. cnt.nOther = 0;
  83182. sqlite3WalkExprList(&w, pExpr->x.pList);
  83183. return cnt.nThis>0 || cnt.nOther==0;
  83184. }
  83185. /*
  83186. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  83187. ** the new element. Return a negative number if malloc fails.
  83188. */
  83189. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  83190. int i;
  83191. pInfo->aCol = sqlite3ArrayAllocate(
  83192. db,
  83193. pInfo->aCol,
  83194. sizeof(pInfo->aCol[0]),
  83195. &pInfo->nColumn,
  83196. &i
  83197. );
  83198. return i;
  83199. }
  83200. /*
  83201. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  83202. ** the new element. Return a negative number if malloc fails.
  83203. */
  83204. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  83205. int i;
  83206. pInfo->aFunc = sqlite3ArrayAllocate(
  83207. db,
  83208. pInfo->aFunc,
  83209. sizeof(pInfo->aFunc[0]),
  83210. &pInfo->nFunc,
  83211. &i
  83212. );
  83213. return i;
  83214. }
  83215. /*
  83216. ** This is the xExprCallback for a tree walker. It is used to
  83217. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  83218. ** for additional information.
  83219. */
  83220. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  83221. int i;
  83222. NameContext *pNC = pWalker->u.pNC;
  83223. Parse *pParse = pNC->pParse;
  83224. SrcList *pSrcList = pNC->pSrcList;
  83225. AggInfo *pAggInfo = pNC->pAggInfo;
  83226. switch( pExpr->op ){
  83227. case TK_AGG_COLUMN:
  83228. case TK_COLUMN: {
  83229. testcase( pExpr->op==TK_AGG_COLUMN );
  83230. testcase( pExpr->op==TK_COLUMN );
  83231. /* Check to see if the column is in one of the tables in the FROM
  83232. ** clause of the aggregate query */
  83233. if( ALWAYS(pSrcList!=0) ){
  83234. struct SrcList_item *pItem = pSrcList->a;
  83235. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  83236. struct AggInfo_col *pCol;
  83237. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  83238. if( pExpr->iTable==pItem->iCursor ){
  83239. /* If we reach this point, it means that pExpr refers to a table
  83240. ** that is in the FROM clause of the aggregate query.
  83241. **
  83242. ** Make an entry for the column in pAggInfo->aCol[] if there
  83243. ** is not an entry there already.
  83244. */
  83245. int k;
  83246. pCol = pAggInfo->aCol;
  83247. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  83248. if( pCol->iTable==pExpr->iTable &&
  83249. pCol->iColumn==pExpr->iColumn ){
  83250. break;
  83251. }
  83252. }
  83253. if( (k>=pAggInfo->nColumn)
  83254. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  83255. ){
  83256. pCol = &pAggInfo->aCol[k];
  83257. pCol->pTab = pExpr->pTab;
  83258. pCol->iTable = pExpr->iTable;
  83259. pCol->iColumn = pExpr->iColumn;
  83260. pCol->iMem = ++pParse->nMem;
  83261. pCol->iSorterColumn = -1;
  83262. pCol->pExpr = pExpr;
  83263. if( pAggInfo->pGroupBy ){
  83264. int j, n;
  83265. ExprList *pGB = pAggInfo->pGroupBy;
  83266. struct ExprList_item *pTerm = pGB->a;
  83267. n = pGB->nExpr;
  83268. for(j=0; j<n; j++, pTerm++){
  83269. Expr *pE = pTerm->pExpr;
  83270. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  83271. pE->iColumn==pExpr->iColumn ){
  83272. pCol->iSorterColumn = j;
  83273. break;
  83274. }
  83275. }
  83276. }
  83277. if( pCol->iSorterColumn<0 ){
  83278. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  83279. }
  83280. }
  83281. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  83282. ** because it was there before or because we just created it).
  83283. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  83284. ** pAggInfo->aCol[] entry.
  83285. */
  83286. ExprSetVVAProperty(pExpr, EP_NoReduce);
  83287. pExpr->pAggInfo = pAggInfo;
  83288. pExpr->op = TK_AGG_COLUMN;
  83289. pExpr->iAgg = (i16)k;
  83290. break;
  83291. } /* endif pExpr->iTable==pItem->iCursor */
  83292. } /* end loop over pSrcList */
  83293. }
  83294. return WRC_Prune;
  83295. }
  83296. case TK_AGG_FUNCTION: {
  83297. if( (pNC->ncFlags & NC_InAggFunc)==0
  83298. && pWalker->walkerDepth==pExpr->op2
  83299. ){
  83300. /* Check to see if pExpr is a duplicate of another aggregate
  83301. ** function that is already in the pAggInfo structure
  83302. */
  83303. struct AggInfo_func *pItem = pAggInfo->aFunc;
  83304. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  83305. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  83306. break;
  83307. }
  83308. }
  83309. if( i>=pAggInfo->nFunc ){
  83310. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  83311. */
  83312. u8 enc = ENC(pParse->db);
  83313. i = addAggInfoFunc(pParse->db, pAggInfo);
  83314. if( i>=0 ){
  83315. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  83316. pItem = &pAggInfo->aFunc[i];
  83317. pItem->pExpr = pExpr;
  83318. pItem->iMem = ++pParse->nMem;
  83319. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83320. pItem->pFunc = sqlite3FindFunction(pParse->db,
  83321. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  83322. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  83323. if( pExpr->flags & EP_Distinct ){
  83324. pItem->iDistinct = pParse->nTab++;
  83325. }else{
  83326. pItem->iDistinct = -1;
  83327. }
  83328. }
  83329. }
  83330. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  83331. */
  83332. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  83333. ExprSetVVAProperty(pExpr, EP_NoReduce);
  83334. pExpr->iAgg = (i16)i;
  83335. pExpr->pAggInfo = pAggInfo;
  83336. return WRC_Prune;
  83337. }else{
  83338. return WRC_Continue;
  83339. }
  83340. }
  83341. }
  83342. return WRC_Continue;
  83343. }
  83344. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  83345. UNUSED_PARAMETER(pWalker);
  83346. UNUSED_PARAMETER(pSelect);
  83347. return WRC_Continue;
  83348. }
  83349. /*
  83350. ** Analyze the pExpr expression looking for aggregate functions and
  83351. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  83352. ** points to. Additional entries are made on the AggInfo object as
  83353. ** necessary.
  83354. **
  83355. ** This routine should only be called after the expression has been
  83356. ** analyzed by sqlite3ResolveExprNames().
  83357. */
  83358. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  83359. Walker w;
  83360. memset(&w, 0, sizeof(w));
  83361. w.xExprCallback = analyzeAggregate;
  83362. w.xSelectCallback = analyzeAggregatesInSelect;
  83363. w.u.pNC = pNC;
  83364. assert( pNC->pSrcList!=0 );
  83365. sqlite3WalkExpr(&w, pExpr);
  83366. }
  83367. /*
  83368. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  83369. ** expression list. Return the number of errors.
  83370. **
  83371. ** If an error is found, the analysis is cut short.
  83372. */
  83373. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  83374. struct ExprList_item *pItem;
  83375. int i;
  83376. if( pList ){
  83377. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  83378. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  83379. }
  83380. }
  83381. }
  83382. /*
  83383. ** Allocate a single new register for use to hold some intermediate result.
  83384. */
  83385. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  83386. if( pParse->nTempReg==0 ){
  83387. return ++pParse->nMem;
  83388. }
  83389. return pParse->aTempReg[--pParse->nTempReg];
  83390. }
  83391. /*
  83392. ** Deallocate a register, making available for reuse for some other
  83393. ** purpose.
  83394. **
  83395. ** If a register is currently being used by the column cache, then
  83396. ** the deallocation is deferred until the column cache line that uses
  83397. ** the register becomes stale.
  83398. */
  83399. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  83400. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  83401. int i;
  83402. struct yColCache *p;
  83403. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83404. if( p->iReg==iReg ){
  83405. p->tempReg = 1;
  83406. return;
  83407. }
  83408. }
  83409. pParse->aTempReg[pParse->nTempReg++] = iReg;
  83410. }
  83411. }
  83412. /*
  83413. ** Allocate or deallocate a block of nReg consecutive registers
  83414. */
  83415. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  83416. int i, n;
  83417. i = pParse->iRangeReg;
  83418. n = pParse->nRangeReg;
  83419. if( nReg<=n ){
  83420. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  83421. pParse->iRangeReg += nReg;
  83422. pParse->nRangeReg -= nReg;
  83423. }else{
  83424. i = pParse->nMem+1;
  83425. pParse->nMem += nReg;
  83426. }
  83427. return i;
  83428. }
  83429. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  83430. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  83431. if( nReg>pParse->nRangeReg ){
  83432. pParse->nRangeReg = nReg;
  83433. pParse->iRangeReg = iReg;
  83434. }
  83435. }
  83436. /*
  83437. ** Mark all temporary registers as being unavailable for reuse.
  83438. */
  83439. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  83440. pParse->nTempReg = 0;
  83441. pParse->nRangeReg = 0;
  83442. }
  83443. /************** End of expr.c ************************************************/
  83444. /************** Begin file alter.c *******************************************/
  83445. /*
  83446. ** 2005 February 15
  83447. **
  83448. ** The author disclaims copyright to this source code. In place of
  83449. ** a legal notice, here is a blessing:
  83450. **
  83451. ** May you do good and not evil.
  83452. ** May you find forgiveness for yourself and forgive others.
  83453. ** May you share freely, never taking more than you give.
  83454. **
  83455. *************************************************************************
  83456. ** This file contains C code routines that used to generate VDBE code
  83457. ** that implements the ALTER TABLE command.
  83458. */
  83459. /* #include "sqliteInt.h" */
  83460. /*
  83461. ** The code in this file only exists if we are not omitting the
  83462. ** ALTER TABLE logic from the build.
  83463. */
  83464. #ifndef SQLITE_OMIT_ALTERTABLE
  83465. /*
  83466. ** This function is used by SQL generated to implement the
  83467. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  83468. ** CREATE INDEX command. The second is a table name. The table name in
  83469. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  83470. ** argument and the result returned. Examples:
  83471. **
  83472. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  83473. ** -> 'CREATE TABLE def(a, b, c)'
  83474. **
  83475. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  83476. ** -> 'CREATE INDEX i ON def(a, b, c)'
  83477. */
  83478. static void renameTableFunc(
  83479. sqlite3_context *context,
  83480. int NotUsed,
  83481. sqlite3_value **argv
  83482. ){
  83483. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  83484. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  83485. int token;
  83486. Token tname;
  83487. unsigned char const *zCsr = zSql;
  83488. int len = 0;
  83489. char *zRet;
  83490. sqlite3 *db = sqlite3_context_db_handle(context);
  83491. UNUSED_PARAMETER(NotUsed);
  83492. /* The principle used to locate the table name in the CREATE TABLE
  83493. ** statement is that the table name is the first non-space token that
  83494. ** is immediately followed by a TK_LP or TK_USING token.
  83495. */
  83496. if( zSql ){
  83497. do {
  83498. if( !*zCsr ){
  83499. /* Ran out of input before finding an opening bracket. Return NULL. */
  83500. return;
  83501. }
  83502. /* Store the token that zCsr points to in tname. */
  83503. tname.z = (char*)zCsr;
  83504. tname.n = len;
  83505. /* Advance zCsr to the next token. Store that token type in 'token',
  83506. ** and its length in 'len' (to be used next iteration of this loop).
  83507. */
  83508. do {
  83509. zCsr += len;
  83510. len = sqlite3GetToken(zCsr, &token);
  83511. } while( token==TK_SPACE );
  83512. assert( len>0 );
  83513. } while( token!=TK_LP && token!=TK_USING );
  83514. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  83515. zSql, zTableName, tname.z+tname.n);
  83516. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  83517. }
  83518. }
  83519. /*
  83520. ** This C function implements an SQL user function that is used by SQL code
  83521. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  83522. ** of any foreign key constraints that use the table being renamed as the
  83523. ** parent table. It is passed three arguments:
  83524. **
  83525. ** 1) The complete text of the CREATE TABLE statement being modified,
  83526. ** 2) The old name of the table being renamed, and
  83527. ** 3) The new name of the table being renamed.
  83528. **
  83529. ** It returns the new CREATE TABLE statement. For example:
  83530. **
  83531. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  83532. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  83533. */
  83534. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83535. static void renameParentFunc(
  83536. sqlite3_context *context,
  83537. int NotUsed,
  83538. sqlite3_value **argv
  83539. ){
  83540. sqlite3 *db = sqlite3_context_db_handle(context);
  83541. char *zOutput = 0;
  83542. char *zResult;
  83543. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  83544. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  83545. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  83546. unsigned const char *z; /* Pointer to token */
  83547. int n; /* Length of token z */
  83548. int token; /* Type of token */
  83549. UNUSED_PARAMETER(NotUsed);
  83550. if( zInput==0 || zOld==0 ) return;
  83551. for(z=zInput; *z; z=z+n){
  83552. n = sqlite3GetToken(z, &token);
  83553. if( token==TK_REFERENCES ){
  83554. char *zParent;
  83555. do {
  83556. z += n;
  83557. n = sqlite3GetToken(z, &token);
  83558. }while( token==TK_SPACE );
  83559. if( token==TK_ILLEGAL ) break;
  83560. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  83561. if( zParent==0 ) break;
  83562. sqlite3Dequote(zParent);
  83563. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  83564. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  83565. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  83566. );
  83567. sqlite3DbFree(db, zOutput);
  83568. zOutput = zOut;
  83569. zInput = &z[n];
  83570. }
  83571. sqlite3DbFree(db, zParent);
  83572. }
  83573. }
  83574. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  83575. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  83576. sqlite3DbFree(db, zOutput);
  83577. }
  83578. #endif
  83579. #ifndef SQLITE_OMIT_TRIGGER
  83580. /* This function is used by SQL generated to implement the
  83581. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  83582. ** statement. The second is a table name. The table name in the CREATE
  83583. ** TRIGGER statement is replaced with the third argument and the result
  83584. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  83585. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  83586. */
  83587. static void renameTriggerFunc(
  83588. sqlite3_context *context,
  83589. int NotUsed,
  83590. sqlite3_value **argv
  83591. ){
  83592. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  83593. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  83594. int token;
  83595. Token tname;
  83596. int dist = 3;
  83597. unsigned char const *zCsr = zSql;
  83598. int len = 0;
  83599. char *zRet;
  83600. sqlite3 *db = sqlite3_context_db_handle(context);
  83601. UNUSED_PARAMETER(NotUsed);
  83602. /* The principle used to locate the table name in the CREATE TRIGGER
  83603. ** statement is that the table name is the first token that is immediately
  83604. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  83605. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  83606. */
  83607. if( zSql ){
  83608. do {
  83609. if( !*zCsr ){
  83610. /* Ran out of input before finding the table name. Return NULL. */
  83611. return;
  83612. }
  83613. /* Store the token that zCsr points to in tname. */
  83614. tname.z = (char*)zCsr;
  83615. tname.n = len;
  83616. /* Advance zCsr to the next token. Store that token type in 'token',
  83617. ** and its length in 'len' (to be used next iteration of this loop).
  83618. */
  83619. do {
  83620. zCsr += len;
  83621. len = sqlite3GetToken(zCsr, &token);
  83622. }while( token==TK_SPACE );
  83623. assert( len>0 );
  83624. /* Variable 'dist' stores the number of tokens read since the most
  83625. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  83626. ** token is read and 'dist' equals 2, the condition stated above
  83627. ** to be met.
  83628. **
  83629. ** Note that ON cannot be a database, table or column name, so
  83630. ** there is no need to worry about syntax like
  83631. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  83632. */
  83633. dist++;
  83634. if( token==TK_DOT || token==TK_ON ){
  83635. dist = 0;
  83636. }
  83637. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  83638. /* Variable tname now contains the token that is the old table-name
  83639. ** in the CREATE TRIGGER statement.
  83640. */
  83641. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  83642. zSql, zTableName, tname.z+tname.n);
  83643. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  83644. }
  83645. }
  83646. #endif /* !SQLITE_OMIT_TRIGGER */
  83647. /*
  83648. ** Register built-in functions used to help implement ALTER TABLE
  83649. */
  83650. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  83651. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  83652. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  83653. #ifndef SQLITE_OMIT_TRIGGER
  83654. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  83655. #endif
  83656. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83657. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  83658. #endif
  83659. };
  83660. int i;
  83661. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  83662. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  83663. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  83664. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  83665. }
  83666. }
  83667. /*
  83668. ** This function is used to create the text of expressions of the form:
  83669. **
  83670. ** name=<constant1> OR name=<constant2> OR ...
  83671. **
  83672. ** If argument zWhere is NULL, then a pointer string containing the text
  83673. ** "name=<constant>" is returned, where <constant> is the quoted version
  83674. ** of the string passed as argument zConstant. The returned buffer is
  83675. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  83676. ** caller to ensure that it is eventually freed.
  83677. **
  83678. ** If argument zWhere is not NULL, then the string returned is
  83679. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  83680. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  83681. **
  83682. */
  83683. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  83684. char *zNew;
  83685. if( !zWhere ){
  83686. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  83687. }else{
  83688. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  83689. sqlite3DbFree(db, zWhere);
  83690. }
  83691. return zNew;
  83692. }
  83693. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  83694. /*
  83695. ** Generate the text of a WHERE expression which can be used to select all
  83696. ** tables that have foreign key constraints that refer to table pTab (i.e.
  83697. ** constraints for which pTab is the parent table) from the sqlite_master
  83698. ** table.
  83699. */
  83700. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  83701. FKey *p;
  83702. char *zWhere = 0;
  83703. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  83704. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  83705. }
  83706. return zWhere;
  83707. }
  83708. #endif
  83709. /*
  83710. ** Generate the text of a WHERE expression which can be used to select all
  83711. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  83712. ** table pTab has no temporary triggers, or is itself stored in the
  83713. ** temporary database, NULL is returned.
  83714. */
  83715. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  83716. Trigger *pTrig;
  83717. char *zWhere = 0;
  83718. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  83719. /* If the table is not located in the temp-db (in which case NULL is
  83720. ** returned, loop through the tables list of triggers. For each trigger
  83721. ** that is not part of the temp-db schema, add a clause to the WHERE
  83722. ** expression being built up in zWhere.
  83723. */
  83724. if( pTab->pSchema!=pTempSchema ){
  83725. sqlite3 *db = pParse->db;
  83726. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  83727. if( pTrig->pSchema==pTempSchema ){
  83728. zWhere = whereOrName(db, zWhere, pTrig->zName);
  83729. }
  83730. }
  83731. }
  83732. if( zWhere ){
  83733. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  83734. sqlite3DbFree(pParse->db, zWhere);
  83735. zWhere = zNew;
  83736. }
  83737. return zWhere;
  83738. }
  83739. /*
  83740. ** Generate code to drop and reload the internal representation of table
  83741. ** pTab from the database, including triggers and temporary triggers.
  83742. ** Argument zName is the name of the table in the database schema at
  83743. ** the time the generated code is executed. This can be different from
  83744. ** pTab->zName if this function is being called to code part of an
  83745. ** "ALTER TABLE RENAME TO" statement.
  83746. */
  83747. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  83748. Vdbe *v;
  83749. char *zWhere;
  83750. int iDb; /* Index of database containing pTab */
  83751. #ifndef SQLITE_OMIT_TRIGGER
  83752. Trigger *pTrig;
  83753. #endif
  83754. v = sqlite3GetVdbe(pParse);
  83755. if( NEVER(v==0) ) return;
  83756. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  83757. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83758. assert( iDb>=0 );
  83759. #ifndef SQLITE_OMIT_TRIGGER
  83760. /* Drop any table triggers from the internal schema. */
  83761. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  83762. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  83763. assert( iTrigDb==iDb || iTrigDb==1 );
  83764. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  83765. }
  83766. #endif
  83767. /* Drop the table and index from the internal schema. */
  83768. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  83769. /* Reload the table, index and permanent trigger schemas. */
  83770. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  83771. if( !zWhere ) return;
  83772. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  83773. #ifndef SQLITE_OMIT_TRIGGER
  83774. /* Now, if the table is not stored in the temp database, reload any temp
  83775. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  83776. */
  83777. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  83778. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  83779. }
  83780. #endif
  83781. }
  83782. /*
  83783. ** Parameter zName is the name of a table that is about to be altered
  83784. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  83785. ** If the table is a system table, this function leaves an error message
  83786. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  83787. **
  83788. ** Or, if zName is not a system table, zero is returned.
  83789. */
  83790. static int isSystemTable(Parse *pParse, const char *zName){
  83791. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  83792. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  83793. return 1;
  83794. }
  83795. return 0;
  83796. }
  83797. /*
  83798. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  83799. ** command.
  83800. */
  83801. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  83802. Parse *pParse, /* Parser context. */
  83803. SrcList *pSrc, /* The table to rename. */
  83804. Token *pName /* The new table name. */
  83805. ){
  83806. int iDb; /* Database that contains the table */
  83807. char *zDb; /* Name of database iDb */
  83808. Table *pTab; /* Table being renamed */
  83809. char *zName = 0; /* NULL-terminated version of pName */
  83810. sqlite3 *db = pParse->db; /* Database connection */
  83811. int nTabName; /* Number of UTF-8 characters in zTabName */
  83812. const char *zTabName; /* Original name of the table */
  83813. Vdbe *v;
  83814. #ifndef SQLITE_OMIT_TRIGGER
  83815. char *zWhere = 0; /* Where clause to locate temp triggers */
  83816. #endif
  83817. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  83818. int savedDbFlags; /* Saved value of db->flags */
  83819. savedDbFlags = db->flags;
  83820. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  83821. assert( pSrc->nSrc==1 );
  83822. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  83823. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  83824. if( !pTab ) goto exit_rename_table;
  83825. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83826. zDb = db->aDb[iDb].zName;
  83827. db->flags |= SQLITE_PreferBuiltin;
  83828. /* Get a NULL terminated version of the new table name. */
  83829. zName = sqlite3NameFromToken(db, pName);
  83830. if( !zName ) goto exit_rename_table;
  83831. /* Check that a table or index named 'zName' does not already exist
  83832. ** in database iDb. If so, this is an error.
  83833. */
  83834. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  83835. sqlite3ErrorMsg(pParse,
  83836. "there is already another table or index with this name: %s", zName);
  83837. goto exit_rename_table;
  83838. }
  83839. /* Make sure it is not a system table being altered, or a reserved name
  83840. ** that the table is being renamed to.
  83841. */
  83842. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  83843. goto exit_rename_table;
  83844. }
  83845. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  83846. exit_rename_table;
  83847. }
  83848. #ifndef SQLITE_OMIT_VIEW
  83849. if( pTab->pSelect ){
  83850. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  83851. goto exit_rename_table;
  83852. }
  83853. #endif
  83854. #ifndef SQLITE_OMIT_AUTHORIZATION
  83855. /* Invoke the authorization callback. */
  83856. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  83857. goto exit_rename_table;
  83858. }
  83859. #endif
  83860. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83861. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  83862. goto exit_rename_table;
  83863. }
  83864. if( IsVirtual(pTab) ){
  83865. pVTab = sqlite3GetVTable(db, pTab);
  83866. if( pVTab->pVtab->pModule->xRename==0 ){
  83867. pVTab = 0;
  83868. }
  83869. }
  83870. #endif
  83871. /* Begin a transaction for database iDb.
  83872. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  83873. ** schema). Open a statement transaction if the table is a virtual
  83874. ** table.
  83875. */
  83876. v = sqlite3GetVdbe(pParse);
  83877. if( v==0 ){
  83878. goto exit_rename_table;
  83879. }
  83880. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  83881. sqlite3ChangeCookie(pParse, iDb);
  83882. /* If this is a virtual table, invoke the xRename() function if
  83883. ** one is defined. The xRename() callback will modify the names
  83884. ** of any resources used by the v-table implementation (including other
  83885. ** SQLite tables) that are identified by the name of the virtual table.
  83886. */
  83887. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83888. if( pVTab ){
  83889. int i = ++pParse->nMem;
  83890. sqlite3VdbeLoadString(v, i, zName);
  83891. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  83892. sqlite3MayAbort(pParse);
  83893. }
  83894. #endif
  83895. /* figure out how many UTF-8 characters are in zName */
  83896. zTabName = pTab->zName;
  83897. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  83898. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  83899. if( db->flags&SQLITE_ForeignKeys ){
  83900. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  83901. ** statements corresponding to all child tables of foreign key constraints
  83902. ** for which the renamed table is the parent table. */
  83903. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  83904. sqlite3NestedParse(pParse,
  83905. "UPDATE \"%w\".%s SET "
  83906. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  83907. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  83908. sqlite3DbFree(db, zWhere);
  83909. }
  83910. }
  83911. #endif
  83912. /* Modify the sqlite_master table to use the new table name. */
  83913. sqlite3NestedParse(pParse,
  83914. "UPDATE %Q.%s SET "
  83915. #ifdef SQLITE_OMIT_TRIGGER
  83916. "sql = sqlite_rename_table(sql, %Q), "
  83917. #else
  83918. "sql = CASE "
  83919. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  83920. "ELSE sqlite_rename_table(sql, %Q) END, "
  83921. #endif
  83922. "tbl_name = %Q, "
  83923. "name = CASE "
  83924. "WHEN type='table' THEN %Q "
  83925. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  83926. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  83927. "ELSE name END "
  83928. "WHERE tbl_name=%Q COLLATE nocase AND "
  83929. "(type='table' OR type='index' OR type='trigger');",
  83930. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  83931. #ifndef SQLITE_OMIT_TRIGGER
  83932. zName,
  83933. #endif
  83934. zName, nTabName, zTabName
  83935. );
  83936. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83937. /* If the sqlite_sequence table exists in this database, then update
  83938. ** it with the new table name.
  83939. */
  83940. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  83941. sqlite3NestedParse(pParse,
  83942. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  83943. zDb, zName, pTab->zName);
  83944. }
  83945. #endif
  83946. #ifndef SQLITE_OMIT_TRIGGER
  83947. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  83948. ** table. Don't do this if the table being ALTERed is itself located in
  83949. ** the temp database.
  83950. */
  83951. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  83952. sqlite3NestedParse(pParse,
  83953. "UPDATE sqlite_temp_master SET "
  83954. "sql = sqlite_rename_trigger(sql, %Q), "
  83955. "tbl_name = %Q "
  83956. "WHERE %s;", zName, zName, zWhere);
  83957. sqlite3DbFree(db, zWhere);
  83958. }
  83959. #endif
  83960. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  83961. if( db->flags&SQLITE_ForeignKeys ){
  83962. FKey *p;
  83963. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  83964. Table *pFrom = p->pFrom;
  83965. if( pFrom!=pTab ){
  83966. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  83967. }
  83968. }
  83969. }
  83970. #endif
  83971. /* Drop and reload the internal table schema. */
  83972. reloadTableSchema(pParse, pTab, zName);
  83973. exit_rename_table:
  83974. sqlite3SrcListDelete(db, pSrc);
  83975. sqlite3DbFree(db, zName);
  83976. db->flags = savedDbFlags;
  83977. }
  83978. /*
  83979. ** Generate code to make sure the file format number is at least minFormat.
  83980. ** The generated code will increase the file format number if necessary.
  83981. */
  83982. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  83983. Vdbe *v;
  83984. v = sqlite3GetVdbe(pParse);
  83985. /* The VDBE should have been allocated before this routine is called.
  83986. ** If that allocation failed, we would have quit before reaching this
  83987. ** point */
  83988. if( ALWAYS(v) ){
  83989. int r1 = sqlite3GetTempReg(pParse);
  83990. int r2 = sqlite3GetTempReg(pParse);
  83991. int addr1;
  83992. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  83993. sqlite3VdbeUsesBtree(v, iDb);
  83994. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  83995. addr1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  83996. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  83997. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  83998. sqlite3VdbeJumpHere(v, addr1);
  83999. sqlite3ReleaseTempReg(pParse, r1);
  84000. sqlite3ReleaseTempReg(pParse, r2);
  84001. }
  84002. }
  84003. /*
  84004. ** This function is called after an "ALTER TABLE ... ADD" statement
  84005. ** has been parsed. Argument pColDef contains the text of the new
  84006. ** column definition.
  84007. **
  84008. ** The Table structure pParse->pNewTable was extended to include
  84009. ** the new column during parsing.
  84010. */
  84011. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  84012. Table *pNew; /* Copy of pParse->pNewTable */
  84013. Table *pTab; /* Table being altered */
  84014. int iDb; /* Database number */
  84015. const char *zDb; /* Database name */
  84016. const char *zTab; /* Table name */
  84017. char *zCol; /* Null-terminated column definition */
  84018. Column *pCol; /* The new column */
  84019. Expr *pDflt; /* Default value for the new column */
  84020. sqlite3 *db; /* The database connection; */
  84021. db = pParse->db;
  84022. if( pParse->nErr || db->mallocFailed ) return;
  84023. pNew = pParse->pNewTable;
  84024. assert( pNew );
  84025. assert( sqlite3BtreeHoldsAllMutexes(db) );
  84026. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  84027. zDb = db->aDb[iDb].zName;
  84028. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  84029. pCol = &pNew->aCol[pNew->nCol-1];
  84030. pDflt = pCol->pDflt;
  84031. pTab = sqlite3FindTable(db, zTab, zDb);
  84032. assert( pTab );
  84033. #ifndef SQLITE_OMIT_AUTHORIZATION
  84034. /* Invoke the authorization callback. */
  84035. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  84036. return;
  84037. }
  84038. #endif
  84039. /* If the default value for the new column was specified with a
  84040. ** literal NULL, then set pDflt to 0. This simplifies checking
  84041. ** for an SQL NULL default below.
  84042. */
  84043. if( pDflt && pDflt->op==TK_NULL ){
  84044. pDflt = 0;
  84045. }
  84046. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  84047. ** If there is a NOT NULL constraint, then the default value for the
  84048. ** column must not be NULL.
  84049. */
  84050. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  84051. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  84052. return;
  84053. }
  84054. if( pNew->pIndex ){
  84055. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  84056. return;
  84057. }
  84058. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  84059. sqlite3ErrorMsg(pParse,
  84060. "Cannot add a REFERENCES column with non-NULL default value");
  84061. return;
  84062. }
  84063. if( pCol->notNull && !pDflt ){
  84064. sqlite3ErrorMsg(pParse,
  84065. "Cannot add a NOT NULL column with default value NULL");
  84066. return;
  84067. }
  84068. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  84069. ** can handle (i.e. not CURRENT_TIME etc.)
  84070. */
  84071. if( pDflt ){
  84072. sqlite3_value *pVal = 0;
  84073. int rc;
  84074. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  84075. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  84076. if( rc!=SQLITE_OK ){
  84077. db->mallocFailed = 1;
  84078. return;
  84079. }
  84080. if( !pVal ){
  84081. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  84082. return;
  84083. }
  84084. sqlite3ValueFree(pVal);
  84085. }
  84086. /* Modify the CREATE TABLE statement. */
  84087. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  84088. if( zCol ){
  84089. char *zEnd = &zCol[pColDef->n-1];
  84090. int savedDbFlags = db->flags;
  84091. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  84092. *zEnd-- = '\0';
  84093. }
  84094. db->flags |= SQLITE_PreferBuiltin;
  84095. sqlite3NestedParse(pParse,
  84096. "UPDATE \"%w\".%s SET "
  84097. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  84098. "WHERE type = 'table' AND name = %Q",
  84099. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  84100. zTab
  84101. );
  84102. sqlite3DbFree(db, zCol);
  84103. db->flags = savedDbFlags;
  84104. }
  84105. /* If the default value of the new column is NULL, then set the file
  84106. ** format to 2. If the default value of the new column is not NULL,
  84107. ** the file format becomes 3.
  84108. */
  84109. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  84110. /* Reload the schema of the modified table. */
  84111. reloadTableSchema(pParse, pTab, pTab->zName);
  84112. }
  84113. /*
  84114. ** This function is called by the parser after the table-name in
  84115. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  84116. ** pSrc is the full-name of the table being altered.
  84117. **
  84118. ** This routine makes a (partial) copy of the Table structure
  84119. ** for the table being altered and sets Parse.pNewTable to point
  84120. ** to it. Routines called by the parser as the column definition
  84121. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  84122. ** the copy. The copy of the Table structure is deleted by tokenize.c
  84123. ** after parsing is finished.
  84124. **
  84125. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  84126. ** coding the "ALTER TABLE ... ADD" statement.
  84127. */
  84128. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  84129. Table *pNew;
  84130. Table *pTab;
  84131. Vdbe *v;
  84132. int iDb;
  84133. int i;
  84134. int nAlloc;
  84135. sqlite3 *db = pParse->db;
  84136. /* Look up the table being altered. */
  84137. assert( pParse->pNewTable==0 );
  84138. assert( sqlite3BtreeHoldsAllMutexes(db) );
  84139. if( db->mallocFailed ) goto exit_begin_add_column;
  84140. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  84141. if( !pTab ) goto exit_begin_add_column;
  84142. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84143. if( IsVirtual(pTab) ){
  84144. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  84145. goto exit_begin_add_column;
  84146. }
  84147. #endif
  84148. /* Make sure this is not an attempt to ALTER a view. */
  84149. if( pTab->pSelect ){
  84150. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  84151. goto exit_begin_add_column;
  84152. }
  84153. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  84154. goto exit_begin_add_column;
  84155. }
  84156. assert( pTab->addColOffset>0 );
  84157. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  84158. /* Put a copy of the Table struct in Parse.pNewTable for the
  84159. ** sqlite3AddColumn() function and friends to modify. But modify
  84160. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  84161. ** prefix, we insure that the name will not collide with an existing
  84162. ** table because user table are not allowed to have the "sqlite_"
  84163. ** prefix on their name.
  84164. */
  84165. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  84166. if( !pNew ) goto exit_begin_add_column;
  84167. pParse->pNewTable = pNew;
  84168. pNew->nRef = 1;
  84169. pNew->nCol = pTab->nCol;
  84170. assert( pNew->nCol>0 );
  84171. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  84172. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  84173. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  84174. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  84175. if( !pNew->aCol || !pNew->zName ){
  84176. db->mallocFailed = 1;
  84177. goto exit_begin_add_column;
  84178. }
  84179. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  84180. for(i=0; i<pNew->nCol; i++){
  84181. Column *pCol = &pNew->aCol[i];
  84182. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  84183. pCol->zColl = 0;
  84184. pCol->zType = 0;
  84185. pCol->pDflt = 0;
  84186. pCol->zDflt = 0;
  84187. }
  84188. pNew->pSchema = db->aDb[iDb].pSchema;
  84189. pNew->addColOffset = pTab->addColOffset;
  84190. pNew->nRef = 1;
  84191. /* Begin a transaction and increment the schema cookie. */
  84192. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84193. v = sqlite3GetVdbe(pParse);
  84194. if( !v ) goto exit_begin_add_column;
  84195. sqlite3ChangeCookie(pParse, iDb);
  84196. exit_begin_add_column:
  84197. sqlite3SrcListDelete(db, pSrc);
  84198. return;
  84199. }
  84200. #endif /* SQLITE_ALTER_TABLE */
  84201. /************** End of alter.c ***********************************************/
  84202. /************** Begin file analyze.c *****************************************/
  84203. /*
  84204. ** 2005-07-08
  84205. **
  84206. ** The author disclaims copyright to this source code. In place of
  84207. ** a legal notice, here is a blessing:
  84208. **
  84209. ** May you do good and not evil.
  84210. ** May you find forgiveness for yourself and forgive others.
  84211. ** May you share freely, never taking more than you give.
  84212. **
  84213. *************************************************************************
  84214. ** This file contains code associated with the ANALYZE command.
  84215. **
  84216. ** The ANALYZE command gather statistics about the content of tables
  84217. ** and indices. These statistics are made available to the query planner
  84218. ** to help it make better decisions about how to perform queries.
  84219. **
  84220. ** The following system tables are or have been supported:
  84221. **
  84222. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  84223. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  84224. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  84225. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  84226. **
  84227. ** Additional tables might be added in future releases of SQLite.
  84228. ** The sqlite_stat2 table is not created or used unless the SQLite version
  84229. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  84230. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  84231. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  84232. ** created and used by SQLite versions 3.7.9 and later and with
  84233. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  84234. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  84235. ** version of sqlite_stat3 and is only available when compiled with
  84236. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  84237. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  84238. ** are both enabled, then STAT4 takes precedence.
  84239. **
  84240. ** For most applications, sqlite_stat1 provides all the statistics required
  84241. ** for the query planner to make good choices.
  84242. **
  84243. ** Format of sqlite_stat1:
  84244. **
  84245. ** There is normally one row per index, with the index identified by the
  84246. ** name in the idx column. The tbl column is the name of the table to
  84247. ** which the index belongs. In each such row, the stat column will be
  84248. ** a string consisting of a list of integers. The first integer in this
  84249. ** list is the number of rows in the index. (This is the same as the
  84250. ** number of rows in the table, except for partial indices.) The second
  84251. ** integer is the average number of rows in the index that have the same
  84252. ** value in the first column of the index. The third integer is the average
  84253. ** number of rows in the index that have the same value for the first two
  84254. ** columns. The N-th integer (for N>1) is the average number of rows in
  84255. ** the index which have the same value for the first N-1 columns. For
  84256. ** a K-column index, there will be K+1 integers in the stat column. If
  84257. ** the index is unique, then the last integer will be 1.
  84258. **
  84259. ** The list of integers in the stat column can optionally be followed
  84260. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  84261. ** must be separated from the last integer by a single space. If the
  84262. ** "unordered" keyword is present, then the query planner assumes that
  84263. ** the index is unordered and will not use the index for a range query.
  84264. **
  84265. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  84266. ** column contains a single integer which is the (estimated) number of
  84267. ** rows in the table identified by sqlite_stat1.tbl.
  84268. **
  84269. ** Format of sqlite_stat2:
  84270. **
  84271. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  84272. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  84273. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  84274. ** about the distribution of keys within an index. The index is identified by
  84275. ** the "idx" column and the "tbl" column is the name of the table to which
  84276. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  84277. ** table for each index.
  84278. **
  84279. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  84280. ** inclusive are samples of the left-most key value in the index taken at
  84281. ** evenly spaced points along the index. Let the number of samples be S
  84282. ** (10 in the standard build) and let C be the number of rows in the index.
  84283. ** Then the sampled rows are given by:
  84284. **
  84285. ** rownumber = (i*C*2 + C)/(S*2)
  84286. **
  84287. ** For i between 0 and S-1. Conceptually, the index space is divided into
  84288. ** S uniform buckets and the samples are the middle row from each bucket.
  84289. **
  84290. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  84291. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  84292. ** writes the sqlite_stat2 table. This version of SQLite only supports
  84293. ** sqlite_stat3.
  84294. **
  84295. ** Format for sqlite_stat3:
  84296. **
  84297. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  84298. ** sqlite_stat4 format will be described first. Further information
  84299. ** about sqlite_stat3 follows the sqlite_stat4 description.
  84300. **
  84301. ** Format for sqlite_stat4:
  84302. **
  84303. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  84304. ** to aid the query planner in choosing good indices based on the values
  84305. ** that indexed columns are compared against in the WHERE clauses of
  84306. ** queries.
  84307. **
  84308. ** The sqlite_stat4 table contains multiple entries for each index.
  84309. ** The idx column names the index and the tbl column is the table of the
  84310. ** index. If the idx and tbl columns are the same, then the sample is
  84311. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  84312. ** binary encoding of a key from the index. The nEq column is a
  84313. ** list of integers. The first integer is the approximate number
  84314. ** of entries in the index whose left-most column exactly matches
  84315. ** the left-most column of the sample. The second integer in nEq
  84316. ** is the approximate number of entries in the index where the
  84317. ** first two columns match the first two columns of the sample.
  84318. ** And so forth. nLt is another list of integers that show the approximate
  84319. ** number of entries that are strictly less than the sample. The first
  84320. ** integer in nLt contains the number of entries in the index where the
  84321. ** left-most column is less than the left-most column of the sample.
  84322. ** The K-th integer in the nLt entry is the number of index entries
  84323. ** where the first K columns are less than the first K columns of the
  84324. ** sample. The nDLt column is like nLt except that it contains the
  84325. ** number of distinct entries in the index that are less than the
  84326. ** sample.
  84327. **
  84328. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  84329. ** The ANALYZE command will typically generate sqlite_stat4 tables
  84330. ** that contain between 10 and 40 samples which are distributed across
  84331. ** the key space, though not uniformly, and which include samples with
  84332. ** large nEq values.
  84333. **
  84334. ** Format for sqlite_stat3 redux:
  84335. **
  84336. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  84337. ** looks at the left-most column of the index. The sqlite_stat3.sample
  84338. ** column contains the actual value of the left-most column instead
  84339. ** of a blob encoding of the complete index key as is found in
  84340. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  84341. ** all contain just a single integer which is the same as the first
  84342. ** integer in the equivalent columns in sqlite_stat4.
  84343. */
  84344. #ifndef SQLITE_OMIT_ANALYZE
  84345. /* #include "sqliteInt.h" */
  84346. #if defined(SQLITE_ENABLE_STAT4)
  84347. # define IsStat4 1
  84348. # define IsStat3 0
  84349. #elif defined(SQLITE_ENABLE_STAT3)
  84350. # define IsStat4 0
  84351. # define IsStat3 1
  84352. #else
  84353. # define IsStat4 0
  84354. # define IsStat3 0
  84355. # undef SQLITE_STAT4_SAMPLES
  84356. # define SQLITE_STAT4_SAMPLES 1
  84357. #endif
  84358. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  84359. /*
  84360. ** This routine generates code that opens the sqlite_statN tables.
  84361. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  84362. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  84363. ** appropriate compile-time options are provided.
  84364. **
  84365. ** If the sqlite_statN tables do not previously exist, it is created.
  84366. **
  84367. ** Argument zWhere may be a pointer to a buffer containing a table name,
  84368. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  84369. ** the sqlite_statN tables associated with the named table are deleted.
  84370. ** If zWhere==0, then code is generated to delete all stat table entries.
  84371. */
  84372. static void openStatTable(
  84373. Parse *pParse, /* Parsing context */
  84374. int iDb, /* The database we are looking in */
  84375. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  84376. const char *zWhere, /* Delete entries for this table or index */
  84377. const char *zWhereType /* Either "tbl" or "idx" */
  84378. ){
  84379. static const struct {
  84380. const char *zName;
  84381. const char *zCols;
  84382. } aTable[] = {
  84383. { "sqlite_stat1", "tbl,idx,stat" },
  84384. #if defined(SQLITE_ENABLE_STAT4)
  84385. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  84386. { "sqlite_stat3", 0 },
  84387. #elif defined(SQLITE_ENABLE_STAT3)
  84388. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  84389. { "sqlite_stat4", 0 },
  84390. #else
  84391. { "sqlite_stat3", 0 },
  84392. { "sqlite_stat4", 0 },
  84393. #endif
  84394. };
  84395. int i;
  84396. sqlite3 *db = pParse->db;
  84397. Db *pDb;
  84398. Vdbe *v = sqlite3GetVdbe(pParse);
  84399. int aRoot[ArraySize(aTable)];
  84400. u8 aCreateTbl[ArraySize(aTable)];
  84401. if( v==0 ) return;
  84402. assert( sqlite3BtreeHoldsAllMutexes(db) );
  84403. assert( sqlite3VdbeDb(v)==db );
  84404. pDb = &db->aDb[iDb];
  84405. /* Create new statistic tables if they do not exist, or clear them
  84406. ** if they do already exist.
  84407. */
  84408. for(i=0; i<ArraySize(aTable); i++){
  84409. const char *zTab = aTable[i].zName;
  84410. Table *pStat;
  84411. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  84412. if( aTable[i].zCols ){
  84413. /* The sqlite_statN table does not exist. Create it. Note that a
  84414. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  84415. ** of the new table in register pParse->regRoot. This is important
  84416. ** because the OpenWrite opcode below will be needing it. */
  84417. sqlite3NestedParse(pParse,
  84418. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  84419. );
  84420. aRoot[i] = pParse->regRoot;
  84421. aCreateTbl[i] = OPFLAG_P2ISREG;
  84422. }
  84423. }else{
  84424. /* The table already exists. If zWhere is not NULL, delete all entries
  84425. ** associated with the table zWhere. If zWhere is NULL, delete the
  84426. ** entire contents of the table. */
  84427. aRoot[i] = pStat->tnum;
  84428. aCreateTbl[i] = 0;
  84429. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  84430. if( zWhere ){
  84431. sqlite3NestedParse(pParse,
  84432. "DELETE FROM %Q.%s WHERE %s=%Q",
  84433. pDb->zName, zTab, zWhereType, zWhere
  84434. );
  84435. }else{
  84436. /* The sqlite_stat[134] table already exists. Delete all rows. */
  84437. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  84438. }
  84439. }
  84440. }
  84441. /* Open the sqlite_stat[134] tables for writing. */
  84442. for(i=0; aTable[i].zCols; i++){
  84443. assert( i<ArraySize(aTable) );
  84444. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  84445. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  84446. VdbeComment((v, aTable[i].zName));
  84447. }
  84448. }
  84449. /*
  84450. ** Recommended number of samples for sqlite_stat4
  84451. */
  84452. #ifndef SQLITE_STAT4_SAMPLES
  84453. # define SQLITE_STAT4_SAMPLES 24
  84454. #endif
  84455. /*
  84456. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  84457. ** share an instance of the following structure to hold their state
  84458. ** information.
  84459. */
  84460. typedef struct Stat4Accum Stat4Accum;
  84461. typedef struct Stat4Sample Stat4Sample;
  84462. struct Stat4Sample {
  84463. tRowcnt *anEq; /* sqlite_stat4.nEq */
  84464. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  84465. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84466. tRowcnt *anLt; /* sqlite_stat4.nLt */
  84467. union {
  84468. i64 iRowid; /* Rowid in main table of the key */
  84469. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  84470. } u;
  84471. u32 nRowid; /* Sizeof aRowid[] */
  84472. u8 isPSample; /* True if a periodic sample */
  84473. int iCol; /* If !isPSample, the reason for inclusion */
  84474. u32 iHash; /* Tiebreaker hash */
  84475. #endif
  84476. };
  84477. struct Stat4Accum {
  84478. tRowcnt nRow; /* Number of rows in the entire table */
  84479. tRowcnt nPSample; /* How often to do a periodic sample */
  84480. int nCol; /* Number of columns in index + pk/rowid */
  84481. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  84482. int mxSample; /* Maximum number of samples to accumulate */
  84483. Stat4Sample current; /* Current row as a Stat4Sample */
  84484. u32 iPrn; /* Pseudo-random number used for sampling */
  84485. Stat4Sample *aBest; /* Array of nCol best samples */
  84486. int iMin; /* Index in a[] of entry with minimum score */
  84487. int nSample; /* Current number of samples */
  84488. int iGet; /* Index of current sample accessed by stat_get() */
  84489. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  84490. sqlite3 *db; /* Database connection, for malloc() */
  84491. };
  84492. /* Reclaim memory used by a Stat4Sample
  84493. */
  84494. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84495. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  84496. assert( db!=0 );
  84497. if( p->nRowid ){
  84498. sqlite3DbFree(db, p->u.aRowid);
  84499. p->nRowid = 0;
  84500. }
  84501. }
  84502. #endif
  84503. /* Initialize the BLOB value of a ROWID
  84504. */
  84505. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84506. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  84507. assert( db!=0 );
  84508. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  84509. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  84510. if( p->u.aRowid ){
  84511. p->nRowid = n;
  84512. memcpy(p->u.aRowid, pData, n);
  84513. }else{
  84514. p->nRowid = 0;
  84515. }
  84516. }
  84517. #endif
  84518. /* Initialize the INTEGER value of a ROWID.
  84519. */
  84520. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84521. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  84522. assert( db!=0 );
  84523. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  84524. p->nRowid = 0;
  84525. p->u.iRowid = iRowid;
  84526. }
  84527. #endif
  84528. /*
  84529. ** Copy the contents of object (*pFrom) into (*pTo).
  84530. */
  84531. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84532. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  84533. pTo->isPSample = pFrom->isPSample;
  84534. pTo->iCol = pFrom->iCol;
  84535. pTo->iHash = pFrom->iHash;
  84536. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  84537. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  84538. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  84539. if( pFrom->nRowid ){
  84540. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  84541. }else{
  84542. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  84543. }
  84544. }
  84545. #endif
  84546. /*
  84547. ** Reclaim all memory of a Stat4Accum structure.
  84548. */
  84549. static void stat4Destructor(void *pOld){
  84550. Stat4Accum *p = (Stat4Accum*)pOld;
  84551. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84552. int i;
  84553. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  84554. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  84555. sampleClear(p->db, &p->current);
  84556. #endif
  84557. sqlite3DbFree(p->db, p);
  84558. }
  84559. /*
  84560. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  84561. ** are:
  84562. ** N: The number of columns in the index including the rowid/pk (note 1)
  84563. ** K: The number of columns in the index excluding the rowid/pk.
  84564. ** C: The number of rows in the index (note 2)
  84565. **
  84566. ** Note 1: In the special case of the covering index that implements a
  84567. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  84568. ** total number of columns in the table.
  84569. **
  84570. ** Note 2: C is only used for STAT3 and STAT4.
  84571. **
  84572. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  84573. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  84574. ** PRIMARY KEY of the table. The covering index that implements the
  84575. ** original WITHOUT ROWID table as N==K as a special case.
  84576. **
  84577. ** This routine allocates the Stat4Accum object in heap memory. The return
  84578. ** value is a pointer to the Stat4Accum object. The datatype of the
  84579. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  84580. ** object.
  84581. */
  84582. static void statInit(
  84583. sqlite3_context *context,
  84584. int argc,
  84585. sqlite3_value **argv
  84586. ){
  84587. Stat4Accum *p;
  84588. int nCol; /* Number of columns in index being sampled */
  84589. int nKeyCol; /* Number of key columns */
  84590. int nColUp; /* nCol rounded up for alignment */
  84591. int n; /* Bytes of space to allocate */
  84592. sqlite3 *db; /* Database connection */
  84593. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84594. int mxSample = SQLITE_STAT4_SAMPLES;
  84595. #endif
  84596. /* Decode the three function arguments */
  84597. UNUSED_PARAMETER(argc);
  84598. nCol = sqlite3_value_int(argv[0]);
  84599. assert( nCol>0 );
  84600. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  84601. nKeyCol = sqlite3_value_int(argv[1]);
  84602. assert( nKeyCol<=nCol );
  84603. assert( nKeyCol>0 );
  84604. /* Allocate the space required for the Stat4Accum object */
  84605. n = sizeof(*p)
  84606. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  84607. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  84608. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84609. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  84610. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  84611. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  84612. #endif
  84613. ;
  84614. db = sqlite3_context_db_handle(context);
  84615. p = sqlite3DbMallocZero(db, n);
  84616. if( p==0 ){
  84617. sqlite3_result_error_nomem(context);
  84618. return;
  84619. }
  84620. p->db = db;
  84621. p->nRow = 0;
  84622. p->nCol = nCol;
  84623. p->nKeyCol = nKeyCol;
  84624. p->current.anDLt = (tRowcnt*)&p[1];
  84625. p->current.anEq = &p->current.anDLt[nColUp];
  84626. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84627. {
  84628. u8 *pSpace; /* Allocated space not yet assigned */
  84629. int i; /* Used to iterate through p->aSample[] */
  84630. p->iGet = -1;
  84631. p->mxSample = mxSample;
  84632. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  84633. p->current.anLt = &p->current.anEq[nColUp];
  84634. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  84635. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  84636. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  84637. p->aBest = &p->a[mxSample];
  84638. pSpace = (u8*)(&p->a[mxSample+nCol]);
  84639. for(i=0; i<(mxSample+nCol); i++){
  84640. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  84641. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  84642. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  84643. }
  84644. assert( (pSpace - (u8*)p)==n );
  84645. for(i=0; i<nCol; i++){
  84646. p->aBest[i].iCol = i;
  84647. }
  84648. }
  84649. #endif
  84650. /* Return a pointer to the allocated object to the caller. Note that
  84651. ** only the pointer (the 2nd parameter) matters. The size of the object
  84652. ** (given by the 3rd parameter) is never used and can be any positive
  84653. ** value. */
  84654. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  84655. }
  84656. static const FuncDef statInitFuncdef = {
  84657. 2+IsStat34, /* nArg */
  84658. SQLITE_UTF8, /* funcFlags */
  84659. 0, /* pUserData */
  84660. 0, /* pNext */
  84661. statInit, /* xFunc */
  84662. 0, /* xStep */
  84663. 0, /* xFinalize */
  84664. "stat_init", /* zName */
  84665. 0, /* pHash */
  84666. 0 /* pDestructor */
  84667. };
  84668. #ifdef SQLITE_ENABLE_STAT4
  84669. /*
  84670. ** pNew and pOld are both candidate non-periodic samples selected for
  84671. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  84672. ** considering only any trailing columns and the sample hash value, this
  84673. ** function returns true if sample pNew is to be preferred over pOld.
  84674. ** In other words, if we assume that the cardinalities of the selected
  84675. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  84676. **
  84677. ** This function assumes that for each argument sample, the contents of
  84678. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  84679. */
  84680. static int sampleIsBetterPost(
  84681. Stat4Accum *pAccum,
  84682. Stat4Sample *pNew,
  84683. Stat4Sample *pOld
  84684. ){
  84685. int nCol = pAccum->nCol;
  84686. int i;
  84687. assert( pNew->iCol==pOld->iCol );
  84688. for(i=pNew->iCol+1; i<nCol; i++){
  84689. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  84690. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  84691. }
  84692. if( pNew->iHash>pOld->iHash ) return 1;
  84693. return 0;
  84694. }
  84695. #endif
  84696. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84697. /*
  84698. ** Return true if pNew is to be preferred over pOld.
  84699. **
  84700. ** This function assumes that for each argument sample, the contents of
  84701. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  84702. */
  84703. static int sampleIsBetter(
  84704. Stat4Accum *pAccum,
  84705. Stat4Sample *pNew,
  84706. Stat4Sample *pOld
  84707. ){
  84708. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  84709. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  84710. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  84711. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  84712. if( (nEqNew>nEqOld) ) return 1;
  84713. #ifdef SQLITE_ENABLE_STAT4
  84714. if( nEqNew==nEqOld ){
  84715. if( pNew->iCol<pOld->iCol ) return 1;
  84716. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  84717. }
  84718. return 0;
  84719. #else
  84720. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  84721. #endif
  84722. }
  84723. /*
  84724. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  84725. ** remove the least desirable sample from p->a[] to make room.
  84726. */
  84727. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  84728. Stat4Sample *pSample = 0;
  84729. int i;
  84730. assert( IsStat4 || nEqZero==0 );
  84731. #ifdef SQLITE_ENABLE_STAT4
  84732. if( pNew->isPSample==0 ){
  84733. Stat4Sample *pUpgrade = 0;
  84734. assert( pNew->anEq[pNew->iCol]>0 );
  84735. /* This sample is being added because the prefix that ends in column
  84736. ** iCol occurs many times in the table. However, if we have already
  84737. ** added a sample that shares this prefix, there is no need to add
  84738. ** this one. Instead, upgrade the priority of the highest priority
  84739. ** existing sample that shares this prefix. */
  84740. for(i=p->nSample-1; i>=0; i--){
  84741. Stat4Sample *pOld = &p->a[i];
  84742. if( pOld->anEq[pNew->iCol]==0 ){
  84743. if( pOld->isPSample ) return;
  84744. assert( pOld->iCol>pNew->iCol );
  84745. assert( sampleIsBetter(p, pNew, pOld) );
  84746. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  84747. pUpgrade = pOld;
  84748. }
  84749. }
  84750. }
  84751. if( pUpgrade ){
  84752. pUpgrade->iCol = pNew->iCol;
  84753. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  84754. goto find_new_min;
  84755. }
  84756. }
  84757. #endif
  84758. /* If necessary, remove sample iMin to make room for the new sample. */
  84759. if( p->nSample>=p->mxSample ){
  84760. Stat4Sample *pMin = &p->a[p->iMin];
  84761. tRowcnt *anEq = pMin->anEq;
  84762. tRowcnt *anLt = pMin->anLt;
  84763. tRowcnt *anDLt = pMin->anDLt;
  84764. sampleClear(p->db, pMin);
  84765. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  84766. pSample = &p->a[p->nSample-1];
  84767. pSample->nRowid = 0;
  84768. pSample->anEq = anEq;
  84769. pSample->anDLt = anDLt;
  84770. pSample->anLt = anLt;
  84771. p->nSample = p->mxSample-1;
  84772. }
  84773. /* The "rows less-than" for the rowid column must be greater than that
  84774. ** for the last sample in the p->a[] array. Otherwise, the samples would
  84775. ** be out of order. */
  84776. #ifdef SQLITE_ENABLE_STAT4
  84777. assert( p->nSample==0
  84778. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  84779. #endif
  84780. /* Insert the new sample */
  84781. pSample = &p->a[p->nSample];
  84782. sampleCopy(p, pSample, pNew);
  84783. p->nSample++;
  84784. /* Zero the first nEqZero entries in the anEq[] array. */
  84785. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  84786. #ifdef SQLITE_ENABLE_STAT4
  84787. find_new_min:
  84788. #endif
  84789. if( p->nSample>=p->mxSample ){
  84790. int iMin = -1;
  84791. for(i=0; i<p->mxSample; i++){
  84792. if( p->a[i].isPSample ) continue;
  84793. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  84794. iMin = i;
  84795. }
  84796. }
  84797. assert( iMin>=0 );
  84798. p->iMin = iMin;
  84799. }
  84800. }
  84801. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  84802. /*
  84803. ** Field iChng of the index being scanned has changed. So at this point
  84804. ** p->current contains a sample that reflects the previous row of the
  84805. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  84806. ** correct at this point.
  84807. */
  84808. static void samplePushPrevious(Stat4Accum *p, int iChng){
  84809. #ifdef SQLITE_ENABLE_STAT4
  84810. int i;
  84811. /* Check if any samples from the aBest[] array should be pushed
  84812. ** into IndexSample.a[] at this point. */
  84813. for(i=(p->nCol-2); i>=iChng; i--){
  84814. Stat4Sample *pBest = &p->aBest[i];
  84815. pBest->anEq[i] = p->current.anEq[i];
  84816. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  84817. sampleInsert(p, pBest, i);
  84818. }
  84819. }
  84820. /* Update the anEq[] fields of any samples already collected. */
  84821. for(i=p->nSample-1; i>=0; i--){
  84822. int j;
  84823. for(j=iChng; j<p->nCol; j++){
  84824. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  84825. }
  84826. }
  84827. #endif
  84828. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  84829. if( iChng==0 ){
  84830. tRowcnt nLt = p->current.anLt[0];
  84831. tRowcnt nEq = p->current.anEq[0];
  84832. /* Check if this is to be a periodic sample. If so, add it. */
  84833. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  84834. p->current.isPSample = 1;
  84835. sampleInsert(p, &p->current, 0);
  84836. p->current.isPSample = 0;
  84837. }else
  84838. /* Or if it is a non-periodic sample. Add it in this case too. */
  84839. if( p->nSample<p->mxSample
  84840. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  84841. ){
  84842. sampleInsert(p, &p->current, 0);
  84843. }
  84844. }
  84845. #endif
  84846. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  84847. UNUSED_PARAMETER( p );
  84848. UNUSED_PARAMETER( iChng );
  84849. #endif
  84850. }
  84851. /*
  84852. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  84853. ** Arguments:
  84854. **
  84855. ** P Pointer to the Stat4Accum object created by stat_init()
  84856. ** C Index of left-most column to differ from previous row
  84857. ** R Rowid for the current row. Might be a key record for
  84858. ** WITHOUT ROWID tables.
  84859. **
  84860. ** This SQL function always returns NULL. It's purpose it to accumulate
  84861. ** statistical data and/or samples in the Stat4Accum object about the
  84862. ** index being analyzed. The stat_get() SQL function will later be used to
  84863. ** extract relevant information for constructing the sqlite_statN tables.
  84864. **
  84865. ** The R parameter is only used for STAT3 and STAT4
  84866. */
  84867. static void statPush(
  84868. sqlite3_context *context,
  84869. int argc,
  84870. sqlite3_value **argv
  84871. ){
  84872. int i;
  84873. /* The three function arguments */
  84874. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  84875. int iChng = sqlite3_value_int(argv[1]);
  84876. UNUSED_PARAMETER( argc );
  84877. UNUSED_PARAMETER( context );
  84878. assert( p->nCol>0 );
  84879. assert( iChng<p->nCol );
  84880. if( p->nRow==0 ){
  84881. /* This is the first call to this function. Do initialization. */
  84882. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  84883. }else{
  84884. /* Second and subsequent calls get processed here */
  84885. samplePushPrevious(p, iChng);
  84886. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  84887. ** to the current row of the index. */
  84888. for(i=0; i<iChng; i++){
  84889. p->current.anEq[i]++;
  84890. }
  84891. for(i=iChng; i<p->nCol; i++){
  84892. p->current.anDLt[i]++;
  84893. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84894. p->current.anLt[i] += p->current.anEq[i];
  84895. #endif
  84896. p->current.anEq[i] = 1;
  84897. }
  84898. }
  84899. p->nRow++;
  84900. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84901. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  84902. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  84903. }else{
  84904. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  84905. sqlite3_value_blob(argv[2]));
  84906. }
  84907. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  84908. #endif
  84909. #ifdef SQLITE_ENABLE_STAT4
  84910. {
  84911. tRowcnt nLt = p->current.anLt[p->nCol-1];
  84912. /* Check if this is to be a periodic sample. If so, add it. */
  84913. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  84914. p->current.isPSample = 1;
  84915. p->current.iCol = 0;
  84916. sampleInsert(p, &p->current, p->nCol-1);
  84917. p->current.isPSample = 0;
  84918. }
  84919. /* Update the aBest[] array. */
  84920. for(i=0; i<(p->nCol-1); i++){
  84921. p->current.iCol = i;
  84922. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  84923. sampleCopy(p, &p->aBest[i], &p->current);
  84924. }
  84925. }
  84926. }
  84927. #endif
  84928. }
  84929. static const FuncDef statPushFuncdef = {
  84930. 2+IsStat34, /* nArg */
  84931. SQLITE_UTF8, /* funcFlags */
  84932. 0, /* pUserData */
  84933. 0, /* pNext */
  84934. statPush, /* xFunc */
  84935. 0, /* xStep */
  84936. 0, /* xFinalize */
  84937. "stat_push", /* zName */
  84938. 0, /* pHash */
  84939. 0 /* pDestructor */
  84940. };
  84941. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  84942. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  84943. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  84944. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  84945. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  84946. /*
  84947. ** Implementation of the stat_get(P,J) SQL function. This routine is
  84948. ** used to query statistical information that has been gathered into
  84949. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  84950. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  84951. ** The content to returned is determined by the parameter J
  84952. ** which is one of the STAT_GET_xxxx values defined above.
  84953. **
  84954. ** If neither STAT3 nor STAT4 are enabled, then J is always
  84955. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  84956. ** a one-parameter function, stat_get(P), that always returns the
  84957. ** stat1 table entry information.
  84958. */
  84959. static void statGet(
  84960. sqlite3_context *context,
  84961. int argc,
  84962. sqlite3_value **argv
  84963. ){
  84964. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  84965. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84966. /* STAT3 and STAT4 have a parameter on this routine. */
  84967. int eCall = sqlite3_value_int(argv[1]);
  84968. assert( argc==2 );
  84969. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  84970. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  84971. || eCall==STAT_GET_NDLT
  84972. );
  84973. if( eCall==STAT_GET_STAT1 )
  84974. #else
  84975. assert( argc==1 );
  84976. #endif
  84977. {
  84978. /* Return the value to store in the "stat" column of the sqlite_stat1
  84979. ** table for this index.
  84980. **
  84981. ** The value is a string composed of a list of integers describing
  84982. ** the index. The first integer in the list is the total number of
  84983. ** entries in the index. There is one additional integer in the list
  84984. ** for each indexed column. This additional integer is an estimate of
  84985. ** the number of rows matched by a stabbing query on the index using
  84986. ** a key with the corresponding number of fields. In other words,
  84987. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  84988. ** "100 10 2", then SQLite estimates that:
  84989. **
  84990. ** * the index contains 100 rows,
  84991. ** * "WHERE a=?" matches 10 rows, and
  84992. ** * "WHERE a=? AND b=?" matches 2 rows.
  84993. **
  84994. ** If D is the count of distinct values and K is the total number of
  84995. ** rows, then each estimate is computed as:
  84996. **
  84997. ** I = (K+D-1)/D
  84998. */
  84999. char *z;
  85000. int i;
  85001. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  85002. if( zRet==0 ){
  85003. sqlite3_result_error_nomem(context);
  85004. return;
  85005. }
  85006. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  85007. z = zRet + sqlite3Strlen30(zRet);
  85008. for(i=0; i<p->nKeyCol; i++){
  85009. u64 nDistinct = p->current.anDLt[i] + 1;
  85010. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  85011. sqlite3_snprintf(24, z, " %llu", iVal);
  85012. z += sqlite3Strlen30(z);
  85013. assert( p->current.anEq[i] );
  85014. }
  85015. assert( z[0]=='\0' && z>zRet );
  85016. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  85017. }
  85018. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85019. else if( eCall==STAT_GET_ROWID ){
  85020. if( p->iGet<0 ){
  85021. samplePushPrevious(p, 0);
  85022. p->iGet = 0;
  85023. }
  85024. if( p->iGet<p->nSample ){
  85025. Stat4Sample *pS = p->a + p->iGet;
  85026. if( pS->nRowid==0 ){
  85027. sqlite3_result_int64(context, pS->u.iRowid);
  85028. }else{
  85029. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  85030. SQLITE_TRANSIENT);
  85031. }
  85032. }
  85033. }else{
  85034. tRowcnt *aCnt = 0;
  85035. assert( p->iGet<p->nSample );
  85036. switch( eCall ){
  85037. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  85038. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  85039. default: {
  85040. aCnt = p->a[p->iGet].anDLt;
  85041. p->iGet++;
  85042. break;
  85043. }
  85044. }
  85045. if( IsStat3 ){
  85046. sqlite3_result_int64(context, (i64)aCnt[0]);
  85047. }else{
  85048. char *zRet = sqlite3MallocZero(p->nCol * 25);
  85049. if( zRet==0 ){
  85050. sqlite3_result_error_nomem(context);
  85051. }else{
  85052. int i;
  85053. char *z = zRet;
  85054. for(i=0; i<p->nCol; i++){
  85055. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  85056. z += sqlite3Strlen30(z);
  85057. }
  85058. assert( z[0]=='\0' && z>zRet );
  85059. z[-1] = '\0';
  85060. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  85061. }
  85062. }
  85063. }
  85064. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85065. #ifndef SQLITE_DEBUG
  85066. UNUSED_PARAMETER( argc );
  85067. #endif
  85068. }
  85069. static const FuncDef statGetFuncdef = {
  85070. 1+IsStat34, /* nArg */
  85071. SQLITE_UTF8, /* funcFlags */
  85072. 0, /* pUserData */
  85073. 0, /* pNext */
  85074. statGet, /* xFunc */
  85075. 0, /* xStep */
  85076. 0, /* xFinalize */
  85077. "stat_get", /* zName */
  85078. 0, /* pHash */
  85079. 0 /* pDestructor */
  85080. };
  85081. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  85082. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  85083. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85084. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  85085. #elif SQLITE_DEBUG
  85086. assert( iParam==STAT_GET_STAT1 );
  85087. #else
  85088. UNUSED_PARAMETER( iParam );
  85089. #endif
  85090. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4, regOut);
  85091. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  85092. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  85093. }
  85094. /*
  85095. ** Generate code to do an analysis of all indices associated with
  85096. ** a single table.
  85097. */
  85098. static void analyzeOneTable(
  85099. Parse *pParse, /* Parser context */
  85100. Table *pTab, /* Table whose indices are to be analyzed */
  85101. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  85102. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  85103. int iMem, /* Available memory locations begin here */
  85104. int iTab /* Next available cursor */
  85105. ){
  85106. sqlite3 *db = pParse->db; /* Database handle */
  85107. Index *pIdx; /* An index to being analyzed */
  85108. int iIdxCur; /* Cursor open on index being analyzed */
  85109. int iTabCur; /* Table cursor */
  85110. Vdbe *v; /* The virtual machine being built up */
  85111. int i; /* Loop counter */
  85112. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  85113. int iDb; /* Index of database containing pTab */
  85114. u8 needTableCnt = 1; /* True to count the table */
  85115. int regNewRowid = iMem++; /* Rowid for the inserted record */
  85116. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  85117. int regChng = iMem++; /* Index of changed index field */
  85118. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85119. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  85120. #endif
  85121. int regTemp = iMem++; /* Temporary use register */
  85122. int regTabname = iMem++; /* Register containing table name */
  85123. int regIdxname = iMem++; /* Register containing index name */
  85124. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  85125. int regPrev = iMem; /* MUST BE LAST (see below) */
  85126. pParse->nMem = MAX(pParse->nMem, iMem);
  85127. v = sqlite3GetVdbe(pParse);
  85128. if( v==0 || NEVER(pTab==0) ){
  85129. return;
  85130. }
  85131. if( pTab->tnum==0 ){
  85132. /* Do not gather statistics on views or virtual tables */
  85133. return;
  85134. }
  85135. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  85136. /* Do not gather statistics on system tables */
  85137. return;
  85138. }
  85139. assert( sqlite3BtreeHoldsAllMutexes(db) );
  85140. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85141. assert( iDb>=0 );
  85142. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85143. #ifndef SQLITE_OMIT_AUTHORIZATION
  85144. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  85145. db->aDb[iDb].zName ) ){
  85146. return;
  85147. }
  85148. #endif
  85149. /* Establish a read-lock on the table at the shared-cache level.
  85150. ** Open a read-only cursor on the table. Also allocate a cursor number
  85151. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  85152. ** this time though. */
  85153. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  85154. iTabCur = iTab++;
  85155. iIdxCur = iTab++;
  85156. pParse->nTab = MAX(pParse->nTab, iTab);
  85157. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  85158. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  85159. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85160. int nCol; /* Number of columns in pIdx. "N" */
  85161. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  85162. int addrNextRow; /* Address of "next_row:" */
  85163. const char *zIdxName; /* Name of the index */
  85164. int nColTest; /* Number of columns to test for changes */
  85165. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  85166. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  85167. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  85168. nCol = pIdx->nKeyCol;
  85169. zIdxName = pTab->zName;
  85170. nColTest = nCol - 1;
  85171. }else{
  85172. nCol = pIdx->nColumn;
  85173. zIdxName = pIdx->zName;
  85174. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  85175. }
  85176. /* Populate the register containing the index name. */
  85177. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  85178. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  85179. /*
  85180. ** Pseudo-code for loop that calls stat_push():
  85181. **
  85182. ** Rewind csr
  85183. ** if eof(csr) goto end_of_scan;
  85184. ** regChng = 0
  85185. ** goto chng_addr_0;
  85186. **
  85187. ** next_row:
  85188. ** regChng = 0
  85189. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  85190. ** regChng = 1
  85191. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  85192. ** ...
  85193. ** regChng = N
  85194. ** goto chng_addr_N
  85195. **
  85196. ** chng_addr_0:
  85197. ** regPrev(0) = idx(0)
  85198. ** chng_addr_1:
  85199. ** regPrev(1) = idx(1)
  85200. ** ...
  85201. **
  85202. ** endDistinctTest:
  85203. ** regRowid = idx(rowid)
  85204. ** stat_push(P, regChng, regRowid)
  85205. ** Next csr
  85206. ** if !eof(csr) goto next_row;
  85207. **
  85208. ** end_of_scan:
  85209. */
  85210. /* Make sure there are enough memory cells allocated to accommodate
  85211. ** the regPrev array and a trailing rowid (the rowid slot is required
  85212. ** when building a record to insert into the sample column of
  85213. ** the sqlite_stat4 table. */
  85214. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  85215. /* Open a read-only cursor on the index being analyzed. */
  85216. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  85217. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  85218. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  85219. VdbeComment((v, "%s", pIdx->zName));
  85220. /* Invoke the stat_init() function. The arguments are:
  85221. **
  85222. ** (1) the number of columns in the index including the rowid
  85223. ** (or for a WITHOUT ROWID table, the number of PK columns),
  85224. ** (2) the number of columns in the key without the rowid/pk
  85225. ** (3) the number of rows in the index,
  85226. **
  85227. **
  85228. ** The third argument is only used for STAT3 and STAT4
  85229. */
  85230. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85231. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  85232. #endif
  85233. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  85234. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  85235. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4+1, regStat4);
  85236. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  85237. sqlite3VdbeChangeP5(v, 2+IsStat34);
  85238. /* Implementation of the following:
  85239. **
  85240. ** Rewind csr
  85241. ** if eof(csr) goto end_of_scan;
  85242. ** regChng = 0
  85243. ** goto next_push_0;
  85244. **
  85245. */
  85246. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  85247. VdbeCoverage(v);
  85248. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  85249. addrNextRow = sqlite3VdbeCurrentAddr(v);
  85250. if( nColTest>0 ){
  85251. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  85252. int *aGotoChng; /* Array of jump instruction addresses */
  85253. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  85254. if( aGotoChng==0 ) continue;
  85255. /*
  85256. ** next_row:
  85257. ** regChng = 0
  85258. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  85259. ** regChng = 1
  85260. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  85261. ** ...
  85262. ** regChng = N
  85263. ** goto endDistinctTest
  85264. */
  85265. sqlite3VdbeAddOp0(v, OP_Goto);
  85266. addrNextRow = sqlite3VdbeCurrentAddr(v);
  85267. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  85268. /* For a single-column UNIQUE index, once we have found a non-NULL
  85269. ** row, we know that all the rest will be distinct, so skip
  85270. ** subsequent distinctness tests. */
  85271. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  85272. VdbeCoverage(v);
  85273. }
  85274. for(i=0; i<nColTest; i++){
  85275. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  85276. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  85277. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  85278. aGotoChng[i] =
  85279. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  85280. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  85281. VdbeCoverage(v);
  85282. }
  85283. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  85284. sqlite3VdbeGoto(v, endDistinctTest);
  85285. /*
  85286. ** chng_addr_0:
  85287. ** regPrev(0) = idx(0)
  85288. ** chng_addr_1:
  85289. ** regPrev(1) = idx(1)
  85290. ** ...
  85291. */
  85292. sqlite3VdbeJumpHere(v, addrNextRow-1);
  85293. for(i=0; i<nColTest; i++){
  85294. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  85295. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  85296. }
  85297. sqlite3VdbeResolveLabel(v, endDistinctTest);
  85298. sqlite3DbFree(db, aGotoChng);
  85299. }
  85300. /*
  85301. ** chng_addr_N:
  85302. ** regRowid = idx(rowid) // STAT34 only
  85303. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  85304. ** Next csr
  85305. ** if !eof(csr) goto next_row;
  85306. */
  85307. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85308. assert( regRowid==(regStat4+2) );
  85309. if( HasRowid(pTab) ){
  85310. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  85311. }else{
  85312. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  85313. int j, k, regKey;
  85314. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  85315. for(j=0; j<pPk->nKeyCol; j++){
  85316. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  85317. assert( k>=0 && k<pTab->nCol );
  85318. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  85319. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  85320. }
  85321. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  85322. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  85323. }
  85324. #endif
  85325. assert( regChng==(regStat4+1) );
  85326. sqlite3VdbeAddOp3(v, OP_Function0, 1, regStat4, regTemp);
  85327. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  85328. sqlite3VdbeChangeP5(v, 2+IsStat34);
  85329. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  85330. /* Add the entry to the stat1 table. */
  85331. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  85332. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  85333. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  85334. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  85335. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  85336. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  85337. /* Add the entries to the stat3 or stat4 table. */
  85338. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85339. {
  85340. int regEq = regStat1;
  85341. int regLt = regStat1+1;
  85342. int regDLt = regStat1+2;
  85343. int regSample = regStat1+3;
  85344. int regCol = regStat1+4;
  85345. int regSampleRowid = regCol + nCol;
  85346. int addrNext;
  85347. int addrIsNull;
  85348. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  85349. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  85350. addrNext = sqlite3VdbeCurrentAddr(v);
  85351. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  85352. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  85353. VdbeCoverage(v);
  85354. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  85355. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  85356. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  85357. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  85358. /* We know that the regSampleRowid row exists because it was read by
  85359. ** the previous loop. Thus the not-found jump of seekOp will never
  85360. ** be taken */
  85361. VdbeCoverageNeverTaken(v);
  85362. #ifdef SQLITE_ENABLE_STAT3
  85363. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  85364. #else
  85365. for(i=0; i<nCol; i++){
  85366. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  85367. }
  85368. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  85369. #endif
  85370. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  85371. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  85372. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  85373. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  85374. sqlite3VdbeJumpHere(v, addrIsNull);
  85375. }
  85376. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85377. /* End of analysis */
  85378. sqlite3VdbeJumpHere(v, addrRewind);
  85379. }
  85380. /* Create a single sqlite_stat1 entry containing NULL as the index
  85381. ** name and the row count as the content.
  85382. */
  85383. if( pOnlyIdx==0 && needTableCnt ){
  85384. VdbeComment((v, "%s", pTab->zName));
  85385. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  85386. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  85387. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  85388. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  85389. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  85390. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  85391. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  85392. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  85393. sqlite3VdbeJumpHere(v, jZeroRows);
  85394. }
  85395. }
  85396. /*
  85397. ** Generate code that will cause the most recent index analysis to
  85398. ** be loaded into internal hash tables where is can be used.
  85399. */
  85400. static void loadAnalysis(Parse *pParse, int iDb){
  85401. Vdbe *v = sqlite3GetVdbe(pParse);
  85402. if( v ){
  85403. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  85404. }
  85405. }
  85406. /*
  85407. ** Generate code that will do an analysis of an entire database
  85408. */
  85409. static void analyzeDatabase(Parse *pParse, int iDb){
  85410. sqlite3 *db = pParse->db;
  85411. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  85412. HashElem *k;
  85413. int iStatCur;
  85414. int iMem;
  85415. int iTab;
  85416. sqlite3BeginWriteOperation(pParse, 0, iDb);
  85417. iStatCur = pParse->nTab;
  85418. pParse->nTab += 3;
  85419. openStatTable(pParse, iDb, iStatCur, 0, 0);
  85420. iMem = pParse->nMem+1;
  85421. iTab = pParse->nTab;
  85422. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85423. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  85424. Table *pTab = (Table*)sqliteHashData(k);
  85425. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  85426. }
  85427. loadAnalysis(pParse, iDb);
  85428. }
  85429. /*
  85430. ** Generate code that will do an analysis of a single table in
  85431. ** a database. If pOnlyIdx is not NULL then it is a single index
  85432. ** in pTab that should be analyzed.
  85433. */
  85434. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  85435. int iDb;
  85436. int iStatCur;
  85437. assert( pTab!=0 );
  85438. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  85439. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85440. sqlite3BeginWriteOperation(pParse, 0, iDb);
  85441. iStatCur = pParse->nTab;
  85442. pParse->nTab += 3;
  85443. if( pOnlyIdx ){
  85444. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  85445. }else{
  85446. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  85447. }
  85448. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  85449. loadAnalysis(pParse, iDb);
  85450. }
  85451. /*
  85452. ** Generate code for the ANALYZE command. The parser calls this routine
  85453. ** when it recognizes an ANALYZE command.
  85454. **
  85455. ** ANALYZE -- 1
  85456. ** ANALYZE <database> -- 2
  85457. ** ANALYZE ?<database>.?<tablename> -- 3
  85458. **
  85459. ** Form 1 causes all indices in all attached databases to be analyzed.
  85460. ** Form 2 analyzes all indices the single database named.
  85461. ** Form 3 analyzes all indices associated with the named table.
  85462. */
  85463. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  85464. sqlite3 *db = pParse->db;
  85465. int iDb;
  85466. int i;
  85467. char *z, *zDb;
  85468. Table *pTab;
  85469. Index *pIdx;
  85470. Token *pTableName;
  85471. Vdbe *v;
  85472. /* Read the database schema. If an error occurs, leave an error message
  85473. ** and code in pParse and return NULL. */
  85474. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  85475. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85476. return;
  85477. }
  85478. assert( pName2!=0 || pName1==0 );
  85479. if( pName1==0 ){
  85480. /* Form 1: Analyze everything */
  85481. for(i=0; i<db->nDb; i++){
  85482. if( i==1 ) continue; /* Do not analyze the TEMP database */
  85483. analyzeDatabase(pParse, i);
  85484. }
  85485. }else if( pName2->n==0 ){
  85486. /* Form 2: Analyze the database or table named */
  85487. iDb = sqlite3FindDb(db, pName1);
  85488. if( iDb>=0 ){
  85489. analyzeDatabase(pParse, iDb);
  85490. }else{
  85491. z = sqlite3NameFromToken(db, pName1);
  85492. if( z ){
  85493. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  85494. analyzeTable(pParse, pIdx->pTable, pIdx);
  85495. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  85496. analyzeTable(pParse, pTab, 0);
  85497. }
  85498. sqlite3DbFree(db, z);
  85499. }
  85500. }
  85501. }else{
  85502. /* Form 3: Analyze the fully qualified table name */
  85503. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  85504. if( iDb>=0 ){
  85505. zDb = db->aDb[iDb].zName;
  85506. z = sqlite3NameFromToken(db, pTableName);
  85507. if( z ){
  85508. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  85509. analyzeTable(pParse, pIdx->pTable, pIdx);
  85510. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  85511. analyzeTable(pParse, pTab, 0);
  85512. }
  85513. sqlite3DbFree(db, z);
  85514. }
  85515. }
  85516. }
  85517. v = sqlite3GetVdbe(pParse);
  85518. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  85519. }
  85520. /*
  85521. ** Used to pass information from the analyzer reader through to the
  85522. ** callback routine.
  85523. */
  85524. typedef struct analysisInfo analysisInfo;
  85525. struct analysisInfo {
  85526. sqlite3 *db;
  85527. const char *zDatabase;
  85528. };
  85529. /*
  85530. ** The first argument points to a nul-terminated string containing a
  85531. ** list of space separated integers. Read the first nOut of these into
  85532. ** the array aOut[].
  85533. */
  85534. static void decodeIntArray(
  85535. char *zIntArray, /* String containing int array to decode */
  85536. int nOut, /* Number of slots in aOut[] */
  85537. tRowcnt *aOut, /* Store integers here */
  85538. LogEst *aLog, /* Or, if aOut==0, here */
  85539. Index *pIndex /* Handle extra flags for this index, if not NULL */
  85540. ){
  85541. char *z = zIntArray;
  85542. int c;
  85543. int i;
  85544. tRowcnt v;
  85545. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85546. if( z==0 ) z = "";
  85547. #else
  85548. assert( z!=0 );
  85549. #endif
  85550. for(i=0; *z && i<nOut; i++){
  85551. v = 0;
  85552. while( (c=z[0])>='0' && c<='9' ){
  85553. v = v*10 + c - '0';
  85554. z++;
  85555. }
  85556. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85557. if( aOut ) aOut[i] = v;
  85558. if( aLog ) aLog[i] = sqlite3LogEst(v);
  85559. #else
  85560. assert( aOut==0 );
  85561. UNUSED_PARAMETER(aOut);
  85562. assert( aLog!=0 );
  85563. aLog[i] = sqlite3LogEst(v);
  85564. #endif
  85565. if( *z==' ' ) z++;
  85566. }
  85567. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  85568. assert( pIndex!=0 ); {
  85569. #else
  85570. if( pIndex ){
  85571. #endif
  85572. pIndex->bUnordered = 0;
  85573. pIndex->noSkipScan = 0;
  85574. while( z[0] ){
  85575. if( sqlite3_strglob("unordered*", z)==0 ){
  85576. pIndex->bUnordered = 1;
  85577. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  85578. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  85579. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  85580. pIndex->noSkipScan = 1;
  85581. }
  85582. #ifdef SQLITE_ENABLE_COSTMULT
  85583. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  85584. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  85585. }
  85586. #endif
  85587. while( z[0]!=0 && z[0]!=' ' ) z++;
  85588. while( z[0]==' ' ) z++;
  85589. }
  85590. }
  85591. }
  85592. /*
  85593. ** This callback is invoked once for each index when reading the
  85594. ** sqlite_stat1 table.
  85595. **
  85596. ** argv[0] = name of the table
  85597. ** argv[1] = name of the index (might be NULL)
  85598. ** argv[2] = results of analysis - on integer for each column
  85599. **
  85600. ** Entries for which argv[1]==NULL simply record the number of rows in
  85601. ** the table.
  85602. */
  85603. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  85604. analysisInfo *pInfo = (analysisInfo*)pData;
  85605. Index *pIndex;
  85606. Table *pTable;
  85607. const char *z;
  85608. assert( argc==3 );
  85609. UNUSED_PARAMETER2(NotUsed, argc);
  85610. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  85611. return 0;
  85612. }
  85613. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  85614. if( pTable==0 ){
  85615. return 0;
  85616. }
  85617. if( argv[1]==0 ){
  85618. pIndex = 0;
  85619. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  85620. pIndex = sqlite3PrimaryKeyIndex(pTable);
  85621. }else{
  85622. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  85623. }
  85624. z = argv[2];
  85625. if( pIndex ){
  85626. tRowcnt *aiRowEst = 0;
  85627. int nCol = pIndex->nKeyCol+1;
  85628. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85629. /* Index.aiRowEst may already be set here if there are duplicate
  85630. ** sqlite_stat1 entries for this index. In that case just clobber
  85631. ** the old data with the new instead of allocating a new array. */
  85632. if( pIndex->aiRowEst==0 ){
  85633. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  85634. if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  85635. }
  85636. aiRowEst = pIndex->aiRowEst;
  85637. #endif
  85638. pIndex->bUnordered = 0;
  85639. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  85640. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  85641. }else{
  85642. Index fakeIdx;
  85643. fakeIdx.szIdxRow = pTable->szTabRow;
  85644. #ifdef SQLITE_ENABLE_COSTMULT
  85645. fakeIdx.pTable = pTable;
  85646. #endif
  85647. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  85648. pTable->szTabRow = fakeIdx.szIdxRow;
  85649. }
  85650. return 0;
  85651. }
  85652. /*
  85653. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  85654. ** and its contents.
  85655. */
  85656. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  85657. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85658. if( pIdx->aSample ){
  85659. int j;
  85660. for(j=0; j<pIdx->nSample; j++){
  85661. IndexSample *p = &pIdx->aSample[j];
  85662. sqlite3DbFree(db, p->p);
  85663. }
  85664. sqlite3DbFree(db, pIdx->aSample);
  85665. }
  85666. if( db && db->pnBytesFreed==0 ){
  85667. pIdx->nSample = 0;
  85668. pIdx->aSample = 0;
  85669. }
  85670. #else
  85671. UNUSED_PARAMETER(db);
  85672. UNUSED_PARAMETER(pIdx);
  85673. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85674. }
  85675. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85676. /*
  85677. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  85678. ** stored in pIdx->aSample[].
  85679. */
  85680. static void initAvgEq(Index *pIdx){
  85681. if( pIdx ){
  85682. IndexSample *aSample = pIdx->aSample;
  85683. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  85684. int iCol;
  85685. int nCol = 1;
  85686. if( pIdx->nSampleCol>1 ){
  85687. /* If this is stat4 data, then calculate aAvgEq[] values for all
  85688. ** sample columns except the last. The last is always set to 1, as
  85689. ** once the trailing PK fields are considered all index keys are
  85690. ** unique. */
  85691. nCol = pIdx->nSampleCol-1;
  85692. pIdx->aAvgEq[nCol] = 1;
  85693. }
  85694. for(iCol=0; iCol<nCol; iCol++){
  85695. int nSample = pIdx->nSample;
  85696. int i; /* Used to iterate through samples */
  85697. tRowcnt sumEq = 0; /* Sum of the nEq values */
  85698. tRowcnt avgEq = 0;
  85699. tRowcnt nRow; /* Number of rows in index */
  85700. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  85701. i64 nDist100; /* Number of distinct values in index */
  85702. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  85703. nRow = pFinal->anLt[iCol];
  85704. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  85705. nSample--;
  85706. }else{
  85707. nRow = pIdx->aiRowEst[0];
  85708. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  85709. }
  85710. pIdx->nRowEst0 = nRow;
  85711. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  85712. ** occur in the stat4 table for this index. Set sumEq to the sum of
  85713. ** the nEq values for column iCol for the same set (adding the value
  85714. ** only once where there exist duplicate prefixes). */
  85715. for(i=0; i<nSample; i++){
  85716. if( i==(pIdx->nSample-1)
  85717. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  85718. ){
  85719. sumEq += aSample[i].anEq[iCol];
  85720. nSum100 += 100;
  85721. }
  85722. }
  85723. if( nDist100>nSum100 ){
  85724. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  85725. }
  85726. if( avgEq==0 ) avgEq = 1;
  85727. pIdx->aAvgEq[iCol] = avgEq;
  85728. }
  85729. }
  85730. }
  85731. /*
  85732. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  85733. ** is supplied instead, find the PRIMARY KEY index for that table.
  85734. */
  85735. static Index *findIndexOrPrimaryKey(
  85736. sqlite3 *db,
  85737. const char *zName,
  85738. const char *zDb
  85739. ){
  85740. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  85741. if( pIdx==0 ){
  85742. Table *pTab = sqlite3FindTable(db, zName, zDb);
  85743. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  85744. }
  85745. return pIdx;
  85746. }
  85747. /*
  85748. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  85749. ** into the relevant Index.aSample[] arrays.
  85750. **
  85751. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  85752. ** data equivalent to the following (statements are different for stat3,
  85753. ** see the caller of this function for details):
  85754. **
  85755. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  85756. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  85757. **
  85758. ** where %Q is replaced with the database name before the SQL is executed.
  85759. */
  85760. static int loadStatTbl(
  85761. sqlite3 *db, /* Database handle */
  85762. int bStat3, /* Assume single column records only */
  85763. const char *zSql1, /* SQL statement 1 (see above) */
  85764. const char *zSql2, /* SQL statement 2 (see above) */
  85765. const char *zDb /* Database name (e.g. "main") */
  85766. ){
  85767. int rc; /* Result codes from subroutines */
  85768. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  85769. char *zSql; /* Text of the SQL statement */
  85770. Index *pPrevIdx = 0; /* Previous index in the loop */
  85771. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  85772. assert( db->lookaside.bEnabled==0 );
  85773. zSql = sqlite3MPrintf(db, zSql1, zDb);
  85774. if( !zSql ){
  85775. return SQLITE_NOMEM;
  85776. }
  85777. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  85778. sqlite3DbFree(db, zSql);
  85779. if( rc ) return rc;
  85780. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  85781. int nIdxCol = 1; /* Number of columns in stat4 records */
  85782. char *zIndex; /* Index name */
  85783. Index *pIdx; /* Pointer to the index object */
  85784. int nSample; /* Number of samples */
  85785. int nByte; /* Bytes of space required */
  85786. int i; /* Bytes of space required */
  85787. tRowcnt *pSpace;
  85788. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  85789. if( zIndex==0 ) continue;
  85790. nSample = sqlite3_column_int(pStmt, 1);
  85791. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  85792. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  85793. /* Index.nSample is non-zero at this point if data has already been
  85794. ** loaded from the stat4 table. In this case ignore stat3 data. */
  85795. if( pIdx==0 || pIdx->nSample ) continue;
  85796. if( bStat3==0 ){
  85797. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  85798. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  85799. nIdxCol = pIdx->nKeyCol;
  85800. }else{
  85801. nIdxCol = pIdx->nColumn;
  85802. }
  85803. }
  85804. pIdx->nSampleCol = nIdxCol;
  85805. nByte = sizeof(IndexSample) * nSample;
  85806. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  85807. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  85808. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  85809. if( pIdx->aSample==0 ){
  85810. sqlite3_finalize(pStmt);
  85811. return SQLITE_NOMEM;
  85812. }
  85813. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  85814. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  85815. for(i=0; i<nSample; i++){
  85816. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  85817. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  85818. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  85819. }
  85820. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  85821. }
  85822. rc = sqlite3_finalize(pStmt);
  85823. if( rc ) return rc;
  85824. zSql = sqlite3MPrintf(db, zSql2, zDb);
  85825. if( !zSql ){
  85826. return SQLITE_NOMEM;
  85827. }
  85828. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  85829. sqlite3DbFree(db, zSql);
  85830. if( rc ) return rc;
  85831. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  85832. char *zIndex; /* Index name */
  85833. Index *pIdx; /* Pointer to the index object */
  85834. int nCol = 1; /* Number of columns in index */
  85835. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  85836. if( zIndex==0 ) continue;
  85837. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  85838. if( pIdx==0 ) continue;
  85839. /* This next condition is true if data has already been loaded from
  85840. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  85841. nCol = pIdx->nSampleCol;
  85842. if( bStat3 && nCol>1 ) continue;
  85843. if( pIdx!=pPrevIdx ){
  85844. initAvgEq(pPrevIdx);
  85845. pPrevIdx = pIdx;
  85846. }
  85847. pSample = &pIdx->aSample[pIdx->nSample];
  85848. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  85849. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  85850. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  85851. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  85852. ** This is in case the sample record is corrupted. In that case, the
  85853. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  85854. ** end of the allocated buffer before it realizes it is dealing with
  85855. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  85856. ** a buffer overread. */
  85857. pSample->n = sqlite3_column_bytes(pStmt, 4);
  85858. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  85859. if( pSample->p==0 ){
  85860. sqlite3_finalize(pStmt);
  85861. return SQLITE_NOMEM;
  85862. }
  85863. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  85864. pIdx->nSample++;
  85865. }
  85866. rc = sqlite3_finalize(pStmt);
  85867. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  85868. return rc;
  85869. }
  85870. /*
  85871. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  85872. ** the Index.aSample[] arrays of all indices.
  85873. */
  85874. static int loadStat4(sqlite3 *db, const char *zDb){
  85875. int rc = SQLITE_OK; /* Result codes from subroutines */
  85876. assert( db->lookaside.bEnabled==0 );
  85877. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  85878. rc = loadStatTbl(db, 0,
  85879. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  85880. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  85881. zDb
  85882. );
  85883. }
  85884. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  85885. rc = loadStatTbl(db, 1,
  85886. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  85887. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  85888. zDb
  85889. );
  85890. }
  85891. return rc;
  85892. }
  85893. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85894. /*
  85895. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  85896. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  85897. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  85898. ** Index.aSample[] arrays.
  85899. **
  85900. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  85901. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  85902. ** during compilation and the sqlite_stat3/4 table is present, no data is
  85903. ** read from it.
  85904. **
  85905. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  85906. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  85907. ** returned. However, in this case, data is read from the sqlite_stat1
  85908. ** table (if it is present) before returning.
  85909. **
  85910. ** If an OOM error occurs, this function always sets db->mallocFailed.
  85911. ** This means if the caller does not care about other errors, the return
  85912. ** code may be ignored.
  85913. */
  85914. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  85915. analysisInfo sInfo;
  85916. HashElem *i;
  85917. char *zSql;
  85918. int rc;
  85919. assert( iDb>=0 && iDb<db->nDb );
  85920. assert( db->aDb[iDb].pBt!=0 );
  85921. /* Clear any prior statistics */
  85922. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85923. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  85924. Index *pIdx = sqliteHashData(i);
  85925. sqlite3DefaultRowEst(pIdx);
  85926. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85927. sqlite3DeleteIndexSamples(db, pIdx);
  85928. pIdx->aSample = 0;
  85929. #endif
  85930. }
  85931. /* Check to make sure the sqlite_stat1 table exists */
  85932. sInfo.db = db;
  85933. sInfo.zDatabase = db->aDb[iDb].zName;
  85934. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  85935. return SQLITE_ERROR;
  85936. }
  85937. /* Load new statistics out of the sqlite_stat1 table */
  85938. zSql = sqlite3MPrintf(db,
  85939. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  85940. if( zSql==0 ){
  85941. rc = SQLITE_NOMEM;
  85942. }else{
  85943. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  85944. sqlite3DbFree(db, zSql);
  85945. }
  85946. /* Load the statistics from the sqlite_stat4 table. */
  85947. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85948. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  85949. int lookasideEnabled = db->lookaside.bEnabled;
  85950. db->lookaside.bEnabled = 0;
  85951. rc = loadStat4(db, sInfo.zDatabase);
  85952. db->lookaside.bEnabled = lookasideEnabled;
  85953. }
  85954. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  85955. Index *pIdx = sqliteHashData(i);
  85956. sqlite3_free(pIdx->aiRowEst);
  85957. pIdx->aiRowEst = 0;
  85958. }
  85959. #endif
  85960. if( rc==SQLITE_NOMEM ){
  85961. db->mallocFailed = 1;
  85962. }
  85963. return rc;
  85964. }
  85965. #endif /* SQLITE_OMIT_ANALYZE */
  85966. /************** End of analyze.c *********************************************/
  85967. /************** Begin file attach.c ******************************************/
  85968. /*
  85969. ** 2003 April 6
  85970. **
  85971. ** The author disclaims copyright to this source code. In place of
  85972. ** a legal notice, here is a blessing:
  85973. **
  85974. ** May you do good and not evil.
  85975. ** May you find forgiveness for yourself and forgive others.
  85976. ** May you share freely, never taking more than you give.
  85977. **
  85978. *************************************************************************
  85979. ** This file contains code used to implement the ATTACH and DETACH commands.
  85980. */
  85981. /* #include "sqliteInt.h" */
  85982. #ifndef SQLITE_OMIT_ATTACH
  85983. /*
  85984. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  85985. ** is slightly different from resolving a normal SQL expression, because simple
  85986. ** identifiers are treated as strings, not possible column names or aliases.
  85987. **
  85988. ** i.e. if the parser sees:
  85989. **
  85990. ** ATTACH DATABASE abc AS def
  85991. **
  85992. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  85993. ** looking for columns of the same name.
  85994. **
  85995. ** This only applies to the root node of pExpr, so the statement:
  85996. **
  85997. ** ATTACH DATABASE abc||def AS 'db2'
  85998. **
  85999. ** will fail because neither abc or def can be resolved.
  86000. */
  86001. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  86002. {
  86003. int rc = SQLITE_OK;
  86004. if( pExpr ){
  86005. if( pExpr->op!=TK_ID ){
  86006. rc = sqlite3ResolveExprNames(pName, pExpr);
  86007. }else{
  86008. pExpr->op = TK_STRING;
  86009. }
  86010. }
  86011. return rc;
  86012. }
  86013. /*
  86014. ** An SQL user-function registered to do the work of an ATTACH statement. The
  86015. ** three arguments to the function come directly from an attach statement:
  86016. **
  86017. ** ATTACH DATABASE x AS y KEY z
  86018. **
  86019. ** SELECT sqlite_attach(x, y, z)
  86020. **
  86021. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  86022. ** third argument.
  86023. */
  86024. static void attachFunc(
  86025. sqlite3_context *context,
  86026. int NotUsed,
  86027. sqlite3_value **argv
  86028. ){
  86029. int i;
  86030. int rc = 0;
  86031. sqlite3 *db = sqlite3_context_db_handle(context);
  86032. const char *zName;
  86033. const char *zFile;
  86034. char *zPath = 0;
  86035. char *zErr = 0;
  86036. unsigned int flags;
  86037. Db *aNew;
  86038. char *zErrDyn = 0;
  86039. sqlite3_vfs *pVfs;
  86040. UNUSED_PARAMETER(NotUsed);
  86041. zFile = (const char *)sqlite3_value_text(argv[0]);
  86042. zName = (const char *)sqlite3_value_text(argv[1]);
  86043. if( zFile==0 ) zFile = "";
  86044. if( zName==0 ) zName = "";
  86045. /* Check for the following errors:
  86046. **
  86047. ** * Too many attached databases,
  86048. ** * Transaction currently open
  86049. ** * Specified database name already being used.
  86050. */
  86051. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  86052. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  86053. db->aLimit[SQLITE_LIMIT_ATTACHED]
  86054. );
  86055. goto attach_error;
  86056. }
  86057. if( !db->autoCommit ){
  86058. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  86059. goto attach_error;
  86060. }
  86061. for(i=0; i<db->nDb; i++){
  86062. char *z = db->aDb[i].zName;
  86063. assert( z && zName );
  86064. if( sqlite3StrICmp(z, zName)==0 ){
  86065. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  86066. goto attach_error;
  86067. }
  86068. }
  86069. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  86070. ** hash tables.
  86071. */
  86072. if( db->aDb==db->aDbStatic ){
  86073. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  86074. if( aNew==0 ) return;
  86075. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  86076. }else{
  86077. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  86078. if( aNew==0 ) return;
  86079. }
  86080. db->aDb = aNew;
  86081. aNew = &db->aDb[db->nDb];
  86082. memset(aNew, 0, sizeof(*aNew));
  86083. /* Open the database file. If the btree is successfully opened, use
  86084. ** it to obtain the database schema. At this point the schema may
  86085. ** or may not be initialized.
  86086. */
  86087. flags = db->openFlags;
  86088. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  86089. if( rc!=SQLITE_OK ){
  86090. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  86091. sqlite3_result_error(context, zErr, -1);
  86092. sqlite3_free(zErr);
  86093. return;
  86094. }
  86095. assert( pVfs );
  86096. flags |= SQLITE_OPEN_MAIN_DB;
  86097. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  86098. sqlite3_free( zPath );
  86099. db->nDb++;
  86100. if( rc==SQLITE_CONSTRAINT ){
  86101. rc = SQLITE_ERROR;
  86102. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  86103. }else if( rc==SQLITE_OK ){
  86104. Pager *pPager;
  86105. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  86106. if( !aNew->pSchema ){
  86107. rc = SQLITE_NOMEM;
  86108. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  86109. zErrDyn = sqlite3MPrintf(db,
  86110. "attached databases must use the same text encoding as main database");
  86111. rc = SQLITE_ERROR;
  86112. }
  86113. sqlite3BtreeEnter(aNew->pBt);
  86114. pPager = sqlite3BtreePager(aNew->pBt);
  86115. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  86116. sqlite3BtreeSecureDelete(aNew->pBt,
  86117. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  86118. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  86119. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  86120. #endif
  86121. sqlite3BtreeLeave(aNew->pBt);
  86122. }
  86123. aNew->safety_level = 3;
  86124. aNew->zName = sqlite3DbStrDup(db, zName);
  86125. if( rc==SQLITE_OK && aNew->zName==0 ){
  86126. rc = SQLITE_NOMEM;
  86127. }
  86128. #ifdef SQLITE_HAS_CODEC
  86129. if( rc==SQLITE_OK ){
  86130. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  86131. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  86132. int nKey;
  86133. char *zKey;
  86134. int t = sqlite3_value_type(argv[2]);
  86135. switch( t ){
  86136. case SQLITE_INTEGER:
  86137. case SQLITE_FLOAT:
  86138. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  86139. rc = SQLITE_ERROR;
  86140. break;
  86141. case SQLITE_TEXT:
  86142. case SQLITE_BLOB:
  86143. nKey = sqlite3_value_bytes(argv[2]);
  86144. zKey = (char *)sqlite3_value_blob(argv[2]);
  86145. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  86146. break;
  86147. case SQLITE_NULL:
  86148. /* No key specified. Use the key from the main database */
  86149. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  86150. if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  86151. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  86152. }
  86153. break;
  86154. }
  86155. }
  86156. #endif
  86157. /* If the file was opened successfully, read the schema for the new database.
  86158. ** If this fails, or if opening the file failed, then close the file and
  86159. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  86160. ** we found it.
  86161. */
  86162. if( rc==SQLITE_OK ){
  86163. sqlite3BtreeEnterAll(db);
  86164. rc = sqlite3Init(db, &zErrDyn);
  86165. sqlite3BtreeLeaveAll(db);
  86166. }
  86167. #ifdef SQLITE_USER_AUTHENTICATION
  86168. if( rc==SQLITE_OK ){
  86169. u8 newAuth = 0;
  86170. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  86171. if( newAuth<db->auth.authLevel ){
  86172. rc = SQLITE_AUTH_USER;
  86173. }
  86174. }
  86175. #endif
  86176. if( rc ){
  86177. int iDb = db->nDb - 1;
  86178. assert( iDb>=2 );
  86179. if( db->aDb[iDb].pBt ){
  86180. sqlite3BtreeClose(db->aDb[iDb].pBt);
  86181. db->aDb[iDb].pBt = 0;
  86182. db->aDb[iDb].pSchema = 0;
  86183. }
  86184. sqlite3ResetAllSchemasOfConnection(db);
  86185. db->nDb = iDb;
  86186. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  86187. db->mallocFailed = 1;
  86188. sqlite3DbFree(db, zErrDyn);
  86189. zErrDyn = sqlite3MPrintf(db, "out of memory");
  86190. }else if( zErrDyn==0 ){
  86191. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  86192. }
  86193. goto attach_error;
  86194. }
  86195. return;
  86196. attach_error:
  86197. /* Return an error if we get here */
  86198. if( zErrDyn ){
  86199. sqlite3_result_error(context, zErrDyn, -1);
  86200. sqlite3DbFree(db, zErrDyn);
  86201. }
  86202. if( rc ) sqlite3_result_error_code(context, rc);
  86203. }
  86204. /*
  86205. ** An SQL user-function registered to do the work of an DETACH statement. The
  86206. ** three arguments to the function come directly from a detach statement:
  86207. **
  86208. ** DETACH DATABASE x
  86209. **
  86210. ** SELECT sqlite_detach(x)
  86211. */
  86212. static void detachFunc(
  86213. sqlite3_context *context,
  86214. int NotUsed,
  86215. sqlite3_value **argv
  86216. ){
  86217. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  86218. sqlite3 *db = sqlite3_context_db_handle(context);
  86219. int i;
  86220. Db *pDb = 0;
  86221. char zErr[128];
  86222. UNUSED_PARAMETER(NotUsed);
  86223. if( zName==0 ) zName = "";
  86224. for(i=0; i<db->nDb; i++){
  86225. pDb = &db->aDb[i];
  86226. if( pDb->pBt==0 ) continue;
  86227. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  86228. }
  86229. if( i>=db->nDb ){
  86230. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  86231. goto detach_error;
  86232. }
  86233. if( i<2 ){
  86234. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  86235. goto detach_error;
  86236. }
  86237. if( !db->autoCommit ){
  86238. sqlite3_snprintf(sizeof(zErr), zErr,
  86239. "cannot DETACH database within transaction");
  86240. goto detach_error;
  86241. }
  86242. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  86243. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  86244. goto detach_error;
  86245. }
  86246. sqlite3BtreeClose(pDb->pBt);
  86247. pDb->pBt = 0;
  86248. pDb->pSchema = 0;
  86249. sqlite3CollapseDatabaseArray(db);
  86250. return;
  86251. detach_error:
  86252. sqlite3_result_error(context, zErr, -1);
  86253. }
  86254. /*
  86255. ** This procedure generates VDBE code for a single invocation of either the
  86256. ** sqlite_detach() or sqlite_attach() SQL user functions.
  86257. */
  86258. static void codeAttach(
  86259. Parse *pParse, /* The parser context */
  86260. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  86261. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  86262. Expr *pAuthArg, /* Expression to pass to authorization callback */
  86263. Expr *pFilename, /* Name of database file */
  86264. Expr *pDbname, /* Name of the database to use internally */
  86265. Expr *pKey /* Database key for encryption extension */
  86266. ){
  86267. int rc;
  86268. NameContext sName;
  86269. Vdbe *v;
  86270. sqlite3* db = pParse->db;
  86271. int regArgs;
  86272. memset(&sName, 0, sizeof(NameContext));
  86273. sName.pParse = pParse;
  86274. if(
  86275. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  86276. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  86277. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  86278. ){
  86279. goto attach_end;
  86280. }
  86281. #ifndef SQLITE_OMIT_AUTHORIZATION
  86282. if( pAuthArg ){
  86283. char *zAuthArg;
  86284. if( pAuthArg->op==TK_STRING ){
  86285. zAuthArg = pAuthArg->u.zToken;
  86286. }else{
  86287. zAuthArg = 0;
  86288. }
  86289. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  86290. if(rc!=SQLITE_OK ){
  86291. goto attach_end;
  86292. }
  86293. }
  86294. #endif /* SQLITE_OMIT_AUTHORIZATION */
  86295. v = sqlite3GetVdbe(pParse);
  86296. regArgs = sqlite3GetTempRange(pParse, 4);
  86297. sqlite3ExprCode(pParse, pFilename, regArgs);
  86298. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  86299. sqlite3ExprCode(pParse, pKey, regArgs+2);
  86300. assert( v || db->mallocFailed );
  86301. if( v ){
  86302. sqlite3VdbeAddOp3(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3);
  86303. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  86304. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  86305. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  86306. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  86307. ** statement only). For DETACH, set it to false (expire all existing
  86308. ** statements).
  86309. */
  86310. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  86311. }
  86312. attach_end:
  86313. sqlite3ExprDelete(db, pFilename);
  86314. sqlite3ExprDelete(db, pDbname);
  86315. sqlite3ExprDelete(db, pKey);
  86316. }
  86317. /*
  86318. ** Called by the parser to compile a DETACH statement.
  86319. **
  86320. ** DETACH pDbname
  86321. */
  86322. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  86323. static const FuncDef detach_func = {
  86324. 1, /* nArg */
  86325. SQLITE_UTF8, /* funcFlags */
  86326. 0, /* pUserData */
  86327. 0, /* pNext */
  86328. detachFunc, /* xFunc */
  86329. 0, /* xStep */
  86330. 0, /* xFinalize */
  86331. "sqlite_detach", /* zName */
  86332. 0, /* pHash */
  86333. 0 /* pDestructor */
  86334. };
  86335. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  86336. }
  86337. /*
  86338. ** Called by the parser to compile an ATTACH statement.
  86339. **
  86340. ** ATTACH p AS pDbname KEY pKey
  86341. */
  86342. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  86343. static const FuncDef attach_func = {
  86344. 3, /* nArg */
  86345. SQLITE_UTF8, /* funcFlags */
  86346. 0, /* pUserData */
  86347. 0, /* pNext */
  86348. attachFunc, /* xFunc */
  86349. 0, /* xStep */
  86350. 0, /* xFinalize */
  86351. "sqlite_attach", /* zName */
  86352. 0, /* pHash */
  86353. 0 /* pDestructor */
  86354. };
  86355. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  86356. }
  86357. #endif /* SQLITE_OMIT_ATTACH */
  86358. /*
  86359. ** Initialize a DbFixer structure. This routine must be called prior
  86360. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  86361. */
  86362. SQLITE_PRIVATE void sqlite3FixInit(
  86363. DbFixer *pFix, /* The fixer to be initialized */
  86364. Parse *pParse, /* Error messages will be written here */
  86365. int iDb, /* This is the database that must be used */
  86366. const char *zType, /* "view", "trigger", or "index" */
  86367. const Token *pName /* Name of the view, trigger, or index */
  86368. ){
  86369. sqlite3 *db;
  86370. db = pParse->db;
  86371. assert( db->nDb>iDb );
  86372. pFix->pParse = pParse;
  86373. pFix->zDb = db->aDb[iDb].zName;
  86374. pFix->pSchema = db->aDb[iDb].pSchema;
  86375. pFix->zType = zType;
  86376. pFix->pName = pName;
  86377. pFix->bVarOnly = (iDb==1);
  86378. }
  86379. /*
  86380. ** The following set of routines walk through the parse tree and assign
  86381. ** a specific database to all table references where the database name
  86382. ** was left unspecified in the original SQL statement. The pFix structure
  86383. ** must have been initialized by a prior call to sqlite3FixInit().
  86384. **
  86385. ** These routines are used to make sure that an index, trigger, or
  86386. ** view in one database does not refer to objects in a different database.
  86387. ** (Exception: indices, triggers, and views in the TEMP database are
  86388. ** allowed to refer to anything.) If a reference is explicitly made
  86389. ** to an object in a different database, an error message is added to
  86390. ** pParse->zErrMsg and these routines return non-zero. If everything
  86391. ** checks out, these routines return 0.
  86392. */
  86393. SQLITE_PRIVATE int sqlite3FixSrcList(
  86394. DbFixer *pFix, /* Context of the fixation */
  86395. SrcList *pList /* The Source list to check and modify */
  86396. ){
  86397. int i;
  86398. const char *zDb;
  86399. struct SrcList_item *pItem;
  86400. if( NEVER(pList==0) ) return 0;
  86401. zDb = pFix->zDb;
  86402. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  86403. if( pFix->bVarOnly==0 ){
  86404. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  86405. sqlite3ErrorMsg(pFix->pParse,
  86406. "%s %T cannot reference objects in database %s",
  86407. pFix->zType, pFix->pName, pItem->zDatabase);
  86408. return 1;
  86409. }
  86410. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  86411. pItem->zDatabase = 0;
  86412. pItem->pSchema = pFix->pSchema;
  86413. }
  86414. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  86415. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  86416. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  86417. #endif
  86418. }
  86419. return 0;
  86420. }
  86421. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  86422. SQLITE_PRIVATE int sqlite3FixSelect(
  86423. DbFixer *pFix, /* Context of the fixation */
  86424. Select *pSelect /* The SELECT statement to be fixed to one database */
  86425. ){
  86426. while( pSelect ){
  86427. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  86428. return 1;
  86429. }
  86430. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  86431. return 1;
  86432. }
  86433. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  86434. return 1;
  86435. }
  86436. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  86437. return 1;
  86438. }
  86439. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  86440. return 1;
  86441. }
  86442. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  86443. return 1;
  86444. }
  86445. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  86446. return 1;
  86447. }
  86448. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  86449. return 1;
  86450. }
  86451. pSelect = pSelect->pPrior;
  86452. }
  86453. return 0;
  86454. }
  86455. SQLITE_PRIVATE int sqlite3FixExpr(
  86456. DbFixer *pFix, /* Context of the fixation */
  86457. Expr *pExpr /* The expression to be fixed to one database */
  86458. ){
  86459. while( pExpr ){
  86460. if( pExpr->op==TK_VARIABLE ){
  86461. if( pFix->pParse->db->init.busy ){
  86462. pExpr->op = TK_NULL;
  86463. }else{
  86464. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  86465. return 1;
  86466. }
  86467. }
  86468. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  86469. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86470. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  86471. }else{
  86472. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  86473. }
  86474. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  86475. return 1;
  86476. }
  86477. pExpr = pExpr->pLeft;
  86478. }
  86479. return 0;
  86480. }
  86481. SQLITE_PRIVATE int sqlite3FixExprList(
  86482. DbFixer *pFix, /* Context of the fixation */
  86483. ExprList *pList /* The expression to be fixed to one database */
  86484. ){
  86485. int i;
  86486. struct ExprList_item *pItem;
  86487. if( pList==0 ) return 0;
  86488. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  86489. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  86490. return 1;
  86491. }
  86492. }
  86493. return 0;
  86494. }
  86495. #endif
  86496. #ifndef SQLITE_OMIT_TRIGGER
  86497. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  86498. DbFixer *pFix, /* Context of the fixation */
  86499. TriggerStep *pStep /* The trigger step be fixed to one database */
  86500. ){
  86501. while( pStep ){
  86502. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  86503. return 1;
  86504. }
  86505. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  86506. return 1;
  86507. }
  86508. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  86509. return 1;
  86510. }
  86511. pStep = pStep->pNext;
  86512. }
  86513. return 0;
  86514. }
  86515. #endif
  86516. /************** End of attach.c **********************************************/
  86517. /************** Begin file auth.c ********************************************/
  86518. /*
  86519. ** 2003 January 11
  86520. **
  86521. ** The author disclaims copyright to this source code. In place of
  86522. ** a legal notice, here is a blessing:
  86523. **
  86524. ** May you do good and not evil.
  86525. ** May you find forgiveness for yourself and forgive others.
  86526. ** May you share freely, never taking more than you give.
  86527. **
  86528. *************************************************************************
  86529. ** This file contains code used to implement the sqlite3_set_authorizer()
  86530. ** API. This facility is an optional feature of the library. Embedded
  86531. ** systems that do not need this facility may omit it by recompiling
  86532. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  86533. */
  86534. /* #include "sqliteInt.h" */
  86535. /*
  86536. ** All of the code in this file may be omitted by defining a single
  86537. ** macro.
  86538. */
  86539. #ifndef SQLITE_OMIT_AUTHORIZATION
  86540. /*
  86541. ** Set or clear the access authorization function.
  86542. **
  86543. ** The access authorization function is be called during the compilation
  86544. ** phase to verify that the user has read and/or write access permission on
  86545. ** various fields of the database. The first argument to the auth function
  86546. ** is a copy of the 3rd argument to this routine. The second argument
  86547. ** to the auth function is one of these constants:
  86548. **
  86549. ** SQLITE_CREATE_INDEX
  86550. ** SQLITE_CREATE_TABLE
  86551. ** SQLITE_CREATE_TEMP_INDEX
  86552. ** SQLITE_CREATE_TEMP_TABLE
  86553. ** SQLITE_CREATE_TEMP_TRIGGER
  86554. ** SQLITE_CREATE_TEMP_VIEW
  86555. ** SQLITE_CREATE_TRIGGER
  86556. ** SQLITE_CREATE_VIEW
  86557. ** SQLITE_DELETE
  86558. ** SQLITE_DROP_INDEX
  86559. ** SQLITE_DROP_TABLE
  86560. ** SQLITE_DROP_TEMP_INDEX
  86561. ** SQLITE_DROP_TEMP_TABLE
  86562. ** SQLITE_DROP_TEMP_TRIGGER
  86563. ** SQLITE_DROP_TEMP_VIEW
  86564. ** SQLITE_DROP_TRIGGER
  86565. ** SQLITE_DROP_VIEW
  86566. ** SQLITE_INSERT
  86567. ** SQLITE_PRAGMA
  86568. ** SQLITE_READ
  86569. ** SQLITE_SELECT
  86570. ** SQLITE_TRANSACTION
  86571. ** SQLITE_UPDATE
  86572. **
  86573. ** The third and fourth arguments to the auth function are the name of
  86574. ** the table and the column that are being accessed. The auth function
  86575. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  86576. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  86577. ** means that the SQL statement will never-run - the sqlite3_exec() call
  86578. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  86579. ** should run but attempts to read the specified column will return NULL
  86580. ** and attempts to write the column will be ignored.
  86581. **
  86582. ** Setting the auth function to NULL disables this hook. The default
  86583. ** setting of the auth function is NULL.
  86584. */
  86585. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  86586. sqlite3 *db,
  86587. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  86588. void *pArg
  86589. ){
  86590. #ifdef SQLITE_ENABLE_API_ARMOR
  86591. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  86592. #endif
  86593. sqlite3_mutex_enter(db->mutex);
  86594. db->xAuth = (sqlite3_xauth)xAuth;
  86595. db->pAuthArg = pArg;
  86596. sqlite3ExpirePreparedStatements(db);
  86597. sqlite3_mutex_leave(db->mutex);
  86598. return SQLITE_OK;
  86599. }
  86600. /*
  86601. ** Write an error message into pParse->zErrMsg that explains that the
  86602. ** user-supplied authorization function returned an illegal value.
  86603. */
  86604. static void sqliteAuthBadReturnCode(Parse *pParse){
  86605. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  86606. pParse->rc = SQLITE_ERROR;
  86607. }
  86608. /*
  86609. ** Invoke the authorization callback for permission to read column zCol from
  86610. ** table zTab in database zDb. This function assumes that an authorization
  86611. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  86612. **
  86613. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  86614. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  86615. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  86616. */
  86617. SQLITE_PRIVATE int sqlite3AuthReadCol(
  86618. Parse *pParse, /* The parser context */
  86619. const char *zTab, /* Table name */
  86620. const char *zCol, /* Column name */
  86621. int iDb /* Index of containing database. */
  86622. ){
  86623. sqlite3 *db = pParse->db; /* Database handle */
  86624. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  86625. int rc; /* Auth callback return code */
  86626. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  86627. #ifdef SQLITE_USER_AUTHENTICATION
  86628. ,db->auth.zAuthUser
  86629. #endif
  86630. );
  86631. if( rc==SQLITE_DENY ){
  86632. if( db->nDb>2 || iDb!=0 ){
  86633. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  86634. }else{
  86635. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  86636. }
  86637. pParse->rc = SQLITE_AUTH;
  86638. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  86639. sqliteAuthBadReturnCode(pParse);
  86640. }
  86641. return rc;
  86642. }
  86643. /*
  86644. ** The pExpr should be a TK_COLUMN expression. The table referred to
  86645. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  86646. ** Check to see if it is OK to read this particular column.
  86647. **
  86648. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  86649. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  86650. ** then generate an error.
  86651. */
  86652. SQLITE_PRIVATE void sqlite3AuthRead(
  86653. Parse *pParse, /* The parser context */
  86654. Expr *pExpr, /* The expression to check authorization on */
  86655. Schema *pSchema, /* The schema of the expression */
  86656. SrcList *pTabList /* All table that pExpr might refer to */
  86657. ){
  86658. sqlite3 *db = pParse->db;
  86659. Table *pTab = 0; /* The table being read */
  86660. const char *zCol; /* Name of the column of the table */
  86661. int iSrc; /* Index in pTabList->a[] of table being read */
  86662. int iDb; /* The index of the database the expression refers to */
  86663. int iCol; /* Index of column in table */
  86664. if( db->xAuth==0 ) return;
  86665. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  86666. if( iDb<0 ){
  86667. /* An attempt to read a column out of a subquery or other
  86668. ** temporary table. */
  86669. return;
  86670. }
  86671. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  86672. if( pExpr->op==TK_TRIGGER ){
  86673. pTab = pParse->pTriggerTab;
  86674. }else{
  86675. assert( pTabList );
  86676. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  86677. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  86678. pTab = pTabList->a[iSrc].pTab;
  86679. break;
  86680. }
  86681. }
  86682. }
  86683. iCol = pExpr->iColumn;
  86684. if( NEVER(pTab==0) ) return;
  86685. if( iCol>=0 ){
  86686. assert( iCol<pTab->nCol );
  86687. zCol = pTab->aCol[iCol].zName;
  86688. }else if( pTab->iPKey>=0 ){
  86689. assert( pTab->iPKey<pTab->nCol );
  86690. zCol = pTab->aCol[pTab->iPKey].zName;
  86691. }else{
  86692. zCol = "ROWID";
  86693. }
  86694. assert( iDb>=0 && iDb<db->nDb );
  86695. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  86696. pExpr->op = TK_NULL;
  86697. }
  86698. }
  86699. /*
  86700. ** Do an authorization check using the code and arguments given. Return
  86701. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  86702. ** is returned, then the error count and error message in pParse are
  86703. ** modified appropriately.
  86704. */
  86705. SQLITE_PRIVATE int sqlite3AuthCheck(
  86706. Parse *pParse,
  86707. int code,
  86708. const char *zArg1,
  86709. const char *zArg2,
  86710. const char *zArg3
  86711. ){
  86712. sqlite3 *db = pParse->db;
  86713. int rc;
  86714. /* Don't do any authorization checks if the database is initialising
  86715. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  86716. */
  86717. if( db->init.busy || IN_DECLARE_VTAB ){
  86718. return SQLITE_OK;
  86719. }
  86720. if( db->xAuth==0 ){
  86721. return SQLITE_OK;
  86722. }
  86723. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  86724. #ifdef SQLITE_USER_AUTHENTICATION
  86725. ,db->auth.zAuthUser
  86726. #endif
  86727. );
  86728. if( rc==SQLITE_DENY ){
  86729. sqlite3ErrorMsg(pParse, "not authorized");
  86730. pParse->rc = SQLITE_AUTH;
  86731. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  86732. rc = SQLITE_DENY;
  86733. sqliteAuthBadReturnCode(pParse);
  86734. }
  86735. return rc;
  86736. }
  86737. /*
  86738. ** Push an authorization context. After this routine is called, the
  86739. ** zArg3 argument to authorization callbacks will be zContext until
  86740. ** popped. Or if pParse==0, this routine is a no-op.
  86741. */
  86742. SQLITE_PRIVATE void sqlite3AuthContextPush(
  86743. Parse *pParse,
  86744. AuthContext *pContext,
  86745. const char *zContext
  86746. ){
  86747. assert( pParse );
  86748. pContext->pParse = pParse;
  86749. pContext->zAuthContext = pParse->zAuthContext;
  86750. pParse->zAuthContext = zContext;
  86751. }
  86752. /*
  86753. ** Pop an authorization context that was previously pushed
  86754. ** by sqlite3AuthContextPush
  86755. */
  86756. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  86757. if( pContext->pParse ){
  86758. pContext->pParse->zAuthContext = pContext->zAuthContext;
  86759. pContext->pParse = 0;
  86760. }
  86761. }
  86762. #endif /* SQLITE_OMIT_AUTHORIZATION */
  86763. /************** End of auth.c ************************************************/
  86764. /************** Begin file build.c *******************************************/
  86765. /*
  86766. ** 2001 September 15
  86767. **
  86768. ** The author disclaims copyright to this source code. In place of
  86769. ** a legal notice, here is a blessing:
  86770. **
  86771. ** May you do good and not evil.
  86772. ** May you find forgiveness for yourself and forgive others.
  86773. ** May you share freely, never taking more than you give.
  86774. **
  86775. *************************************************************************
  86776. ** This file contains C code routines that are called by the SQLite parser
  86777. ** when syntax rules are reduced. The routines in this file handle the
  86778. ** following kinds of SQL syntax:
  86779. **
  86780. ** CREATE TABLE
  86781. ** DROP TABLE
  86782. ** CREATE INDEX
  86783. ** DROP INDEX
  86784. ** creating ID lists
  86785. ** BEGIN TRANSACTION
  86786. ** COMMIT
  86787. ** ROLLBACK
  86788. */
  86789. /* #include "sqliteInt.h" */
  86790. /*
  86791. ** This routine is called when a new SQL statement is beginning to
  86792. ** be parsed. Initialize the pParse structure as needed.
  86793. */
  86794. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  86795. pParse->explain = (u8)explainFlag;
  86796. pParse->nVar = 0;
  86797. }
  86798. #ifndef SQLITE_OMIT_SHARED_CACHE
  86799. /*
  86800. ** The TableLock structure is only used by the sqlite3TableLock() and
  86801. ** codeTableLocks() functions.
  86802. */
  86803. struct TableLock {
  86804. int iDb; /* The database containing the table to be locked */
  86805. int iTab; /* The root page of the table to be locked */
  86806. u8 isWriteLock; /* True for write lock. False for a read lock */
  86807. const char *zName; /* Name of the table */
  86808. };
  86809. /*
  86810. ** Record the fact that we want to lock a table at run-time.
  86811. **
  86812. ** The table to be locked has root page iTab and is found in database iDb.
  86813. ** A read or a write lock can be taken depending on isWritelock.
  86814. **
  86815. ** This routine just records the fact that the lock is desired. The
  86816. ** code to make the lock occur is generated by a later call to
  86817. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  86818. */
  86819. SQLITE_PRIVATE void sqlite3TableLock(
  86820. Parse *pParse, /* Parsing context */
  86821. int iDb, /* Index of the database containing the table to lock */
  86822. int iTab, /* Root page number of the table to be locked */
  86823. u8 isWriteLock, /* True for a write lock */
  86824. const char *zName /* Name of the table to be locked */
  86825. ){
  86826. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86827. int i;
  86828. int nBytes;
  86829. TableLock *p;
  86830. assert( iDb>=0 );
  86831. for(i=0; i<pToplevel->nTableLock; i++){
  86832. p = &pToplevel->aTableLock[i];
  86833. if( p->iDb==iDb && p->iTab==iTab ){
  86834. p->isWriteLock = (p->isWriteLock || isWriteLock);
  86835. return;
  86836. }
  86837. }
  86838. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  86839. pToplevel->aTableLock =
  86840. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  86841. if( pToplevel->aTableLock ){
  86842. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  86843. p->iDb = iDb;
  86844. p->iTab = iTab;
  86845. p->isWriteLock = isWriteLock;
  86846. p->zName = zName;
  86847. }else{
  86848. pToplevel->nTableLock = 0;
  86849. pToplevel->db->mallocFailed = 1;
  86850. }
  86851. }
  86852. /*
  86853. ** Code an OP_TableLock instruction for each table locked by the
  86854. ** statement (configured by calls to sqlite3TableLock()).
  86855. */
  86856. static void codeTableLocks(Parse *pParse){
  86857. int i;
  86858. Vdbe *pVdbe;
  86859. pVdbe = sqlite3GetVdbe(pParse);
  86860. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  86861. for(i=0; i<pParse->nTableLock; i++){
  86862. TableLock *p = &pParse->aTableLock[i];
  86863. int p1 = p->iDb;
  86864. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  86865. p->zName, P4_STATIC);
  86866. }
  86867. }
  86868. #else
  86869. #define codeTableLocks(x)
  86870. #endif
  86871. /*
  86872. ** Return TRUE if the given yDbMask object is empty - if it contains no
  86873. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  86874. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  86875. */
  86876. #if SQLITE_MAX_ATTACHED>30
  86877. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  86878. int i;
  86879. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  86880. return 1;
  86881. }
  86882. #endif
  86883. /*
  86884. ** This routine is called after a single SQL statement has been
  86885. ** parsed and a VDBE program to execute that statement has been
  86886. ** prepared. This routine puts the finishing touches on the
  86887. ** VDBE program and resets the pParse structure for the next
  86888. ** parse.
  86889. **
  86890. ** Note that if an error occurred, it might be the case that
  86891. ** no VDBE code was generated.
  86892. */
  86893. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  86894. sqlite3 *db;
  86895. Vdbe *v;
  86896. assert( pParse->pToplevel==0 );
  86897. db = pParse->db;
  86898. if( pParse->nested ) return;
  86899. if( db->mallocFailed || pParse->nErr ){
  86900. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  86901. return;
  86902. }
  86903. /* Begin by generating some termination code at the end of the
  86904. ** vdbe program
  86905. */
  86906. v = sqlite3GetVdbe(pParse);
  86907. assert( !pParse->isMultiWrite
  86908. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  86909. if( v ){
  86910. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  86911. sqlite3VdbeAddOp0(v, OP_Halt);
  86912. #if SQLITE_USER_AUTHENTICATION
  86913. if( pParse->nTableLock>0 && db->init.busy==0 ){
  86914. sqlite3UserAuthInit(db);
  86915. if( db->auth.authLevel<UAUTH_User ){
  86916. pParse->rc = SQLITE_AUTH_USER;
  86917. sqlite3ErrorMsg(pParse, "user not authenticated");
  86918. return;
  86919. }
  86920. }
  86921. #endif
  86922. /* The cookie mask contains one bit for each database file open.
  86923. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  86924. ** set for each database that is used. Generate code to start a
  86925. ** transaction on each used database and to verify the schema cookie
  86926. ** on each used database.
  86927. */
  86928. if( db->mallocFailed==0
  86929. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  86930. ){
  86931. int iDb, i;
  86932. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  86933. sqlite3VdbeJumpHere(v, 0);
  86934. for(iDb=0; iDb<db->nDb; iDb++){
  86935. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  86936. sqlite3VdbeUsesBtree(v, iDb);
  86937. sqlite3VdbeAddOp4Int(v,
  86938. OP_Transaction, /* Opcode */
  86939. iDb, /* P1 */
  86940. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  86941. pParse->cookieValue[iDb], /* P3 */
  86942. db->aDb[iDb].pSchema->iGeneration /* P4 */
  86943. );
  86944. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  86945. VdbeComment((v,
  86946. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  86947. }
  86948. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86949. for(i=0; i<pParse->nVtabLock; i++){
  86950. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  86951. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  86952. }
  86953. pParse->nVtabLock = 0;
  86954. #endif
  86955. /* Once all the cookies have been verified and transactions opened,
  86956. ** obtain the required table-locks. This is a no-op unless the
  86957. ** shared-cache feature is enabled.
  86958. */
  86959. codeTableLocks(pParse);
  86960. /* Initialize any AUTOINCREMENT data structures required.
  86961. */
  86962. sqlite3AutoincrementBegin(pParse);
  86963. /* Code constant expressions that where factored out of inner loops */
  86964. if( pParse->pConstExpr ){
  86965. ExprList *pEL = pParse->pConstExpr;
  86966. pParse->okConstFactor = 0;
  86967. for(i=0; i<pEL->nExpr; i++){
  86968. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  86969. }
  86970. }
  86971. /* Finally, jump back to the beginning of the executable code. */
  86972. sqlite3VdbeGoto(v, 1);
  86973. }
  86974. }
  86975. /* Get the VDBE program ready for execution
  86976. */
  86977. if( v && pParse->nErr==0 && !db->mallocFailed ){
  86978. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  86979. /* A minimum of one cursor is required if autoincrement is used
  86980. * See ticket [a696379c1f08866] */
  86981. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  86982. sqlite3VdbeMakeReady(v, pParse);
  86983. pParse->rc = SQLITE_DONE;
  86984. pParse->colNamesSet = 0;
  86985. }else{
  86986. pParse->rc = SQLITE_ERROR;
  86987. }
  86988. pParse->nTab = 0;
  86989. pParse->nMem = 0;
  86990. pParse->nSet = 0;
  86991. pParse->nVar = 0;
  86992. DbMaskZero(pParse->cookieMask);
  86993. }
  86994. /*
  86995. ** Run the parser and code generator recursively in order to generate
  86996. ** code for the SQL statement given onto the end of the pParse context
  86997. ** currently under construction. When the parser is run recursively
  86998. ** this way, the final OP_Halt is not appended and other initialization
  86999. ** and finalization steps are omitted because those are handling by the
  87000. ** outermost parser.
  87001. **
  87002. ** Not everything is nestable. This facility is designed to permit
  87003. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  87004. ** care if you decide to try to use this routine for some other purposes.
  87005. */
  87006. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  87007. va_list ap;
  87008. char *zSql;
  87009. char *zErrMsg = 0;
  87010. sqlite3 *db = pParse->db;
  87011. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  87012. char saveBuf[SAVE_SZ];
  87013. if( pParse->nErr ) return;
  87014. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  87015. va_start(ap, zFormat);
  87016. zSql = sqlite3VMPrintf(db, zFormat, ap);
  87017. va_end(ap);
  87018. if( zSql==0 ){
  87019. return; /* A malloc must have failed */
  87020. }
  87021. pParse->nested++;
  87022. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  87023. memset(&pParse->nVar, 0, SAVE_SZ);
  87024. sqlite3RunParser(pParse, zSql, &zErrMsg);
  87025. sqlite3DbFree(db, zErrMsg);
  87026. sqlite3DbFree(db, zSql);
  87027. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  87028. pParse->nested--;
  87029. }
  87030. #if SQLITE_USER_AUTHENTICATION
  87031. /*
  87032. ** Return TRUE if zTable is the name of the system table that stores the
  87033. ** list of users and their access credentials.
  87034. */
  87035. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  87036. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  87037. }
  87038. #endif
  87039. /*
  87040. ** Locate the in-memory structure that describes a particular database
  87041. ** table given the name of that table and (optionally) the name of the
  87042. ** database containing the table. Return NULL if not found.
  87043. **
  87044. ** If zDatabase is 0, all databases are searched for the table and the
  87045. ** first matching table is returned. (No checking for duplicate table
  87046. ** names is done.) The search order is TEMP first, then MAIN, then any
  87047. ** auxiliary databases added using the ATTACH command.
  87048. **
  87049. ** See also sqlite3LocateTable().
  87050. */
  87051. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  87052. Table *p = 0;
  87053. int i;
  87054. /* All mutexes are required for schema access. Make sure we hold them. */
  87055. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  87056. #if SQLITE_USER_AUTHENTICATION
  87057. /* Only the admin user is allowed to know that the sqlite_user table
  87058. ** exists */
  87059. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  87060. return 0;
  87061. }
  87062. #endif
  87063. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  87064. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  87065. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  87066. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  87067. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  87068. if( p ) break;
  87069. }
  87070. return p;
  87071. }
  87072. /*
  87073. ** Locate the in-memory structure that describes a particular database
  87074. ** table given the name of that table and (optionally) the name of the
  87075. ** database containing the table. Return NULL if not found. Also leave an
  87076. ** error message in pParse->zErrMsg.
  87077. **
  87078. ** The difference between this routine and sqlite3FindTable() is that this
  87079. ** routine leaves an error message in pParse->zErrMsg where
  87080. ** sqlite3FindTable() does not.
  87081. */
  87082. SQLITE_PRIVATE Table *sqlite3LocateTable(
  87083. Parse *pParse, /* context in which to report errors */
  87084. int isView, /* True if looking for a VIEW rather than a TABLE */
  87085. const char *zName, /* Name of the table we are looking for */
  87086. const char *zDbase /* Name of the database. Might be NULL */
  87087. ){
  87088. Table *p;
  87089. /* Read the database schema. If an error occurs, leave an error message
  87090. ** and code in pParse and return NULL. */
  87091. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87092. return 0;
  87093. }
  87094. p = sqlite3FindTable(pParse->db, zName, zDbase);
  87095. if( p==0 ){
  87096. const char *zMsg = isView ? "no such view" : "no such table";
  87097. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87098. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  87099. /* If zName is the not the name of a table in the schema created using
  87100. ** CREATE, then check to see if it is the name of an virtual table that
  87101. ** can be an eponymous virtual table. */
  87102. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  87103. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  87104. return pMod->pEpoTab;
  87105. }
  87106. }
  87107. #endif
  87108. if( zDbase ){
  87109. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  87110. }else{
  87111. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  87112. }
  87113. pParse->checkSchema = 1;
  87114. }
  87115. #if SQLITE_USER_AUTHENTICATION
  87116. else if( pParse->db->auth.authLevel<UAUTH_User ){
  87117. sqlite3ErrorMsg(pParse, "user not authenticated");
  87118. p = 0;
  87119. }
  87120. #endif
  87121. return p;
  87122. }
  87123. /*
  87124. ** Locate the table identified by *p.
  87125. **
  87126. ** This is a wrapper around sqlite3LocateTable(). The difference between
  87127. ** sqlite3LocateTable() and this function is that this function restricts
  87128. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  87129. ** non-NULL if it is part of a view or trigger program definition. See
  87130. ** sqlite3FixSrcList() for details.
  87131. */
  87132. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  87133. Parse *pParse,
  87134. int isView,
  87135. struct SrcList_item *p
  87136. ){
  87137. const char *zDb;
  87138. assert( p->pSchema==0 || p->zDatabase==0 );
  87139. if( p->pSchema ){
  87140. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  87141. zDb = pParse->db->aDb[iDb].zName;
  87142. }else{
  87143. zDb = p->zDatabase;
  87144. }
  87145. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  87146. }
  87147. /*
  87148. ** Locate the in-memory structure that describes
  87149. ** a particular index given the name of that index
  87150. ** and the name of the database that contains the index.
  87151. ** Return NULL if not found.
  87152. **
  87153. ** If zDatabase is 0, all databases are searched for the
  87154. ** table and the first matching index is returned. (No checking
  87155. ** for duplicate index names is done.) The search order is
  87156. ** TEMP first, then MAIN, then any auxiliary databases added
  87157. ** using the ATTACH command.
  87158. */
  87159. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  87160. Index *p = 0;
  87161. int i;
  87162. /* All mutexes are required for schema access. Make sure we hold them. */
  87163. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  87164. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  87165. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  87166. Schema *pSchema = db->aDb[j].pSchema;
  87167. assert( pSchema );
  87168. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  87169. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  87170. p = sqlite3HashFind(&pSchema->idxHash, zName);
  87171. if( p ) break;
  87172. }
  87173. return p;
  87174. }
  87175. /*
  87176. ** Reclaim the memory used by an index
  87177. */
  87178. static void freeIndex(sqlite3 *db, Index *p){
  87179. #ifndef SQLITE_OMIT_ANALYZE
  87180. sqlite3DeleteIndexSamples(db, p);
  87181. #endif
  87182. sqlite3ExprDelete(db, p->pPartIdxWhere);
  87183. sqlite3ExprListDelete(db, p->aColExpr);
  87184. sqlite3DbFree(db, p->zColAff);
  87185. if( p->isResized ) sqlite3DbFree(db, p->azColl);
  87186. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87187. sqlite3_free(p->aiRowEst);
  87188. #endif
  87189. sqlite3DbFree(db, p);
  87190. }
  87191. /*
  87192. ** For the index called zIdxName which is found in the database iDb,
  87193. ** unlike that index from its Table then remove the index from
  87194. ** the index hash table and free all memory structures associated
  87195. ** with the index.
  87196. */
  87197. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  87198. Index *pIndex;
  87199. Hash *pHash;
  87200. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87201. pHash = &db->aDb[iDb].pSchema->idxHash;
  87202. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  87203. if( ALWAYS(pIndex) ){
  87204. if( pIndex->pTable->pIndex==pIndex ){
  87205. pIndex->pTable->pIndex = pIndex->pNext;
  87206. }else{
  87207. Index *p;
  87208. /* Justification of ALWAYS(); The index must be on the list of
  87209. ** indices. */
  87210. p = pIndex->pTable->pIndex;
  87211. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  87212. if( ALWAYS(p && p->pNext==pIndex) ){
  87213. p->pNext = pIndex->pNext;
  87214. }
  87215. }
  87216. freeIndex(db, pIndex);
  87217. }
  87218. db->flags |= SQLITE_InternChanges;
  87219. }
  87220. /*
  87221. ** Look through the list of open database files in db->aDb[] and if
  87222. ** any have been closed, remove them from the list. Reallocate the
  87223. ** db->aDb[] structure to a smaller size, if possible.
  87224. **
  87225. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  87226. ** are never candidates for being collapsed.
  87227. */
  87228. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  87229. int i, j;
  87230. for(i=j=2; i<db->nDb; i++){
  87231. struct Db *pDb = &db->aDb[i];
  87232. if( pDb->pBt==0 ){
  87233. sqlite3DbFree(db, pDb->zName);
  87234. pDb->zName = 0;
  87235. continue;
  87236. }
  87237. if( j<i ){
  87238. db->aDb[j] = db->aDb[i];
  87239. }
  87240. j++;
  87241. }
  87242. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  87243. db->nDb = j;
  87244. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  87245. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  87246. sqlite3DbFree(db, db->aDb);
  87247. db->aDb = db->aDbStatic;
  87248. }
  87249. }
  87250. /*
  87251. ** Reset the schema for the database at index iDb. Also reset the
  87252. ** TEMP schema.
  87253. */
  87254. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  87255. Db *pDb;
  87256. assert( iDb<db->nDb );
  87257. /* Case 1: Reset the single schema identified by iDb */
  87258. pDb = &db->aDb[iDb];
  87259. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87260. assert( pDb->pSchema!=0 );
  87261. sqlite3SchemaClear(pDb->pSchema);
  87262. /* If any database other than TEMP is reset, then also reset TEMP
  87263. ** since TEMP might be holding triggers that reference tables in the
  87264. ** other database.
  87265. */
  87266. if( iDb!=1 ){
  87267. pDb = &db->aDb[1];
  87268. assert( pDb->pSchema!=0 );
  87269. sqlite3SchemaClear(pDb->pSchema);
  87270. }
  87271. return;
  87272. }
  87273. /*
  87274. ** Erase all schema information from all attached databases (including
  87275. ** "main" and "temp") for a single database connection.
  87276. */
  87277. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  87278. int i;
  87279. sqlite3BtreeEnterAll(db);
  87280. for(i=0; i<db->nDb; i++){
  87281. Db *pDb = &db->aDb[i];
  87282. if( pDb->pSchema ){
  87283. sqlite3SchemaClear(pDb->pSchema);
  87284. }
  87285. }
  87286. db->flags &= ~SQLITE_InternChanges;
  87287. sqlite3VtabUnlockList(db);
  87288. sqlite3BtreeLeaveAll(db);
  87289. sqlite3CollapseDatabaseArray(db);
  87290. }
  87291. /*
  87292. ** This routine is called when a commit occurs.
  87293. */
  87294. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  87295. db->flags &= ~SQLITE_InternChanges;
  87296. }
  87297. /*
  87298. ** Delete memory allocated for the column names of a table or view (the
  87299. ** Table.aCol[] array).
  87300. */
  87301. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  87302. int i;
  87303. Column *pCol;
  87304. assert( pTable!=0 );
  87305. if( (pCol = pTable->aCol)!=0 ){
  87306. for(i=0; i<pTable->nCol; i++, pCol++){
  87307. sqlite3DbFree(db, pCol->zName);
  87308. sqlite3ExprDelete(db, pCol->pDflt);
  87309. sqlite3DbFree(db, pCol->zDflt);
  87310. sqlite3DbFree(db, pCol->zType);
  87311. sqlite3DbFree(db, pCol->zColl);
  87312. }
  87313. sqlite3DbFree(db, pTable->aCol);
  87314. }
  87315. }
  87316. /*
  87317. ** Remove the memory data structures associated with the given
  87318. ** Table. No changes are made to disk by this routine.
  87319. **
  87320. ** This routine just deletes the data structure. It does not unlink
  87321. ** the table data structure from the hash table. But it does destroy
  87322. ** memory structures of the indices and foreign keys associated with
  87323. ** the table.
  87324. **
  87325. ** The db parameter is optional. It is needed if the Table object
  87326. ** contains lookaside memory. (Table objects in the schema do not use
  87327. ** lookaside memory, but some ephemeral Table objects do.) Or the
  87328. ** db parameter can be used with db->pnBytesFreed to measure the memory
  87329. ** used by the Table object.
  87330. */
  87331. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  87332. Index *pIndex, *pNext;
  87333. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  87334. assert( !pTable || pTable->nRef>0 );
  87335. /* Do not delete the table until the reference count reaches zero. */
  87336. if( !pTable ) return;
  87337. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  87338. /* Record the number of outstanding lookaside allocations in schema Tables
  87339. ** prior to doing any free() operations. Since schema Tables do not use
  87340. ** lookaside, this number should not change. */
  87341. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  87342. db->lookaside.nOut : 0 );
  87343. /* Delete all indices associated with this table. */
  87344. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  87345. pNext = pIndex->pNext;
  87346. assert( pIndex->pSchema==pTable->pSchema );
  87347. if( !db || db->pnBytesFreed==0 ){
  87348. char *zName = pIndex->zName;
  87349. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  87350. &pIndex->pSchema->idxHash, zName, 0
  87351. );
  87352. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  87353. assert( pOld==pIndex || pOld==0 );
  87354. }
  87355. freeIndex(db, pIndex);
  87356. }
  87357. /* Delete any foreign keys attached to this table. */
  87358. sqlite3FkDelete(db, pTable);
  87359. /* Delete the Table structure itself.
  87360. */
  87361. sqlite3DeleteColumnNames(db, pTable);
  87362. sqlite3DbFree(db, pTable->zName);
  87363. sqlite3DbFree(db, pTable->zColAff);
  87364. sqlite3SelectDelete(db, pTable->pSelect);
  87365. sqlite3ExprListDelete(db, pTable->pCheck);
  87366. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87367. sqlite3VtabClear(db, pTable);
  87368. #endif
  87369. sqlite3DbFree(db, pTable);
  87370. /* Verify that no lookaside memory was used by schema tables */
  87371. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  87372. }
  87373. /*
  87374. ** Unlink the given table from the hash tables and the delete the
  87375. ** table structure with all its indices and foreign keys.
  87376. */
  87377. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  87378. Table *p;
  87379. Db *pDb;
  87380. assert( db!=0 );
  87381. assert( iDb>=0 && iDb<db->nDb );
  87382. assert( zTabName );
  87383. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87384. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  87385. pDb = &db->aDb[iDb];
  87386. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  87387. sqlite3DeleteTable(db, p);
  87388. db->flags |= SQLITE_InternChanges;
  87389. }
  87390. /*
  87391. ** Given a token, return a string that consists of the text of that
  87392. ** token. Space to hold the returned string
  87393. ** is obtained from sqliteMalloc() and must be freed by the calling
  87394. ** function.
  87395. **
  87396. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  87397. ** surround the body of the token are removed.
  87398. **
  87399. ** Tokens are often just pointers into the original SQL text and so
  87400. ** are not \000 terminated and are not persistent. The returned string
  87401. ** is \000 terminated and is persistent.
  87402. */
  87403. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  87404. char *zName;
  87405. if( pName ){
  87406. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  87407. sqlite3Dequote(zName);
  87408. }else{
  87409. zName = 0;
  87410. }
  87411. return zName;
  87412. }
  87413. /*
  87414. ** Open the sqlite_master table stored in database number iDb for
  87415. ** writing. The table is opened using cursor 0.
  87416. */
  87417. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  87418. Vdbe *v = sqlite3GetVdbe(p);
  87419. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  87420. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  87421. if( p->nTab==0 ){
  87422. p->nTab = 1;
  87423. }
  87424. }
  87425. /*
  87426. ** Parameter zName points to a nul-terminated buffer containing the name
  87427. ** of a database ("main", "temp" or the name of an attached db). This
  87428. ** function returns the index of the named database in db->aDb[], or
  87429. ** -1 if the named db cannot be found.
  87430. */
  87431. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  87432. int i = -1; /* Database number */
  87433. if( zName ){
  87434. Db *pDb;
  87435. int n = sqlite3Strlen30(zName);
  87436. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  87437. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  87438. 0==sqlite3StrICmp(pDb->zName, zName) ){
  87439. break;
  87440. }
  87441. }
  87442. }
  87443. return i;
  87444. }
  87445. /*
  87446. ** The token *pName contains the name of a database (either "main" or
  87447. ** "temp" or the name of an attached db). This routine returns the
  87448. ** index of the named database in db->aDb[], or -1 if the named db
  87449. ** does not exist.
  87450. */
  87451. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  87452. int i; /* Database number */
  87453. char *zName; /* Name we are searching for */
  87454. zName = sqlite3NameFromToken(db, pName);
  87455. i = sqlite3FindDbName(db, zName);
  87456. sqlite3DbFree(db, zName);
  87457. return i;
  87458. }
  87459. /* The table or view or trigger name is passed to this routine via tokens
  87460. ** pName1 and pName2. If the table name was fully qualified, for example:
  87461. **
  87462. ** CREATE TABLE xxx.yyy (...);
  87463. **
  87464. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  87465. ** the table name is not fully qualified, i.e.:
  87466. **
  87467. ** CREATE TABLE yyy(...);
  87468. **
  87469. ** Then pName1 is set to "yyy" and pName2 is "".
  87470. **
  87471. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  87472. ** pName2) that stores the unqualified table name. The index of the
  87473. ** database "xxx" is returned.
  87474. */
  87475. SQLITE_PRIVATE int sqlite3TwoPartName(
  87476. Parse *pParse, /* Parsing and code generating context */
  87477. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  87478. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  87479. Token **pUnqual /* Write the unqualified object name here */
  87480. ){
  87481. int iDb; /* Database holding the object */
  87482. sqlite3 *db = pParse->db;
  87483. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  87484. if( db->init.busy ) {
  87485. sqlite3ErrorMsg(pParse, "corrupt database");
  87486. return -1;
  87487. }
  87488. *pUnqual = pName2;
  87489. iDb = sqlite3FindDb(db, pName1);
  87490. if( iDb<0 ){
  87491. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  87492. return -1;
  87493. }
  87494. }else{
  87495. assert( db->init.iDb==0 || db->init.busy );
  87496. iDb = db->init.iDb;
  87497. *pUnqual = pName1;
  87498. }
  87499. return iDb;
  87500. }
  87501. /*
  87502. ** This routine is used to check if the UTF-8 string zName is a legal
  87503. ** unqualified name for a new schema object (table, index, view or
  87504. ** trigger). All names are legal except those that begin with the string
  87505. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  87506. ** is reserved for internal use.
  87507. */
  87508. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  87509. if( !pParse->db->init.busy && pParse->nested==0
  87510. && (pParse->db->flags & SQLITE_WriteSchema)==0
  87511. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  87512. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  87513. return SQLITE_ERROR;
  87514. }
  87515. return SQLITE_OK;
  87516. }
  87517. /*
  87518. ** Return the PRIMARY KEY index of a table
  87519. */
  87520. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  87521. Index *p;
  87522. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  87523. return p;
  87524. }
  87525. /*
  87526. ** Return the column of index pIdx that corresponds to table
  87527. ** column iCol. Return -1 if not found.
  87528. */
  87529. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  87530. int i;
  87531. for(i=0; i<pIdx->nColumn; i++){
  87532. if( iCol==pIdx->aiColumn[i] ) return i;
  87533. }
  87534. return -1;
  87535. }
  87536. /*
  87537. ** Begin constructing a new table representation in memory. This is
  87538. ** the first of several action routines that get called in response
  87539. ** to a CREATE TABLE statement. In particular, this routine is called
  87540. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  87541. ** flag is true if the table should be stored in the auxiliary database
  87542. ** file instead of in the main database file. This is normally the case
  87543. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  87544. ** CREATE and TABLE.
  87545. **
  87546. ** The new table record is initialized and put in pParse->pNewTable.
  87547. ** As more of the CREATE TABLE statement is parsed, additional action
  87548. ** routines will be called to add more information to this record.
  87549. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  87550. ** is called to complete the construction of the new table record.
  87551. */
  87552. SQLITE_PRIVATE void sqlite3StartTable(
  87553. Parse *pParse, /* Parser context */
  87554. Token *pName1, /* First part of the name of the table or view */
  87555. Token *pName2, /* Second part of the name of the table or view */
  87556. int isTemp, /* True if this is a TEMP table */
  87557. int isView, /* True if this is a VIEW */
  87558. int isVirtual, /* True if this is a VIRTUAL table */
  87559. int noErr /* Do nothing if table already exists */
  87560. ){
  87561. Table *pTable;
  87562. char *zName = 0; /* The name of the new table */
  87563. sqlite3 *db = pParse->db;
  87564. Vdbe *v;
  87565. int iDb; /* Database number to create the table in */
  87566. Token *pName; /* Unqualified name of the table to create */
  87567. /* The table or view name to create is passed to this routine via tokens
  87568. ** pName1 and pName2. If the table name was fully qualified, for example:
  87569. **
  87570. ** CREATE TABLE xxx.yyy (...);
  87571. **
  87572. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  87573. ** the table name is not fully qualified, i.e.:
  87574. **
  87575. ** CREATE TABLE yyy(...);
  87576. **
  87577. ** Then pName1 is set to "yyy" and pName2 is "".
  87578. **
  87579. ** The call below sets the pName pointer to point at the token (pName1 or
  87580. ** pName2) that stores the unqualified table name. The variable iDb is
  87581. ** set to the index of the database that the table or view is to be
  87582. ** created in.
  87583. */
  87584. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  87585. if( iDb<0 ) return;
  87586. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  87587. /* If creating a temp table, the name may not be qualified. Unless
  87588. ** the database name is "temp" anyway. */
  87589. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  87590. return;
  87591. }
  87592. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  87593. pParse->sNameToken = *pName;
  87594. zName = sqlite3NameFromToken(db, pName);
  87595. if( zName==0 ) return;
  87596. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  87597. goto begin_table_error;
  87598. }
  87599. if( db->init.iDb==1 ) isTemp = 1;
  87600. #ifndef SQLITE_OMIT_AUTHORIZATION
  87601. assert( (isTemp & 1)==isTemp );
  87602. {
  87603. int code;
  87604. char *zDb = db->aDb[iDb].zName;
  87605. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  87606. goto begin_table_error;
  87607. }
  87608. if( isView ){
  87609. if( !OMIT_TEMPDB && isTemp ){
  87610. code = SQLITE_CREATE_TEMP_VIEW;
  87611. }else{
  87612. code = SQLITE_CREATE_VIEW;
  87613. }
  87614. }else{
  87615. if( !OMIT_TEMPDB && isTemp ){
  87616. code = SQLITE_CREATE_TEMP_TABLE;
  87617. }else{
  87618. code = SQLITE_CREATE_TABLE;
  87619. }
  87620. }
  87621. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  87622. goto begin_table_error;
  87623. }
  87624. }
  87625. #endif
  87626. /* Make sure the new table name does not collide with an existing
  87627. ** index or table name in the same database. Issue an error message if
  87628. ** it does. The exception is if the statement being parsed was passed
  87629. ** to an sqlite3_declare_vtab() call. In that case only the column names
  87630. ** and types will be used, so there is no need to test for namespace
  87631. ** collisions.
  87632. */
  87633. if( !IN_DECLARE_VTAB ){
  87634. char *zDb = db->aDb[iDb].zName;
  87635. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87636. goto begin_table_error;
  87637. }
  87638. pTable = sqlite3FindTable(db, zName, zDb);
  87639. if( pTable ){
  87640. if( !noErr ){
  87641. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  87642. }else{
  87643. assert( !db->init.busy || CORRUPT_DB );
  87644. sqlite3CodeVerifySchema(pParse, iDb);
  87645. }
  87646. goto begin_table_error;
  87647. }
  87648. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  87649. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  87650. goto begin_table_error;
  87651. }
  87652. }
  87653. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  87654. if( pTable==0 ){
  87655. db->mallocFailed = 1;
  87656. pParse->rc = SQLITE_NOMEM;
  87657. pParse->nErr++;
  87658. goto begin_table_error;
  87659. }
  87660. pTable->zName = zName;
  87661. pTable->iPKey = -1;
  87662. pTable->pSchema = db->aDb[iDb].pSchema;
  87663. pTable->nRef = 1;
  87664. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  87665. assert( pParse->pNewTable==0 );
  87666. pParse->pNewTable = pTable;
  87667. /* If this is the magic sqlite_sequence table used by autoincrement,
  87668. ** then record a pointer to this table in the main database structure
  87669. ** so that INSERT can find the table easily.
  87670. */
  87671. #ifndef SQLITE_OMIT_AUTOINCREMENT
  87672. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  87673. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87674. pTable->pSchema->pSeqTab = pTable;
  87675. }
  87676. #endif
  87677. /* Begin generating the code that will insert the table record into
  87678. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  87679. ** and allocate the record number for the table entry now. Before any
  87680. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  87681. ** indices to be created and the table record must come before the
  87682. ** indices. Hence, the record number for the table must be allocated
  87683. ** now.
  87684. */
  87685. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  87686. int addr1;
  87687. int fileFormat;
  87688. int reg1, reg2, reg3;
  87689. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  87690. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  87691. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87692. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87693. if( isVirtual ){
  87694. sqlite3VdbeAddOp0(v, OP_VBegin);
  87695. }
  87696. #endif
  87697. /* If the file format and encoding in the database have not been set,
  87698. ** set them now.
  87699. */
  87700. reg1 = pParse->regRowid = ++pParse->nMem;
  87701. reg2 = pParse->regRoot = ++pParse->nMem;
  87702. reg3 = ++pParse->nMem;
  87703. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  87704. sqlite3VdbeUsesBtree(v, iDb);
  87705. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  87706. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  87707. 1 : SQLITE_MAX_FILE_FORMAT;
  87708. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  87709. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  87710. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  87711. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  87712. sqlite3VdbeJumpHere(v, addr1);
  87713. /* This just creates a place-holder record in the sqlite_master table.
  87714. ** The record created does not contain anything yet. It will be replaced
  87715. ** by the real entry in code generated at sqlite3EndTable().
  87716. **
  87717. ** The rowid for the new entry is left in register pParse->regRowid.
  87718. ** The root page number of the new table is left in reg pParse->regRoot.
  87719. ** The rowid and root page number values are needed by the code that
  87720. ** sqlite3EndTable will generate.
  87721. */
  87722. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  87723. if( isView || isVirtual ){
  87724. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  87725. }else
  87726. #endif
  87727. {
  87728. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  87729. }
  87730. sqlite3OpenMasterTable(pParse, iDb);
  87731. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  87732. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  87733. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  87734. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  87735. sqlite3VdbeAddOp0(v, OP_Close);
  87736. }
  87737. /* Normal (non-error) return. */
  87738. return;
  87739. /* If an error occurs, we jump here */
  87740. begin_table_error:
  87741. sqlite3DbFree(db, zName);
  87742. return;
  87743. }
  87744. /*
  87745. ** This macro is used to compare two strings in a case-insensitive manner.
  87746. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  87747. ** produces larger code.
  87748. **
  87749. ** WARNING: This macro is not compatible with the strcmp() family. It
  87750. ** returns true if the two strings are equal, otherwise false.
  87751. */
  87752. #define STRICMP(x, y) (\
  87753. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  87754. sqlite3UpperToLower[*(unsigned char *)(y)] \
  87755. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  87756. /*
  87757. ** Add a new column to the table currently being constructed.
  87758. **
  87759. ** The parser calls this routine once for each column declaration
  87760. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  87761. ** first to get things going. Then this routine is called for each
  87762. ** column.
  87763. */
  87764. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  87765. Table *p;
  87766. int i;
  87767. char *z;
  87768. Column *pCol;
  87769. sqlite3 *db = pParse->db;
  87770. if( (p = pParse->pNewTable)==0 ) return;
  87771. #if SQLITE_MAX_COLUMN
  87772. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  87773. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  87774. return;
  87775. }
  87776. #endif
  87777. z = sqlite3NameFromToken(db, pName);
  87778. if( z==0 ) return;
  87779. for(i=0; i<p->nCol; i++){
  87780. if( STRICMP(z, p->aCol[i].zName) ){
  87781. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  87782. sqlite3DbFree(db, z);
  87783. return;
  87784. }
  87785. }
  87786. if( (p->nCol & 0x7)==0 ){
  87787. Column *aNew;
  87788. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  87789. if( aNew==0 ){
  87790. sqlite3DbFree(db, z);
  87791. return;
  87792. }
  87793. p->aCol = aNew;
  87794. }
  87795. pCol = &p->aCol[p->nCol];
  87796. memset(pCol, 0, sizeof(p->aCol[0]));
  87797. pCol->zName = z;
  87798. /* If there is no type specified, columns have the default affinity
  87799. ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
  87800. ** be called next to set pCol->affinity correctly.
  87801. */
  87802. pCol->affinity = SQLITE_AFF_BLOB;
  87803. pCol->szEst = 1;
  87804. p->nCol++;
  87805. }
  87806. /*
  87807. ** This routine is called by the parser while in the middle of
  87808. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  87809. ** been seen on a column. This routine sets the notNull flag on
  87810. ** the column currently under construction.
  87811. */
  87812. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  87813. Table *p;
  87814. p = pParse->pNewTable;
  87815. if( p==0 || NEVER(p->nCol<1) ) return;
  87816. p->aCol[p->nCol-1].notNull = (u8)onError;
  87817. }
  87818. /*
  87819. ** Scan the column type name zType (length nType) and return the
  87820. ** associated affinity type.
  87821. **
  87822. ** This routine does a case-independent search of zType for the
  87823. ** substrings in the following table. If one of the substrings is
  87824. ** found, the corresponding affinity is returned. If zType contains
  87825. ** more than one of the substrings, entries toward the top of
  87826. ** the table take priority. For example, if zType is 'BLOBINT',
  87827. ** SQLITE_AFF_INTEGER is returned.
  87828. **
  87829. ** Substring | Affinity
  87830. ** --------------------------------
  87831. ** 'INT' | SQLITE_AFF_INTEGER
  87832. ** 'CHAR' | SQLITE_AFF_TEXT
  87833. ** 'CLOB' | SQLITE_AFF_TEXT
  87834. ** 'TEXT' | SQLITE_AFF_TEXT
  87835. ** 'BLOB' | SQLITE_AFF_BLOB
  87836. ** 'REAL' | SQLITE_AFF_REAL
  87837. ** 'FLOA' | SQLITE_AFF_REAL
  87838. ** 'DOUB' | SQLITE_AFF_REAL
  87839. **
  87840. ** If none of the substrings in the above table are found,
  87841. ** SQLITE_AFF_NUMERIC is returned.
  87842. */
  87843. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  87844. u32 h = 0;
  87845. char aff = SQLITE_AFF_NUMERIC;
  87846. const char *zChar = 0;
  87847. if( zIn==0 ) return aff;
  87848. while( zIn[0] ){
  87849. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  87850. zIn++;
  87851. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  87852. aff = SQLITE_AFF_TEXT;
  87853. zChar = zIn;
  87854. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  87855. aff = SQLITE_AFF_TEXT;
  87856. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  87857. aff = SQLITE_AFF_TEXT;
  87858. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  87859. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  87860. aff = SQLITE_AFF_BLOB;
  87861. if( zIn[0]=='(' ) zChar = zIn;
  87862. #ifndef SQLITE_OMIT_FLOATING_POINT
  87863. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  87864. && aff==SQLITE_AFF_NUMERIC ){
  87865. aff = SQLITE_AFF_REAL;
  87866. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  87867. && aff==SQLITE_AFF_NUMERIC ){
  87868. aff = SQLITE_AFF_REAL;
  87869. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  87870. && aff==SQLITE_AFF_NUMERIC ){
  87871. aff = SQLITE_AFF_REAL;
  87872. #endif
  87873. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  87874. aff = SQLITE_AFF_INTEGER;
  87875. break;
  87876. }
  87877. }
  87878. /* If pszEst is not NULL, store an estimate of the field size. The
  87879. ** estimate is scaled so that the size of an integer is 1. */
  87880. if( pszEst ){
  87881. *pszEst = 1; /* default size is approx 4 bytes */
  87882. if( aff<SQLITE_AFF_NUMERIC ){
  87883. if( zChar ){
  87884. while( zChar[0] ){
  87885. if( sqlite3Isdigit(zChar[0]) ){
  87886. int v = 0;
  87887. sqlite3GetInt32(zChar, &v);
  87888. v = v/4 + 1;
  87889. if( v>255 ) v = 255;
  87890. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  87891. break;
  87892. }
  87893. zChar++;
  87894. }
  87895. }else{
  87896. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  87897. }
  87898. }
  87899. }
  87900. return aff;
  87901. }
  87902. /*
  87903. ** This routine is called by the parser while in the middle of
  87904. ** parsing a CREATE TABLE statement. The pFirst token is the first
  87905. ** token in the sequence of tokens that describe the type of the
  87906. ** column currently under construction. pLast is the last token
  87907. ** in the sequence. Use this information to construct a string
  87908. ** that contains the typename of the column and store that string
  87909. ** in zType.
  87910. */
  87911. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  87912. Table *p;
  87913. Column *pCol;
  87914. p = pParse->pNewTable;
  87915. if( p==0 || NEVER(p->nCol<1) ) return;
  87916. pCol = &p->aCol[p->nCol-1];
  87917. assert( pCol->zType==0 || CORRUPT_DB );
  87918. sqlite3DbFree(pParse->db, pCol->zType);
  87919. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  87920. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  87921. }
  87922. /*
  87923. ** The expression is the default value for the most recently added column
  87924. ** of the table currently under construction.
  87925. **
  87926. ** Default value expressions must be constant. Raise an exception if this
  87927. ** is not the case.
  87928. **
  87929. ** This routine is called by the parser while in the middle of
  87930. ** parsing a CREATE TABLE statement.
  87931. */
  87932. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  87933. Table *p;
  87934. Column *pCol;
  87935. sqlite3 *db = pParse->db;
  87936. p = pParse->pNewTable;
  87937. if( p!=0 ){
  87938. pCol = &(p->aCol[p->nCol-1]);
  87939. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  87940. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  87941. pCol->zName);
  87942. }else{
  87943. /* A copy of pExpr is used instead of the original, as pExpr contains
  87944. ** tokens that point to volatile memory. The 'span' of the expression
  87945. ** is required by pragma table_info.
  87946. */
  87947. sqlite3ExprDelete(db, pCol->pDflt);
  87948. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  87949. sqlite3DbFree(db, pCol->zDflt);
  87950. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  87951. (int)(pSpan->zEnd - pSpan->zStart));
  87952. }
  87953. }
  87954. sqlite3ExprDelete(db, pSpan->pExpr);
  87955. }
  87956. /*
  87957. ** Designate the PRIMARY KEY for the table. pList is a list of names
  87958. ** of columns that form the primary key. If pList is NULL, then the
  87959. ** most recently added column of the table is the primary key.
  87960. **
  87961. ** A table can have at most one primary key. If the table already has
  87962. ** a primary key (and this is the second primary key) then create an
  87963. ** error.
  87964. **
  87965. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  87966. ** then we will try to use that column as the rowid. Set the Table.iPKey
  87967. ** field of the table under construction to be the index of the
  87968. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  87969. ** no INTEGER PRIMARY KEY.
  87970. **
  87971. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  87972. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  87973. */
  87974. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  87975. Parse *pParse, /* Parsing context */
  87976. ExprList *pList, /* List of field names to be indexed */
  87977. int onError, /* What to do with a uniqueness conflict */
  87978. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  87979. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  87980. ){
  87981. Table *pTab = pParse->pNewTable;
  87982. char *zType = 0;
  87983. int iCol = -1, i;
  87984. int nTerm;
  87985. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  87986. if( pTab->tabFlags & TF_HasPrimaryKey ){
  87987. sqlite3ErrorMsg(pParse,
  87988. "table \"%s\" has more than one primary key", pTab->zName);
  87989. goto primary_key_exit;
  87990. }
  87991. pTab->tabFlags |= TF_HasPrimaryKey;
  87992. if( pList==0 ){
  87993. iCol = pTab->nCol - 1;
  87994. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  87995. zType = pTab->aCol[iCol].zType;
  87996. nTerm = 1;
  87997. }else{
  87998. nTerm = pList->nExpr;
  87999. for(i=0; i<nTerm; i++){
  88000. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  88001. assert( pCExpr!=0 );
  88002. if( pCExpr->op==TK_ID ){
  88003. const char *zCName = pCExpr->u.zToken;
  88004. for(iCol=0; iCol<pTab->nCol; iCol++){
  88005. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  88006. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  88007. zType = pTab->aCol[iCol].zType;
  88008. break;
  88009. }
  88010. }
  88011. }
  88012. }
  88013. }
  88014. if( nTerm==1
  88015. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  88016. && sortOrder!=SQLITE_SO_DESC
  88017. ){
  88018. pTab->iPKey = iCol;
  88019. pTab->keyConf = (u8)onError;
  88020. assert( autoInc==0 || autoInc==1 );
  88021. pTab->tabFlags |= autoInc*TF_Autoincrement;
  88022. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  88023. }else if( autoInc ){
  88024. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88025. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  88026. "INTEGER PRIMARY KEY");
  88027. #endif
  88028. }else{
  88029. Index *p;
  88030. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  88031. 0, sortOrder, 0);
  88032. if( p ){
  88033. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  88034. }
  88035. pList = 0;
  88036. }
  88037. primary_key_exit:
  88038. sqlite3ExprListDelete(pParse->db, pList);
  88039. return;
  88040. }
  88041. /*
  88042. ** Add a new CHECK constraint to the table currently under construction.
  88043. */
  88044. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  88045. Parse *pParse, /* Parsing context */
  88046. Expr *pCheckExpr /* The check expression */
  88047. ){
  88048. #ifndef SQLITE_OMIT_CHECK
  88049. Table *pTab = pParse->pNewTable;
  88050. sqlite3 *db = pParse->db;
  88051. if( pTab && !IN_DECLARE_VTAB
  88052. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  88053. ){
  88054. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  88055. if( pParse->constraintName.n ){
  88056. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  88057. }
  88058. }else
  88059. #endif
  88060. {
  88061. sqlite3ExprDelete(pParse->db, pCheckExpr);
  88062. }
  88063. }
  88064. /*
  88065. ** Set the collation function of the most recently parsed table column
  88066. ** to the CollSeq given.
  88067. */
  88068. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  88069. Table *p;
  88070. int i;
  88071. char *zColl; /* Dequoted name of collation sequence */
  88072. sqlite3 *db;
  88073. if( (p = pParse->pNewTable)==0 ) return;
  88074. i = p->nCol-1;
  88075. db = pParse->db;
  88076. zColl = sqlite3NameFromToken(db, pToken);
  88077. if( !zColl ) return;
  88078. if( sqlite3LocateCollSeq(pParse, zColl) ){
  88079. Index *pIdx;
  88080. sqlite3DbFree(db, p->aCol[i].zColl);
  88081. p->aCol[i].zColl = zColl;
  88082. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  88083. ** then an index may have been created on this column before the
  88084. ** collation type was added. Correct this if it is the case.
  88085. */
  88086. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  88087. assert( pIdx->nKeyCol==1 );
  88088. if( pIdx->aiColumn[0]==i ){
  88089. pIdx->azColl[0] = p->aCol[i].zColl;
  88090. }
  88091. }
  88092. }else{
  88093. sqlite3DbFree(db, zColl);
  88094. }
  88095. }
  88096. /*
  88097. ** This function returns the collation sequence for database native text
  88098. ** encoding identified by the string zName, length nName.
  88099. **
  88100. ** If the requested collation sequence is not available, or not available
  88101. ** in the database native encoding, the collation factory is invoked to
  88102. ** request it. If the collation factory does not supply such a sequence,
  88103. ** and the sequence is available in another text encoding, then that is
  88104. ** returned instead.
  88105. **
  88106. ** If no versions of the requested collations sequence are available, or
  88107. ** another error occurs, NULL is returned and an error message written into
  88108. ** pParse.
  88109. **
  88110. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  88111. ** invokes the collation factory if the named collation cannot be found
  88112. ** and generates an error message.
  88113. **
  88114. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  88115. */
  88116. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  88117. sqlite3 *db = pParse->db;
  88118. u8 enc = ENC(db);
  88119. u8 initbusy = db->init.busy;
  88120. CollSeq *pColl;
  88121. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  88122. if( !initbusy && (!pColl || !pColl->xCmp) ){
  88123. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  88124. }
  88125. return pColl;
  88126. }
  88127. /*
  88128. ** Generate code that will increment the schema cookie.
  88129. **
  88130. ** The schema cookie is used to determine when the schema for the
  88131. ** database changes. After each schema change, the cookie value
  88132. ** changes. When a process first reads the schema it records the
  88133. ** cookie. Thereafter, whenever it goes to access the database,
  88134. ** it checks the cookie to make sure the schema has not changed
  88135. ** since it was last read.
  88136. **
  88137. ** This plan is not completely bullet-proof. It is possible for
  88138. ** the schema to change multiple times and for the cookie to be
  88139. ** set back to prior value. But schema changes are infrequent
  88140. ** and the probability of hitting the same cookie value is only
  88141. ** 1 chance in 2^32. So we're safe enough.
  88142. */
  88143. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  88144. int r1 = sqlite3GetTempReg(pParse);
  88145. sqlite3 *db = pParse->db;
  88146. Vdbe *v = pParse->pVdbe;
  88147. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88148. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  88149. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  88150. sqlite3ReleaseTempReg(pParse, r1);
  88151. }
  88152. /*
  88153. ** Measure the number of characters needed to output the given
  88154. ** identifier. The number returned includes any quotes used
  88155. ** but does not include the null terminator.
  88156. **
  88157. ** The estimate is conservative. It might be larger that what is
  88158. ** really needed.
  88159. */
  88160. static int identLength(const char *z){
  88161. int n;
  88162. for(n=0; *z; n++, z++){
  88163. if( *z=='"' ){ n++; }
  88164. }
  88165. return n + 2;
  88166. }
  88167. /*
  88168. ** The first parameter is a pointer to an output buffer. The second
  88169. ** parameter is a pointer to an integer that contains the offset at
  88170. ** which to write into the output buffer. This function copies the
  88171. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  88172. ** to the specified offset in the buffer and updates *pIdx to refer
  88173. ** to the first byte after the last byte written before returning.
  88174. **
  88175. ** If the string zSignedIdent consists entirely of alpha-numeric
  88176. ** characters, does not begin with a digit and is not an SQL keyword,
  88177. ** then it is copied to the output buffer exactly as it is. Otherwise,
  88178. ** it is quoted using double-quotes.
  88179. */
  88180. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  88181. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  88182. int i, j, needQuote;
  88183. i = *pIdx;
  88184. for(j=0; zIdent[j]; j++){
  88185. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  88186. }
  88187. needQuote = sqlite3Isdigit(zIdent[0])
  88188. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  88189. || zIdent[j]!=0
  88190. || j==0;
  88191. if( needQuote ) z[i++] = '"';
  88192. for(j=0; zIdent[j]; j++){
  88193. z[i++] = zIdent[j];
  88194. if( zIdent[j]=='"' ) z[i++] = '"';
  88195. }
  88196. if( needQuote ) z[i++] = '"';
  88197. z[i] = 0;
  88198. *pIdx = i;
  88199. }
  88200. /*
  88201. ** Generate a CREATE TABLE statement appropriate for the given
  88202. ** table. Memory to hold the text of the statement is obtained
  88203. ** from sqliteMalloc() and must be freed by the calling function.
  88204. */
  88205. static char *createTableStmt(sqlite3 *db, Table *p){
  88206. int i, k, n;
  88207. char *zStmt;
  88208. char *zSep, *zSep2, *zEnd;
  88209. Column *pCol;
  88210. n = 0;
  88211. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  88212. n += identLength(pCol->zName) + 5;
  88213. }
  88214. n += identLength(p->zName);
  88215. if( n<50 ){
  88216. zSep = "";
  88217. zSep2 = ",";
  88218. zEnd = ")";
  88219. }else{
  88220. zSep = "\n ";
  88221. zSep2 = ",\n ";
  88222. zEnd = "\n)";
  88223. }
  88224. n += 35 + 6*p->nCol;
  88225. zStmt = sqlite3DbMallocRaw(0, n);
  88226. if( zStmt==0 ){
  88227. db->mallocFailed = 1;
  88228. return 0;
  88229. }
  88230. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  88231. k = sqlite3Strlen30(zStmt);
  88232. identPut(zStmt, &k, p->zName);
  88233. zStmt[k++] = '(';
  88234. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  88235. static const char * const azType[] = {
  88236. /* SQLITE_AFF_BLOB */ "",
  88237. /* SQLITE_AFF_TEXT */ " TEXT",
  88238. /* SQLITE_AFF_NUMERIC */ " NUM",
  88239. /* SQLITE_AFF_INTEGER */ " INT",
  88240. /* SQLITE_AFF_REAL */ " REAL"
  88241. };
  88242. int len;
  88243. const char *zType;
  88244. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  88245. k += sqlite3Strlen30(&zStmt[k]);
  88246. zSep = zSep2;
  88247. identPut(zStmt, &k, pCol->zName);
  88248. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  88249. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  88250. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  88251. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  88252. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  88253. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  88254. testcase( pCol->affinity==SQLITE_AFF_REAL );
  88255. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  88256. len = sqlite3Strlen30(zType);
  88257. assert( pCol->affinity==SQLITE_AFF_BLOB
  88258. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  88259. memcpy(&zStmt[k], zType, len);
  88260. k += len;
  88261. assert( k<=n );
  88262. }
  88263. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  88264. return zStmt;
  88265. }
  88266. /*
  88267. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  88268. ** on success and SQLITE_NOMEM on an OOM error.
  88269. */
  88270. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  88271. char *zExtra;
  88272. int nByte;
  88273. if( pIdx->nColumn>=N ) return SQLITE_OK;
  88274. assert( pIdx->isResized==0 );
  88275. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  88276. zExtra = sqlite3DbMallocZero(db, nByte);
  88277. if( zExtra==0 ) return SQLITE_NOMEM;
  88278. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  88279. pIdx->azColl = (char**)zExtra;
  88280. zExtra += sizeof(char*)*N;
  88281. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  88282. pIdx->aiColumn = (i16*)zExtra;
  88283. zExtra += sizeof(i16)*N;
  88284. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  88285. pIdx->aSortOrder = (u8*)zExtra;
  88286. pIdx->nColumn = N;
  88287. pIdx->isResized = 1;
  88288. return SQLITE_OK;
  88289. }
  88290. /*
  88291. ** Estimate the total row width for a table.
  88292. */
  88293. static void estimateTableWidth(Table *pTab){
  88294. unsigned wTable = 0;
  88295. const Column *pTabCol;
  88296. int i;
  88297. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  88298. wTable += pTabCol->szEst;
  88299. }
  88300. if( pTab->iPKey<0 ) wTable++;
  88301. pTab->szTabRow = sqlite3LogEst(wTable*4);
  88302. }
  88303. /*
  88304. ** Estimate the average size of a row for an index.
  88305. */
  88306. static void estimateIndexWidth(Index *pIdx){
  88307. unsigned wIndex = 0;
  88308. int i;
  88309. const Column *aCol = pIdx->pTable->aCol;
  88310. for(i=0; i<pIdx->nColumn; i++){
  88311. i16 x = pIdx->aiColumn[i];
  88312. assert( x<pIdx->pTable->nCol );
  88313. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  88314. }
  88315. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  88316. }
  88317. /* Return true if value x is found any of the first nCol entries of aiCol[]
  88318. */
  88319. static int hasColumn(const i16 *aiCol, int nCol, int x){
  88320. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  88321. return 0;
  88322. }
  88323. /*
  88324. ** This routine runs at the end of parsing a CREATE TABLE statement that
  88325. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  88326. ** internal schema data structures and the generated VDBE code so that they
  88327. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  88328. ** Changes include:
  88329. **
  88330. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  88331. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  88332. ** data storage is a covering index btree.
  88333. ** (2) Bypass the creation of the sqlite_master table entry
  88334. ** for the PRIMARY KEY as the primary key index is now
  88335. ** identified by the sqlite_master table entry of the table itself.
  88336. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  88337. ** schema to the rootpage from the main table.
  88338. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  88339. ** (5) Add all table columns to the PRIMARY KEY Index object
  88340. ** so that the PRIMARY KEY is a covering index. The surplus
  88341. ** columns are part of KeyInfo.nXField and are not used for
  88342. ** sorting or lookup or uniqueness checks.
  88343. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  88344. ** indices with the PRIMARY KEY columns.
  88345. */
  88346. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  88347. Index *pIdx;
  88348. Index *pPk;
  88349. int nPk;
  88350. int i, j;
  88351. sqlite3 *db = pParse->db;
  88352. Vdbe *v = pParse->pVdbe;
  88353. /* Convert the OP_CreateTable opcode that would normally create the
  88354. ** root-page for the table into an OP_CreateIndex opcode. The index
  88355. ** created will become the PRIMARY KEY index.
  88356. */
  88357. if( pParse->addrCrTab ){
  88358. assert( v );
  88359. sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
  88360. }
  88361. /* Locate the PRIMARY KEY index. Or, if this table was originally
  88362. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  88363. */
  88364. if( pTab->iPKey>=0 ){
  88365. ExprList *pList;
  88366. Token ipkToken;
  88367. ipkToken.z = pTab->aCol[pTab->iPKey].zName;
  88368. ipkToken.n = sqlite3Strlen30(ipkToken.z);
  88369. pList = sqlite3ExprListAppend(pParse, 0,
  88370. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  88371. if( pList==0 ) return;
  88372. pList->a[0].sortOrder = pParse->iPkSortOrder;
  88373. assert( pParse->pNewTable==pTab );
  88374. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  88375. if( pPk==0 ) return;
  88376. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  88377. pTab->iPKey = -1;
  88378. }else{
  88379. pPk = sqlite3PrimaryKeyIndex(pTab);
  88380. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  88381. ** table entry. This is only required if currently generating VDBE
  88382. ** code for a CREATE TABLE (not when parsing one as part of reading
  88383. ** a database schema). */
  88384. if( v ){
  88385. assert( db->init.busy==0 );
  88386. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  88387. }
  88388. /*
  88389. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  88390. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  88391. ** code assumes the PRIMARY KEY contains no repeated columns.
  88392. */
  88393. for(i=j=1; i<pPk->nKeyCol; i++){
  88394. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  88395. pPk->nColumn--;
  88396. }else{
  88397. pPk->aiColumn[j++] = pPk->aiColumn[i];
  88398. }
  88399. }
  88400. pPk->nKeyCol = j;
  88401. }
  88402. pPk->isCovering = 1;
  88403. assert( pPk!=0 );
  88404. nPk = pPk->nKeyCol;
  88405. /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
  88406. ** do not enforce this for imposter tables.) */
  88407. if( !db->init.imposterTable ){
  88408. for(i=0; i<nPk; i++){
  88409. pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  88410. }
  88411. pPk->uniqNotNull = 1;
  88412. }
  88413. /* The root page of the PRIMARY KEY is the table root page */
  88414. pPk->tnum = pTab->tnum;
  88415. /* Update the in-memory representation of all UNIQUE indices by converting
  88416. ** the final rowid column into one or more columns of the PRIMARY KEY.
  88417. */
  88418. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88419. int n;
  88420. if( IsPrimaryKeyIndex(pIdx) ) continue;
  88421. for(i=n=0; i<nPk; i++){
  88422. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  88423. }
  88424. if( n==0 ){
  88425. /* This index is a superset of the primary key */
  88426. pIdx->nColumn = pIdx->nKeyCol;
  88427. continue;
  88428. }
  88429. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  88430. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  88431. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  88432. pIdx->aiColumn[j] = pPk->aiColumn[i];
  88433. pIdx->azColl[j] = pPk->azColl[i];
  88434. j++;
  88435. }
  88436. }
  88437. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  88438. assert( pIdx->nColumn>=j );
  88439. }
  88440. /* Add all table columns to the PRIMARY KEY index
  88441. */
  88442. if( nPk<pTab->nCol ){
  88443. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  88444. for(i=0, j=nPk; i<pTab->nCol; i++){
  88445. if( !hasColumn(pPk->aiColumn, j, i) ){
  88446. assert( j<pPk->nColumn );
  88447. pPk->aiColumn[j] = i;
  88448. pPk->azColl[j] = "BINARY";
  88449. j++;
  88450. }
  88451. }
  88452. assert( pPk->nColumn==j );
  88453. assert( pTab->nCol==j );
  88454. }else{
  88455. pPk->nColumn = pTab->nCol;
  88456. }
  88457. }
  88458. /*
  88459. ** This routine is called to report the final ")" that terminates
  88460. ** a CREATE TABLE statement.
  88461. **
  88462. ** The table structure that other action routines have been building
  88463. ** is added to the internal hash tables, assuming no errors have
  88464. ** occurred.
  88465. **
  88466. ** An entry for the table is made in the master table on disk, unless
  88467. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  88468. ** it means we are reading the sqlite_master table because we just
  88469. ** connected to the database or because the sqlite_master table has
  88470. ** recently changed, so the entry for this table already exists in
  88471. ** the sqlite_master table. We do not want to create it again.
  88472. **
  88473. ** If the pSelect argument is not NULL, it means that this routine
  88474. ** was called to create a table generated from a
  88475. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  88476. ** the new table will match the result set of the SELECT.
  88477. */
  88478. SQLITE_PRIVATE void sqlite3EndTable(
  88479. Parse *pParse, /* Parse context */
  88480. Token *pCons, /* The ',' token after the last column defn. */
  88481. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  88482. u8 tabOpts, /* Extra table options. Usually 0. */
  88483. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  88484. ){
  88485. Table *p; /* The new table */
  88486. sqlite3 *db = pParse->db; /* The database connection */
  88487. int iDb; /* Database in which the table lives */
  88488. Index *pIdx; /* An implied index of the table */
  88489. if( pEnd==0 && pSelect==0 ){
  88490. return;
  88491. }
  88492. assert( !db->mallocFailed );
  88493. p = pParse->pNewTable;
  88494. if( p==0 ) return;
  88495. assert( !db->init.busy || !pSelect );
  88496. /* If the db->init.busy is 1 it means we are reading the SQL off the
  88497. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  88498. ** So do not write to the disk again. Extract the root page number
  88499. ** for the table from the db->init.newTnum field. (The page number
  88500. ** should have been put there by the sqliteOpenCb routine.)
  88501. */
  88502. if( db->init.busy ){
  88503. p->tnum = db->init.newTnum;
  88504. }
  88505. /* Special processing for WITHOUT ROWID Tables */
  88506. if( tabOpts & TF_WithoutRowid ){
  88507. if( (p->tabFlags & TF_Autoincrement) ){
  88508. sqlite3ErrorMsg(pParse,
  88509. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  88510. return;
  88511. }
  88512. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  88513. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  88514. }else{
  88515. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  88516. convertToWithoutRowidTable(pParse, p);
  88517. }
  88518. }
  88519. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  88520. #ifndef SQLITE_OMIT_CHECK
  88521. /* Resolve names in all CHECK constraint expressions.
  88522. */
  88523. if( p->pCheck ){
  88524. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  88525. }
  88526. #endif /* !defined(SQLITE_OMIT_CHECK) */
  88527. /* Estimate the average row size for the table and for all implied indices */
  88528. estimateTableWidth(p);
  88529. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  88530. estimateIndexWidth(pIdx);
  88531. }
  88532. /* If not initializing, then create a record for the new table
  88533. ** in the SQLITE_MASTER table of the database.
  88534. **
  88535. ** If this is a TEMPORARY table, write the entry into the auxiliary
  88536. ** file instead of into the main database file.
  88537. */
  88538. if( !db->init.busy ){
  88539. int n;
  88540. Vdbe *v;
  88541. char *zType; /* "view" or "table" */
  88542. char *zType2; /* "VIEW" or "TABLE" */
  88543. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  88544. v = sqlite3GetVdbe(pParse);
  88545. if( NEVER(v==0) ) return;
  88546. sqlite3VdbeAddOp1(v, OP_Close, 0);
  88547. /*
  88548. ** Initialize zType for the new view or table.
  88549. */
  88550. if( p->pSelect==0 ){
  88551. /* A regular table */
  88552. zType = "table";
  88553. zType2 = "TABLE";
  88554. #ifndef SQLITE_OMIT_VIEW
  88555. }else{
  88556. /* A view */
  88557. zType = "view";
  88558. zType2 = "VIEW";
  88559. #endif
  88560. }
  88561. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  88562. ** statement to populate the new table. The root-page number for the
  88563. ** new table is in register pParse->regRoot.
  88564. **
  88565. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  88566. ** suitable state to query for the column names and types to be used
  88567. ** by the new table.
  88568. **
  88569. ** A shared-cache write-lock is not required to write to the new table,
  88570. ** as a schema-lock must have already been obtained to create it. Since
  88571. ** a schema-lock excludes all other database users, the write-lock would
  88572. ** be redundant.
  88573. */
  88574. if( pSelect ){
  88575. SelectDest dest; /* Where the SELECT should store results */
  88576. int regYield; /* Register holding co-routine entry-point */
  88577. int addrTop; /* Top of the co-routine */
  88578. int regRec; /* A record to be insert into the new table */
  88579. int regRowid; /* Rowid of the next row to insert */
  88580. int addrInsLoop; /* Top of the loop for inserting rows */
  88581. Table *pSelTab; /* A table that describes the SELECT results */
  88582. regYield = ++pParse->nMem;
  88583. regRec = ++pParse->nMem;
  88584. regRowid = ++pParse->nMem;
  88585. assert(pParse->nTab==1);
  88586. sqlite3MayAbort(pParse);
  88587. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  88588. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  88589. pParse->nTab = 2;
  88590. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  88591. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  88592. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  88593. sqlite3Select(pParse, pSelect, &dest);
  88594. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  88595. sqlite3VdbeJumpHere(v, addrTop - 1);
  88596. if( pParse->nErr ) return;
  88597. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  88598. if( pSelTab==0 ) return;
  88599. assert( p->aCol==0 );
  88600. p->nCol = pSelTab->nCol;
  88601. p->aCol = pSelTab->aCol;
  88602. pSelTab->nCol = 0;
  88603. pSelTab->aCol = 0;
  88604. sqlite3DeleteTable(db, pSelTab);
  88605. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  88606. VdbeCoverage(v);
  88607. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  88608. sqlite3TableAffinity(v, p, 0);
  88609. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  88610. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  88611. sqlite3VdbeGoto(v, addrInsLoop);
  88612. sqlite3VdbeJumpHere(v, addrInsLoop);
  88613. sqlite3VdbeAddOp1(v, OP_Close, 1);
  88614. }
  88615. /* Compute the complete text of the CREATE statement */
  88616. if( pSelect ){
  88617. zStmt = createTableStmt(db, p);
  88618. }else{
  88619. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  88620. n = (int)(pEnd2->z - pParse->sNameToken.z);
  88621. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  88622. zStmt = sqlite3MPrintf(db,
  88623. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  88624. );
  88625. }
  88626. /* A slot for the record has already been allocated in the
  88627. ** SQLITE_MASTER table. We just need to update that slot with all
  88628. ** the information we've collected.
  88629. */
  88630. sqlite3NestedParse(pParse,
  88631. "UPDATE %Q.%s "
  88632. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  88633. "WHERE rowid=#%d",
  88634. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  88635. zType,
  88636. p->zName,
  88637. p->zName,
  88638. pParse->regRoot,
  88639. zStmt,
  88640. pParse->regRowid
  88641. );
  88642. sqlite3DbFree(db, zStmt);
  88643. sqlite3ChangeCookie(pParse, iDb);
  88644. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88645. /* Check to see if we need to create an sqlite_sequence table for
  88646. ** keeping track of autoincrement keys.
  88647. */
  88648. if( p->tabFlags & TF_Autoincrement ){
  88649. Db *pDb = &db->aDb[iDb];
  88650. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88651. if( pDb->pSchema->pSeqTab==0 ){
  88652. sqlite3NestedParse(pParse,
  88653. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  88654. pDb->zName
  88655. );
  88656. }
  88657. }
  88658. #endif
  88659. /* Reparse everything to update our internal data structures */
  88660. sqlite3VdbeAddParseSchemaOp(v, iDb,
  88661. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  88662. }
  88663. /* Add the table to the in-memory representation of the database.
  88664. */
  88665. if( db->init.busy ){
  88666. Table *pOld;
  88667. Schema *pSchema = p->pSchema;
  88668. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88669. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  88670. if( pOld ){
  88671. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  88672. db->mallocFailed = 1;
  88673. return;
  88674. }
  88675. pParse->pNewTable = 0;
  88676. db->flags |= SQLITE_InternChanges;
  88677. #ifndef SQLITE_OMIT_ALTERTABLE
  88678. if( !p->pSelect ){
  88679. const char *zName = (const char *)pParse->sNameToken.z;
  88680. int nName;
  88681. assert( !pSelect && pCons && pEnd );
  88682. if( pCons->z==0 ){
  88683. pCons = pEnd;
  88684. }
  88685. nName = (int)((const char *)pCons->z - zName);
  88686. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  88687. }
  88688. #endif
  88689. }
  88690. }
  88691. #ifndef SQLITE_OMIT_VIEW
  88692. /*
  88693. ** The parser calls this routine in order to create a new VIEW
  88694. */
  88695. SQLITE_PRIVATE void sqlite3CreateView(
  88696. Parse *pParse, /* The parsing context */
  88697. Token *pBegin, /* The CREATE token that begins the statement */
  88698. Token *pName1, /* The token that holds the name of the view */
  88699. Token *pName2, /* The token that holds the name of the view */
  88700. ExprList *pCNames, /* Optional list of view column names */
  88701. Select *pSelect, /* A SELECT statement that will become the new view */
  88702. int isTemp, /* TRUE for a TEMPORARY view */
  88703. int noErr /* Suppress error messages if VIEW already exists */
  88704. ){
  88705. Table *p;
  88706. int n;
  88707. const char *z;
  88708. Token sEnd;
  88709. DbFixer sFix;
  88710. Token *pName = 0;
  88711. int iDb;
  88712. sqlite3 *db = pParse->db;
  88713. if( pParse->nVar>0 ){
  88714. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  88715. goto create_view_fail;
  88716. }
  88717. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  88718. p = pParse->pNewTable;
  88719. if( p==0 || pParse->nErr ) goto create_view_fail;
  88720. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  88721. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  88722. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  88723. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  88724. /* Make a copy of the entire SELECT statement that defines the view.
  88725. ** This will force all the Expr.token.z values to be dynamically
  88726. ** allocated rather than point to the input string - which means that
  88727. ** they will persist after the current sqlite3_exec() call returns.
  88728. */
  88729. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  88730. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  88731. if( db->mallocFailed ) goto create_view_fail;
  88732. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  88733. ** the end.
  88734. */
  88735. sEnd = pParse->sLastToken;
  88736. assert( sEnd.z[0]!=0 );
  88737. if( sEnd.z[0]!=';' ){
  88738. sEnd.z += sEnd.n;
  88739. }
  88740. sEnd.n = 0;
  88741. n = (int)(sEnd.z - pBegin->z);
  88742. assert( n>0 );
  88743. z = pBegin->z;
  88744. while( sqlite3Isspace(z[n-1]) ){ n--; }
  88745. sEnd.z = &z[n-1];
  88746. sEnd.n = 1;
  88747. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  88748. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  88749. create_view_fail:
  88750. sqlite3SelectDelete(db, pSelect);
  88751. sqlite3ExprListDelete(db, pCNames);
  88752. return;
  88753. }
  88754. #endif /* SQLITE_OMIT_VIEW */
  88755. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  88756. /*
  88757. ** The Table structure pTable is really a VIEW. Fill in the names of
  88758. ** the columns of the view in the pTable structure. Return the number
  88759. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  88760. */
  88761. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  88762. Table *pSelTab; /* A fake table from which we get the result set */
  88763. Select *pSel; /* Copy of the SELECT that implements the view */
  88764. int nErr = 0; /* Number of errors encountered */
  88765. int n; /* Temporarily holds the number of cursors assigned */
  88766. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  88767. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  88768. u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
  88769. assert( pTable );
  88770. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88771. if( sqlite3VtabCallConnect(pParse, pTable) ){
  88772. return SQLITE_ERROR;
  88773. }
  88774. if( IsVirtual(pTable) ) return 0;
  88775. #endif
  88776. #ifndef SQLITE_OMIT_VIEW
  88777. /* A positive nCol means the columns names for this view are
  88778. ** already known.
  88779. */
  88780. if( pTable->nCol>0 ) return 0;
  88781. /* A negative nCol is a special marker meaning that we are currently
  88782. ** trying to compute the column names. If we enter this routine with
  88783. ** a negative nCol, it means two or more views form a loop, like this:
  88784. **
  88785. ** CREATE VIEW one AS SELECT * FROM two;
  88786. ** CREATE VIEW two AS SELECT * FROM one;
  88787. **
  88788. ** Actually, the error above is now caught prior to reaching this point.
  88789. ** But the following test is still important as it does come up
  88790. ** in the following:
  88791. **
  88792. ** CREATE TABLE main.ex1(a);
  88793. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  88794. ** SELECT * FROM temp.ex1;
  88795. */
  88796. if( pTable->nCol<0 ){
  88797. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  88798. return 1;
  88799. }
  88800. assert( pTable->nCol>=0 );
  88801. /* If we get this far, it means we need to compute the table names.
  88802. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  88803. ** "*" elements in the results set of the view and will assign cursors
  88804. ** to the elements of the FROM clause. But we do not want these changes
  88805. ** to be permanent. So the computation is done on a copy of the SELECT
  88806. ** statement that defines the view.
  88807. */
  88808. assert( pTable->pSelect );
  88809. bEnabledLA = db->lookaside.bEnabled;
  88810. if( pTable->pCheck ){
  88811. db->lookaside.bEnabled = 0;
  88812. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  88813. &pTable->nCol, &pTable->aCol);
  88814. }else{
  88815. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  88816. if( pSel ){
  88817. n = pParse->nTab;
  88818. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  88819. pTable->nCol = -1;
  88820. db->lookaside.bEnabled = 0;
  88821. #ifndef SQLITE_OMIT_AUTHORIZATION
  88822. xAuth = db->xAuth;
  88823. db->xAuth = 0;
  88824. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  88825. db->xAuth = xAuth;
  88826. #else
  88827. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  88828. #endif
  88829. pParse->nTab = n;
  88830. if( pSelTab ){
  88831. assert( pTable->aCol==0 );
  88832. pTable->nCol = pSelTab->nCol;
  88833. pTable->aCol = pSelTab->aCol;
  88834. pSelTab->nCol = 0;
  88835. pSelTab->aCol = 0;
  88836. sqlite3DeleteTable(db, pSelTab);
  88837. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  88838. }else{
  88839. pTable->nCol = 0;
  88840. nErr++;
  88841. }
  88842. sqlite3SelectDelete(db, pSel);
  88843. } else {
  88844. nErr++;
  88845. }
  88846. }
  88847. db->lookaside.bEnabled = bEnabledLA;
  88848. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  88849. #endif /* SQLITE_OMIT_VIEW */
  88850. return nErr;
  88851. }
  88852. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  88853. #ifndef SQLITE_OMIT_VIEW
  88854. /*
  88855. ** Clear the column names from every VIEW in database idx.
  88856. */
  88857. static void sqliteViewResetAll(sqlite3 *db, int idx){
  88858. HashElem *i;
  88859. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  88860. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  88861. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  88862. Table *pTab = sqliteHashData(i);
  88863. if( pTab->pSelect ){
  88864. sqlite3DeleteColumnNames(db, pTab);
  88865. pTab->aCol = 0;
  88866. pTab->nCol = 0;
  88867. }
  88868. }
  88869. DbClearProperty(db, idx, DB_UnresetViews);
  88870. }
  88871. #else
  88872. # define sqliteViewResetAll(A,B)
  88873. #endif /* SQLITE_OMIT_VIEW */
  88874. /*
  88875. ** This function is called by the VDBE to adjust the internal schema
  88876. ** used by SQLite when the btree layer moves a table root page. The
  88877. ** root-page of a table or index in database iDb has changed from iFrom
  88878. ** to iTo.
  88879. **
  88880. ** Ticket #1728: The symbol table might still contain information
  88881. ** on tables and/or indices that are the process of being deleted.
  88882. ** If you are unlucky, one of those deleted indices or tables might
  88883. ** have the same rootpage number as the real table or index that is
  88884. ** being moved. So we cannot stop searching after the first match
  88885. ** because the first match might be for one of the deleted indices
  88886. ** or tables and not the table/index that is actually being moved.
  88887. ** We must continue looping until all tables and indices with
  88888. ** rootpage==iFrom have been converted to have a rootpage of iTo
  88889. ** in order to be certain that we got the right one.
  88890. */
  88891. #ifndef SQLITE_OMIT_AUTOVACUUM
  88892. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  88893. HashElem *pElem;
  88894. Hash *pHash;
  88895. Db *pDb;
  88896. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88897. pDb = &db->aDb[iDb];
  88898. pHash = &pDb->pSchema->tblHash;
  88899. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  88900. Table *pTab = sqliteHashData(pElem);
  88901. if( pTab->tnum==iFrom ){
  88902. pTab->tnum = iTo;
  88903. }
  88904. }
  88905. pHash = &pDb->pSchema->idxHash;
  88906. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  88907. Index *pIdx = sqliteHashData(pElem);
  88908. if( pIdx->tnum==iFrom ){
  88909. pIdx->tnum = iTo;
  88910. }
  88911. }
  88912. }
  88913. #endif
  88914. /*
  88915. ** Write code to erase the table with root-page iTable from database iDb.
  88916. ** Also write code to modify the sqlite_master table and internal schema
  88917. ** if a root-page of another table is moved by the btree-layer whilst
  88918. ** erasing iTable (this can happen with an auto-vacuum database).
  88919. */
  88920. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  88921. Vdbe *v = sqlite3GetVdbe(pParse);
  88922. int r1 = sqlite3GetTempReg(pParse);
  88923. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  88924. sqlite3MayAbort(pParse);
  88925. #ifndef SQLITE_OMIT_AUTOVACUUM
  88926. /* OP_Destroy stores an in integer r1. If this integer
  88927. ** is non-zero, then it is the root page number of a table moved to
  88928. ** location iTable. The following code modifies the sqlite_master table to
  88929. ** reflect this.
  88930. **
  88931. ** The "#NNN" in the SQL is a special constant that means whatever value
  88932. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  88933. ** token for additional information.
  88934. */
  88935. sqlite3NestedParse(pParse,
  88936. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  88937. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  88938. #endif
  88939. sqlite3ReleaseTempReg(pParse, r1);
  88940. }
  88941. /*
  88942. ** Write VDBE code to erase table pTab and all associated indices on disk.
  88943. ** Code to update the sqlite_master tables and internal schema definitions
  88944. ** in case a root-page belonging to another table is moved by the btree layer
  88945. ** is also added (this can happen with an auto-vacuum database).
  88946. */
  88947. static void destroyTable(Parse *pParse, Table *pTab){
  88948. #ifdef SQLITE_OMIT_AUTOVACUUM
  88949. Index *pIdx;
  88950. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88951. destroyRootPage(pParse, pTab->tnum, iDb);
  88952. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88953. destroyRootPage(pParse, pIdx->tnum, iDb);
  88954. }
  88955. #else
  88956. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  88957. ** is not defined), then it is important to call OP_Destroy on the
  88958. ** table and index root-pages in order, starting with the numerically
  88959. ** largest root-page number. This guarantees that none of the root-pages
  88960. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  88961. ** following were coded:
  88962. **
  88963. ** OP_Destroy 4 0
  88964. ** ...
  88965. ** OP_Destroy 5 0
  88966. **
  88967. ** and root page 5 happened to be the largest root-page number in the
  88968. ** database, then root page 5 would be moved to page 4 by the
  88969. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  88970. ** a free-list page.
  88971. */
  88972. int iTab = pTab->tnum;
  88973. int iDestroyed = 0;
  88974. while( 1 ){
  88975. Index *pIdx;
  88976. int iLargest = 0;
  88977. if( iDestroyed==0 || iTab<iDestroyed ){
  88978. iLargest = iTab;
  88979. }
  88980. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88981. int iIdx = pIdx->tnum;
  88982. assert( pIdx->pSchema==pTab->pSchema );
  88983. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  88984. iLargest = iIdx;
  88985. }
  88986. }
  88987. if( iLargest==0 ){
  88988. return;
  88989. }else{
  88990. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88991. assert( iDb>=0 && iDb<pParse->db->nDb );
  88992. destroyRootPage(pParse, iLargest, iDb);
  88993. iDestroyed = iLargest;
  88994. }
  88995. }
  88996. #endif
  88997. }
  88998. /*
  88999. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  89000. ** after a DROP INDEX or DROP TABLE command.
  89001. */
  89002. static void sqlite3ClearStatTables(
  89003. Parse *pParse, /* The parsing context */
  89004. int iDb, /* The database number */
  89005. const char *zType, /* "idx" or "tbl" */
  89006. const char *zName /* Name of index or table */
  89007. ){
  89008. int i;
  89009. const char *zDbName = pParse->db->aDb[iDb].zName;
  89010. for(i=1; i<=4; i++){
  89011. char zTab[24];
  89012. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  89013. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  89014. sqlite3NestedParse(pParse,
  89015. "DELETE FROM %Q.%s WHERE %s=%Q",
  89016. zDbName, zTab, zType, zName
  89017. );
  89018. }
  89019. }
  89020. }
  89021. /*
  89022. ** Generate code to drop a table.
  89023. */
  89024. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  89025. Vdbe *v;
  89026. sqlite3 *db = pParse->db;
  89027. Trigger *pTrigger;
  89028. Db *pDb = &db->aDb[iDb];
  89029. v = sqlite3GetVdbe(pParse);
  89030. assert( v!=0 );
  89031. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89032. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89033. if( IsVirtual(pTab) ){
  89034. sqlite3VdbeAddOp0(v, OP_VBegin);
  89035. }
  89036. #endif
  89037. /* Drop all triggers associated with the table being dropped. Code
  89038. ** is generated to remove entries from sqlite_master and/or
  89039. ** sqlite_temp_master if required.
  89040. */
  89041. pTrigger = sqlite3TriggerList(pParse, pTab);
  89042. while( pTrigger ){
  89043. assert( pTrigger->pSchema==pTab->pSchema ||
  89044. pTrigger->pSchema==db->aDb[1].pSchema );
  89045. sqlite3DropTriggerPtr(pParse, pTrigger);
  89046. pTrigger = pTrigger->pNext;
  89047. }
  89048. #ifndef SQLITE_OMIT_AUTOINCREMENT
  89049. /* Remove any entries of the sqlite_sequence table associated with
  89050. ** the table being dropped. This is done before the table is dropped
  89051. ** at the btree level, in case the sqlite_sequence table needs to
  89052. ** move as a result of the drop (can happen in auto-vacuum mode).
  89053. */
  89054. if( pTab->tabFlags & TF_Autoincrement ){
  89055. sqlite3NestedParse(pParse,
  89056. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  89057. pDb->zName, pTab->zName
  89058. );
  89059. }
  89060. #endif
  89061. /* Drop all SQLITE_MASTER table and index entries that refer to the
  89062. ** table. The program name loops through the master table and deletes
  89063. ** every row that refers to a table of the same name as the one being
  89064. ** dropped. Triggers are handled separately because a trigger can be
  89065. ** created in the temp database that refers to a table in another
  89066. ** database.
  89067. */
  89068. sqlite3NestedParse(pParse,
  89069. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  89070. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  89071. if( !isView && !IsVirtual(pTab) ){
  89072. destroyTable(pParse, pTab);
  89073. }
  89074. /* Remove the table entry from SQLite's internal schema and modify
  89075. ** the schema cookie.
  89076. */
  89077. if( IsVirtual(pTab) ){
  89078. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  89079. }
  89080. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  89081. sqlite3ChangeCookie(pParse, iDb);
  89082. sqliteViewResetAll(db, iDb);
  89083. }
  89084. /*
  89085. ** This routine is called to do the work of a DROP TABLE statement.
  89086. ** pName is the name of the table to be dropped.
  89087. */
  89088. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  89089. Table *pTab;
  89090. Vdbe *v;
  89091. sqlite3 *db = pParse->db;
  89092. int iDb;
  89093. if( db->mallocFailed ){
  89094. goto exit_drop_table;
  89095. }
  89096. assert( pParse->nErr==0 );
  89097. assert( pName->nSrc==1 );
  89098. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  89099. if( noErr ) db->suppressErr++;
  89100. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  89101. if( noErr ) db->suppressErr--;
  89102. if( pTab==0 ){
  89103. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  89104. goto exit_drop_table;
  89105. }
  89106. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89107. assert( iDb>=0 && iDb<db->nDb );
  89108. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  89109. ** it is initialized.
  89110. */
  89111. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  89112. goto exit_drop_table;
  89113. }
  89114. #ifndef SQLITE_OMIT_AUTHORIZATION
  89115. {
  89116. int code;
  89117. const char *zTab = SCHEMA_TABLE(iDb);
  89118. const char *zDb = db->aDb[iDb].zName;
  89119. const char *zArg2 = 0;
  89120. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  89121. goto exit_drop_table;
  89122. }
  89123. if( isView ){
  89124. if( !OMIT_TEMPDB && iDb==1 ){
  89125. code = SQLITE_DROP_TEMP_VIEW;
  89126. }else{
  89127. code = SQLITE_DROP_VIEW;
  89128. }
  89129. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89130. }else if( IsVirtual(pTab) ){
  89131. code = SQLITE_DROP_VTABLE;
  89132. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  89133. #endif
  89134. }else{
  89135. if( !OMIT_TEMPDB && iDb==1 ){
  89136. code = SQLITE_DROP_TEMP_TABLE;
  89137. }else{
  89138. code = SQLITE_DROP_TABLE;
  89139. }
  89140. }
  89141. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  89142. goto exit_drop_table;
  89143. }
  89144. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  89145. goto exit_drop_table;
  89146. }
  89147. }
  89148. #endif
  89149. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  89150. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  89151. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  89152. goto exit_drop_table;
  89153. }
  89154. #ifndef SQLITE_OMIT_VIEW
  89155. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  89156. ** on a table.
  89157. */
  89158. if( isView && pTab->pSelect==0 ){
  89159. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  89160. goto exit_drop_table;
  89161. }
  89162. if( !isView && pTab->pSelect ){
  89163. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  89164. goto exit_drop_table;
  89165. }
  89166. #endif
  89167. /* Generate code to remove the table from the master table
  89168. ** on disk.
  89169. */
  89170. v = sqlite3GetVdbe(pParse);
  89171. if( v ){
  89172. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89173. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  89174. sqlite3FkDropTable(pParse, pName, pTab);
  89175. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  89176. }
  89177. exit_drop_table:
  89178. sqlite3SrcListDelete(db, pName);
  89179. }
  89180. /*
  89181. ** This routine is called to create a new foreign key on the table
  89182. ** currently under construction. pFromCol determines which columns
  89183. ** in the current table point to the foreign key. If pFromCol==0 then
  89184. ** connect the key to the last column inserted. pTo is the name of
  89185. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  89186. ** of tables in the parent pTo table. flags contains all
  89187. ** information about the conflict resolution algorithms specified
  89188. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  89189. **
  89190. ** An FKey structure is created and added to the table currently
  89191. ** under construction in the pParse->pNewTable field.
  89192. **
  89193. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  89194. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  89195. */
  89196. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  89197. Parse *pParse, /* Parsing context */
  89198. ExprList *pFromCol, /* Columns in this table that point to other table */
  89199. Token *pTo, /* Name of the other table */
  89200. ExprList *pToCol, /* Columns in the other table */
  89201. int flags /* Conflict resolution algorithms. */
  89202. ){
  89203. sqlite3 *db = pParse->db;
  89204. #ifndef SQLITE_OMIT_FOREIGN_KEY
  89205. FKey *pFKey = 0;
  89206. FKey *pNextTo;
  89207. Table *p = pParse->pNewTable;
  89208. int nByte;
  89209. int i;
  89210. int nCol;
  89211. char *z;
  89212. assert( pTo!=0 );
  89213. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  89214. if( pFromCol==0 ){
  89215. int iCol = p->nCol-1;
  89216. if( NEVER(iCol<0) ) goto fk_end;
  89217. if( pToCol && pToCol->nExpr!=1 ){
  89218. sqlite3ErrorMsg(pParse, "foreign key on %s"
  89219. " should reference only one column of table %T",
  89220. p->aCol[iCol].zName, pTo);
  89221. goto fk_end;
  89222. }
  89223. nCol = 1;
  89224. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  89225. sqlite3ErrorMsg(pParse,
  89226. "number of columns in foreign key does not match the number of "
  89227. "columns in the referenced table");
  89228. goto fk_end;
  89229. }else{
  89230. nCol = pFromCol->nExpr;
  89231. }
  89232. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  89233. if( pToCol ){
  89234. for(i=0; i<pToCol->nExpr; i++){
  89235. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  89236. }
  89237. }
  89238. pFKey = sqlite3DbMallocZero(db, nByte );
  89239. if( pFKey==0 ){
  89240. goto fk_end;
  89241. }
  89242. pFKey->pFrom = p;
  89243. pFKey->pNextFrom = p->pFKey;
  89244. z = (char*)&pFKey->aCol[nCol];
  89245. pFKey->zTo = z;
  89246. memcpy(z, pTo->z, pTo->n);
  89247. z[pTo->n] = 0;
  89248. sqlite3Dequote(z);
  89249. z += pTo->n+1;
  89250. pFKey->nCol = nCol;
  89251. if( pFromCol==0 ){
  89252. pFKey->aCol[0].iFrom = p->nCol-1;
  89253. }else{
  89254. for(i=0; i<nCol; i++){
  89255. int j;
  89256. for(j=0; j<p->nCol; j++){
  89257. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  89258. pFKey->aCol[i].iFrom = j;
  89259. break;
  89260. }
  89261. }
  89262. if( j>=p->nCol ){
  89263. sqlite3ErrorMsg(pParse,
  89264. "unknown column \"%s\" in foreign key definition",
  89265. pFromCol->a[i].zName);
  89266. goto fk_end;
  89267. }
  89268. }
  89269. }
  89270. if( pToCol ){
  89271. for(i=0; i<nCol; i++){
  89272. int n = sqlite3Strlen30(pToCol->a[i].zName);
  89273. pFKey->aCol[i].zCol = z;
  89274. memcpy(z, pToCol->a[i].zName, n);
  89275. z[n] = 0;
  89276. z += n+1;
  89277. }
  89278. }
  89279. pFKey->isDeferred = 0;
  89280. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  89281. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  89282. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  89283. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  89284. pFKey->zTo, (void *)pFKey
  89285. );
  89286. if( pNextTo==pFKey ){
  89287. db->mallocFailed = 1;
  89288. goto fk_end;
  89289. }
  89290. if( pNextTo ){
  89291. assert( pNextTo->pPrevTo==0 );
  89292. pFKey->pNextTo = pNextTo;
  89293. pNextTo->pPrevTo = pFKey;
  89294. }
  89295. /* Link the foreign key to the table as the last step.
  89296. */
  89297. p->pFKey = pFKey;
  89298. pFKey = 0;
  89299. fk_end:
  89300. sqlite3DbFree(db, pFKey);
  89301. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  89302. sqlite3ExprListDelete(db, pFromCol);
  89303. sqlite3ExprListDelete(db, pToCol);
  89304. }
  89305. /*
  89306. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  89307. ** clause is seen as part of a foreign key definition. The isDeferred
  89308. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  89309. ** The behavior of the most recently created foreign key is adjusted
  89310. ** accordingly.
  89311. */
  89312. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  89313. #ifndef SQLITE_OMIT_FOREIGN_KEY
  89314. Table *pTab;
  89315. FKey *pFKey;
  89316. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  89317. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  89318. pFKey->isDeferred = (u8)isDeferred;
  89319. #endif
  89320. }
  89321. /*
  89322. ** Generate code that will erase and refill index *pIdx. This is
  89323. ** used to initialize a newly created index or to recompute the
  89324. ** content of an index in response to a REINDEX command.
  89325. **
  89326. ** if memRootPage is not negative, it means that the index is newly
  89327. ** created. The register specified by memRootPage contains the
  89328. ** root page number of the index. If memRootPage is negative, then
  89329. ** the index already exists and must be cleared before being refilled and
  89330. ** the root page number of the index is taken from pIndex->tnum.
  89331. */
  89332. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  89333. Table *pTab = pIndex->pTable; /* The table that is indexed */
  89334. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  89335. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  89336. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  89337. int addr1; /* Address of top of loop */
  89338. int addr2; /* Address to jump to for next iteration */
  89339. int tnum; /* Root page of index */
  89340. int iPartIdxLabel; /* Jump to this label to skip a row */
  89341. Vdbe *v; /* Generate code into this virtual machine */
  89342. KeyInfo *pKey; /* KeyInfo for index */
  89343. int regRecord; /* Register holding assembled index record */
  89344. sqlite3 *db = pParse->db; /* The database connection */
  89345. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  89346. #ifndef SQLITE_OMIT_AUTHORIZATION
  89347. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  89348. db->aDb[iDb].zName ) ){
  89349. return;
  89350. }
  89351. #endif
  89352. /* Require a write-lock on the table to perform this operation */
  89353. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  89354. v = sqlite3GetVdbe(pParse);
  89355. if( v==0 ) return;
  89356. if( memRootPage>=0 ){
  89357. tnum = memRootPage;
  89358. }else{
  89359. tnum = pIndex->tnum;
  89360. }
  89361. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  89362. /* Open the sorter cursor if we are to use one. */
  89363. iSorter = pParse->nTab++;
  89364. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  89365. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  89366. /* Open the table. Loop through all rows of the table, inserting index
  89367. ** records into the sorter. */
  89368. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  89369. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  89370. regRecord = sqlite3GetTempReg(pParse);
  89371. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  89372. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  89373. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  89374. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  89375. sqlite3VdbeJumpHere(v, addr1);
  89376. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  89377. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  89378. (char *)pKey, P4_KEYINFO);
  89379. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  89380. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  89381. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  89382. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  89383. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  89384. sqlite3VdbeGoto(v, j2);
  89385. addr2 = sqlite3VdbeCurrentAddr(v);
  89386. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  89387. pIndex->nKeyCol); VdbeCoverage(v);
  89388. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  89389. }else{
  89390. addr2 = sqlite3VdbeCurrentAddr(v);
  89391. }
  89392. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  89393. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  89394. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  89395. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  89396. sqlite3ReleaseTempReg(pParse, regRecord);
  89397. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  89398. sqlite3VdbeJumpHere(v, addr1);
  89399. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  89400. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  89401. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  89402. }
  89403. /*
  89404. ** Allocate heap space to hold an Index object with nCol columns.
  89405. **
  89406. ** Increase the allocation size to provide an extra nExtra bytes
  89407. ** of 8-byte aligned space after the Index object and return a
  89408. ** pointer to this extra space in *ppExtra.
  89409. */
  89410. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  89411. sqlite3 *db, /* Database connection */
  89412. i16 nCol, /* Total number of columns in the index */
  89413. int nExtra, /* Number of bytes of extra space to alloc */
  89414. char **ppExtra /* Pointer to the "extra" space */
  89415. ){
  89416. Index *p; /* Allocated index object */
  89417. int nByte; /* Bytes of space for Index object + arrays */
  89418. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  89419. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  89420. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  89421. sizeof(i16)*nCol + /* Index.aiColumn */
  89422. sizeof(u8)*nCol); /* Index.aSortOrder */
  89423. p = sqlite3DbMallocZero(db, nByte + nExtra);
  89424. if( p ){
  89425. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  89426. p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  89427. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  89428. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  89429. p->aSortOrder = (u8*)pExtra;
  89430. p->nColumn = nCol;
  89431. p->nKeyCol = nCol - 1;
  89432. *ppExtra = ((char*)p) + nByte;
  89433. }
  89434. return p;
  89435. }
  89436. /*
  89437. ** Backwards Compatibility Hack:
  89438. **
  89439. ** Historical versions of SQLite accepted strings as column names in
  89440. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  89441. **
  89442. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  89443. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  89444. **
  89445. ** This is goofy. But to preserve backwards compatibility we continue to
  89446. ** accept it. This routine does the necessary conversion. It converts
  89447. ** the expression given in its argument from a TK_STRING into a TK_ID
  89448. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  89449. ** If the epxression is anything other than TK_STRING, the expression is
  89450. ** unchanged.
  89451. */
  89452. static void sqlite3StringToId(Expr *p){
  89453. if( p->op==TK_STRING ){
  89454. p->op = TK_ID;
  89455. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  89456. p->pLeft->op = TK_ID;
  89457. }
  89458. }
  89459. /*
  89460. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  89461. ** and pTblList is the name of the table that is to be indexed. Both will
  89462. ** be NULL for a primary key or an index that is created to satisfy a
  89463. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  89464. ** as the table to be indexed. pParse->pNewTable is a table that is
  89465. ** currently being constructed by a CREATE TABLE statement.
  89466. **
  89467. ** pList is a list of columns to be indexed. pList will be NULL if this
  89468. ** is a primary key or unique-constraint on the most recent column added
  89469. ** to the table currently under construction.
  89470. **
  89471. ** If the index is created successfully, return a pointer to the new Index
  89472. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  89473. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  89474. */
  89475. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  89476. Parse *pParse, /* All information about this parse */
  89477. Token *pName1, /* First part of index name. May be NULL */
  89478. Token *pName2, /* Second part of index name. May be NULL */
  89479. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  89480. ExprList *pList, /* A list of columns to be indexed */
  89481. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  89482. Token *pStart, /* The CREATE token that begins this statement */
  89483. Expr *pPIWhere, /* WHERE clause for partial indices */
  89484. int sortOrder, /* Sort order of primary key when pList==NULL */
  89485. int ifNotExist /* Omit error if index already exists */
  89486. ){
  89487. Index *pRet = 0; /* Pointer to return */
  89488. Table *pTab = 0; /* Table to be indexed */
  89489. Index *pIndex = 0; /* The index to be created */
  89490. char *zName = 0; /* Name of the index */
  89491. int nName; /* Number of characters in zName */
  89492. int i, j;
  89493. DbFixer sFix; /* For assigning database names to pTable */
  89494. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  89495. sqlite3 *db = pParse->db;
  89496. Db *pDb; /* The specific table containing the indexed database */
  89497. int iDb; /* Index of the database that is being written */
  89498. Token *pName = 0; /* Unqualified name of the index to create */
  89499. struct ExprList_item *pListItem; /* For looping over pList */
  89500. int nExtra = 0; /* Space allocated for zExtra[] */
  89501. int nExtraCol; /* Number of extra columns needed */
  89502. char *zExtra = 0; /* Extra space after the Index object */
  89503. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  89504. if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
  89505. goto exit_create_index;
  89506. }
  89507. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  89508. goto exit_create_index;
  89509. }
  89510. /*
  89511. ** Find the table that is to be indexed. Return early if not found.
  89512. */
  89513. if( pTblName!=0 ){
  89514. /* Use the two-part index name to determine the database
  89515. ** to search for the table. 'Fix' the table name to this db
  89516. ** before looking up the table.
  89517. */
  89518. assert( pName1 && pName2 );
  89519. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  89520. if( iDb<0 ) goto exit_create_index;
  89521. assert( pName && pName->z );
  89522. #ifndef SQLITE_OMIT_TEMPDB
  89523. /* If the index name was unqualified, check if the table
  89524. ** is a temp table. If so, set the database to 1. Do not do this
  89525. ** if initialising a database schema.
  89526. */
  89527. if( !db->init.busy ){
  89528. pTab = sqlite3SrcListLookup(pParse, pTblName);
  89529. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  89530. iDb = 1;
  89531. }
  89532. }
  89533. #endif
  89534. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  89535. if( sqlite3FixSrcList(&sFix, pTblName) ){
  89536. /* Because the parser constructs pTblName from a single identifier,
  89537. ** sqlite3FixSrcList can never fail. */
  89538. assert(0);
  89539. }
  89540. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  89541. assert( db->mallocFailed==0 || pTab==0 );
  89542. if( pTab==0 ) goto exit_create_index;
  89543. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  89544. sqlite3ErrorMsg(pParse,
  89545. "cannot create a TEMP index on non-TEMP table \"%s\"",
  89546. pTab->zName);
  89547. goto exit_create_index;
  89548. }
  89549. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  89550. }else{
  89551. assert( pName==0 );
  89552. assert( pStart==0 );
  89553. pTab = pParse->pNewTable;
  89554. if( !pTab ) goto exit_create_index;
  89555. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89556. }
  89557. pDb = &db->aDb[iDb];
  89558. assert( pTab!=0 );
  89559. assert( pParse->nErr==0 );
  89560. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  89561. && db->init.busy==0
  89562. #if SQLITE_USER_AUTHENTICATION
  89563. && sqlite3UserAuthTable(pTab->zName)==0
  89564. #endif
  89565. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  89566. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  89567. goto exit_create_index;
  89568. }
  89569. #ifndef SQLITE_OMIT_VIEW
  89570. if( pTab->pSelect ){
  89571. sqlite3ErrorMsg(pParse, "views may not be indexed");
  89572. goto exit_create_index;
  89573. }
  89574. #endif
  89575. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89576. if( IsVirtual(pTab) ){
  89577. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  89578. goto exit_create_index;
  89579. }
  89580. #endif
  89581. /*
  89582. ** Find the name of the index. Make sure there is not already another
  89583. ** index or table with the same name.
  89584. **
  89585. ** Exception: If we are reading the names of permanent indices from the
  89586. ** sqlite_master table (because some other process changed the schema) and
  89587. ** one of the index names collides with the name of a temporary table or
  89588. ** index, then we will continue to process this index.
  89589. **
  89590. ** If pName==0 it means that we are
  89591. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  89592. ** own name.
  89593. */
  89594. if( pName ){
  89595. zName = sqlite3NameFromToken(db, pName);
  89596. if( zName==0 ) goto exit_create_index;
  89597. assert( pName->z!=0 );
  89598. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  89599. goto exit_create_index;
  89600. }
  89601. if( !db->init.busy ){
  89602. if( sqlite3FindTable(db, zName, 0)!=0 ){
  89603. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  89604. goto exit_create_index;
  89605. }
  89606. }
  89607. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  89608. if( !ifNotExist ){
  89609. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  89610. }else{
  89611. assert( !db->init.busy );
  89612. sqlite3CodeVerifySchema(pParse, iDb);
  89613. }
  89614. goto exit_create_index;
  89615. }
  89616. }else{
  89617. int n;
  89618. Index *pLoop;
  89619. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  89620. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  89621. if( zName==0 ){
  89622. goto exit_create_index;
  89623. }
  89624. }
  89625. /* Check for authorization to create an index.
  89626. */
  89627. #ifndef SQLITE_OMIT_AUTHORIZATION
  89628. {
  89629. const char *zDb = pDb->zName;
  89630. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  89631. goto exit_create_index;
  89632. }
  89633. i = SQLITE_CREATE_INDEX;
  89634. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  89635. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  89636. goto exit_create_index;
  89637. }
  89638. }
  89639. #endif
  89640. /* If pList==0, it means this routine was called to make a primary
  89641. ** key out of the last column added to the table under construction.
  89642. ** So create a fake list to simulate this.
  89643. */
  89644. if( pList==0 ){
  89645. Token prevCol;
  89646. prevCol.z = pTab->aCol[pTab->nCol-1].zName;
  89647. prevCol.n = sqlite3Strlen30(prevCol.z);
  89648. pList = sqlite3ExprListAppend(pParse, 0,
  89649. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  89650. if( pList==0 ) goto exit_create_index;
  89651. assert( pList->nExpr==1 );
  89652. sqlite3ExprListSetSortOrder(pList, sortOrder);
  89653. }else{
  89654. sqlite3ExprListCheckLength(pParse, pList, "index");
  89655. }
  89656. /* Figure out how many bytes of space are required to store explicitly
  89657. ** specified collation sequence names.
  89658. */
  89659. for(i=0; i<pList->nExpr; i++){
  89660. Expr *pExpr = pList->a[i].pExpr;
  89661. assert( pExpr!=0 );
  89662. if( pExpr->op==TK_COLLATE ){
  89663. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  89664. }
  89665. }
  89666. /*
  89667. ** Allocate the index structure.
  89668. */
  89669. nName = sqlite3Strlen30(zName);
  89670. nExtraCol = pPk ? pPk->nKeyCol : 1;
  89671. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  89672. nName + nExtra + 1, &zExtra);
  89673. if( db->mallocFailed ){
  89674. goto exit_create_index;
  89675. }
  89676. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  89677. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  89678. pIndex->zName = zExtra;
  89679. zExtra += nName + 1;
  89680. memcpy(pIndex->zName, zName, nName+1);
  89681. pIndex->pTable = pTab;
  89682. pIndex->onError = (u8)onError;
  89683. pIndex->uniqNotNull = onError!=OE_None;
  89684. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  89685. pIndex->pSchema = db->aDb[iDb].pSchema;
  89686. pIndex->nKeyCol = pList->nExpr;
  89687. if( pPIWhere ){
  89688. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  89689. pIndex->pPartIdxWhere = pPIWhere;
  89690. pPIWhere = 0;
  89691. }
  89692. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89693. /* Check to see if we should honor DESC requests on index columns
  89694. */
  89695. if( pDb->pSchema->file_format>=4 ){
  89696. sortOrderMask = -1; /* Honor DESC */
  89697. }else{
  89698. sortOrderMask = 0; /* Ignore DESC */
  89699. }
  89700. /* Analyze the list of expressions that form the terms of the index and
  89701. ** report any errors. In the common case where the expression is exactly
  89702. ** a table column, store that column in aiColumn[]. For general expressions,
  89703. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  89704. **
  89705. ** TODO: Issue a warning if two or more columns of the index are identical.
  89706. ** TODO: Issue a warning if the table primary key is used as part of the
  89707. ** index key.
  89708. */
  89709. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  89710. Expr *pCExpr; /* The i-th index expression */
  89711. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  89712. char *zColl; /* Collation sequence name */
  89713. sqlite3StringToId(pListItem->pExpr);
  89714. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  89715. if( pParse->nErr ) goto exit_create_index;
  89716. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  89717. if( pCExpr->op!=TK_COLUMN ){
  89718. if( pTab==pParse->pNewTable ){
  89719. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  89720. "UNIQUE constraints");
  89721. goto exit_create_index;
  89722. }
  89723. if( pIndex->aColExpr==0 ){
  89724. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  89725. pIndex->aColExpr = pCopy;
  89726. if( !db->mallocFailed ){
  89727. assert( pCopy!=0 );
  89728. pListItem = &pCopy->a[i];
  89729. }
  89730. }
  89731. j = XN_EXPR;
  89732. pIndex->aiColumn[i] = XN_EXPR;
  89733. pIndex->uniqNotNull = 0;
  89734. }else{
  89735. j = pCExpr->iColumn;
  89736. assert( j<=0x7fff );
  89737. if( j<0 ){
  89738. j = pTab->iPKey;
  89739. }else if( pTab->aCol[j].notNull==0 ){
  89740. pIndex->uniqNotNull = 0;
  89741. }
  89742. pIndex->aiColumn[i] = (i16)j;
  89743. }
  89744. zColl = 0;
  89745. if( pListItem->pExpr->op==TK_COLLATE ){
  89746. int nColl;
  89747. zColl = pListItem->pExpr->u.zToken;
  89748. nColl = sqlite3Strlen30(zColl) + 1;
  89749. assert( nExtra>=nColl );
  89750. memcpy(zExtra, zColl, nColl);
  89751. zColl = zExtra;
  89752. zExtra += nColl;
  89753. nExtra -= nColl;
  89754. }else if( j>=0 ){
  89755. zColl = pTab->aCol[j].zColl;
  89756. }
  89757. if( !zColl ) zColl = "BINARY";
  89758. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  89759. goto exit_create_index;
  89760. }
  89761. pIndex->azColl[i] = zColl;
  89762. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  89763. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  89764. }
  89765. /* Append the table key to the end of the index. For WITHOUT ROWID
  89766. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  89767. ** normal tables (when pPk==0) this will be the rowid.
  89768. */
  89769. if( pPk ){
  89770. for(j=0; j<pPk->nKeyCol; j++){
  89771. int x = pPk->aiColumn[j];
  89772. assert( x>=0 );
  89773. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  89774. pIndex->nColumn--;
  89775. }else{
  89776. pIndex->aiColumn[i] = x;
  89777. pIndex->azColl[i] = pPk->azColl[j];
  89778. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  89779. i++;
  89780. }
  89781. }
  89782. assert( i==pIndex->nColumn );
  89783. }else{
  89784. pIndex->aiColumn[i] = XN_ROWID;
  89785. pIndex->azColl[i] = "BINARY";
  89786. }
  89787. sqlite3DefaultRowEst(pIndex);
  89788. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  89789. if( pTab==pParse->pNewTable ){
  89790. /* This routine has been called to create an automatic index as a
  89791. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  89792. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  89793. ** i.e. one of:
  89794. **
  89795. ** CREATE TABLE t(x PRIMARY KEY, y);
  89796. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  89797. **
  89798. ** Either way, check to see if the table already has such an index. If
  89799. ** so, don't bother creating this one. This only applies to
  89800. ** automatically created indices. Users can do as they wish with
  89801. ** explicit indices.
  89802. **
  89803. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  89804. ** (and thus suppressing the second one) even if they have different
  89805. ** sort orders.
  89806. **
  89807. ** If there are different collating sequences or if the columns of
  89808. ** the constraint occur in different orders, then the constraints are
  89809. ** considered distinct and both result in separate indices.
  89810. */
  89811. Index *pIdx;
  89812. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89813. int k;
  89814. assert( IsUniqueIndex(pIdx) );
  89815. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  89816. assert( IsUniqueIndex(pIndex) );
  89817. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  89818. for(k=0; k<pIdx->nKeyCol; k++){
  89819. const char *z1;
  89820. const char *z2;
  89821. assert( pIdx->aiColumn[k]>=0 );
  89822. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  89823. z1 = pIdx->azColl[k];
  89824. z2 = pIndex->azColl[k];
  89825. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  89826. }
  89827. if( k==pIdx->nKeyCol ){
  89828. if( pIdx->onError!=pIndex->onError ){
  89829. /* This constraint creates the same index as a previous
  89830. ** constraint specified somewhere in the CREATE TABLE statement.
  89831. ** However the ON CONFLICT clauses are different. If both this
  89832. ** constraint and the previous equivalent constraint have explicit
  89833. ** ON CONFLICT clauses this is an error. Otherwise, use the
  89834. ** explicitly specified behavior for the index.
  89835. */
  89836. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  89837. sqlite3ErrorMsg(pParse,
  89838. "conflicting ON CONFLICT clauses specified", 0);
  89839. }
  89840. if( pIdx->onError==OE_Default ){
  89841. pIdx->onError = pIndex->onError;
  89842. }
  89843. }
  89844. pRet = pIdx;
  89845. goto exit_create_index;
  89846. }
  89847. }
  89848. }
  89849. /* Link the new Index structure to its table and to the other
  89850. ** in-memory database structures.
  89851. */
  89852. assert( pParse->nErr==0 );
  89853. if( db->init.busy ){
  89854. Index *p;
  89855. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  89856. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  89857. pIndex->zName, pIndex);
  89858. if( p ){
  89859. assert( p==pIndex ); /* Malloc must have failed */
  89860. db->mallocFailed = 1;
  89861. goto exit_create_index;
  89862. }
  89863. db->flags |= SQLITE_InternChanges;
  89864. if( pTblName!=0 ){
  89865. pIndex->tnum = db->init.newTnum;
  89866. }
  89867. }
  89868. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  89869. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  89870. ** emit code to allocate the index rootpage on disk and make an entry for
  89871. ** the index in the sqlite_master table and populate the index with
  89872. ** content. But, do not do this if we are simply reading the sqlite_master
  89873. ** table to parse the schema, or if this index is the PRIMARY KEY index
  89874. ** of a WITHOUT ROWID table.
  89875. **
  89876. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  89877. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  89878. ** has just been created, it contains no data and the index initialization
  89879. ** step can be skipped.
  89880. */
  89881. else if( HasRowid(pTab) || pTblName!=0 ){
  89882. Vdbe *v;
  89883. char *zStmt;
  89884. int iMem = ++pParse->nMem;
  89885. v = sqlite3GetVdbe(pParse);
  89886. if( v==0 ) goto exit_create_index;
  89887. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89888. /* Create the rootpage for the index using CreateIndex. But before
  89889. ** doing so, code a Noop instruction and store its address in
  89890. ** Index.tnum. This is required in case this index is actually a
  89891. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  89892. ** that case the convertToWithoutRowidTable() routine will replace
  89893. ** the Noop with a Goto to jump over the VDBE code generated below. */
  89894. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  89895. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  89896. /* Gather the complete text of the CREATE INDEX statement into
  89897. ** the zStmt variable
  89898. */
  89899. if( pStart ){
  89900. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  89901. if( pName->z[n-1]==';' ) n--;
  89902. /* A named index with an explicit CREATE INDEX statement */
  89903. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  89904. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  89905. }else{
  89906. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  89907. /* zStmt = sqlite3MPrintf(""); */
  89908. zStmt = 0;
  89909. }
  89910. /* Add an entry in sqlite_master for this index
  89911. */
  89912. sqlite3NestedParse(pParse,
  89913. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  89914. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  89915. pIndex->zName,
  89916. pTab->zName,
  89917. iMem,
  89918. zStmt
  89919. );
  89920. sqlite3DbFree(db, zStmt);
  89921. /* Fill the index with data and reparse the schema. Code an OP_Expire
  89922. ** to invalidate all pre-compiled statements.
  89923. */
  89924. if( pTblName ){
  89925. sqlite3RefillIndex(pParse, pIndex, iMem);
  89926. sqlite3ChangeCookie(pParse, iDb);
  89927. sqlite3VdbeAddParseSchemaOp(v, iDb,
  89928. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  89929. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  89930. }
  89931. sqlite3VdbeJumpHere(v, pIndex->tnum);
  89932. }
  89933. /* When adding an index to the list of indices for a table, make
  89934. ** sure all indices labeled OE_Replace come after all those labeled
  89935. ** OE_Ignore. This is necessary for the correct constraint check
  89936. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  89937. ** UPDATE and INSERT statements.
  89938. */
  89939. if( db->init.busy || pTblName==0 ){
  89940. if( onError!=OE_Replace || pTab->pIndex==0
  89941. || pTab->pIndex->onError==OE_Replace){
  89942. pIndex->pNext = pTab->pIndex;
  89943. pTab->pIndex = pIndex;
  89944. }else{
  89945. Index *pOther = pTab->pIndex;
  89946. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  89947. pOther = pOther->pNext;
  89948. }
  89949. pIndex->pNext = pOther->pNext;
  89950. pOther->pNext = pIndex;
  89951. }
  89952. pRet = pIndex;
  89953. pIndex = 0;
  89954. }
  89955. /* Clean up before exiting */
  89956. exit_create_index:
  89957. if( pIndex ) freeIndex(db, pIndex);
  89958. sqlite3ExprDelete(db, pPIWhere);
  89959. sqlite3ExprListDelete(db, pList);
  89960. sqlite3SrcListDelete(db, pTblName);
  89961. sqlite3DbFree(db, zName);
  89962. return pRet;
  89963. }
  89964. /*
  89965. ** Fill the Index.aiRowEst[] array with default information - information
  89966. ** to be used when we have not run the ANALYZE command.
  89967. **
  89968. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  89969. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  89970. ** number of rows in the table that match any particular value of the
  89971. ** first column of the index. aiRowEst[2] is an estimate of the number
  89972. ** of rows that match any particular combination of the first 2 columns
  89973. ** of the index. And so forth. It must always be the case that
  89974. *
  89975. ** aiRowEst[N]<=aiRowEst[N-1]
  89976. ** aiRowEst[N]>=1
  89977. **
  89978. ** Apart from that, we have little to go on besides intuition as to
  89979. ** how aiRowEst[] should be initialized. The numbers generated here
  89980. ** are based on typical values found in actual indices.
  89981. */
  89982. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  89983. /* 10, 9, 8, 7, 6 */
  89984. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  89985. LogEst *a = pIdx->aiRowLogEst;
  89986. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  89987. int i;
  89988. /* Set the first entry (number of rows in the index) to the estimated
  89989. ** number of rows in the table. Or 10, if the estimated number of rows
  89990. ** in the table is less than that. */
  89991. a[0] = pIdx->pTable->nRowLogEst;
  89992. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  89993. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  89994. ** 6 and each subsequent value (if any) is 5. */
  89995. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  89996. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  89997. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  89998. }
  89999. assert( 0==sqlite3LogEst(1) );
  90000. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  90001. }
  90002. /*
  90003. ** This routine will drop an existing named index. This routine
  90004. ** implements the DROP INDEX statement.
  90005. */
  90006. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  90007. Index *pIndex;
  90008. Vdbe *v;
  90009. sqlite3 *db = pParse->db;
  90010. int iDb;
  90011. assert( pParse->nErr==0 ); /* Never called with prior errors */
  90012. if( db->mallocFailed ){
  90013. goto exit_drop_index;
  90014. }
  90015. assert( pName->nSrc==1 );
  90016. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  90017. goto exit_drop_index;
  90018. }
  90019. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  90020. if( pIndex==0 ){
  90021. if( !ifExists ){
  90022. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  90023. }else{
  90024. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  90025. }
  90026. pParse->checkSchema = 1;
  90027. goto exit_drop_index;
  90028. }
  90029. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  90030. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  90031. "or PRIMARY KEY constraint cannot be dropped", 0);
  90032. goto exit_drop_index;
  90033. }
  90034. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  90035. #ifndef SQLITE_OMIT_AUTHORIZATION
  90036. {
  90037. int code = SQLITE_DROP_INDEX;
  90038. Table *pTab = pIndex->pTable;
  90039. const char *zDb = db->aDb[iDb].zName;
  90040. const char *zTab = SCHEMA_TABLE(iDb);
  90041. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  90042. goto exit_drop_index;
  90043. }
  90044. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  90045. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  90046. goto exit_drop_index;
  90047. }
  90048. }
  90049. #endif
  90050. /* Generate code to remove the index and from the master table */
  90051. v = sqlite3GetVdbe(pParse);
  90052. if( v ){
  90053. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90054. sqlite3NestedParse(pParse,
  90055. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  90056. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  90057. );
  90058. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  90059. sqlite3ChangeCookie(pParse, iDb);
  90060. destroyRootPage(pParse, pIndex->tnum, iDb);
  90061. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  90062. }
  90063. exit_drop_index:
  90064. sqlite3SrcListDelete(db, pName);
  90065. }
  90066. /*
  90067. ** pArray is a pointer to an array of objects. Each object in the
  90068. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  90069. ** to extend the array so that there is space for a new object at the end.
  90070. **
  90071. ** When this function is called, *pnEntry contains the current size of
  90072. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  90073. ** in total).
  90074. **
  90075. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  90076. ** space allocated for the new object is zeroed, *pnEntry updated to
  90077. ** reflect the new size of the array and a pointer to the new allocation
  90078. ** returned. *pIdx is set to the index of the new array entry in this case.
  90079. **
  90080. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  90081. ** unchanged and a copy of pArray returned.
  90082. */
  90083. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  90084. sqlite3 *db, /* Connection to notify of malloc failures */
  90085. void *pArray, /* Array of objects. Might be reallocated */
  90086. int szEntry, /* Size of each object in the array */
  90087. int *pnEntry, /* Number of objects currently in use */
  90088. int *pIdx /* Write the index of a new slot here */
  90089. ){
  90090. char *z;
  90091. int n = *pnEntry;
  90092. if( (n & (n-1))==0 ){
  90093. int sz = (n==0) ? 1 : 2*n;
  90094. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  90095. if( pNew==0 ){
  90096. *pIdx = -1;
  90097. return pArray;
  90098. }
  90099. pArray = pNew;
  90100. }
  90101. z = (char*)pArray;
  90102. memset(&z[n * szEntry], 0, szEntry);
  90103. *pIdx = n;
  90104. ++*pnEntry;
  90105. return pArray;
  90106. }
  90107. /*
  90108. ** Append a new element to the given IdList. Create a new IdList if
  90109. ** need be.
  90110. **
  90111. ** A new IdList is returned, or NULL if malloc() fails.
  90112. */
  90113. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  90114. int i;
  90115. if( pList==0 ){
  90116. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  90117. if( pList==0 ) return 0;
  90118. }
  90119. pList->a = sqlite3ArrayAllocate(
  90120. db,
  90121. pList->a,
  90122. sizeof(pList->a[0]),
  90123. &pList->nId,
  90124. &i
  90125. );
  90126. if( i<0 ){
  90127. sqlite3IdListDelete(db, pList);
  90128. return 0;
  90129. }
  90130. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  90131. return pList;
  90132. }
  90133. /*
  90134. ** Delete an IdList.
  90135. */
  90136. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  90137. int i;
  90138. if( pList==0 ) return;
  90139. for(i=0; i<pList->nId; i++){
  90140. sqlite3DbFree(db, pList->a[i].zName);
  90141. }
  90142. sqlite3DbFree(db, pList->a);
  90143. sqlite3DbFree(db, pList);
  90144. }
  90145. /*
  90146. ** Return the index in pList of the identifier named zId. Return -1
  90147. ** if not found.
  90148. */
  90149. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  90150. int i;
  90151. if( pList==0 ) return -1;
  90152. for(i=0; i<pList->nId; i++){
  90153. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  90154. }
  90155. return -1;
  90156. }
  90157. /*
  90158. ** Expand the space allocated for the given SrcList object by
  90159. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  90160. ** New slots are zeroed.
  90161. **
  90162. ** For example, suppose a SrcList initially contains two entries: A,B.
  90163. ** To append 3 new entries onto the end, do this:
  90164. **
  90165. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  90166. **
  90167. ** After the call above it would contain: A, B, nil, nil, nil.
  90168. ** If the iStart argument had been 1 instead of 2, then the result
  90169. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  90170. ** the iStart value would be 0. The result then would
  90171. ** be: nil, nil, nil, A, B.
  90172. **
  90173. ** If a memory allocation fails the SrcList is unchanged. The
  90174. ** db->mallocFailed flag will be set to true.
  90175. */
  90176. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  90177. sqlite3 *db, /* Database connection to notify of OOM errors */
  90178. SrcList *pSrc, /* The SrcList to be enlarged */
  90179. int nExtra, /* Number of new slots to add to pSrc->a[] */
  90180. int iStart /* Index in pSrc->a[] of first new slot */
  90181. ){
  90182. int i;
  90183. /* Sanity checking on calling parameters */
  90184. assert( iStart>=0 );
  90185. assert( nExtra>=1 );
  90186. assert( pSrc!=0 );
  90187. assert( iStart<=pSrc->nSrc );
  90188. /* Allocate additional space if needed */
  90189. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  90190. SrcList *pNew;
  90191. int nAlloc = pSrc->nSrc+nExtra;
  90192. int nGot;
  90193. pNew = sqlite3DbRealloc(db, pSrc,
  90194. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  90195. if( pNew==0 ){
  90196. assert( db->mallocFailed );
  90197. return pSrc;
  90198. }
  90199. pSrc = pNew;
  90200. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  90201. pSrc->nAlloc = nGot;
  90202. }
  90203. /* Move existing slots that come after the newly inserted slots
  90204. ** out of the way */
  90205. for(i=pSrc->nSrc-1; i>=iStart; i--){
  90206. pSrc->a[i+nExtra] = pSrc->a[i];
  90207. }
  90208. pSrc->nSrc += nExtra;
  90209. /* Zero the newly allocated slots */
  90210. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  90211. for(i=iStart; i<iStart+nExtra; i++){
  90212. pSrc->a[i].iCursor = -1;
  90213. }
  90214. /* Return a pointer to the enlarged SrcList */
  90215. return pSrc;
  90216. }
  90217. /*
  90218. ** Append a new table name to the given SrcList. Create a new SrcList if
  90219. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  90220. **
  90221. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  90222. ** SrcList might be the same as the SrcList that was input or it might be
  90223. ** a new one. If an OOM error does occurs, then the prior value of pList
  90224. ** that is input to this routine is automatically freed.
  90225. **
  90226. ** If pDatabase is not null, it means that the table has an optional
  90227. ** database name prefix. Like this: "database.table". The pDatabase
  90228. ** points to the table name and the pTable points to the database name.
  90229. ** The SrcList.a[].zName field is filled with the table name which might
  90230. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  90231. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  90232. ** or with NULL if no database is specified.
  90233. **
  90234. ** In other words, if call like this:
  90235. **
  90236. ** sqlite3SrcListAppend(D,A,B,0);
  90237. **
  90238. ** Then B is a table name and the database name is unspecified. If called
  90239. ** like this:
  90240. **
  90241. ** sqlite3SrcListAppend(D,A,B,C);
  90242. **
  90243. ** Then C is the table name and B is the database name. If C is defined
  90244. ** then so is B. In other words, we never have a case where:
  90245. **
  90246. ** sqlite3SrcListAppend(D,A,0,C);
  90247. **
  90248. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  90249. ** before being added to the SrcList.
  90250. */
  90251. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  90252. sqlite3 *db, /* Connection to notify of malloc failures */
  90253. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  90254. Token *pTable, /* Table to append */
  90255. Token *pDatabase /* Database of the table */
  90256. ){
  90257. struct SrcList_item *pItem;
  90258. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  90259. if( pList==0 ){
  90260. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  90261. if( pList==0 ) return 0;
  90262. pList->nAlloc = 1;
  90263. }
  90264. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  90265. if( db->mallocFailed ){
  90266. sqlite3SrcListDelete(db, pList);
  90267. return 0;
  90268. }
  90269. pItem = &pList->a[pList->nSrc-1];
  90270. if( pDatabase && pDatabase->z==0 ){
  90271. pDatabase = 0;
  90272. }
  90273. if( pDatabase ){
  90274. Token *pTemp = pDatabase;
  90275. pDatabase = pTable;
  90276. pTable = pTemp;
  90277. }
  90278. pItem->zName = sqlite3NameFromToken(db, pTable);
  90279. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  90280. return pList;
  90281. }
  90282. /*
  90283. ** Assign VdbeCursor index numbers to all tables in a SrcList
  90284. */
  90285. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  90286. int i;
  90287. struct SrcList_item *pItem;
  90288. assert(pList || pParse->db->mallocFailed );
  90289. if( pList ){
  90290. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  90291. if( pItem->iCursor>=0 ) break;
  90292. pItem->iCursor = pParse->nTab++;
  90293. if( pItem->pSelect ){
  90294. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  90295. }
  90296. }
  90297. }
  90298. }
  90299. /*
  90300. ** Delete an entire SrcList including all its substructure.
  90301. */
  90302. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  90303. int i;
  90304. struct SrcList_item *pItem;
  90305. if( pList==0 ) return;
  90306. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  90307. sqlite3DbFree(db, pItem->zDatabase);
  90308. sqlite3DbFree(db, pItem->zName);
  90309. sqlite3DbFree(db, pItem->zAlias);
  90310. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  90311. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  90312. sqlite3DeleteTable(db, pItem->pTab);
  90313. sqlite3SelectDelete(db, pItem->pSelect);
  90314. sqlite3ExprDelete(db, pItem->pOn);
  90315. sqlite3IdListDelete(db, pItem->pUsing);
  90316. }
  90317. sqlite3DbFree(db, pList);
  90318. }
  90319. /*
  90320. ** This routine is called by the parser to add a new term to the
  90321. ** end of a growing FROM clause. The "p" parameter is the part of
  90322. ** the FROM clause that has already been constructed. "p" is NULL
  90323. ** if this is the first term of the FROM clause. pTable and pDatabase
  90324. ** are the name of the table and database named in the FROM clause term.
  90325. ** pDatabase is NULL if the database name qualifier is missing - the
  90326. ** usual case. If the term has an alias, then pAlias points to the
  90327. ** alias token. If the term is a subquery, then pSubquery is the
  90328. ** SELECT statement that the subquery encodes. The pTable and
  90329. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  90330. ** parameters are the content of the ON and USING clauses.
  90331. **
  90332. ** Return a new SrcList which encodes is the FROM with the new
  90333. ** term added.
  90334. */
  90335. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  90336. Parse *pParse, /* Parsing context */
  90337. SrcList *p, /* The left part of the FROM clause already seen */
  90338. Token *pTable, /* Name of the table to add to the FROM clause */
  90339. Token *pDatabase, /* Name of the database containing pTable */
  90340. Token *pAlias, /* The right-hand side of the AS subexpression */
  90341. Select *pSubquery, /* A subquery used in place of a table name */
  90342. Expr *pOn, /* The ON clause of a join */
  90343. IdList *pUsing /* The USING clause of a join */
  90344. ){
  90345. struct SrcList_item *pItem;
  90346. sqlite3 *db = pParse->db;
  90347. if( !p && (pOn || pUsing) ){
  90348. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  90349. (pOn ? "ON" : "USING")
  90350. );
  90351. goto append_from_error;
  90352. }
  90353. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  90354. if( p==0 || NEVER(p->nSrc==0) ){
  90355. goto append_from_error;
  90356. }
  90357. pItem = &p->a[p->nSrc-1];
  90358. assert( pAlias!=0 );
  90359. if( pAlias->n ){
  90360. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  90361. }
  90362. pItem->pSelect = pSubquery;
  90363. pItem->pOn = pOn;
  90364. pItem->pUsing = pUsing;
  90365. return p;
  90366. append_from_error:
  90367. assert( p==0 );
  90368. sqlite3ExprDelete(db, pOn);
  90369. sqlite3IdListDelete(db, pUsing);
  90370. sqlite3SelectDelete(db, pSubquery);
  90371. return 0;
  90372. }
  90373. /*
  90374. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  90375. ** element of the source-list passed as the second argument.
  90376. */
  90377. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  90378. assert( pIndexedBy!=0 );
  90379. if( p && ALWAYS(p->nSrc>0) ){
  90380. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  90381. assert( pItem->fg.notIndexed==0 );
  90382. assert( pItem->fg.isIndexedBy==0 );
  90383. assert( pItem->fg.isTabFunc==0 );
  90384. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  90385. /* A "NOT INDEXED" clause was supplied. See parse.y
  90386. ** construct "indexed_opt" for details. */
  90387. pItem->fg.notIndexed = 1;
  90388. }else{
  90389. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  90390. pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
  90391. }
  90392. }
  90393. }
  90394. /*
  90395. ** Add the list of function arguments to the SrcList entry for a
  90396. ** table-valued-function.
  90397. */
  90398. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  90399. if( p && pList ){
  90400. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  90401. assert( pItem->fg.notIndexed==0 );
  90402. assert( pItem->fg.isIndexedBy==0 );
  90403. assert( pItem->fg.isTabFunc==0 );
  90404. pItem->u1.pFuncArg = pList;
  90405. pItem->fg.isTabFunc = 1;
  90406. }else{
  90407. sqlite3ExprListDelete(pParse->db, pList);
  90408. }
  90409. }
  90410. /*
  90411. ** When building up a FROM clause in the parser, the join operator
  90412. ** is initially attached to the left operand. But the code generator
  90413. ** expects the join operator to be on the right operand. This routine
  90414. ** Shifts all join operators from left to right for an entire FROM
  90415. ** clause.
  90416. **
  90417. ** Example: Suppose the join is like this:
  90418. **
  90419. ** A natural cross join B
  90420. **
  90421. ** The operator is "natural cross join". The A and B operands are stored
  90422. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  90423. ** operator with A. This routine shifts that operator over to B.
  90424. */
  90425. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  90426. if( p ){
  90427. int i;
  90428. for(i=p->nSrc-1; i>0; i--){
  90429. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  90430. }
  90431. p->a[0].fg.jointype = 0;
  90432. }
  90433. }
  90434. /*
  90435. ** Begin a transaction
  90436. */
  90437. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  90438. sqlite3 *db;
  90439. Vdbe *v;
  90440. int i;
  90441. assert( pParse!=0 );
  90442. db = pParse->db;
  90443. assert( db!=0 );
  90444. /* if( db->aDb[0].pBt==0 ) return; */
  90445. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  90446. return;
  90447. }
  90448. v = sqlite3GetVdbe(pParse);
  90449. if( !v ) return;
  90450. if( type!=TK_DEFERRED ){
  90451. for(i=0; i<db->nDb; i++){
  90452. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  90453. sqlite3VdbeUsesBtree(v, i);
  90454. }
  90455. }
  90456. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  90457. }
  90458. /*
  90459. ** Commit a transaction
  90460. */
  90461. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  90462. Vdbe *v;
  90463. assert( pParse!=0 );
  90464. assert( pParse->db!=0 );
  90465. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  90466. return;
  90467. }
  90468. v = sqlite3GetVdbe(pParse);
  90469. if( v ){
  90470. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  90471. }
  90472. }
  90473. /*
  90474. ** Rollback a transaction
  90475. */
  90476. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  90477. Vdbe *v;
  90478. assert( pParse!=0 );
  90479. assert( pParse->db!=0 );
  90480. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  90481. return;
  90482. }
  90483. v = sqlite3GetVdbe(pParse);
  90484. if( v ){
  90485. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  90486. }
  90487. }
  90488. /*
  90489. ** This function is called by the parser when it parses a command to create,
  90490. ** release or rollback an SQL savepoint.
  90491. */
  90492. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  90493. char *zName = sqlite3NameFromToken(pParse->db, pName);
  90494. if( zName ){
  90495. Vdbe *v = sqlite3GetVdbe(pParse);
  90496. #ifndef SQLITE_OMIT_AUTHORIZATION
  90497. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  90498. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  90499. #endif
  90500. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  90501. sqlite3DbFree(pParse->db, zName);
  90502. return;
  90503. }
  90504. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  90505. }
  90506. }
  90507. /*
  90508. ** Make sure the TEMP database is open and available for use. Return
  90509. ** the number of errors. Leave any error messages in the pParse structure.
  90510. */
  90511. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  90512. sqlite3 *db = pParse->db;
  90513. if( db->aDb[1].pBt==0 && !pParse->explain ){
  90514. int rc;
  90515. Btree *pBt;
  90516. static const int flags =
  90517. SQLITE_OPEN_READWRITE |
  90518. SQLITE_OPEN_CREATE |
  90519. SQLITE_OPEN_EXCLUSIVE |
  90520. SQLITE_OPEN_DELETEONCLOSE |
  90521. SQLITE_OPEN_TEMP_DB;
  90522. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  90523. if( rc!=SQLITE_OK ){
  90524. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  90525. "file for storing temporary tables");
  90526. pParse->rc = rc;
  90527. return 1;
  90528. }
  90529. db->aDb[1].pBt = pBt;
  90530. assert( db->aDb[1].pSchema );
  90531. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  90532. db->mallocFailed = 1;
  90533. return 1;
  90534. }
  90535. }
  90536. return 0;
  90537. }
  90538. /*
  90539. ** Record the fact that the schema cookie will need to be verified
  90540. ** for database iDb. The code to actually verify the schema cookie
  90541. ** will occur at the end of the top-level VDBE and will be generated
  90542. ** later, by sqlite3FinishCoding().
  90543. */
  90544. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  90545. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90546. sqlite3 *db = pToplevel->db;
  90547. assert( iDb>=0 && iDb<db->nDb );
  90548. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  90549. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  90550. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90551. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  90552. DbMaskSet(pToplevel->cookieMask, iDb);
  90553. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  90554. if( !OMIT_TEMPDB && iDb==1 ){
  90555. sqlite3OpenTempDatabase(pToplevel);
  90556. }
  90557. }
  90558. }
  90559. /*
  90560. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  90561. ** attached database. Otherwise, invoke it for the database named zDb only.
  90562. */
  90563. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  90564. sqlite3 *db = pParse->db;
  90565. int i;
  90566. for(i=0; i<db->nDb; i++){
  90567. Db *pDb = &db->aDb[i];
  90568. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  90569. sqlite3CodeVerifySchema(pParse, i);
  90570. }
  90571. }
  90572. }
  90573. /*
  90574. ** Generate VDBE code that prepares for doing an operation that
  90575. ** might change the database.
  90576. **
  90577. ** This routine starts a new transaction if we are not already within
  90578. ** a transaction. If we are already within a transaction, then a checkpoint
  90579. ** is set if the setStatement parameter is true. A checkpoint should
  90580. ** be set for operations that might fail (due to a constraint) part of
  90581. ** the way through and which will need to undo some writes without having to
  90582. ** rollback the whole transaction. For operations where all constraints
  90583. ** can be checked before any changes are made to the database, it is never
  90584. ** necessary to undo a write and the checkpoint should not be set.
  90585. */
  90586. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  90587. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90588. sqlite3CodeVerifySchema(pParse, iDb);
  90589. DbMaskSet(pToplevel->writeMask, iDb);
  90590. pToplevel->isMultiWrite |= setStatement;
  90591. }
  90592. /*
  90593. ** Indicate that the statement currently under construction might write
  90594. ** more than one entry (example: deleting one row then inserting another,
  90595. ** inserting multiple rows in a table, or inserting a row and index entries.)
  90596. ** If an abort occurs after some of these writes have completed, then it will
  90597. ** be necessary to undo the completed writes.
  90598. */
  90599. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  90600. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90601. pToplevel->isMultiWrite = 1;
  90602. }
  90603. /*
  90604. ** The code generator calls this routine if is discovers that it is
  90605. ** possible to abort a statement prior to completion. In order to
  90606. ** perform this abort without corrupting the database, we need to make
  90607. ** sure that the statement is protected by a statement transaction.
  90608. **
  90609. ** Technically, we only need to set the mayAbort flag if the
  90610. ** isMultiWrite flag was previously set. There is a time dependency
  90611. ** such that the abort must occur after the multiwrite. This makes
  90612. ** some statements involving the REPLACE conflict resolution algorithm
  90613. ** go a little faster. But taking advantage of this time dependency
  90614. ** makes it more difficult to prove that the code is correct (in
  90615. ** particular, it prevents us from writing an effective
  90616. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  90617. ** to take the safe route and skip the optimization.
  90618. */
  90619. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  90620. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90621. pToplevel->mayAbort = 1;
  90622. }
  90623. /*
  90624. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  90625. ** error. The onError parameter determines which (if any) of the statement
  90626. ** and/or current transaction is rolled back.
  90627. */
  90628. SQLITE_PRIVATE void sqlite3HaltConstraint(
  90629. Parse *pParse, /* Parsing context */
  90630. int errCode, /* extended error code */
  90631. int onError, /* Constraint type */
  90632. char *p4, /* Error message */
  90633. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  90634. u8 p5Errmsg /* P5_ErrMsg type */
  90635. ){
  90636. Vdbe *v = sqlite3GetVdbe(pParse);
  90637. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  90638. if( onError==OE_Abort ){
  90639. sqlite3MayAbort(pParse);
  90640. }
  90641. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  90642. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  90643. }
  90644. /*
  90645. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  90646. */
  90647. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  90648. Parse *pParse, /* Parsing context */
  90649. int onError, /* Constraint type */
  90650. Index *pIdx /* The index that triggers the constraint */
  90651. ){
  90652. char *zErr;
  90653. int j;
  90654. StrAccum errMsg;
  90655. Table *pTab = pIdx->pTable;
  90656. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  90657. if( pIdx->aColExpr ){
  90658. sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
  90659. }else{
  90660. for(j=0; j<pIdx->nKeyCol; j++){
  90661. char *zCol;
  90662. assert( pIdx->aiColumn[j]>=0 );
  90663. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  90664. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  90665. sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
  90666. }
  90667. }
  90668. zErr = sqlite3StrAccumFinish(&errMsg);
  90669. sqlite3HaltConstraint(pParse,
  90670. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  90671. : SQLITE_CONSTRAINT_UNIQUE,
  90672. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  90673. }
  90674. /*
  90675. ** Code an OP_Halt due to non-unique rowid.
  90676. */
  90677. SQLITE_PRIVATE void sqlite3RowidConstraint(
  90678. Parse *pParse, /* Parsing context */
  90679. int onError, /* Conflict resolution algorithm */
  90680. Table *pTab /* The table with the non-unique rowid */
  90681. ){
  90682. char *zMsg;
  90683. int rc;
  90684. if( pTab->iPKey>=0 ){
  90685. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  90686. pTab->aCol[pTab->iPKey].zName);
  90687. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  90688. }else{
  90689. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  90690. rc = SQLITE_CONSTRAINT_ROWID;
  90691. }
  90692. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  90693. P5_ConstraintUnique);
  90694. }
  90695. /*
  90696. ** Check to see if pIndex uses the collating sequence pColl. Return
  90697. ** true if it does and false if it does not.
  90698. */
  90699. #ifndef SQLITE_OMIT_REINDEX
  90700. static int collationMatch(const char *zColl, Index *pIndex){
  90701. int i;
  90702. assert( zColl!=0 );
  90703. for(i=0; i<pIndex->nColumn; i++){
  90704. const char *z = pIndex->azColl[i];
  90705. assert( z!=0 || pIndex->aiColumn[i]<0 );
  90706. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  90707. return 1;
  90708. }
  90709. }
  90710. return 0;
  90711. }
  90712. #endif
  90713. /*
  90714. ** Recompute all indices of pTab that use the collating sequence pColl.
  90715. ** If pColl==0 then recompute all indices of pTab.
  90716. */
  90717. #ifndef SQLITE_OMIT_REINDEX
  90718. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  90719. Index *pIndex; /* An index associated with pTab */
  90720. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  90721. if( zColl==0 || collationMatch(zColl, pIndex) ){
  90722. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90723. sqlite3BeginWriteOperation(pParse, 0, iDb);
  90724. sqlite3RefillIndex(pParse, pIndex, -1);
  90725. }
  90726. }
  90727. }
  90728. #endif
  90729. /*
  90730. ** Recompute all indices of all tables in all databases where the
  90731. ** indices use the collating sequence pColl. If pColl==0 then recompute
  90732. ** all indices everywhere.
  90733. */
  90734. #ifndef SQLITE_OMIT_REINDEX
  90735. static void reindexDatabases(Parse *pParse, char const *zColl){
  90736. Db *pDb; /* A single database */
  90737. int iDb; /* The database index number */
  90738. sqlite3 *db = pParse->db; /* The database connection */
  90739. HashElem *k; /* For looping over tables in pDb */
  90740. Table *pTab; /* A table in the database */
  90741. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  90742. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  90743. assert( pDb!=0 );
  90744. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  90745. pTab = (Table*)sqliteHashData(k);
  90746. reindexTable(pParse, pTab, zColl);
  90747. }
  90748. }
  90749. }
  90750. #endif
  90751. /*
  90752. ** Generate code for the REINDEX command.
  90753. **
  90754. ** REINDEX -- 1
  90755. ** REINDEX <collation> -- 2
  90756. ** REINDEX ?<database>.?<tablename> -- 3
  90757. ** REINDEX ?<database>.?<indexname> -- 4
  90758. **
  90759. ** Form 1 causes all indices in all attached databases to be rebuilt.
  90760. ** Form 2 rebuilds all indices in all databases that use the named
  90761. ** collating function. Forms 3 and 4 rebuild the named index or all
  90762. ** indices associated with the named table.
  90763. */
  90764. #ifndef SQLITE_OMIT_REINDEX
  90765. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  90766. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  90767. char *z; /* Name of a table or index */
  90768. const char *zDb; /* Name of the database */
  90769. Table *pTab; /* A table in the database */
  90770. Index *pIndex; /* An index associated with pTab */
  90771. int iDb; /* The database index number */
  90772. sqlite3 *db = pParse->db; /* The database connection */
  90773. Token *pObjName; /* Name of the table or index to be reindexed */
  90774. /* Read the database schema. If an error occurs, leave an error message
  90775. ** and code in pParse and return NULL. */
  90776. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  90777. return;
  90778. }
  90779. if( pName1==0 ){
  90780. reindexDatabases(pParse, 0);
  90781. return;
  90782. }else if( NEVER(pName2==0) || pName2->z==0 ){
  90783. char *zColl;
  90784. assert( pName1->z );
  90785. zColl = sqlite3NameFromToken(pParse->db, pName1);
  90786. if( !zColl ) return;
  90787. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  90788. if( pColl ){
  90789. reindexDatabases(pParse, zColl);
  90790. sqlite3DbFree(db, zColl);
  90791. return;
  90792. }
  90793. sqlite3DbFree(db, zColl);
  90794. }
  90795. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  90796. if( iDb<0 ) return;
  90797. z = sqlite3NameFromToken(db, pObjName);
  90798. if( z==0 ) return;
  90799. zDb = db->aDb[iDb].zName;
  90800. pTab = sqlite3FindTable(db, z, zDb);
  90801. if( pTab ){
  90802. reindexTable(pParse, pTab, 0);
  90803. sqlite3DbFree(db, z);
  90804. return;
  90805. }
  90806. pIndex = sqlite3FindIndex(db, z, zDb);
  90807. sqlite3DbFree(db, z);
  90808. if( pIndex ){
  90809. sqlite3BeginWriteOperation(pParse, 0, iDb);
  90810. sqlite3RefillIndex(pParse, pIndex, -1);
  90811. return;
  90812. }
  90813. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  90814. }
  90815. #endif
  90816. /*
  90817. ** Return a KeyInfo structure that is appropriate for the given Index.
  90818. **
  90819. ** The KeyInfo structure for an index is cached in the Index object.
  90820. ** So there might be multiple references to the returned pointer. The
  90821. ** caller should not try to modify the KeyInfo object.
  90822. **
  90823. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  90824. ** when it has finished using it.
  90825. */
  90826. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  90827. int i;
  90828. int nCol = pIdx->nColumn;
  90829. int nKey = pIdx->nKeyCol;
  90830. KeyInfo *pKey;
  90831. if( pParse->nErr ) return 0;
  90832. if( pIdx->uniqNotNull ){
  90833. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  90834. }else{
  90835. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  90836. }
  90837. if( pKey ){
  90838. assert( sqlite3KeyInfoIsWriteable(pKey) );
  90839. for(i=0; i<nCol; i++){
  90840. char *zColl = pIdx->azColl[i];
  90841. assert( zColl!=0 );
  90842. pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
  90843. sqlite3LocateCollSeq(pParse, zColl);
  90844. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  90845. }
  90846. if( pParse->nErr ){
  90847. sqlite3KeyInfoUnref(pKey);
  90848. pKey = 0;
  90849. }
  90850. }
  90851. return pKey;
  90852. }
  90853. #ifndef SQLITE_OMIT_CTE
  90854. /*
  90855. ** This routine is invoked once per CTE by the parser while parsing a
  90856. ** WITH clause.
  90857. */
  90858. SQLITE_PRIVATE With *sqlite3WithAdd(
  90859. Parse *pParse, /* Parsing context */
  90860. With *pWith, /* Existing WITH clause, or NULL */
  90861. Token *pName, /* Name of the common-table */
  90862. ExprList *pArglist, /* Optional column name list for the table */
  90863. Select *pQuery /* Query used to initialize the table */
  90864. ){
  90865. sqlite3 *db = pParse->db;
  90866. With *pNew;
  90867. char *zName;
  90868. /* Check that the CTE name is unique within this WITH clause. If
  90869. ** not, store an error in the Parse structure. */
  90870. zName = sqlite3NameFromToken(pParse->db, pName);
  90871. if( zName && pWith ){
  90872. int i;
  90873. for(i=0; i<pWith->nCte; i++){
  90874. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  90875. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  90876. }
  90877. }
  90878. }
  90879. if( pWith ){
  90880. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  90881. pNew = sqlite3DbRealloc(db, pWith, nByte);
  90882. }else{
  90883. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  90884. }
  90885. assert( zName!=0 || pNew==0 );
  90886. assert( db->mallocFailed==0 || pNew==0 );
  90887. if( pNew==0 ){
  90888. sqlite3ExprListDelete(db, pArglist);
  90889. sqlite3SelectDelete(db, pQuery);
  90890. sqlite3DbFree(db, zName);
  90891. pNew = pWith;
  90892. }else{
  90893. pNew->a[pNew->nCte].pSelect = pQuery;
  90894. pNew->a[pNew->nCte].pCols = pArglist;
  90895. pNew->a[pNew->nCte].zName = zName;
  90896. pNew->a[pNew->nCte].zCteErr = 0;
  90897. pNew->nCte++;
  90898. }
  90899. return pNew;
  90900. }
  90901. /*
  90902. ** Free the contents of the With object passed as the second argument.
  90903. */
  90904. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  90905. if( pWith ){
  90906. int i;
  90907. for(i=0; i<pWith->nCte; i++){
  90908. struct Cte *pCte = &pWith->a[i];
  90909. sqlite3ExprListDelete(db, pCte->pCols);
  90910. sqlite3SelectDelete(db, pCte->pSelect);
  90911. sqlite3DbFree(db, pCte->zName);
  90912. }
  90913. sqlite3DbFree(db, pWith);
  90914. }
  90915. }
  90916. #endif /* !defined(SQLITE_OMIT_CTE) */
  90917. /************** End of build.c ***********************************************/
  90918. /************** Begin file callback.c ****************************************/
  90919. /*
  90920. ** 2005 May 23
  90921. **
  90922. ** The author disclaims copyright to this source code. In place of
  90923. ** a legal notice, here is a blessing:
  90924. **
  90925. ** May you do good and not evil.
  90926. ** May you find forgiveness for yourself and forgive others.
  90927. ** May you share freely, never taking more than you give.
  90928. **
  90929. *************************************************************************
  90930. **
  90931. ** This file contains functions used to access the internal hash tables
  90932. ** of user defined functions and collation sequences.
  90933. */
  90934. /* #include "sqliteInt.h" */
  90935. /*
  90936. ** Invoke the 'collation needed' callback to request a collation sequence
  90937. ** in the encoding enc of name zName, length nName.
  90938. */
  90939. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  90940. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  90941. if( db->xCollNeeded ){
  90942. char *zExternal = sqlite3DbStrDup(db, zName);
  90943. if( !zExternal ) return;
  90944. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  90945. sqlite3DbFree(db, zExternal);
  90946. }
  90947. #ifndef SQLITE_OMIT_UTF16
  90948. if( db->xCollNeeded16 ){
  90949. char const *zExternal;
  90950. sqlite3_value *pTmp = sqlite3ValueNew(db);
  90951. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  90952. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  90953. if( zExternal ){
  90954. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  90955. }
  90956. sqlite3ValueFree(pTmp);
  90957. }
  90958. #endif
  90959. }
  90960. /*
  90961. ** This routine is called if the collation factory fails to deliver a
  90962. ** collation function in the best encoding but there may be other versions
  90963. ** of this collation function (for other text encodings) available. Use one
  90964. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  90965. ** possible.
  90966. */
  90967. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  90968. CollSeq *pColl2;
  90969. char *z = pColl->zName;
  90970. int i;
  90971. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  90972. for(i=0; i<3; i++){
  90973. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  90974. if( pColl2->xCmp!=0 ){
  90975. memcpy(pColl, pColl2, sizeof(CollSeq));
  90976. pColl->xDel = 0; /* Do not copy the destructor */
  90977. return SQLITE_OK;
  90978. }
  90979. }
  90980. return SQLITE_ERROR;
  90981. }
  90982. /*
  90983. ** This function is responsible for invoking the collation factory callback
  90984. ** or substituting a collation sequence of a different encoding when the
  90985. ** requested collation sequence is not available in the desired encoding.
  90986. **
  90987. ** If it is not NULL, then pColl must point to the database native encoding
  90988. ** collation sequence with name zName, length nName.
  90989. **
  90990. ** The return value is either the collation sequence to be used in database
  90991. ** db for collation type name zName, length nName, or NULL, if no collation
  90992. ** sequence can be found. If no collation is found, leave an error message.
  90993. **
  90994. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  90995. */
  90996. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  90997. Parse *pParse, /* Parsing context */
  90998. u8 enc, /* The desired encoding for the collating sequence */
  90999. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  91000. const char *zName /* Collating sequence name */
  91001. ){
  91002. CollSeq *p;
  91003. sqlite3 *db = pParse->db;
  91004. p = pColl;
  91005. if( !p ){
  91006. p = sqlite3FindCollSeq(db, enc, zName, 0);
  91007. }
  91008. if( !p || !p->xCmp ){
  91009. /* No collation sequence of this type for this encoding is registered.
  91010. ** Call the collation factory to see if it can supply us with one.
  91011. */
  91012. callCollNeeded(db, enc, zName);
  91013. p = sqlite3FindCollSeq(db, enc, zName, 0);
  91014. }
  91015. if( p && !p->xCmp && synthCollSeq(db, p) ){
  91016. p = 0;
  91017. }
  91018. assert( !p || p->xCmp );
  91019. if( p==0 ){
  91020. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  91021. }
  91022. return p;
  91023. }
  91024. /*
  91025. ** This routine is called on a collation sequence before it is used to
  91026. ** check that it is defined. An undefined collation sequence exists when
  91027. ** a database is loaded that contains references to collation sequences
  91028. ** that have not been defined by sqlite3_create_collation() etc.
  91029. **
  91030. ** If required, this routine calls the 'collation needed' callback to
  91031. ** request a definition of the collating sequence. If this doesn't work,
  91032. ** an equivalent collating sequence that uses a text encoding different
  91033. ** from the main database is substituted, if one is available.
  91034. */
  91035. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  91036. if( pColl ){
  91037. const char *zName = pColl->zName;
  91038. sqlite3 *db = pParse->db;
  91039. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  91040. if( !p ){
  91041. return SQLITE_ERROR;
  91042. }
  91043. assert( p==pColl );
  91044. }
  91045. return SQLITE_OK;
  91046. }
  91047. /*
  91048. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  91049. ** specified by zName and nName is not found and parameter 'create' is
  91050. ** true, then create a new entry. Otherwise return NULL.
  91051. **
  91052. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  91053. ** array of three CollSeq structures. The first is the collation sequence
  91054. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  91055. **
  91056. ** Stored immediately after the three collation sequences is a copy of
  91057. ** the collation sequence name. A pointer to this string is stored in
  91058. ** each collation sequence structure.
  91059. */
  91060. static CollSeq *findCollSeqEntry(
  91061. sqlite3 *db, /* Database connection */
  91062. const char *zName, /* Name of the collating sequence */
  91063. int create /* Create a new entry if true */
  91064. ){
  91065. CollSeq *pColl;
  91066. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  91067. if( 0==pColl && create ){
  91068. int nName = sqlite3Strlen30(zName);
  91069. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  91070. if( pColl ){
  91071. CollSeq *pDel = 0;
  91072. pColl[0].zName = (char*)&pColl[3];
  91073. pColl[0].enc = SQLITE_UTF8;
  91074. pColl[1].zName = (char*)&pColl[3];
  91075. pColl[1].enc = SQLITE_UTF16LE;
  91076. pColl[2].zName = (char*)&pColl[3];
  91077. pColl[2].enc = SQLITE_UTF16BE;
  91078. memcpy(pColl[0].zName, zName, nName);
  91079. pColl[0].zName[nName] = 0;
  91080. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  91081. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  91082. ** return the pColl pointer to be deleted (because it wasn't added
  91083. ** to the hash table).
  91084. */
  91085. assert( pDel==0 || pDel==pColl );
  91086. if( pDel!=0 ){
  91087. db->mallocFailed = 1;
  91088. sqlite3DbFree(db, pDel);
  91089. pColl = 0;
  91090. }
  91091. }
  91092. }
  91093. return pColl;
  91094. }
  91095. /*
  91096. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  91097. ** Return the CollSeq* pointer for the collation sequence named zName
  91098. ** for the encoding 'enc' from the database 'db'.
  91099. **
  91100. ** If the entry specified is not found and 'create' is true, then create a
  91101. ** new entry. Otherwise return NULL.
  91102. **
  91103. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  91104. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  91105. ** if necessary and generates an error message if the collating sequence
  91106. ** cannot be found.
  91107. **
  91108. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  91109. */
  91110. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  91111. sqlite3 *db,
  91112. u8 enc,
  91113. const char *zName,
  91114. int create
  91115. ){
  91116. CollSeq *pColl;
  91117. if( zName ){
  91118. pColl = findCollSeqEntry(db, zName, create);
  91119. }else{
  91120. pColl = db->pDfltColl;
  91121. }
  91122. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  91123. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  91124. if( pColl ) pColl += enc-1;
  91125. return pColl;
  91126. }
  91127. /* During the search for the best function definition, this procedure
  91128. ** is called to test how well the function passed as the first argument
  91129. ** matches the request for a function with nArg arguments in a system
  91130. ** that uses encoding enc. The value returned indicates how well the
  91131. ** request is matched. A higher value indicates a better match.
  91132. **
  91133. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  91134. ** is also -1. In other words, we are searching for a function that
  91135. ** takes a variable number of arguments.
  91136. **
  91137. ** If nArg is -2 that means that we are searching for any function
  91138. ** regardless of the number of arguments it uses, so return a positive
  91139. ** match score for any
  91140. **
  91141. ** The returned value is always between 0 and 6, as follows:
  91142. **
  91143. ** 0: Not a match.
  91144. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  91145. ** 2: UTF16 byte order change required and function takes any number of args.
  91146. ** 3: encoding matches and function takes any number of arguments
  91147. ** 4: UTF8/16 conversion required - argument count matches exactly
  91148. ** 5: UTF16 byte order conversion required - argument count matches exactly
  91149. ** 6: Perfect match: encoding and argument count match exactly.
  91150. **
  91151. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  91152. ** a perfect match and any function with both xStep and xFunc NULL is
  91153. ** a non-match.
  91154. */
  91155. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  91156. static int matchQuality(
  91157. FuncDef *p, /* The function we are evaluating for match quality */
  91158. int nArg, /* Desired number of arguments. (-1)==any */
  91159. u8 enc /* Desired text encoding */
  91160. ){
  91161. int match;
  91162. /* nArg of -2 is a special case */
  91163. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  91164. /* Wrong number of arguments means "no match" */
  91165. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  91166. /* Give a better score to a function with a specific number of arguments
  91167. ** than to function that accepts any number of arguments. */
  91168. if( p->nArg==nArg ){
  91169. match = 4;
  91170. }else{
  91171. match = 1;
  91172. }
  91173. /* Bonus points if the text encoding matches */
  91174. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  91175. match += 2; /* Exact encoding match */
  91176. }else if( (enc & p->funcFlags & 2)!=0 ){
  91177. match += 1; /* Both are UTF16, but with different byte orders */
  91178. }
  91179. return match;
  91180. }
  91181. /*
  91182. ** Search a FuncDefHash for a function with the given name. Return
  91183. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  91184. */
  91185. static FuncDef *functionSearch(
  91186. FuncDefHash *pHash, /* Hash table to search */
  91187. int h, /* Hash of the name */
  91188. const char *zFunc, /* Name of function */
  91189. int nFunc /* Number of bytes in zFunc */
  91190. ){
  91191. FuncDef *p;
  91192. for(p=pHash->a[h]; p; p=p->pHash){
  91193. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  91194. return p;
  91195. }
  91196. }
  91197. return 0;
  91198. }
  91199. /*
  91200. ** Insert a new FuncDef into a FuncDefHash hash table.
  91201. */
  91202. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  91203. FuncDefHash *pHash, /* The hash table into which to insert */
  91204. FuncDef *pDef /* The function definition to insert */
  91205. ){
  91206. FuncDef *pOther;
  91207. int nName = sqlite3Strlen30(pDef->zName);
  91208. u8 c1 = (u8)pDef->zName[0];
  91209. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  91210. pOther = functionSearch(pHash, h, pDef->zName, nName);
  91211. if( pOther ){
  91212. assert( pOther!=pDef && pOther->pNext!=pDef );
  91213. pDef->pNext = pOther->pNext;
  91214. pOther->pNext = pDef;
  91215. }else{
  91216. pDef->pNext = 0;
  91217. pDef->pHash = pHash->a[h];
  91218. pHash->a[h] = pDef;
  91219. }
  91220. }
  91221. /*
  91222. ** Locate a user function given a name, a number of arguments and a flag
  91223. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  91224. ** pointer to the FuncDef structure that defines that function, or return
  91225. ** NULL if the function does not exist.
  91226. **
  91227. ** If the createFlag argument is true, then a new (blank) FuncDef
  91228. ** structure is created and liked into the "db" structure if a
  91229. ** no matching function previously existed.
  91230. **
  91231. ** If nArg is -2, then the first valid function found is returned. A
  91232. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  91233. ** case is used to see if zName is a valid function name for some number
  91234. ** of arguments. If nArg is -2, then createFlag must be 0.
  91235. **
  91236. ** If createFlag is false, then a function with the required name and
  91237. ** number of arguments may be returned even if the eTextRep flag does not
  91238. ** match that requested.
  91239. */
  91240. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  91241. sqlite3 *db, /* An open database */
  91242. const char *zName, /* Name of the function. Not null-terminated */
  91243. int nName, /* Number of characters in the name */
  91244. int nArg, /* Number of arguments. -1 means any number */
  91245. u8 enc, /* Preferred text encoding */
  91246. u8 createFlag /* Create new entry if true and does not otherwise exist */
  91247. ){
  91248. FuncDef *p; /* Iterator variable */
  91249. FuncDef *pBest = 0; /* Best match found so far */
  91250. int bestScore = 0; /* Score of best match */
  91251. int h; /* Hash value */
  91252. assert( nArg>=(-2) );
  91253. assert( nArg>=(-1) || createFlag==0 );
  91254. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  91255. /* First search for a match amongst the application-defined functions.
  91256. */
  91257. p = functionSearch(&db->aFunc, h, zName, nName);
  91258. while( p ){
  91259. int score = matchQuality(p, nArg, enc);
  91260. if( score>bestScore ){
  91261. pBest = p;
  91262. bestScore = score;
  91263. }
  91264. p = p->pNext;
  91265. }
  91266. /* If no match is found, search the built-in functions.
  91267. **
  91268. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  91269. ** functions even if a prior app-defined function was found. And give
  91270. ** priority to built-in functions.
  91271. **
  91272. ** Except, if createFlag is true, that means that we are trying to
  91273. ** install a new function. Whatever FuncDef structure is returned it will
  91274. ** have fields overwritten with new information appropriate for the
  91275. ** new function. But the FuncDefs for built-in functions are read-only.
  91276. ** So we must not search for built-ins when creating a new function.
  91277. */
  91278. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  91279. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  91280. bestScore = 0;
  91281. p = functionSearch(pHash, h, zName, nName);
  91282. while( p ){
  91283. int score = matchQuality(p, nArg, enc);
  91284. if( score>bestScore ){
  91285. pBest = p;
  91286. bestScore = score;
  91287. }
  91288. p = p->pNext;
  91289. }
  91290. }
  91291. /* If the createFlag parameter is true and the search did not reveal an
  91292. ** exact match for the name, number of arguments and encoding, then add a
  91293. ** new entry to the hash table and return it.
  91294. */
  91295. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  91296. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  91297. pBest->zName = (char *)&pBest[1];
  91298. pBest->nArg = (u16)nArg;
  91299. pBest->funcFlags = enc;
  91300. memcpy(pBest->zName, zName, nName);
  91301. pBest->zName[nName] = 0;
  91302. sqlite3FuncDefInsert(&db->aFunc, pBest);
  91303. }
  91304. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  91305. return pBest;
  91306. }
  91307. return 0;
  91308. }
  91309. /*
  91310. ** Free all resources held by the schema structure. The void* argument points
  91311. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  91312. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  91313. ** of the schema hash tables).
  91314. **
  91315. ** The Schema.cache_size variable is not cleared.
  91316. */
  91317. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  91318. Hash temp1;
  91319. Hash temp2;
  91320. HashElem *pElem;
  91321. Schema *pSchema = (Schema *)p;
  91322. temp1 = pSchema->tblHash;
  91323. temp2 = pSchema->trigHash;
  91324. sqlite3HashInit(&pSchema->trigHash);
  91325. sqlite3HashClear(&pSchema->idxHash);
  91326. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  91327. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  91328. }
  91329. sqlite3HashClear(&temp2);
  91330. sqlite3HashInit(&pSchema->tblHash);
  91331. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  91332. Table *pTab = sqliteHashData(pElem);
  91333. sqlite3DeleteTable(0, pTab);
  91334. }
  91335. sqlite3HashClear(&temp1);
  91336. sqlite3HashClear(&pSchema->fkeyHash);
  91337. pSchema->pSeqTab = 0;
  91338. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  91339. pSchema->iGeneration++;
  91340. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  91341. }
  91342. }
  91343. /*
  91344. ** Find and return the schema associated with a BTree. Create
  91345. ** a new one if necessary.
  91346. */
  91347. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  91348. Schema * p;
  91349. if( pBt ){
  91350. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  91351. }else{
  91352. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  91353. }
  91354. if( !p ){
  91355. db->mallocFailed = 1;
  91356. }else if ( 0==p->file_format ){
  91357. sqlite3HashInit(&p->tblHash);
  91358. sqlite3HashInit(&p->idxHash);
  91359. sqlite3HashInit(&p->trigHash);
  91360. sqlite3HashInit(&p->fkeyHash);
  91361. p->enc = SQLITE_UTF8;
  91362. }
  91363. return p;
  91364. }
  91365. /************** End of callback.c ********************************************/
  91366. /************** Begin file delete.c ******************************************/
  91367. /*
  91368. ** 2001 September 15
  91369. **
  91370. ** The author disclaims copyright to this source code. In place of
  91371. ** a legal notice, here is a blessing:
  91372. **
  91373. ** May you do good and not evil.
  91374. ** May you find forgiveness for yourself and forgive others.
  91375. ** May you share freely, never taking more than you give.
  91376. **
  91377. *************************************************************************
  91378. ** This file contains C code routines that are called by the parser
  91379. ** in order to generate code for DELETE FROM statements.
  91380. */
  91381. /* #include "sqliteInt.h" */
  91382. /*
  91383. ** While a SrcList can in general represent multiple tables and subqueries
  91384. ** (as in the FROM clause of a SELECT statement) in this case it contains
  91385. ** the name of a single table, as one might find in an INSERT, DELETE,
  91386. ** or UPDATE statement. Look up that table in the symbol table and
  91387. ** return a pointer. Set an error message and return NULL if the table
  91388. ** name is not found or if any other error occurs.
  91389. **
  91390. ** The following fields are initialized appropriate in pSrc:
  91391. **
  91392. ** pSrc->a[0].pTab Pointer to the Table object
  91393. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  91394. **
  91395. */
  91396. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  91397. struct SrcList_item *pItem = pSrc->a;
  91398. Table *pTab;
  91399. assert( pItem && pSrc->nSrc==1 );
  91400. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  91401. sqlite3DeleteTable(pParse->db, pItem->pTab);
  91402. pItem->pTab = pTab;
  91403. if( pTab ){
  91404. pTab->nRef++;
  91405. }
  91406. if( sqlite3IndexedByLookup(pParse, pItem) ){
  91407. pTab = 0;
  91408. }
  91409. return pTab;
  91410. }
  91411. /*
  91412. ** Check to make sure the given table is writable. If it is not
  91413. ** writable, generate an error message and return 1. If it is
  91414. ** writable return 0;
  91415. */
  91416. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  91417. /* A table is not writable under the following circumstances:
  91418. **
  91419. ** 1) It is a virtual table and no implementation of the xUpdate method
  91420. ** has been provided, or
  91421. ** 2) It is a system table (i.e. sqlite_master), this call is not
  91422. ** part of a nested parse and writable_schema pragma has not
  91423. ** been specified.
  91424. **
  91425. ** In either case leave an error message in pParse and return non-zero.
  91426. */
  91427. if( ( IsVirtual(pTab)
  91428. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  91429. || ( (pTab->tabFlags & TF_Readonly)!=0
  91430. && (pParse->db->flags & SQLITE_WriteSchema)==0
  91431. && pParse->nested==0 )
  91432. ){
  91433. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  91434. return 1;
  91435. }
  91436. #ifndef SQLITE_OMIT_VIEW
  91437. if( !viewOk && pTab->pSelect ){
  91438. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  91439. return 1;
  91440. }
  91441. #endif
  91442. return 0;
  91443. }
  91444. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  91445. /*
  91446. ** Evaluate a view and store its result in an ephemeral table. The
  91447. ** pWhere argument is an optional WHERE clause that restricts the
  91448. ** set of rows in the view that are to be added to the ephemeral table.
  91449. */
  91450. SQLITE_PRIVATE void sqlite3MaterializeView(
  91451. Parse *pParse, /* Parsing context */
  91452. Table *pView, /* View definition */
  91453. Expr *pWhere, /* Optional WHERE clause to be added */
  91454. int iCur /* Cursor number for ephemeral table */
  91455. ){
  91456. SelectDest dest;
  91457. Select *pSel;
  91458. SrcList *pFrom;
  91459. sqlite3 *db = pParse->db;
  91460. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  91461. pWhere = sqlite3ExprDup(db, pWhere, 0);
  91462. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  91463. if( pFrom ){
  91464. assert( pFrom->nSrc==1 );
  91465. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  91466. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  91467. assert( pFrom->a[0].pOn==0 );
  91468. assert( pFrom->a[0].pUsing==0 );
  91469. }
  91470. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  91471. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  91472. sqlite3Select(pParse, pSel, &dest);
  91473. sqlite3SelectDelete(db, pSel);
  91474. }
  91475. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  91476. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  91477. /*
  91478. ** Generate an expression tree to implement the WHERE, ORDER BY,
  91479. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  91480. **
  91481. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  91482. ** \__________________________/
  91483. ** pLimitWhere (pInClause)
  91484. */
  91485. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  91486. Parse *pParse, /* The parser context */
  91487. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  91488. Expr *pWhere, /* The WHERE clause. May be null */
  91489. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  91490. Expr *pLimit, /* The LIMIT clause. May be null */
  91491. Expr *pOffset, /* The OFFSET clause. May be null */
  91492. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  91493. ){
  91494. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  91495. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  91496. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  91497. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  91498. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  91499. Select *pSelect = NULL; /* Complete SELECT tree */
  91500. /* Check that there isn't an ORDER BY without a LIMIT clause.
  91501. */
  91502. if( pOrderBy && (pLimit == 0) ) {
  91503. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  91504. goto limit_where_cleanup_2;
  91505. }
  91506. /* We only need to generate a select expression if there
  91507. ** is a limit/offset term to enforce.
  91508. */
  91509. if( pLimit == 0 ) {
  91510. /* if pLimit is null, pOffset will always be null as well. */
  91511. assert( pOffset == 0 );
  91512. return pWhere;
  91513. }
  91514. /* Generate a select expression tree to enforce the limit/offset
  91515. ** term for the DELETE or UPDATE statement. For example:
  91516. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  91517. ** becomes:
  91518. ** DELETE FROM table_a WHERE rowid IN (
  91519. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  91520. ** );
  91521. */
  91522. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  91523. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  91524. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  91525. if( pEList == 0 ) goto limit_where_cleanup_2;
  91526. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  91527. ** and the SELECT subtree. */
  91528. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  91529. if( pSelectSrc == 0 ) {
  91530. sqlite3ExprListDelete(pParse->db, pEList);
  91531. goto limit_where_cleanup_2;
  91532. }
  91533. /* generate the SELECT expression tree. */
  91534. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  91535. pOrderBy,0,pLimit,pOffset);
  91536. if( pSelect == 0 ) return 0;
  91537. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  91538. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  91539. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  91540. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  91541. if( pInClause == 0 ) goto limit_where_cleanup_1;
  91542. pInClause->x.pSelect = pSelect;
  91543. pInClause->flags |= EP_xIsSelect;
  91544. sqlite3ExprSetHeightAndFlags(pParse, pInClause);
  91545. return pInClause;
  91546. /* something went wrong. clean up anything allocated. */
  91547. limit_where_cleanup_1:
  91548. sqlite3SelectDelete(pParse->db, pSelect);
  91549. return 0;
  91550. limit_where_cleanup_2:
  91551. sqlite3ExprDelete(pParse->db, pWhere);
  91552. sqlite3ExprListDelete(pParse->db, pOrderBy);
  91553. sqlite3ExprDelete(pParse->db, pLimit);
  91554. sqlite3ExprDelete(pParse->db, pOffset);
  91555. return 0;
  91556. }
  91557. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  91558. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  91559. /*
  91560. ** Generate code for a DELETE FROM statement.
  91561. **
  91562. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  91563. ** \________/ \________________/
  91564. ** pTabList pWhere
  91565. */
  91566. SQLITE_PRIVATE void sqlite3DeleteFrom(
  91567. Parse *pParse, /* The parser context */
  91568. SrcList *pTabList, /* The table from which we should delete things */
  91569. Expr *pWhere /* The WHERE clause. May be null */
  91570. ){
  91571. Vdbe *v; /* The virtual database engine */
  91572. Table *pTab; /* The table from which records will be deleted */
  91573. const char *zDb; /* Name of database holding pTab */
  91574. int i; /* Loop counter */
  91575. WhereInfo *pWInfo; /* Information about the WHERE clause */
  91576. Index *pIdx; /* For looping over indices of the table */
  91577. int iTabCur; /* Cursor number for the table */
  91578. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  91579. int iIdxCur = 0; /* Cursor number of the first index */
  91580. int nIdx; /* Number of indices */
  91581. sqlite3 *db; /* Main database structure */
  91582. AuthContext sContext; /* Authorization context */
  91583. NameContext sNC; /* Name context to resolve expressions in */
  91584. int iDb; /* Database number */
  91585. int memCnt = -1; /* Memory cell used for change counting */
  91586. int rcauth; /* Value returned by authorization callback */
  91587. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  91588. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  91589. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  91590. Index *pPk; /* The PRIMARY KEY index on the table */
  91591. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  91592. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  91593. int iKey; /* Memory cell holding key of row to be deleted */
  91594. i16 nKey; /* Number of memory cells in the row key */
  91595. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  91596. int iRowSet = 0; /* Register for rowset of rows to delete */
  91597. int addrBypass = 0; /* Address of jump over the delete logic */
  91598. int addrLoop = 0; /* Top of the delete loop */
  91599. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  91600. #ifndef SQLITE_OMIT_TRIGGER
  91601. int isView; /* True if attempting to delete from a view */
  91602. Trigger *pTrigger; /* List of table triggers, if required */
  91603. int bComplex; /* True if there are either triggers or FKs */
  91604. #endif
  91605. memset(&sContext, 0, sizeof(sContext));
  91606. db = pParse->db;
  91607. if( pParse->nErr || db->mallocFailed ){
  91608. goto delete_from_cleanup;
  91609. }
  91610. assert( pTabList->nSrc==1 );
  91611. /* Locate the table which we want to delete. This table has to be
  91612. ** put in an SrcList structure because some of the subroutines we
  91613. ** will be calling are designed to work with multiple tables and expect
  91614. ** an SrcList* parameter instead of just a Table* parameter.
  91615. */
  91616. pTab = sqlite3SrcListLookup(pParse, pTabList);
  91617. if( pTab==0 ) goto delete_from_cleanup;
  91618. /* Figure out if we have any triggers and if the table being
  91619. ** deleted from is a view
  91620. */
  91621. #ifndef SQLITE_OMIT_TRIGGER
  91622. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  91623. isView = pTab->pSelect!=0;
  91624. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  91625. #else
  91626. # define pTrigger 0
  91627. # define isView 0
  91628. # define bComplex 0
  91629. #endif
  91630. #ifdef SQLITE_OMIT_VIEW
  91631. # undef isView
  91632. # define isView 0
  91633. #endif
  91634. /* If pTab is really a view, make sure it has been initialized.
  91635. */
  91636. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  91637. goto delete_from_cleanup;
  91638. }
  91639. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  91640. goto delete_from_cleanup;
  91641. }
  91642. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91643. assert( iDb<db->nDb );
  91644. zDb = db->aDb[iDb].zName;
  91645. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  91646. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  91647. if( rcauth==SQLITE_DENY ){
  91648. goto delete_from_cleanup;
  91649. }
  91650. assert(!isView || pTrigger);
  91651. /* Assign cursor numbers to the table and all its indices.
  91652. */
  91653. assert( pTabList->nSrc==1 );
  91654. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  91655. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  91656. pParse->nTab++;
  91657. }
  91658. /* Start the view context
  91659. */
  91660. if( isView ){
  91661. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  91662. }
  91663. /* Begin generating code.
  91664. */
  91665. v = sqlite3GetVdbe(pParse);
  91666. if( v==0 ){
  91667. goto delete_from_cleanup;
  91668. }
  91669. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  91670. sqlite3BeginWriteOperation(pParse, 1, iDb);
  91671. /* If we are trying to delete from a view, realize that view into
  91672. ** an ephemeral table.
  91673. */
  91674. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  91675. if( isView ){
  91676. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  91677. iDataCur = iIdxCur = iTabCur;
  91678. }
  91679. #endif
  91680. /* Resolve the column names in the WHERE clause.
  91681. */
  91682. memset(&sNC, 0, sizeof(sNC));
  91683. sNC.pParse = pParse;
  91684. sNC.pSrcList = pTabList;
  91685. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  91686. goto delete_from_cleanup;
  91687. }
  91688. /* Initialize the counter of the number of rows deleted, if
  91689. ** we are counting rows.
  91690. */
  91691. if( db->flags & SQLITE_CountRows ){
  91692. memCnt = ++pParse->nMem;
  91693. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  91694. }
  91695. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  91696. /* Special case: A DELETE without a WHERE clause deletes everything.
  91697. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  91698. ** this optimization caused the row change count (the value returned by
  91699. ** API function sqlite3_count_changes) to be set incorrectly. */
  91700. if( rcauth==SQLITE_OK
  91701. && pWhere==0
  91702. && !bComplex
  91703. && !IsVirtual(pTab)
  91704. ){
  91705. assert( !isView );
  91706. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  91707. if( HasRowid(pTab) ){
  91708. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  91709. pTab->zName, P4_STATIC);
  91710. }
  91711. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91712. assert( pIdx->pSchema==pTab->pSchema );
  91713. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  91714. }
  91715. }else
  91716. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  91717. {
  91718. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
  91719. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  91720. if( HasRowid(pTab) ){
  91721. /* For a rowid table, initialize the RowSet to an empty set */
  91722. pPk = 0;
  91723. nPk = 1;
  91724. iRowSet = ++pParse->nMem;
  91725. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  91726. }else{
  91727. /* For a WITHOUT ROWID table, create an ephemeral table used to
  91728. ** hold all primary keys for rows to be deleted. */
  91729. pPk = sqlite3PrimaryKeyIndex(pTab);
  91730. assert( pPk!=0 );
  91731. nPk = pPk->nKeyCol;
  91732. iPk = pParse->nMem+1;
  91733. pParse->nMem += nPk;
  91734. iEphCur = pParse->nTab++;
  91735. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  91736. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  91737. }
  91738. /* Construct a query to find the rowid or primary key for every row
  91739. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  91740. ** to indicate the strategy used to implement this delete:
  91741. **
  91742. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  91743. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  91744. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  91745. */
  91746. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  91747. if( pWInfo==0 ) goto delete_from_cleanup;
  91748. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  91749. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  91750. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  91751. /* Keep track of the number of rows to be deleted */
  91752. if( db->flags & SQLITE_CountRows ){
  91753. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  91754. }
  91755. /* Extract the rowid or primary key for the current row */
  91756. if( pPk ){
  91757. for(i=0; i<nPk; i++){
  91758. assert( pPk->aiColumn[i]>=0 );
  91759. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  91760. pPk->aiColumn[i], iPk+i);
  91761. }
  91762. iKey = iPk;
  91763. }else{
  91764. iKey = pParse->nMem + 1;
  91765. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  91766. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  91767. }
  91768. if( eOnePass!=ONEPASS_OFF ){
  91769. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  91770. ** one, so just keep it in its register(s) and fall through to the
  91771. ** delete code. */
  91772. nKey = nPk; /* OP_Found will use an unpacked key */
  91773. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  91774. if( aToOpen==0 ){
  91775. sqlite3WhereEnd(pWInfo);
  91776. goto delete_from_cleanup;
  91777. }
  91778. memset(aToOpen, 1, nIdx+1);
  91779. aToOpen[nIdx+1] = 0;
  91780. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  91781. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  91782. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  91783. }else{
  91784. if( pPk ){
  91785. /* Add the PK key for this row to the temporary table */
  91786. iKey = ++pParse->nMem;
  91787. nKey = 0; /* Zero tells OP_Found to use a composite key */
  91788. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  91789. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  91790. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  91791. }else{
  91792. /* Add the rowid of the row to be deleted to the RowSet */
  91793. nKey = 1; /* OP_Seek always uses a single rowid */
  91794. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  91795. }
  91796. }
  91797. /* If this DELETE cannot use the ONEPASS strategy, this is the
  91798. ** end of the WHERE loop */
  91799. if( eOnePass!=ONEPASS_OFF ){
  91800. addrBypass = sqlite3VdbeMakeLabel(v);
  91801. }else{
  91802. sqlite3WhereEnd(pWInfo);
  91803. }
  91804. /* Unless this is a view, open cursors for the table we are
  91805. ** deleting from and all its indices. If this is a view, then the
  91806. ** only effect this statement has is to fire the INSTEAD OF
  91807. ** triggers.
  91808. */
  91809. if( !isView ){
  91810. int iAddrOnce = 0;
  91811. if( eOnePass==ONEPASS_MULTI ){
  91812. iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  91813. }
  91814. testcase( IsVirtual(pTab) );
  91815. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
  91816. &iDataCur, &iIdxCur);
  91817. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  91818. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  91819. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  91820. }
  91821. /* Set up a loop over the rowids/primary-keys that were found in the
  91822. ** where-clause loop above.
  91823. */
  91824. if( eOnePass!=ONEPASS_OFF ){
  91825. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  91826. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  91827. assert( pPk!=0 || pTab->pSelect!=0 );
  91828. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  91829. VdbeCoverage(v);
  91830. }
  91831. }else if( pPk ){
  91832. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  91833. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  91834. assert( nKey==0 ); /* OP_Found will use a composite key */
  91835. }else{
  91836. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  91837. VdbeCoverage(v);
  91838. assert( nKey==1 );
  91839. }
  91840. /* Delete the row */
  91841. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91842. if( IsVirtual(pTab) ){
  91843. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  91844. sqlite3VtabMakeWritable(pParse, pTab);
  91845. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  91846. sqlite3VdbeChangeP5(v, OE_Abort);
  91847. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  91848. sqlite3MayAbort(pParse);
  91849. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  91850. pParse->isMultiWrite = 0;
  91851. }
  91852. }else
  91853. #endif
  91854. {
  91855. int count = (pParse->nested==0); /* True to count changes */
  91856. int iIdxNoSeek = -1;
  91857. if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
  91858. iIdxNoSeek = aiCurOnePass[1];
  91859. }
  91860. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  91861. iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
  91862. }
  91863. /* End of the loop over all rowids/primary-keys. */
  91864. if( eOnePass!=ONEPASS_OFF ){
  91865. sqlite3VdbeResolveLabel(v, addrBypass);
  91866. sqlite3WhereEnd(pWInfo);
  91867. }else if( pPk ){
  91868. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  91869. sqlite3VdbeJumpHere(v, addrLoop);
  91870. }else{
  91871. sqlite3VdbeGoto(v, addrLoop);
  91872. sqlite3VdbeJumpHere(v, addrLoop);
  91873. }
  91874. /* Close the cursors open on the table and its indexes. */
  91875. if( !isView && !IsVirtual(pTab) ){
  91876. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  91877. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  91878. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  91879. }
  91880. }
  91881. } /* End non-truncate path */
  91882. /* Update the sqlite_sequence table by storing the content of the
  91883. ** maximum rowid counter values recorded while inserting into
  91884. ** autoincrement tables.
  91885. */
  91886. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  91887. sqlite3AutoincrementEnd(pParse);
  91888. }
  91889. /* Return the number of rows that were deleted. If this routine is
  91890. ** generating code because of a call to sqlite3NestedParse(), do not
  91891. ** invoke the callback function.
  91892. */
  91893. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  91894. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  91895. sqlite3VdbeSetNumCols(v, 1);
  91896. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  91897. }
  91898. delete_from_cleanup:
  91899. sqlite3AuthContextPop(&sContext);
  91900. sqlite3SrcListDelete(db, pTabList);
  91901. sqlite3ExprDelete(db, pWhere);
  91902. sqlite3DbFree(db, aToOpen);
  91903. return;
  91904. }
  91905. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  91906. ** they may interfere with compilation of other functions in this file
  91907. ** (or in another file, if this file becomes part of the amalgamation). */
  91908. #ifdef isView
  91909. #undef isView
  91910. #endif
  91911. #ifdef pTrigger
  91912. #undef pTrigger
  91913. #endif
  91914. /*
  91915. ** This routine generates VDBE code that causes a single row of a
  91916. ** single table to be deleted. Both the original table entry and
  91917. ** all indices are removed.
  91918. **
  91919. ** Preconditions:
  91920. **
  91921. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  91922. ** store for the table. (This will be either the table itself,
  91923. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  91924. ** of a WITHOUT ROWID table.)
  91925. **
  91926. ** 2. Read/write cursors for all indices of pTab must be open as
  91927. ** cursor number iIdxCur+i for the i-th index.
  91928. **
  91929. ** 3. The primary key for the row to be deleted must be stored in a
  91930. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  91931. ** that a search record formed from OP_MakeRecord is contained in the
  91932. ** single memory location iPk.
  91933. **
  91934. ** eMode:
  91935. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  91936. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  91937. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  91938. ** then this function must seek iDataCur to the entry identified by iPk
  91939. ** and nPk before reading from it.
  91940. **
  91941. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  91942. ** of a ONEPASS delete that affects multiple rows. In this case, if
  91943. ** iIdxNoSeek is a valid cursor number (>=0), then its position should
  91944. ** be preserved following the delete operation. Or, if iIdxNoSeek is not
  91945. ** a valid cursor number, the position of iDataCur should be preserved
  91946. ** instead.
  91947. **
  91948. ** iIdxNoSeek:
  91949. ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
  91950. ** index cursor (from within array of cursors starting at iIdxCur) that
  91951. ** already points to the index entry to be deleted.
  91952. */
  91953. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  91954. Parse *pParse, /* Parsing context */
  91955. Table *pTab, /* Table containing the row to be deleted */
  91956. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  91957. int iDataCur, /* Cursor from which column data is extracted */
  91958. int iIdxCur, /* First index cursor */
  91959. int iPk, /* First memory cell containing the PRIMARY KEY */
  91960. i16 nPk, /* Number of PRIMARY KEY memory cells */
  91961. u8 count, /* If non-zero, increment the row change counter */
  91962. u8 onconf, /* Default ON CONFLICT policy for triggers */
  91963. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  91964. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  91965. ){
  91966. Vdbe *v = pParse->pVdbe; /* Vdbe */
  91967. int iOld = 0; /* First register in OLD.* array */
  91968. int iLabel; /* Label resolved to end of generated code */
  91969. u8 opSeek; /* Seek opcode */
  91970. /* Vdbe is guaranteed to have been allocated by this stage. */
  91971. assert( v );
  91972. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  91973. iDataCur, iIdxCur, iPk, (int)nPk));
  91974. /* Seek cursor iCur to the row to delete. If this row no longer exists
  91975. ** (this can happen if a trigger program has already deleted it), do
  91976. ** not attempt to delete it or fire any DELETE triggers. */
  91977. iLabel = sqlite3VdbeMakeLabel(v);
  91978. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  91979. if( eMode==ONEPASS_OFF ){
  91980. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  91981. VdbeCoverageIf(v, opSeek==OP_NotExists);
  91982. VdbeCoverageIf(v, opSeek==OP_NotFound);
  91983. }
  91984. /* If there are any triggers to fire, allocate a range of registers to
  91985. ** use for the old.* references in the triggers. */
  91986. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  91987. u32 mask; /* Mask of OLD.* columns in use */
  91988. int iCol; /* Iterator used while populating OLD.* */
  91989. int addrStart; /* Start of BEFORE trigger programs */
  91990. /* TODO: Could use temporary registers here. Also could attempt to
  91991. ** avoid copying the contents of the rowid register. */
  91992. mask = sqlite3TriggerColmask(
  91993. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  91994. );
  91995. mask |= sqlite3FkOldmask(pParse, pTab);
  91996. iOld = pParse->nMem+1;
  91997. pParse->nMem += (1 + pTab->nCol);
  91998. /* Populate the OLD.* pseudo-table register array. These values will be
  91999. ** used by any BEFORE and AFTER triggers that exist. */
  92000. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  92001. for(iCol=0; iCol<pTab->nCol; iCol++){
  92002. testcase( mask!=0xffffffff && iCol==31 );
  92003. testcase( mask!=0xffffffff && iCol==32 );
  92004. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  92005. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  92006. }
  92007. }
  92008. /* Invoke BEFORE DELETE trigger programs. */
  92009. addrStart = sqlite3VdbeCurrentAddr(v);
  92010. sqlite3CodeRowTrigger(pParse, pTrigger,
  92011. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  92012. );
  92013. /* If any BEFORE triggers were coded, then seek the cursor to the
  92014. ** row to be deleted again. It may be that the BEFORE triggers moved
  92015. ** the cursor or of already deleted the row that the cursor was
  92016. ** pointing to.
  92017. */
  92018. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  92019. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  92020. VdbeCoverageIf(v, opSeek==OP_NotExists);
  92021. VdbeCoverageIf(v, opSeek==OP_NotFound);
  92022. }
  92023. /* Do FK processing. This call checks that any FK constraints that
  92024. ** refer to this table (i.e. constraints attached to other tables)
  92025. ** are not violated by deleting this row. */
  92026. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  92027. }
  92028. /* Delete the index and table entries. Skip this step if pTab is really
  92029. ** a view (in which case the only effect of the DELETE statement is to
  92030. ** fire the INSTEAD OF triggers). */
  92031. if( pTab->pSelect==0 ){
  92032. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  92033. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  92034. if( count ){
  92035. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  92036. }
  92037. if( iIdxNoSeek>=0 ){
  92038. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  92039. }
  92040. sqlite3VdbeChangeP5(v, eMode==ONEPASS_MULTI);
  92041. }
  92042. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  92043. ** handle rows (possibly in other tables) that refer via a foreign key
  92044. ** to the row just deleted. */
  92045. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  92046. /* Invoke AFTER DELETE trigger programs. */
  92047. sqlite3CodeRowTrigger(pParse, pTrigger,
  92048. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  92049. );
  92050. /* Jump here if the row had already been deleted before any BEFORE
  92051. ** trigger programs were invoked. Or if a trigger program throws a
  92052. ** RAISE(IGNORE) exception. */
  92053. sqlite3VdbeResolveLabel(v, iLabel);
  92054. VdbeModuleComment((v, "END: GenRowDel()"));
  92055. }
  92056. /*
  92057. ** This routine generates VDBE code that causes the deletion of all
  92058. ** index entries associated with a single row of a single table, pTab
  92059. **
  92060. ** Preconditions:
  92061. **
  92062. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  92063. ** btree for the table pTab. (This will be either the table itself
  92064. ** for rowid tables or to the primary key index for WITHOUT ROWID
  92065. ** tables.)
  92066. **
  92067. ** 2. Read/write cursors for all indices of pTab must be open as
  92068. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  92069. ** index is the 0-th index.)
  92070. **
  92071. ** 3. The "iDataCur" cursor must be already be positioned on the row
  92072. ** that is to be deleted.
  92073. */
  92074. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  92075. Parse *pParse, /* Parsing and code generating context */
  92076. Table *pTab, /* Table containing the row to be deleted */
  92077. int iDataCur, /* Cursor of table holding data. */
  92078. int iIdxCur, /* First index cursor */
  92079. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  92080. int iIdxNoSeek /* Do not delete from this cursor */
  92081. ){
  92082. int i; /* Index loop counter */
  92083. int r1 = -1; /* Register holding an index key */
  92084. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  92085. Index *pIdx; /* Current index */
  92086. Index *pPrior = 0; /* Prior index */
  92087. Vdbe *v; /* The prepared statement under construction */
  92088. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  92089. v = pParse->pVdbe;
  92090. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  92091. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  92092. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  92093. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  92094. if( pIdx==pPk ) continue;
  92095. if( iIdxCur+i==iIdxNoSeek ) continue;
  92096. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  92097. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  92098. &iPartIdxLabel, pPrior, r1);
  92099. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  92100. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  92101. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  92102. pPrior = pIdx;
  92103. }
  92104. }
  92105. /*
  92106. ** Generate code that will assemble an index key and stores it in register
  92107. ** regOut. The key with be for index pIdx which is an index on pTab.
  92108. ** iCur is the index of a cursor open on the pTab table and pointing to
  92109. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  92110. ** iCur must be the cursor of the PRIMARY KEY index.
  92111. **
  92112. ** Return a register number which is the first in a block of
  92113. ** registers that holds the elements of the index key. The
  92114. ** block of registers has already been deallocated by the time
  92115. ** this routine returns.
  92116. **
  92117. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  92118. ** to that label if pIdx is a partial index that should be skipped.
  92119. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  92120. ** A partial index should be skipped if its WHERE clause evaluates
  92121. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  92122. ** will be set to zero which is an empty label that is ignored by
  92123. ** sqlite3ResolvePartIdxLabel().
  92124. **
  92125. ** The pPrior and regPrior parameters are used to implement a cache to
  92126. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  92127. ** a pointer to a different index for which an index key has just been
  92128. ** computed into register regPrior. If the current pIdx index is generating
  92129. ** its key into the same sequence of registers and if pPrior and pIdx share
  92130. ** a column in common, then the register corresponding to that column already
  92131. ** holds the correct value and the loading of that register is skipped.
  92132. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  92133. ** on a table with multiple indices, and especially with the ROWID or
  92134. ** PRIMARY KEY columns of the index.
  92135. */
  92136. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  92137. Parse *pParse, /* Parsing context */
  92138. Index *pIdx, /* The index for which to generate a key */
  92139. int iDataCur, /* Cursor number from which to take column data */
  92140. int regOut, /* Put the new key into this register if not 0 */
  92141. int prefixOnly, /* Compute only a unique prefix of the key */
  92142. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  92143. Index *pPrior, /* Previously generated index key */
  92144. int regPrior /* Register holding previous generated key */
  92145. ){
  92146. Vdbe *v = pParse->pVdbe;
  92147. int j;
  92148. int regBase;
  92149. int nCol;
  92150. if( piPartIdxLabel ){
  92151. if( pIdx->pPartIdxWhere ){
  92152. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  92153. pParse->iSelfTab = iDataCur;
  92154. sqlite3ExprCachePush(pParse);
  92155. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  92156. SQLITE_JUMPIFNULL);
  92157. }else{
  92158. *piPartIdxLabel = 0;
  92159. }
  92160. }
  92161. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  92162. regBase = sqlite3GetTempRange(pParse, nCol);
  92163. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  92164. for(j=0; j<nCol; j++){
  92165. if( pPrior
  92166. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  92167. && pPrior->aiColumn[j]!=XN_EXPR
  92168. ){
  92169. /* This column was already computed by the previous index */
  92170. continue;
  92171. }
  92172. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  92173. /* If the column affinity is REAL but the number is an integer, then it
  92174. ** might be stored in the table as an integer (using a compact
  92175. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  92176. ** But we are getting ready to store this value back into an index, where
  92177. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  92178. ** opcode if it is present */
  92179. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  92180. }
  92181. if( regOut ){
  92182. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  92183. }
  92184. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  92185. return regBase;
  92186. }
  92187. /*
  92188. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  92189. ** because it was a partial index, then this routine should be called to
  92190. ** resolve that label.
  92191. */
  92192. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  92193. if( iLabel ){
  92194. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  92195. sqlite3ExprCachePop(pParse);
  92196. }
  92197. }
  92198. /************** End of delete.c **********************************************/
  92199. /************** Begin file func.c ********************************************/
  92200. /*
  92201. ** 2002 February 23
  92202. **
  92203. ** The author disclaims copyright to this source code. In place of
  92204. ** a legal notice, here is a blessing:
  92205. **
  92206. ** May you do good and not evil.
  92207. ** May you find forgiveness for yourself and forgive others.
  92208. ** May you share freely, never taking more than you give.
  92209. **
  92210. *************************************************************************
  92211. ** This file contains the C-language implementations for many of the SQL
  92212. ** functions of SQLite. (Some function, and in particular the date and
  92213. ** time functions, are implemented separately.)
  92214. */
  92215. /* #include "sqliteInt.h" */
  92216. /* #include <stdlib.h> */
  92217. /* #include <assert.h> */
  92218. /* #include "vdbeInt.h" */
  92219. /*
  92220. ** Return the collating function associated with a function.
  92221. */
  92222. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  92223. VdbeOp *pOp;
  92224. assert( context->pVdbe!=0 );
  92225. pOp = &context->pVdbe->aOp[context->iOp-1];
  92226. assert( pOp->opcode==OP_CollSeq );
  92227. assert( pOp->p4type==P4_COLLSEQ );
  92228. return pOp->p4.pColl;
  92229. }
  92230. /*
  92231. ** Indicate that the accumulator load should be skipped on this
  92232. ** iteration of the aggregate loop.
  92233. */
  92234. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  92235. context->skipFlag = 1;
  92236. }
  92237. /*
  92238. ** Implementation of the non-aggregate min() and max() functions
  92239. */
  92240. static void minmaxFunc(
  92241. sqlite3_context *context,
  92242. int argc,
  92243. sqlite3_value **argv
  92244. ){
  92245. int i;
  92246. int mask; /* 0 for min() or 0xffffffff for max() */
  92247. int iBest;
  92248. CollSeq *pColl;
  92249. assert( argc>1 );
  92250. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  92251. pColl = sqlite3GetFuncCollSeq(context);
  92252. assert( pColl );
  92253. assert( mask==-1 || mask==0 );
  92254. iBest = 0;
  92255. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  92256. for(i=1; i<argc; i++){
  92257. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  92258. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  92259. testcase( mask==0 );
  92260. iBest = i;
  92261. }
  92262. }
  92263. sqlite3_result_value(context, argv[iBest]);
  92264. }
  92265. /*
  92266. ** Return the type of the argument.
  92267. */
  92268. static void typeofFunc(
  92269. sqlite3_context *context,
  92270. int NotUsed,
  92271. sqlite3_value **argv
  92272. ){
  92273. const char *z = 0;
  92274. UNUSED_PARAMETER(NotUsed);
  92275. switch( sqlite3_value_type(argv[0]) ){
  92276. case SQLITE_INTEGER: z = "integer"; break;
  92277. case SQLITE_TEXT: z = "text"; break;
  92278. case SQLITE_FLOAT: z = "real"; break;
  92279. case SQLITE_BLOB: z = "blob"; break;
  92280. default: z = "null"; break;
  92281. }
  92282. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  92283. }
  92284. /*
  92285. ** Implementation of the length() function
  92286. */
  92287. static void lengthFunc(
  92288. sqlite3_context *context,
  92289. int argc,
  92290. sqlite3_value **argv
  92291. ){
  92292. int len;
  92293. assert( argc==1 );
  92294. UNUSED_PARAMETER(argc);
  92295. switch( sqlite3_value_type(argv[0]) ){
  92296. case SQLITE_BLOB:
  92297. case SQLITE_INTEGER:
  92298. case SQLITE_FLOAT: {
  92299. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  92300. break;
  92301. }
  92302. case SQLITE_TEXT: {
  92303. const unsigned char *z = sqlite3_value_text(argv[0]);
  92304. if( z==0 ) return;
  92305. len = 0;
  92306. while( *z ){
  92307. len++;
  92308. SQLITE_SKIP_UTF8(z);
  92309. }
  92310. sqlite3_result_int(context, len);
  92311. break;
  92312. }
  92313. default: {
  92314. sqlite3_result_null(context);
  92315. break;
  92316. }
  92317. }
  92318. }
  92319. /*
  92320. ** Implementation of the abs() function.
  92321. **
  92322. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  92323. ** the numeric argument X.
  92324. */
  92325. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  92326. assert( argc==1 );
  92327. UNUSED_PARAMETER(argc);
  92328. switch( sqlite3_value_type(argv[0]) ){
  92329. case SQLITE_INTEGER: {
  92330. i64 iVal = sqlite3_value_int64(argv[0]);
  92331. if( iVal<0 ){
  92332. if( iVal==SMALLEST_INT64 ){
  92333. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  92334. ** then abs(X) throws an integer overflow error since there is no
  92335. ** equivalent positive 64-bit two complement value. */
  92336. sqlite3_result_error(context, "integer overflow", -1);
  92337. return;
  92338. }
  92339. iVal = -iVal;
  92340. }
  92341. sqlite3_result_int64(context, iVal);
  92342. break;
  92343. }
  92344. case SQLITE_NULL: {
  92345. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  92346. sqlite3_result_null(context);
  92347. break;
  92348. }
  92349. default: {
  92350. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  92351. ** something that can be converted into a number, we have:
  92352. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  92353. ** that cannot be converted to a numeric value.
  92354. */
  92355. double rVal = sqlite3_value_double(argv[0]);
  92356. if( rVal<0 ) rVal = -rVal;
  92357. sqlite3_result_double(context, rVal);
  92358. break;
  92359. }
  92360. }
  92361. }
  92362. /*
  92363. ** Implementation of the instr() function.
  92364. **
  92365. ** instr(haystack,needle) finds the first occurrence of needle
  92366. ** in haystack and returns the number of previous characters plus 1,
  92367. ** or 0 if needle does not occur within haystack.
  92368. **
  92369. ** If both haystack and needle are BLOBs, then the result is one more than
  92370. ** the number of bytes in haystack prior to the first occurrence of needle,
  92371. ** or 0 if needle never occurs in haystack.
  92372. */
  92373. static void instrFunc(
  92374. sqlite3_context *context,
  92375. int argc,
  92376. sqlite3_value **argv
  92377. ){
  92378. const unsigned char *zHaystack;
  92379. const unsigned char *zNeedle;
  92380. int nHaystack;
  92381. int nNeedle;
  92382. int typeHaystack, typeNeedle;
  92383. int N = 1;
  92384. int isText;
  92385. UNUSED_PARAMETER(argc);
  92386. typeHaystack = sqlite3_value_type(argv[0]);
  92387. typeNeedle = sqlite3_value_type(argv[1]);
  92388. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  92389. nHaystack = sqlite3_value_bytes(argv[0]);
  92390. nNeedle = sqlite3_value_bytes(argv[1]);
  92391. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  92392. zHaystack = sqlite3_value_blob(argv[0]);
  92393. zNeedle = sqlite3_value_blob(argv[1]);
  92394. isText = 0;
  92395. }else{
  92396. zHaystack = sqlite3_value_text(argv[0]);
  92397. zNeedle = sqlite3_value_text(argv[1]);
  92398. isText = 1;
  92399. }
  92400. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  92401. N++;
  92402. do{
  92403. nHaystack--;
  92404. zHaystack++;
  92405. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  92406. }
  92407. if( nNeedle>nHaystack ) N = 0;
  92408. sqlite3_result_int(context, N);
  92409. }
  92410. /*
  92411. ** Implementation of the printf() function.
  92412. */
  92413. static void printfFunc(
  92414. sqlite3_context *context,
  92415. int argc,
  92416. sqlite3_value **argv
  92417. ){
  92418. PrintfArguments x;
  92419. StrAccum str;
  92420. const char *zFormat;
  92421. int n;
  92422. sqlite3 *db = sqlite3_context_db_handle(context);
  92423. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  92424. x.nArg = argc-1;
  92425. x.nUsed = 0;
  92426. x.apArg = argv+1;
  92427. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  92428. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  92429. n = str.nChar;
  92430. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  92431. SQLITE_DYNAMIC);
  92432. }
  92433. }
  92434. /*
  92435. ** Implementation of the substr() function.
  92436. **
  92437. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  92438. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  92439. ** of x. If x is text, then we actually count UTF-8 characters.
  92440. ** If x is a blob, then we count bytes.
  92441. **
  92442. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  92443. **
  92444. ** If p2 is negative, return the p2 characters preceding p1.
  92445. */
  92446. static void substrFunc(
  92447. sqlite3_context *context,
  92448. int argc,
  92449. sqlite3_value **argv
  92450. ){
  92451. const unsigned char *z;
  92452. const unsigned char *z2;
  92453. int len;
  92454. int p0type;
  92455. i64 p1, p2;
  92456. int negP2 = 0;
  92457. assert( argc==3 || argc==2 );
  92458. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  92459. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  92460. ){
  92461. return;
  92462. }
  92463. p0type = sqlite3_value_type(argv[0]);
  92464. p1 = sqlite3_value_int(argv[1]);
  92465. if( p0type==SQLITE_BLOB ){
  92466. len = sqlite3_value_bytes(argv[0]);
  92467. z = sqlite3_value_blob(argv[0]);
  92468. if( z==0 ) return;
  92469. assert( len==sqlite3_value_bytes(argv[0]) );
  92470. }else{
  92471. z = sqlite3_value_text(argv[0]);
  92472. if( z==0 ) return;
  92473. len = 0;
  92474. if( p1<0 ){
  92475. for(z2=z; *z2; len++){
  92476. SQLITE_SKIP_UTF8(z2);
  92477. }
  92478. }
  92479. }
  92480. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  92481. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  92482. ** as substr(X,1,N) - it returns the first N characters of X. This
  92483. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  92484. ** from 2009-02-02 for compatibility of applications that exploited the
  92485. ** old buggy behavior. */
  92486. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  92487. #endif
  92488. if( argc==3 ){
  92489. p2 = sqlite3_value_int(argv[2]);
  92490. if( p2<0 ){
  92491. p2 = -p2;
  92492. negP2 = 1;
  92493. }
  92494. }else{
  92495. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  92496. }
  92497. if( p1<0 ){
  92498. p1 += len;
  92499. if( p1<0 ){
  92500. p2 += p1;
  92501. if( p2<0 ) p2 = 0;
  92502. p1 = 0;
  92503. }
  92504. }else if( p1>0 ){
  92505. p1--;
  92506. }else if( p2>0 ){
  92507. p2--;
  92508. }
  92509. if( negP2 ){
  92510. p1 -= p2;
  92511. if( p1<0 ){
  92512. p2 += p1;
  92513. p1 = 0;
  92514. }
  92515. }
  92516. assert( p1>=0 && p2>=0 );
  92517. if( p0type!=SQLITE_BLOB ){
  92518. while( *z && p1 ){
  92519. SQLITE_SKIP_UTF8(z);
  92520. p1--;
  92521. }
  92522. for(z2=z; *z2 && p2; p2--){
  92523. SQLITE_SKIP_UTF8(z2);
  92524. }
  92525. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  92526. SQLITE_UTF8);
  92527. }else{
  92528. if( p1+p2>len ){
  92529. p2 = len-p1;
  92530. if( p2<0 ) p2 = 0;
  92531. }
  92532. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  92533. }
  92534. }
  92535. /*
  92536. ** Implementation of the round() function
  92537. */
  92538. #ifndef SQLITE_OMIT_FLOATING_POINT
  92539. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  92540. int n = 0;
  92541. double r;
  92542. char *zBuf;
  92543. assert( argc==1 || argc==2 );
  92544. if( argc==2 ){
  92545. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  92546. n = sqlite3_value_int(argv[1]);
  92547. if( n>30 ) n = 30;
  92548. if( n<0 ) n = 0;
  92549. }
  92550. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  92551. r = sqlite3_value_double(argv[0]);
  92552. /* If Y==0 and X will fit in a 64-bit int,
  92553. ** handle the rounding directly,
  92554. ** otherwise use printf.
  92555. */
  92556. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  92557. r = (double)((sqlite_int64)(r+0.5));
  92558. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  92559. r = -(double)((sqlite_int64)((-r)+0.5));
  92560. }else{
  92561. zBuf = sqlite3_mprintf("%.*f",n,r);
  92562. if( zBuf==0 ){
  92563. sqlite3_result_error_nomem(context);
  92564. return;
  92565. }
  92566. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  92567. sqlite3_free(zBuf);
  92568. }
  92569. sqlite3_result_double(context, r);
  92570. }
  92571. #endif
  92572. /*
  92573. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  92574. ** allocation fails, call sqlite3_result_error_nomem() to notify
  92575. ** the database handle that malloc() has failed and return NULL.
  92576. ** If nByte is larger than the maximum string or blob length, then
  92577. ** raise an SQLITE_TOOBIG exception and return NULL.
  92578. */
  92579. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  92580. char *z;
  92581. sqlite3 *db = sqlite3_context_db_handle(context);
  92582. assert( nByte>0 );
  92583. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  92584. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  92585. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  92586. sqlite3_result_error_toobig(context);
  92587. z = 0;
  92588. }else{
  92589. z = sqlite3Malloc(nByte);
  92590. if( !z ){
  92591. sqlite3_result_error_nomem(context);
  92592. }
  92593. }
  92594. return z;
  92595. }
  92596. /*
  92597. ** Implementation of the upper() and lower() SQL functions.
  92598. */
  92599. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  92600. char *z1;
  92601. const char *z2;
  92602. int i, n;
  92603. UNUSED_PARAMETER(argc);
  92604. z2 = (char*)sqlite3_value_text(argv[0]);
  92605. n = sqlite3_value_bytes(argv[0]);
  92606. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  92607. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  92608. if( z2 ){
  92609. z1 = contextMalloc(context, ((i64)n)+1);
  92610. if( z1 ){
  92611. for(i=0; i<n; i++){
  92612. z1[i] = (char)sqlite3Toupper(z2[i]);
  92613. }
  92614. sqlite3_result_text(context, z1, n, sqlite3_free);
  92615. }
  92616. }
  92617. }
  92618. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  92619. char *z1;
  92620. const char *z2;
  92621. int i, n;
  92622. UNUSED_PARAMETER(argc);
  92623. z2 = (char*)sqlite3_value_text(argv[0]);
  92624. n = sqlite3_value_bytes(argv[0]);
  92625. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  92626. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  92627. if( z2 ){
  92628. z1 = contextMalloc(context, ((i64)n)+1);
  92629. if( z1 ){
  92630. for(i=0; i<n; i++){
  92631. z1[i] = sqlite3Tolower(z2[i]);
  92632. }
  92633. sqlite3_result_text(context, z1, n, sqlite3_free);
  92634. }
  92635. }
  92636. }
  92637. /*
  92638. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  92639. ** as VDBE code so that unused argument values do not have to be computed.
  92640. ** However, we still need some kind of function implementation for this
  92641. ** routines in the function table. The noopFunc macro provides this.
  92642. ** noopFunc will never be called so it doesn't matter what the implementation
  92643. ** is. We might as well use the "version()" function as a substitute.
  92644. */
  92645. #define noopFunc versionFunc /* Substitute function - never called */
  92646. /*
  92647. ** Implementation of random(). Return a random integer.
  92648. */
  92649. static void randomFunc(
  92650. sqlite3_context *context,
  92651. int NotUsed,
  92652. sqlite3_value **NotUsed2
  92653. ){
  92654. sqlite_int64 r;
  92655. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92656. sqlite3_randomness(sizeof(r), &r);
  92657. if( r<0 ){
  92658. /* We need to prevent a random number of 0x8000000000000000
  92659. ** (or -9223372036854775808) since when you do abs() of that
  92660. ** number of you get the same value back again. To do this
  92661. ** in a way that is testable, mask the sign bit off of negative
  92662. ** values, resulting in a positive value. Then take the
  92663. ** 2s complement of that positive value. The end result can
  92664. ** therefore be no less than -9223372036854775807.
  92665. */
  92666. r = -(r & LARGEST_INT64);
  92667. }
  92668. sqlite3_result_int64(context, r);
  92669. }
  92670. /*
  92671. ** Implementation of randomblob(N). Return a random blob
  92672. ** that is N bytes long.
  92673. */
  92674. static void randomBlob(
  92675. sqlite3_context *context,
  92676. int argc,
  92677. sqlite3_value **argv
  92678. ){
  92679. int n;
  92680. unsigned char *p;
  92681. assert( argc==1 );
  92682. UNUSED_PARAMETER(argc);
  92683. n = sqlite3_value_int(argv[0]);
  92684. if( n<1 ){
  92685. n = 1;
  92686. }
  92687. p = contextMalloc(context, n);
  92688. if( p ){
  92689. sqlite3_randomness(n, p);
  92690. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  92691. }
  92692. }
  92693. /*
  92694. ** Implementation of the last_insert_rowid() SQL function. The return
  92695. ** value is the same as the sqlite3_last_insert_rowid() API function.
  92696. */
  92697. static void last_insert_rowid(
  92698. sqlite3_context *context,
  92699. int NotUsed,
  92700. sqlite3_value **NotUsed2
  92701. ){
  92702. sqlite3 *db = sqlite3_context_db_handle(context);
  92703. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92704. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  92705. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  92706. ** function. */
  92707. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  92708. }
  92709. /*
  92710. ** Implementation of the changes() SQL function.
  92711. **
  92712. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  92713. ** around the sqlite3_changes() C/C++ function and hence follows the same
  92714. ** rules for counting changes.
  92715. */
  92716. static void changes(
  92717. sqlite3_context *context,
  92718. int NotUsed,
  92719. sqlite3_value **NotUsed2
  92720. ){
  92721. sqlite3 *db = sqlite3_context_db_handle(context);
  92722. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92723. sqlite3_result_int(context, sqlite3_changes(db));
  92724. }
  92725. /*
  92726. ** Implementation of the total_changes() SQL function. The return value is
  92727. ** the same as the sqlite3_total_changes() API function.
  92728. */
  92729. static void total_changes(
  92730. sqlite3_context *context,
  92731. int NotUsed,
  92732. sqlite3_value **NotUsed2
  92733. ){
  92734. sqlite3 *db = sqlite3_context_db_handle(context);
  92735. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92736. /* IMP: R-52756-41993 This function is a wrapper around the
  92737. ** sqlite3_total_changes() C/C++ interface. */
  92738. sqlite3_result_int(context, sqlite3_total_changes(db));
  92739. }
  92740. /*
  92741. ** A structure defining how to do GLOB-style comparisons.
  92742. */
  92743. struct compareInfo {
  92744. u8 matchAll;
  92745. u8 matchOne;
  92746. u8 matchSet;
  92747. u8 noCase;
  92748. };
  92749. /*
  92750. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  92751. ** character is exactly one byte in size. Also, provde the Utf8Read()
  92752. ** macro for fast reading of the next character in the common case where
  92753. ** the next character is ASCII.
  92754. */
  92755. #if defined(SQLITE_EBCDIC)
  92756. # define sqlite3Utf8Read(A) (*((*A)++))
  92757. # define Utf8Read(A) (*(A++))
  92758. #else
  92759. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  92760. #endif
  92761. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  92762. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  92763. ** case. Thus 'a' LIKE 'A' would be true. */
  92764. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  92765. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  92766. ** is case sensitive causing 'a' LIKE 'A' to be false */
  92767. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  92768. /*
  92769. ** Compare two UTF-8 strings for equality where the first string can
  92770. ** potentially be a "glob" or "like" expression. Return true (1) if they
  92771. ** are the same and false (0) if they are different.
  92772. **
  92773. ** Globbing rules:
  92774. **
  92775. ** '*' Matches any sequence of zero or more characters.
  92776. **
  92777. ** '?' Matches exactly one character.
  92778. **
  92779. ** [...] Matches one character from the enclosed list of
  92780. ** characters.
  92781. **
  92782. ** [^...] Matches one character not in the enclosed list.
  92783. **
  92784. ** With the [...] and [^...] matching, a ']' character can be included
  92785. ** in the list by making it the first character after '[' or '^'. A
  92786. ** range of characters can be specified using '-'. Example:
  92787. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  92788. ** it the last character in the list.
  92789. **
  92790. ** Like matching rules:
  92791. **
  92792. ** '%' Matches any sequence of zero or more characters
  92793. **
  92794. *** '_' Matches any one character
  92795. **
  92796. ** Ec Where E is the "esc" character and c is any other
  92797. ** character, including '%', '_', and esc, match exactly c.
  92798. **
  92799. ** The comments within this routine usually assume glob matching.
  92800. **
  92801. ** This routine is usually quick, but can be N**2 in the worst case.
  92802. */
  92803. static int patternCompare(
  92804. const u8 *zPattern, /* The glob pattern */
  92805. const u8 *zString, /* The string to compare against the glob */
  92806. const struct compareInfo *pInfo, /* Information about how to do the compare */
  92807. u32 esc /* The escape character */
  92808. ){
  92809. u32 c, c2; /* Next pattern and input string chars */
  92810. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  92811. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  92812. u32 matchOther; /* "[" or the escape character */
  92813. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  92814. const u8 *zEscaped = 0; /* One past the last escaped input char */
  92815. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  92816. ** have the matchSet operator. So we either have to look for one or
  92817. ** the other, never both. Hence the single variable matchOther is used
  92818. ** to store the one we have to look for.
  92819. */
  92820. matchOther = esc ? esc : pInfo->matchSet;
  92821. while( (c = Utf8Read(zPattern))!=0 ){
  92822. if( c==matchAll ){ /* Match "*" */
  92823. /* Skip over multiple "*" characters in the pattern. If there
  92824. ** are also "?" characters, skip those as well, but consume a
  92825. ** single character of the input string for each "?" skipped */
  92826. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  92827. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  92828. return 0;
  92829. }
  92830. }
  92831. if( c==0 ){
  92832. return 1; /* "*" at the end of the pattern matches */
  92833. }else if( c==matchOther ){
  92834. if( esc ){
  92835. c = sqlite3Utf8Read(&zPattern);
  92836. if( c==0 ) return 0;
  92837. }else{
  92838. /* "[...]" immediately follows the "*". We have to do a slow
  92839. ** recursive search in this case, but it is an unusual case. */
  92840. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  92841. while( *zString
  92842. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  92843. SQLITE_SKIP_UTF8(zString);
  92844. }
  92845. return *zString!=0;
  92846. }
  92847. }
  92848. /* At this point variable c contains the first character of the
  92849. ** pattern string past the "*". Search in the input string for the
  92850. ** first matching character and recursively contine the match from
  92851. ** that point.
  92852. **
  92853. ** For a case-insensitive search, set variable cx to be the same as
  92854. ** c but in the other case and search the input string for either
  92855. ** c or cx.
  92856. */
  92857. if( c<=0x80 ){
  92858. u32 cx;
  92859. if( noCase ){
  92860. cx = sqlite3Toupper(c);
  92861. c = sqlite3Tolower(c);
  92862. }else{
  92863. cx = c;
  92864. }
  92865. while( (c2 = *(zString++))!=0 ){
  92866. if( c2!=c && c2!=cx ) continue;
  92867. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  92868. }
  92869. }else{
  92870. while( (c2 = Utf8Read(zString))!=0 ){
  92871. if( c2!=c ) continue;
  92872. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  92873. }
  92874. }
  92875. return 0;
  92876. }
  92877. if( c==matchOther ){
  92878. if( esc ){
  92879. c = sqlite3Utf8Read(&zPattern);
  92880. if( c==0 ) return 0;
  92881. zEscaped = zPattern;
  92882. }else{
  92883. u32 prior_c = 0;
  92884. int seen = 0;
  92885. int invert = 0;
  92886. c = sqlite3Utf8Read(&zString);
  92887. if( c==0 ) return 0;
  92888. c2 = sqlite3Utf8Read(&zPattern);
  92889. if( c2=='^' ){
  92890. invert = 1;
  92891. c2 = sqlite3Utf8Read(&zPattern);
  92892. }
  92893. if( c2==']' ){
  92894. if( c==']' ) seen = 1;
  92895. c2 = sqlite3Utf8Read(&zPattern);
  92896. }
  92897. while( c2 && c2!=']' ){
  92898. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  92899. c2 = sqlite3Utf8Read(&zPattern);
  92900. if( c>=prior_c && c<=c2 ) seen = 1;
  92901. prior_c = 0;
  92902. }else{
  92903. if( c==c2 ){
  92904. seen = 1;
  92905. }
  92906. prior_c = c2;
  92907. }
  92908. c2 = sqlite3Utf8Read(&zPattern);
  92909. }
  92910. if( c2==0 || (seen ^ invert)==0 ){
  92911. return 0;
  92912. }
  92913. continue;
  92914. }
  92915. }
  92916. c2 = Utf8Read(zString);
  92917. if( c==c2 ) continue;
  92918. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  92919. continue;
  92920. }
  92921. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  92922. return 0;
  92923. }
  92924. return *zString==0;
  92925. }
  92926. /*
  92927. ** The sqlite3_strglob() interface.
  92928. */
  92929. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
  92930. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  92931. }
  92932. /*
  92933. ** Count the number of times that the LIKE operator (or GLOB which is
  92934. ** just a variation of LIKE) gets called. This is used for testing
  92935. ** only.
  92936. */
  92937. #ifdef SQLITE_TEST
  92938. SQLITE_API int sqlite3_like_count = 0;
  92939. #endif
  92940. /*
  92941. ** Implementation of the like() SQL function. This function implements
  92942. ** the build-in LIKE operator. The first argument to the function is the
  92943. ** pattern and the second argument is the string. So, the SQL statements:
  92944. **
  92945. ** A LIKE B
  92946. **
  92947. ** is implemented as like(B,A).
  92948. **
  92949. ** This same function (with a different compareInfo structure) computes
  92950. ** the GLOB operator.
  92951. */
  92952. static void likeFunc(
  92953. sqlite3_context *context,
  92954. int argc,
  92955. sqlite3_value **argv
  92956. ){
  92957. const unsigned char *zA, *zB;
  92958. u32 escape = 0;
  92959. int nPat;
  92960. sqlite3 *db = sqlite3_context_db_handle(context);
  92961. zB = sqlite3_value_text(argv[0]);
  92962. zA = sqlite3_value_text(argv[1]);
  92963. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  92964. ** of deep recursion and N*N behavior in patternCompare().
  92965. */
  92966. nPat = sqlite3_value_bytes(argv[0]);
  92967. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  92968. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  92969. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  92970. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  92971. return;
  92972. }
  92973. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  92974. if( argc==3 ){
  92975. /* The escape character string must consist of a single UTF-8 character.
  92976. ** Otherwise, return an error.
  92977. */
  92978. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  92979. if( zEsc==0 ) return;
  92980. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  92981. sqlite3_result_error(context,
  92982. "ESCAPE expression must be a single character", -1);
  92983. return;
  92984. }
  92985. escape = sqlite3Utf8Read(&zEsc);
  92986. }
  92987. if( zA && zB ){
  92988. struct compareInfo *pInfo = sqlite3_user_data(context);
  92989. #ifdef SQLITE_TEST
  92990. sqlite3_like_count++;
  92991. #endif
  92992. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  92993. }
  92994. }
  92995. /*
  92996. ** Implementation of the NULLIF(x,y) function. The result is the first
  92997. ** argument if the arguments are different. The result is NULL if the
  92998. ** arguments are equal to each other.
  92999. */
  93000. static void nullifFunc(
  93001. sqlite3_context *context,
  93002. int NotUsed,
  93003. sqlite3_value **argv
  93004. ){
  93005. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  93006. UNUSED_PARAMETER(NotUsed);
  93007. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  93008. sqlite3_result_value(context, argv[0]);
  93009. }
  93010. }
  93011. /*
  93012. ** Implementation of the sqlite_version() function. The result is the version
  93013. ** of the SQLite library that is running.
  93014. */
  93015. static void versionFunc(
  93016. sqlite3_context *context,
  93017. int NotUsed,
  93018. sqlite3_value **NotUsed2
  93019. ){
  93020. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93021. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  93022. ** sqlite3_libversion() C-interface. */
  93023. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  93024. }
  93025. /*
  93026. ** Implementation of the sqlite_source_id() function. The result is a string
  93027. ** that identifies the particular version of the source code used to build
  93028. ** SQLite.
  93029. */
  93030. static void sourceidFunc(
  93031. sqlite3_context *context,
  93032. int NotUsed,
  93033. sqlite3_value **NotUsed2
  93034. ){
  93035. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93036. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  93037. ** sqlite3_sourceid() C interface. */
  93038. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  93039. }
  93040. /*
  93041. ** Implementation of the sqlite_log() function. This is a wrapper around
  93042. ** sqlite3_log(). The return value is NULL. The function exists purely for
  93043. ** its side-effects.
  93044. */
  93045. static void errlogFunc(
  93046. sqlite3_context *context,
  93047. int argc,
  93048. sqlite3_value **argv
  93049. ){
  93050. UNUSED_PARAMETER(argc);
  93051. UNUSED_PARAMETER(context);
  93052. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  93053. }
  93054. /*
  93055. ** Implementation of the sqlite_compileoption_used() function.
  93056. ** The result is an integer that identifies if the compiler option
  93057. ** was used to build SQLite.
  93058. */
  93059. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93060. static void compileoptionusedFunc(
  93061. sqlite3_context *context,
  93062. int argc,
  93063. sqlite3_value **argv
  93064. ){
  93065. const char *zOptName;
  93066. assert( argc==1 );
  93067. UNUSED_PARAMETER(argc);
  93068. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  93069. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  93070. ** function.
  93071. */
  93072. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  93073. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  93074. }
  93075. }
  93076. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  93077. /*
  93078. ** Implementation of the sqlite_compileoption_get() function.
  93079. ** The result is a string that identifies the compiler options
  93080. ** used to build SQLite.
  93081. */
  93082. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93083. static void compileoptiongetFunc(
  93084. sqlite3_context *context,
  93085. int argc,
  93086. sqlite3_value **argv
  93087. ){
  93088. int n;
  93089. assert( argc==1 );
  93090. UNUSED_PARAMETER(argc);
  93091. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  93092. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  93093. */
  93094. n = sqlite3_value_int(argv[0]);
  93095. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  93096. }
  93097. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  93098. /* Array for converting from half-bytes (nybbles) into ASCII hex
  93099. ** digits. */
  93100. static const char hexdigits[] = {
  93101. '0', '1', '2', '3', '4', '5', '6', '7',
  93102. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  93103. };
  93104. /*
  93105. ** Implementation of the QUOTE() function. This function takes a single
  93106. ** argument. If the argument is numeric, the return value is the same as
  93107. ** the argument. If the argument is NULL, the return value is the string
  93108. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  93109. ** single-quote escapes.
  93110. */
  93111. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93112. assert( argc==1 );
  93113. UNUSED_PARAMETER(argc);
  93114. switch( sqlite3_value_type(argv[0]) ){
  93115. case SQLITE_FLOAT: {
  93116. double r1, r2;
  93117. char zBuf[50];
  93118. r1 = sqlite3_value_double(argv[0]);
  93119. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  93120. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  93121. if( r1!=r2 ){
  93122. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  93123. }
  93124. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  93125. break;
  93126. }
  93127. case SQLITE_INTEGER: {
  93128. sqlite3_result_value(context, argv[0]);
  93129. break;
  93130. }
  93131. case SQLITE_BLOB: {
  93132. char *zText = 0;
  93133. char const *zBlob = sqlite3_value_blob(argv[0]);
  93134. int nBlob = sqlite3_value_bytes(argv[0]);
  93135. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  93136. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  93137. if( zText ){
  93138. int i;
  93139. for(i=0; i<nBlob; i++){
  93140. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  93141. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  93142. }
  93143. zText[(nBlob*2)+2] = '\'';
  93144. zText[(nBlob*2)+3] = '\0';
  93145. zText[0] = 'X';
  93146. zText[1] = '\'';
  93147. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  93148. sqlite3_free(zText);
  93149. }
  93150. break;
  93151. }
  93152. case SQLITE_TEXT: {
  93153. int i,j;
  93154. u64 n;
  93155. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  93156. char *z;
  93157. if( zArg==0 ) return;
  93158. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  93159. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  93160. if( z ){
  93161. z[0] = '\'';
  93162. for(i=0, j=1; zArg[i]; i++){
  93163. z[j++] = zArg[i];
  93164. if( zArg[i]=='\'' ){
  93165. z[j++] = '\'';
  93166. }
  93167. }
  93168. z[j++] = '\'';
  93169. z[j] = 0;
  93170. sqlite3_result_text(context, z, j, sqlite3_free);
  93171. }
  93172. break;
  93173. }
  93174. default: {
  93175. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  93176. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  93177. break;
  93178. }
  93179. }
  93180. }
  93181. /*
  93182. ** The unicode() function. Return the integer unicode code-point value
  93183. ** for the first character of the input string.
  93184. */
  93185. static void unicodeFunc(
  93186. sqlite3_context *context,
  93187. int argc,
  93188. sqlite3_value **argv
  93189. ){
  93190. const unsigned char *z = sqlite3_value_text(argv[0]);
  93191. (void)argc;
  93192. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  93193. }
  93194. /*
  93195. ** The char() function takes zero or more arguments, each of which is
  93196. ** an integer. It constructs a string where each character of the string
  93197. ** is the unicode character for the corresponding integer argument.
  93198. */
  93199. static void charFunc(
  93200. sqlite3_context *context,
  93201. int argc,
  93202. sqlite3_value **argv
  93203. ){
  93204. unsigned char *z, *zOut;
  93205. int i;
  93206. zOut = z = sqlite3_malloc64( argc*4+1 );
  93207. if( z==0 ){
  93208. sqlite3_result_error_nomem(context);
  93209. return;
  93210. }
  93211. for(i=0; i<argc; i++){
  93212. sqlite3_int64 x;
  93213. unsigned c;
  93214. x = sqlite3_value_int64(argv[i]);
  93215. if( x<0 || x>0x10ffff ) x = 0xfffd;
  93216. c = (unsigned)(x & 0x1fffff);
  93217. if( c<0x00080 ){
  93218. *zOut++ = (u8)(c&0xFF);
  93219. }else if( c<0x00800 ){
  93220. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  93221. *zOut++ = 0x80 + (u8)(c & 0x3F);
  93222. }else if( c<0x10000 ){
  93223. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  93224. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  93225. *zOut++ = 0x80 + (u8)(c & 0x3F);
  93226. }else{
  93227. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  93228. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  93229. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  93230. *zOut++ = 0x80 + (u8)(c & 0x3F);
  93231. } \
  93232. }
  93233. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  93234. }
  93235. /*
  93236. ** The hex() function. Interpret the argument as a blob. Return
  93237. ** a hexadecimal rendering as text.
  93238. */
  93239. static void hexFunc(
  93240. sqlite3_context *context,
  93241. int argc,
  93242. sqlite3_value **argv
  93243. ){
  93244. int i, n;
  93245. const unsigned char *pBlob;
  93246. char *zHex, *z;
  93247. assert( argc==1 );
  93248. UNUSED_PARAMETER(argc);
  93249. pBlob = sqlite3_value_blob(argv[0]);
  93250. n = sqlite3_value_bytes(argv[0]);
  93251. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  93252. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  93253. if( zHex ){
  93254. for(i=0; i<n; i++, pBlob++){
  93255. unsigned char c = *pBlob;
  93256. *(z++) = hexdigits[(c>>4)&0xf];
  93257. *(z++) = hexdigits[c&0xf];
  93258. }
  93259. *z = 0;
  93260. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  93261. }
  93262. }
  93263. /*
  93264. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  93265. */
  93266. static void zeroblobFunc(
  93267. sqlite3_context *context,
  93268. int argc,
  93269. sqlite3_value **argv
  93270. ){
  93271. i64 n;
  93272. int rc;
  93273. assert( argc==1 );
  93274. UNUSED_PARAMETER(argc);
  93275. n = sqlite3_value_int64(argv[0]);
  93276. if( n<0 ) n = 0;
  93277. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  93278. if( rc ){
  93279. sqlite3_result_error_code(context, rc);
  93280. }
  93281. }
  93282. /*
  93283. ** The replace() function. Three arguments are all strings: call
  93284. ** them A, B, and C. The result is also a string which is derived
  93285. ** from A by replacing every occurrence of B with C. The match
  93286. ** must be exact. Collating sequences are not used.
  93287. */
  93288. static void replaceFunc(
  93289. sqlite3_context *context,
  93290. int argc,
  93291. sqlite3_value **argv
  93292. ){
  93293. const unsigned char *zStr; /* The input string A */
  93294. const unsigned char *zPattern; /* The pattern string B */
  93295. const unsigned char *zRep; /* The replacement string C */
  93296. unsigned char *zOut; /* The output */
  93297. int nStr; /* Size of zStr */
  93298. int nPattern; /* Size of zPattern */
  93299. int nRep; /* Size of zRep */
  93300. i64 nOut; /* Maximum size of zOut */
  93301. int loopLimit; /* Last zStr[] that might match zPattern[] */
  93302. int i, j; /* Loop counters */
  93303. assert( argc==3 );
  93304. UNUSED_PARAMETER(argc);
  93305. zStr = sqlite3_value_text(argv[0]);
  93306. if( zStr==0 ) return;
  93307. nStr = sqlite3_value_bytes(argv[0]);
  93308. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  93309. zPattern = sqlite3_value_text(argv[1]);
  93310. if( zPattern==0 ){
  93311. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  93312. || sqlite3_context_db_handle(context)->mallocFailed );
  93313. return;
  93314. }
  93315. if( zPattern[0]==0 ){
  93316. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  93317. sqlite3_result_value(context, argv[0]);
  93318. return;
  93319. }
  93320. nPattern = sqlite3_value_bytes(argv[1]);
  93321. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  93322. zRep = sqlite3_value_text(argv[2]);
  93323. if( zRep==0 ) return;
  93324. nRep = sqlite3_value_bytes(argv[2]);
  93325. assert( zRep==sqlite3_value_text(argv[2]) );
  93326. nOut = nStr + 1;
  93327. assert( nOut<SQLITE_MAX_LENGTH );
  93328. zOut = contextMalloc(context, (i64)nOut);
  93329. if( zOut==0 ){
  93330. return;
  93331. }
  93332. loopLimit = nStr - nPattern;
  93333. for(i=j=0; i<=loopLimit; i++){
  93334. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  93335. zOut[j++] = zStr[i];
  93336. }else{
  93337. u8 *zOld;
  93338. sqlite3 *db = sqlite3_context_db_handle(context);
  93339. nOut += nRep - nPattern;
  93340. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  93341. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  93342. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  93343. sqlite3_result_error_toobig(context);
  93344. sqlite3_free(zOut);
  93345. return;
  93346. }
  93347. zOld = zOut;
  93348. zOut = sqlite3_realloc64(zOut, (int)nOut);
  93349. if( zOut==0 ){
  93350. sqlite3_result_error_nomem(context);
  93351. sqlite3_free(zOld);
  93352. return;
  93353. }
  93354. memcpy(&zOut[j], zRep, nRep);
  93355. j += nRep;
  93356. i += nPattern-1;
  93357. }
  93358. }
  93359. assert( j+nStr-i+1==nOut );
  93360. memcpy(&zOut[j], &zStr[i], nStr-i);
  93361. j += nStr - i;
  93362. assert( j<=nOut );
  93363. zOut[j] = 0;
  93364. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  93365. }
  93366. /*
  93367. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  93368. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  93369. */
  93370. static void trimFunc(
  93371. sqlite3_context *context,
  93372. int argc,
  93373. sqlite3_value **argv
  93374. ){
  93375. const unsigned char *zIn; /* Input string */
  93376. const unsigned char *zCharSet; /* Set of characters to trim */
  93377. int nIn; /* Number of bytes in input */
  93378. int flags; /* 1: trimleft 2: trimright 3: trim */
  93379. int i; /* Loop counter */
  93380. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  93381. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  93382. int nChar; /* Number of characters in zCharSet */
  93383. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  93384. return;
  93385. }
  93386. zIn = sqlite3_value_text(argv[0]);
  93387. if( zIn==0 ) return;
  93388. nIn = sqlite3_value_bytes(argv[0]);
  93389. assert( zIn==sqlite3_value_text(argv[0]) );
  93390. if( argc==1 ){
  93391. static const unsigned char lenOne[] = { 1 };
  93392. static unsigned char * const azOne[] = { (u8*)" " };
  93393. nChar = 1;
  93394. aLen = (u8*)lenOne;
  93395. azChar = (unsigned char **)azOne;
  93396. zCharSet = 0;
  93397. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  93398. return;
  93399. }else{
  93400. const unsigned char *z;
  93401. for(z=zCharSet, nChar=0; *z; nChar++){
  93402. SQLITE_SKIP_UTF8(z);
  93403. }
  93404. if( nChar>0 ){
  93405. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  93406. if( azChar==0 ){
  93407. return;
  93408. }
  93409. aLen = (unsigned char*)&azChar[nChar];
  93410. for(z=zCharSet, nChar=0; *z; nChar++){
  93411. azChar[nChar] = (unsigned char *)z;
  93412. SQLITE_SKIP_UTF8(z);
  93413. aLen[nChar] = (u8)(z - azChar[nChar]);
  93414. }
  93415. }
  93416. }
  93417. if( nChar>0 ){
  93418. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  93419. if( flags & 1 ){
  93420. while( nIn>0 ){
  93421. int len = 0;
  93422. for(i=0; i<nChar; i++){
  93423. len = aLen[i];
  93424. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  93425. }
  93426. if( i>=nChar ) break;
  93427. zIn += len;
  93428. nIn -= len;
  93429. }
  93430. }
  93431. if( flags & 2 ){
  93432. while( nIn>0 ){
  93433. int len = 0;
  93434. for(i=0; i<nChar; i++){
  93435. len = aLen[i];
  93436. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  93437. }
  93438. if( i>=nChar ) break;
  93439. nIn -= len;
  93440. }
  93441. }
  93442. if( zCharSet ){
  93443. sqlite3_free(azChar);
  93444. }
  93445. }
  93446. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  93447. }
  93448. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  93449. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  93450. ** when SQLite is built.
  93451. */
  93452. #ifdef SQLITE_SOUNDEX
  93453. /*
  93454. ** Compute the soundex encoding of a word.
  93455. **
  93456. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  93457. ** soundex encoding of the string X.
  93458. */
  93459. static void soundexFunc(
  93460. sqlite3_context *context,
  93461. int argc,
  93462. sqlite3_value **argv
  93463. ){
  93464. char zResult[8];
  93465. const u8 *zIn;
  93466. int i, j;
  93467. static const unsigned char iCode[] = {
  93468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93472. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  93473. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  93474. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  93475. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  93476. };
  93477. assert( argc==1 );
  93478. zIn = (u8*)sqlite3_value_text(argv[0]);
  93479. if( zIn==0 ) zIn = (u8*)"";
  93480. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  93481. if( zIn[i] ){
  93482. u8 prevcode = iCode[zIn[i]&0x7f];
  93483. zResult[0] = sqlite3Toupper(zIn[i]);
  93484. for(j=1; j<4 && zIn[i]; i++){
  93485. int code = iCode[zIn[i]&0x7f];
  93486. if( code>0 ){
  93487. if( code!=prevcode ){
  93488. prevcode = code;
  93489. zResult[j++] = code + '0';
  93490. }
  93491. }else{
  93492. prevcode = 0;
  93493. }
  93494. }
  93495. while( j<4 ){
  93496. zResult[j++] = '0';
  93497. }
  93498. zResult[j] = 0;
  93499. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  93500. }else{
  93501. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  93502. ** is NULL or contains no ASCII alphabetic characters. */
  93503. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  93504. }
  93505. }
  93506. #endif /* SQLITE_SOUNDEX */
  93507. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  93508. /*
  93509. ** A function that loads a shared-library extension then returns NULL.
  93510. */
  93511. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  93512. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  93513. const char *zProc;
  93514. sqlite3 *db = sqlite3_context_db_handle(context);
  93515. char *zErrMsg = 0;
  93516. if( argc==2 ){
  93517. zProc = (const char *)sqlite3_value_text(argv[1]);
  93518. }else{
  93519. zProc = 0;
  93520. }
  93521. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  93522. sqlite3_result_error(context, zErrMsg, -1);
  93523. sqlite3_free(zErrMsg);
  93524. }
  93525. }
  93526. #endif
  93527. /*
  93528. ** An instance of the following structure holds the context of a
  93529. ** sum() or avg() aggregate computation.
  93530. */
  93531. typedef struct SumCtx SumCtx;
  93532. struct SumCtx {
  93533. double rSum; /* Floating point sum */
  93534. i64 iSum; /* Integer sum */
  93535. i64 cnt; /* Number of elements summed */
  93536. u8 overflow; /* True if integer overflow seen */
  93537. u8 approx; /* True if non-integer value was input to the sum */
  93538. };
  93539. /*
  93540. ** Routines used to compute the sum, average, and total.
  93541. **
  93542. ** The SUM() function follows the (broken) SQL standard which means
  93543. ** that it returns NULL if it sums over no inputs. TOTAL returns
  93544. ** 0.0 in that case. In addition, TOTAL always returns a float where
  93545. ** SUM might return an integer if it never encounters a floating point
  93546. ** value. TOTAL never fails, but SUM might through an exception if
  93547. ** it overflows an integer.
  93548. */
  93549. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  93550. SumCtx *p;
  93551. int type;
  93552. assert( argc==1 );
  93553. UNUSED_PARAMETER(argc);
  93554. p = sqlite3_aggregate_context(context, sizeof(*p));
  93555. type = sqlite3_value_numeric_type(argv[0]);
  93556. if( p && type!=SQLITE_NULL ){
  93557. p->cnt++;
  93558. if( type==SQLITE_INTEGER ){
  93559. i64 v = sqlite3_value_int64(argv[0]);
  93560. p->rSum += v;
  93561. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  93562. p->overflow = 1;
  93563. }
  93564. }else{
  93565. p->rSum += sqlite3_value_double(argv[0]);
  93566. p->approx = 1;
  93567. }
  93568. }
  93569. }
  93570. static void sumFinalize(sqlite3_context *context){
  93571. SumCtx *p;
  93572. p = sqlite3_aggregate_context(context, 0);
  93573. if( p && p->cnt>0 ){
  93574. if( p->overflow ){
  93575. sqlite3_result_error(context,"integer overflow",-1);
  93576. }else if( p->approx ){
  93577. sqlite3_result_double(context, p->rSum);
  93578. }else{
  93579. sqlite3_result_int64(context, p->iSum);
  93580. }
  93581. }
  93582. }
  93583. static void avgFinalize(sqlite3_context *context){
  93584. SumCtx *p;
  93585. p = sqlite3_aggregate_context(context, 0);
  93586. if( p && p->cnt>0 ){
  93587. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  93588. }
  93589. }
  93590. static void totalFinalize(sqlite3_context *context){
  93591. SumCtx *p;
  93592. p = sqlite3_aggregate_context(context, 0);
  93593. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  93594. sqlite3_result_double(context, p ? p->rSum : (double)0);
  93595. }
  93596. /*
  93597. ** The following structure keeps track of state information for the
  93598. ** count() aggregate function.
  93599. */
  93600. typedef struct CountCtx CountCtx;
  93601. struct CountCtx {
  93602. i64 n;
  93603. };
  93604. /*
  93605. ** Routines to implement the count() aggregate function.
  93606. */
  93607. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  93608. CountCtx *p;
  93609. p = sqlite3_aggregate_context(context, sizeof(*p));
  93610. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  93611. p->n++;
  93612. }
  93613. #ifndef SQLITE_OMIT_DEPRECATED
  93614. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  93615. ** sure it still operates correctly, verify that its count agrees with our
  93616. ** internal count when using count(*) and when the total count can be
  93617. ** expressed as a 32-bit integer. */
  93618. assert( argc==1 || p==0 || p->n>0x7fffffff
  93619. || p->n==sqlite3_aggregate_count(context) );
  93620. #endif
  93621. }
  93622. static void countFinalize(sqlite3_context *context){
  93623. CountCtx *p;
  93624. p = sqlite3_aggregate_context(context, 0);
  93625. sqlite3_result_int64(context, p ? p->n : 0);
  93626. }
  93627. /*
  93628. ** Routines to implement min() and max() aggregate functions.
  93629. */
  93630. static void minmaxStep(
  93631. sqlite3_context *context,
  93632. int NotUsed,
  93633. sqlite3_value **argv
  93634. ){
  93635. Mem *pArg = (Mem *)argv[0];
  93636. Mem *pBest;
  93637. UNUSED_PARAMETER(NotUsed);
  93638. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  93639. if( !pBest ) return;
  93640. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  93641. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  93642. }else if( pBest->flags ){
  93643. int max;
  93644. int cmp;
  93645. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  93646. /* This step function is used for both the min() and max() aggregates,
  93647. ** the only difference between the two being that the sense of the
  93648. ** comparison is inverted. For the max() aggregate, the
  93649. ** sqlite3_user_data() function returns (void *)-1. For min() it
  93650. ** returns (void *)db, where db is the sqlite3* database pointer.
  93651. ** Therefore the next statement sets variable 'max' to 1 for the max()
  93652. ** aggregate, or 0 for min().
  93653. */
  93654. max = sqlite3_user_data(context)!=0;
  93655. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  93656. if( (max && cmp<0) || (!max && cmp>0) ){
  93657. sqlite3VdbeMemCopy(pBest, pArg);
  93658. }else{
  93659. sqlite3SkipAccumulatorLoad(context);
  93660. }
  93661. }else{
  93662. pBest->db = sqlite3_context_db_handle(context);
  93663. sqlite3VdbeMemCopy(pBest, pArg);
  93664. }
  93665. }
  93666. static void minMaxFinalize(sqlite3_context *context){
  93667. sqlite3_value *pRes;
  93668. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  93669. if( pRes ){
  93670. if( pRes->flags ){
  93671. sqlite3_result_value(context, pRes);
  93672. }
  93673. sqlite3VdbeMemRelease(pRes);
  93674. }
  93675. }
  93676. /*
  93677. ** group_concat(EXPR, ?SEPARATOR?)
  93678. */
  93679. static void groupConcatStep(
  93680. sqlite3_context *context,
  93681. int argc,
  93682. sqlite3_value **argv
  93683. ){
  93684. const char *zVal;
  93685. StrAccum *pAccum;
  93686. const char *zSep;
  93687. int nVal, nSep;
  93688. assert( argc==1 || argc==2 );
  93689. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  93690. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  93691. if( pAccum ){
  93692. sqlite3 *db = sqlite3_context_db_handle(context);
  93693. int firstTerm = pAccum->mxAlloc==0;
  93694. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  93695. if( !firstTerm ){
  93696. if( argc==2 ){
  93697. zSep = (char*)sqlite3_value_text(argv[1]);
  93698. nSep = sqlite3_value_bytes(argv[1]);
  93699. }else{
  93700. zSep = ",";
  93701. nSep = 1;
  93702. }
  93703. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  93704. }
  93705. zVal = (char*)sqlite3_value_text(argv[0]);
  93706. nVal = sqlite3_value_bytes(argv[0]);
  93707. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  93708. }
  93709. }
  93710. static void groupConcatFinalize(sqlite3_context *context){
  93711. StrAccum *pAccum;
  93712. pAccum = sqlite3_aggregate_context(context, 0);
  93713. if( pAccum ){
  93714. if( pAccum->accError==STRACCUM_TOOBIG ){
  93715. sqlite3_result_error_toobig(context);
  93716. }else if( pAccum->accError==STRACCUM_NOMEM ){
  93717. sqlite3_result_error_nomem(context);
  93718. }else{
  93719. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  93720. sqlite3_free);
  93721. }
  93722. }
  93723. }
  93724. /*
  93725. ** This routine does per-connection function registration. Most
  93726. ** of the built-in functions above are part of the global function set.
  93727. ** This routine only deals with those that are not global.
  93728. */
  93729. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  93730. int rc = sqlite3_overload_function(db, "MATCH", 2);
  93731. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  93732. if( rc==SQLITE_NOMEM ){
  93733. db->mallocFailed = 1;
  93734. }
  93735. }
  93736. /*
  93737. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  93738. */
  93739. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  93740. FuncDef *pDef;
  93741. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  93742. 2, SQLITE_UTF8, 0);
  93743. if( ALWAYS(pDef) ){
  93744. pDef->funcFlags |= flagVal;
  93745. }
  93746. }
  93747. /*
  93748. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  93749. ** parameter determines whether or not the LIKE operator is case
  93750. ** sensitive. GLOB is always case sensitive.
  93751. */
  93752. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  93753. struct compareInfo *pInfo;
  93754. if( caseSensitive ){
  93755. pInfo = (struct compareInfo*)&likeInfoAlt;
  93756. }else{
  93757. pInfo = (struct compareInfo*)&likeInfoNorm;
  93758. }
  93759. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  93760. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  93761. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  93762. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  93763. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  93764. setLikeOptFlag(db, "like",
  93765. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  93766. }
  93767. /*
  93768. ** pExpr points to an expression which implements a function. If
  93769. ** it is appropriate to apply the LIKE optimization to that function
  93770. ** then set aWc[0] through aWc[2] to the wildcard characters and
  93771. ** return TRUE. If the function is not a LIKE-style function then
  93772. ** return FALSE.
  93773. **
  93774. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  93775. ** the function (default for LIKE). If the function makes the distinction
  93776. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  93777. ** false.
  93778. */
  93779. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  93780. FuncDef *pDef;
  93781. if( pExpr->op!=TK_FUNCTION
  93782. || !pExpr->x.pList
  93783. || pExpr->x.pList->nExpr!=2
  93784. ){
  93785. return 0;
  93786. }
  93787. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93788. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  93789. sqlite3Strlen30(pExpr->u.zToken),
  93790. 2, SQLITE_UTF8, 0);
  93791. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  93792. return 0;
  93793. }
  93794. /* The memcpy() statement assumes that the wildcard characters are
  93795. ** the first three statements in the compareInfo structure. The
  93796. ** asserts() that follow verify that assumption
  93797. */
  93798. memcpy(aWc, pDef->pUserData, 3);
  93799. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  93800. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  93801. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  93802. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  93803. return 1;
  93804. }
  93805. /*
  93806. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  93807. ** to the global function hash table. This occurs at start-time (as
  93808. ** a consequence of calling sqlite3_initialize()).
  93809. **
  93810. ** After this routine runs
  93811. */
  93812. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  93813. /*
  93814. ** The following array holds FuncDef structures for all of the functions
  93815. ** defined in this file.
  93816. **
  93817. ** The array cannot be constant since changes are made to the
  93818. ** FuncDef.pHash elements at start-time. The elements of this array
  93819. ** are read-only after initialization is complete.
  93820. */
  93821. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  93822. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  93823. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  93824. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  93825. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  93826. FUNCTION(trim, 1, 3, 0, trimFunc ),
  93827. FUNCTION(trim, 2, 3, 0, trimFunc ),
  93828. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  93829. FUNCTION(min, 0, 0, 1, 0 ),
  93830. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  93831. SQLITE_FUNC_MINMAX ),
  93832. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  93833. FUNCTION(max, 0, 1, 1, 0 ),
  93834. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  93835. SQLITE_FUNC_MINMAX ),
  93836. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  93837. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  93838. FUNCTION(instr, 2, 0, 0, instrFunc ),
  93839. FUNCTION(substr, 2, 0, 0, substrFunc ),
  93840. FUNCTION(substr, 3, 0, 0, substrFunc ),
  93841. FUNCTION(printf, -1, 0, 0, printfFunc ),
  93842. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  93843. FUNCTION(char, -1, 0, 0, charFunc ),
  93844. FUNCTION(abs, 1, 0, 0, absFunc ),
  93845. #ifndef SQLITE_OMIT_FLOATING_POINT
  93846. FUNCTION(round, 1, 0, 0, roundFunc ),
  93847. FUNCTION(round, 2, 0, 0, roundFunc ),
  93848. #endif
  93849. FUNCTION(upper, 1, 0, 0, upperFunc ),
  93850. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  93851. FUNCTION(coalesce, 1, 0, 0, 0 ),
  93852. FUNCTION(coalesce, 0, 0, 0, 0 ),
  93853. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  93854. FUNCTION(hex, 1, 0, 0, hexFunc ),
  93855. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  93856. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  93857. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  93858. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  93859. VFUNCTION(random, 0, 0, 0, randomFunc ),
  93860. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  93861. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  93862. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  93863. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  93864. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  93865. #if SQLITE_USER_AUTHENTICATION
  93866. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  93867. #endif
  93868. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93869. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  93870. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  93871. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  93872. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  93873. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  93874. VFUNCTION(changes, 0, 0, 0, changes ),
  93875. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  93876. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  93877. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  93878. #ifdef SQLITE_SOUNDEX
  93879. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  93880. #endif
  93881. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  93882. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  93883. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  93884. #endif
  93885. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  93886. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  93887. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  93888. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  93889. SQLITE_FUNC_COUNT ),
  93890. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  93891. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  93892. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  93893. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  93894. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  93895. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  93896. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  93897. #else
  93898. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  93899. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  93900. #endif
  93901. };
  93902. int i;
  93903. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  93904. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  93905. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  93906. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  93907. }
  93908. sqlite3RegisterDateTimeFunctions();
  93909. #ifndef SQLITE_OMIT_ALTERTABLE
  93910. sqlite3AlterFunctions();
  93911. #endif
  93912. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  93913. sqlite3AnalyzeFunctions();
  93914. #endif
  93915. }
  93916. /************** End of func.c ************************************************/
  93917. /************** Begin file fkey.c ********************************************/
  93918. /*
  93919. **
  93920. ** The author disclaims copyright to this source code. In place of
  93921. ** a legal notice, here is a blessing:
  93922. **
  93923. ** May you do good and not evil.
  93924. ** May you find forgiveness for yourself and forgive others.
  93925. ** May you share freely, never taking more than you give.
  93926. **
  93927. *************************************************************************
  93928. ** This file contains code used by the compiler to add foreign key
  93929. ** support to compiled SQL statements.
  93930. */
  93931. /* #include "sqliteInt.h" */
  93932. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93933. #ifndef SQLITE_OMIT_TRIGGER
  93934. /*
  93935. ** Deferred and Immediate FKs
  93936. ** --------------------------
  93937. **
  93938. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  93939. ** If an immediate foreign key constraint is violated,
  93940. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  93941. ** statement transaction rolled back. If a
  93942. ** deferred foreign key constraint is violated, no action is taken
  93943. ** immediately. However if the application attempts to commit the
  93944. ** transaction before fixing the constraint violation, the attempt fails.
  93945. **
  93946. ** Deferred constraints are implemented using a simple counter associated
  93947. ** with the database handle. The counter is set to zero each time a
  93948. ** database transaction is opened. Each time a statement is executed
  93949. ** that causes a foreign key violation, the counter is incremented. Each
  93950. ** time a statement is executed that removes an existing violation from
  93951. ** the database, the counter is decremented. When the transaction is
  93952. ** committed, the commit fails if the current value of the counter is
  93953. ** greater than zero. This scheme has two big drawbacks:
  93954. **
  93955. ** * When a commit fails due to a deferred foreign key constraint,
  93956. ** there is no way to tell which foreign constraint is not satisfied,
  93957. ** or which row it is not satisfied for.
  93958. **
  93959. ** * If the database contains foreign key violations when the
  93960. ** transaction is opened, this may cause the mechanism to malfunction.
  93961. **
  93962. ** Despite these problems, this approach is adopted as it seems simpler
  93963. ** than the alternatives.
  93964. **
  93965. ** INSERT operations:
  93966. **
  93967. ** I.1) For each FK for which the table is the child table, search
  93968. ** the parent table for a match. If none is found increment the
  93969. ** constraint counter.
  93970. **
  93971. ** I.2) For each FK for which the table is the parent table,
  93972. ** search the child table for rows that correspond to the new
  93973. ** row in the parent table. Decrement the counter for each row
  93974. ** found (as the constraint is now satisfied).
  93975. **
  93976. ** DELETE operations:
  93977. **
  93978. ** D.1) For each FK for which the table is the child table,
  93979. ** search the parent table for a row that corresponds to the
  93980. ** deleted row in the child table. If such a row is not found,
  93981. ** decrement the counter.
  93982. **
  93983. ** D.2) For each FK for which the table is the parent table, search
  93984. ** the child table for rows that correspond to the deleted row
  93985. ** in the parent table. For each found increment the counter.
  93986. **
  93987. ** UPDATE operations:
  93988. **
  93989. ** An UPDATE command requires that all 4 steps above are taken, but only
  93990. ** for FK constraints for which the affected columns are actually
  93991. ** modified (values must be compared at runtime).
  93992. **
  93993. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  93994. ** This simplifies the implementation a bit.
  93995. **
  93996. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  93997. ** resolution is considered to delete rows before the new row is inserted.
  93998. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  93999. ** is thrown, even if the FK constraint would be satisfied after the new
  94000. ** row is inserted.
  94001. **
  94002. ** Immediate constraints are usually handled similarly. The only difference
  94003. ** is that the counter used is stored as part of each individual statement
  94004. ** object (struct Vdbe). If, after the statement has run, its immediate
  94005. ** constraint counter is greater than zero,
  94006. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  94007. ** and the statement transaction is rolled back. An exception is an INSERT
  94008. ** statement that inserts a single row only (no triggers). In this case,
  94009. ** instead of using a counter, an exception is thrown immediately if the
  94010. ** INSERT violates a foreign key constraint. This is necessary as such
  94011. ** an INSERT does not open a statement transaction.
  94012. **
  94013. ** TODO: How should dropping a table be handled? How should renaming a
  94014. ** table be handled?
  94015. **
  94016. **
  94017. ** Query API Notes
  94018. ** ---------------
  94019. **
  94020. ** Before coding an UPDATE or DELETE row operation, the code-generator
  94021. ** for those two operations needs to know whether or not the operation
  94022. ** requires any FK processing and, if so, which columns of the original
  94023. ** row are required by the FK processing VDBE code (i.e. if FKs were
  94024. ** implemented using triggers, which of the old.* columns would be
  94025. ** accessed). No information is required by the code-generator before
  94026. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  94027. ** generation code to query for this information are:
  94028. **
  94029. ** sqlite3FkRequired() - Test to see if FK processing is required.
  94030. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  94031. **
  94032. **
  94033. ** Externally accessible module functions
  94034. ** --------------------------------------
  94035. **
  94036. ** sqlite3FkCheck() - Check for foreign key violations.
  94037. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  94038. ** sqlite3FkDelete() - Delete an FKey structure.
  94039. */
  94040. /*
  94041. ** VDBE Calling Convention
  94042. ** -----------------------
  94043. **
  94044. ** Example:
  94045. **
  94046. ** For the following INSERT statement:
  94047. **
  94048. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  94049. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  94050. **
  94051. ** Register (x): 2 (type integer)
  94052. ** Register (x+1): 1 (type integer)
  94053. ** Register (x+2): NULL (type NULL)
  94054. ** Register (x+3): 3.1 (type real)
  94055. */
  94056. /*
  94057. ** A foreign key constraint requires that the key columns in the parent
  94058. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  94059. ** Given that pParent is the parent table for foreign key constraint pFKey,
  94060. ** search the schema for a unique index on the parent key columns.
  94061. **
  94062. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  94063. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  94064. ** is set to point to the unique index.
  94065. **
  94066. ** If the parent key consists of a single column (the foreign key constraint
  94067. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  94068. ** Otherwise, it is set to point to an allocated array of size N, where
  94069. ** N is the number of columns in the parent key. The first element of the
  94070. ** array is the index of the child table column that is mapped by the FK
  94071. ** constraint to the parent table column stored in the left-most column
  94072. ** of index *ppIdx. The second element of the array is the index of the
  94073. ** child table column that corresponds to the second left-most column of
  94074. ** *ppIdx, and so on.
  94075. **
  94076. ** If the required index cannot be found, either because:
  94077. **
  94078. ** 1) The named parent key columns do not exist, or
  94079. **
  94080. ** 2) The named parent key columns do exist, but are not subject to a
  94081. ** UNIQUE or PRIMARY KEY constraint, or
  94082. **
  94083. ** 3) No parent key columns were provided explicitly as part of the
  94084. ** foreign key definition, and the parent table does not have a
  94085. ** PRIMARY KEY, or
  94086. **
  94087. ** 4) No parent key columns were provided explicitly as part of the
  94088. ** foreign key definition, and the PRIMARY KEY of the parent table
  94089. ** consists of a different number of columns to the child key in
  94090. ** the child table.
  94091. **
  94092. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  94093. ** into pParse. If an OOM error occurs, non-zero is returned and the
  94094. ** pParse->db->mallocFailed flag is set.
  94095. */
  94096. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  94097. Parse *pParse, /* Parse context to store any error in */
  94098. Table *pParent, /* Parent table of FK constraint pFKey */
  94099. FKey *pFKey, /* Foreign key to find index for */
  94100. Index **ppIdx, /* OUT: Unique index on parent table */
  94101. int **paiCol /* OUT: Map of index columns in pFKey */
  94102. ){
  94103. Index *pIdx = 0; /* Value to return via *ppIdx */
  94104. int *aiCol = 0; /* Value to return via *paiCol */
  94105. int nCol = pFKey->nCol; /* Number of columns in parent key */
  94106. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  94107. /* The caller is responsible for zeroing output parameters. */
  94108. assert( ppIdx && *ppIdx==0 );
  94109. assert( !paiCol || *paiCol==0 );
  94110. assert( pParse );
  94111. /* If this is a non-composite (single column) foreign key, check if it
  94112. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  94113. ** and *paiCol set to zero and return early.
  94114. **
  94115. ** Otherwise, for a composite foreign key (more than one column), allocate
  94116. ** space for the aiCol array (returned via output parameter *paiCol).
  94117. ** Non-composite foreign keys do not require the aiCol array.
  94118. */
  94119. if( nCol==1 ){
  94120. /* The FK maps to the IPK if any of the following are true:
  94121. **
  94122. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  94123. ** mapped to the primary key of table pParent, or
  94124. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  94125. ** PRIMARY KEY.
  94126. */
  94127. if( pParent->iPKey>=0 ){
  94128. if( !zKey ) return 0;
  94129. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  94130. }
  94131. }else if( paiCol ){
  94132. assert( nCol>1 );
  94133. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  94134. if( !aiCol ) return 1;
  94135. *paiCol = aiCol;
  94136. }
  94137. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  94138. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  94139. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  94140. ** of columns. If each indexed column corresponds to a foreign key
  94141. ** column of pFKey, then this index is a winner. */
  94142. if( zKey==0 ){
  94143. /* If zKey is NULL, then this foreign key is implicitly mapped to
  94144. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  94145. ** identified by the test. */
  94146. if( IsPrimaryKeyIndex(pIdx) ){
  94147. if( aiCol ){
  94148. int i;
  94149. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  94150. }
  94151. break;
  94152. }
  94153. }else{
  94154. /* If zKey is non-NULL, then this foreign key was declared to
  94155. ** map to an explicit list of columns in table pParent. Check if this
  94156. ** index matches those columns. Also, check that the index uses
  94157. ** the default collation sequences for each column. */
  94158. int i, j;
  94159. for(i=0; i<nCol; i++){
  94160. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  94161. char *zDfltColl; /* Def. collation for column */
  94162. char *zIdxCol; /* Name of indexed column */
  94163. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  94164. /* If the index uses a collation sequence that is different from
  94165. ** the default collation sequence for the column, this index is
  94166. ** unusable. Bail out early in this case. */
  94167. zDfltColl = pParent->aCol[iCol].zColl;
  94168. if( !zDfltColl ){
  94169. zDfltColl = "BINARY";
  94170. }
  94171. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  94172. zIdxCol = pParent->aCol[iCol].zName;
  94173. for(j=0; j<nCol; j++){
  94174. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  94175. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  94176. break;
  94177. }
  94178. }
  94179. if( j==nCol ) break;
  94180. }
  94181. if( i==nCol ) break; /* pIdx is usable */
  94182. }
  94183. }
  94184. }
  94185. if( !pIdx ){
  94186. if( !pParse->disableTriggers ){
  94187. sqlite3ErrorMsg(pParse,
  94188. "foreign key mismatch - \"%w\" referencing \"%w\"",
  94189. pFKey->pFrom->zName, pFKey->zTo);
  94190. }
  94191. sqlite3DbFree(pParse->db, aiCol);
  94192. return 1;
  94193. }
  94194. *ppIdx = pIdx;
  94195. return 0;
  94196. }
  94197. /*
  94198. ** This function is called when a row is inserted into or deleted from the
  94199. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  94200. ** on the child table of pFKey, this function is invoked twice for each row
  94201. ** affected - once to "delete" the old row, and then again to "insert" the
  94202. ** new row.
  94203. **
  94204. ** Each time it is called, this function generates VDBE code to locate the
  94205. ** row in the parent table that corresponds to the row being inserted into
  94206. ** or deleted from the child table. If the parent row can be found, no
  94207. ** special action is taken. Otherwise, if the parent row can *not* be
  94208. ** found in the parent table:
  94209. **
  94210. ** Operation | FK type | Action taken
  94211. ** --------------------------------------------------------------------------
  94212. ** INSERT immediate Increment the "immediate constraint counter".
  94213. **
  94214. ** DELETE immediate Decrement the "immediate constraint counter".
  94215. **
  94216. ** INSERT deferred Increment the "deferred constraint counter".
  94217. **
  94218. ** DELETE deferred Decrement the "deferred constraint counter".
  94219. **
  94220. ** These operations are identified in the comment at the top of this file
  94221. ** (fkey.c) as "I.1" and "D.1".
  94222. */
  94223. static void fkLookupParent(
  94224. Parse *pParse, /* Parse context */
  94225. int iDb, /* Index of database housing pTab */
  94226. Table *pTab, /* Parent table of FK pFKey */
  94227. Index *pIdx, /* Unique index on parent key columns in pTab */
  94228. FKey *pFKey, /* Foreign key constraint */
  94229. int *aiCol, /* Map from parent key columns to child table columns */
  94230. int regData, /* Address of array containing child table row */
  94231. int nIncr, /* Increment constraint counter by this */
  94232. int isIgnore /* If true, pretend pTab contains all NULL values */
  94233. ){
  94234. int i; /* Iterator variable */
  94235. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  94236. int iCur = pParse->nTab - 1; /* Cursor number to use */
  94237. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  94238. /* If nIncr is less than zero, then check at runtime if there are any
  94239. ** outstanding constraints to resolve. If there are not, there is no need
  94240. ** to check if deleting this row resolves any outstanding violations.
  94241. **
  94242. ** Check if any of the key columns in the child table row are NULL. If
  94243. ** any are, then the constraint is considered satisfied. No need to
  94244. ** search for a matching row in the parent table. */
  94245. if( nIncr<0 ){
  94246. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  94247. VdbeCoverage(v);
  94248. }
  94249. for(i=0; i<pFKey->nCol; i++){
  94250. int iReg = aiCol[i] + regData + 1;
  94251. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  94252. }
  94253. if( isIgnore==0 ){
  94254. if( pIdx==0 ){
  94255. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  94256. ** column of the parent table (table pTab). */
  94257. int iMustBeInt; /* Address of MustBeInt instruction */
  94258. int regTemp = sqlite3GetTempReg(pParse);
  94259. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  94260. ** apply the affinity of the parent key). If this fails, then there
  94261. ** is no matching parent key. Before using MustBeInt, make a copy of
  94262. ** the value. Otherwise, the value inserted into the child key column
  94263. ** will have INTEGER affinity applied to it, which may not be correct. */
  94264. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  94265. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  94266. VdbeCoverage(v);
  94267. /* If the parent table is the same as the child table, and we are about
  94268. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  94269. ** then check if the row being inserted matches itself. If so, do not
  94270. ** increment the constraint-counter. */
  94271. if( pTab==pFKey->pFrom && nIncr==1 ){
  94272. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  94273. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  94274. }
  94275. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  94276. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  94277. sqlite3VdbeGoto(v, iOk);
  94278. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  94279. sqlite3VdbeJumpHere(v, iMustBeInt);
  94280. sqlite3ReleaseTempReg(pParse, regTemp);
  94281. }else{
  94282. int nCol = pFKey->nCol;
  94283. int regTemp = sqlite3GetTempRange(pParse, nCol);
  94284. int regRec = sqlite3GetTempReg(pParse);
  94285. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  94286. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  94287. for(i=0; i<nCol; i++){
  94288. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  94289. }
  94290. /* If the parent table is the same as the child table, and we are about
  94291. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  94292. ** then check if the row being inserted matches itself. If so, do not
  94293. ** increment the constraint-counter.
  94294. **
  94295. ** If any of the parent-key values are NULL, then the row cannot match
  94296. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  94297. ** of the parent-key values are NULL (at this point it is known that
  94298. ** none of the child key values are).
  94299. */
  94300. if( pTab==pFKey->pFrom && nIncr==1 ){
  94301. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  94302. for(i=0; i<nCol; i++){
  94303. int iChild = aiCol[i]+1+regData;
  94304. int iParent = pIdx->aiColumn[i]+1+regData;
  94305. assert( pIdx->aiColumn[i]>=0 );
  94306. assert( aiCol[i]!=pTab->iPKey );
  94307. if( pIdx->aiColumn[i]==pTab->iPKey ){
  94308. /* The parent key is a composite key that includes the IPK column */
  94309. iParent = regData;
  94310. }
  94311. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  94312. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  94313. }
  94314. sqlite3VdbeGoto(v, iOk);
  94315. }
  94316. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  94317. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  94318. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  94319. sqlite3ReleaseTempReg(pParse, regRec);
  94320. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  94321. }
  94322. }
  94323. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  94324. && !pParse->pToplevel
  94325. && !pParse->isMultiWrite
  94326. ){
  94327. /* Special case: If this is an INSERT statement that will insert exactly
  94328. ** one row into the table, raise a constraint immediately instead of
  94329. ** incrementing a counter. This is necessary as the VM code is being
  94330. ** generated for will not open a statement transaction. */
  94331. assert( nIncr==1 );
  94332. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  94333. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  94334. }else{
  94335. if( nIncr>0 && pFKey->isDeferred==0 ){
  94336. sqlite3MayAbort(pParse);
  94337. }
  94338. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  94339. }
  94340. sqlite3VdbeResolveLabel(v, iOk);
  94341. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  94342. }
  94343. /*
  94344. ** Return an Expr object that refers to a memory register corresponding
  94345. ** to column iCol of table pTab.
  94346. **
  94347. ** regBase is the first of an array of register that contains the data
  94348. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  94349. ** column. regBase+2 holds the second column, and so forth.
  94350. */
  94351. static Expr *exprTableRegister(
  94352. Parse *pParse, /* Parsing and code generating context */
  94353. Table *pTab, /* The table whose content is at r[regBase]... */
  94354. int regBase, /* Contents of table pTab */
  94355. i16 iCol /* Which column of pTab is desired */
  94356. ){
  94357. Expr *pExpr;
  94358. Column *pCol;
  94359. const char *zColl;
  94360. sqlite3 *db = pParse->db;
  94361. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  94362. if( pExpr ){
  94363. if( iCol>=0 && iCol!=pTab->iPKey ){
  94364. pCol = &pTab->aCol[iCol];
  94365. pExpr->iTable = regBase + iCol + 1;
  94366. pExpr->affinity = pCol->affinity;
  94367. zColl = pCol->zColl;
  94368. if( zColl==0 ) zColl = db->pDfltColl->zName;
  94369. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  94370. }else{
  94371. pExpr->iTable = regBase;
  94372. pExpr->affinity = SQLITE_AFF_INTEGER;
  94373. }
  94374. }
  94375. return pExpr;
  94376. }
  94377. /*
  94378. ** Return an Expr object that refers to column iCol of table pTab which
  94379. ** has cursor iCur.
  94380. */
  94381. static Expr *exprTableColumn(
  94382. sqlite3 *db, /* The database connection */
  94383. Table *pTab, /* The table whose column is desired */
  94384. int iCursor, /* The open cursor on the table */
  94385. i16 iCol /* The column that is wanted */
  94386. ){
  94387. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  94388. if( pExpr ){
  94389. pExpr->pTab = pTab;
  94390. pExpr->iTable = iCursor;
  94391. pExpr->iColumn = iCol;
  94392. }
  94393. return pExpr;
  94394. }
  94395. /*
  94396. ** This function is called to generate code executed when a row is deleted
  94397. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  94398. ** deferred, when a row is inserted into the same table. When generating
  94399. ** code for an SQL UPDATE operation, this function may be called twice -
  94400. ** once to "delete" the old row and once to "insert" the new row.
  94401. **
  94402. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  94403. ** the number of FK violations in the db) or +1 when deleting one (as this
  94404. ** may increase the number of FK constraint problems).
  94405. **
  94406. ** The code generated by this function scans through the rows in the child
  94407. ** table that correspond to the parent table row being deleted or inserted.
  94408. ** For each child row found, one of the following actions is taken:
  94409. **
  94410. ** Operation | FK type | Action taken
  94411. ** --------------------------------------------------------------------------
  94412. ** DELETE immediate Increment the "immediate constraint counter".
  94413. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  94414. ** throw a "FOREIGN KEY constraint failed" exception.
  94415. **
  94416. ** INSERT immediate Decrement the "immediate constraint counter".
  94417. **
  94418. ** DELETE deferred Increment the "deferred constraint counter".
  94419. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  94420. ** throw a "FOREIGN KEY constraint failed" exception.
  94421. **
  94422. ** INSERT deferred Decrement the "deferred constraint counter".
  94423. **
  94424. ** These operations are identified in the comment at the top of this file
  94425. ** (fkey.c) as "I.2" and "D.2".
  94426. */
  94427. static void fkScanChildren(
  94428. Parse *pParse, /* Parse context */
  94429. SrcList *pSrc, /* The child table to be scanned */
  94430. Table *pTab, /* The parent table */
  94431. Index *pIdx, /* Index on parent covering the foreign key */
  94432. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  94433. int *aiCol, /* Map from pIdx cols to child table cols */
  94434. int regData, /* Parent row data starts here */
  94435. int nIncr /* Amount to increment deferred counter by */
  94436. ){
  94437. sqlite3 *db = pParse->db; /* Database handle */
  94438. int i; /* Iterator variable */
  94439. Expr *pWhere = 0; /* WHERE clause to scan with */
  94440. NameContext sNameContext; /* Context used to resolve WHERE clause */
  94441. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  94442. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  94443. Vdbe *v = sqlite3GetVdbe(pParse);
  94444. assert( pIdx==0 || pIdx->pTable==pTab );
  94445. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  94446. assert( pIdx!=0 || pFKey->nCol==1 );
  94447. assert( pIdx!=0 || HasRowid(pTab) );
  94448. if( nIncr<0 ){
  94449. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  94450. VdbeCoverage(v);
  94451. }
  94452. /* Create an Expr object representing an SQL expression like:
  94453. **
  94454. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  94455. **
  94456. ** The collation sequence used for the comparison should be that of
  94457. ** the parent key columns. The affinity of the parent key column should
  94458. ** be applied to each child key value before the comparison takes place.
  94459. */
  94460. for(i=0; i<pFKey->nCol; i++){
  94461. Expr *pLeft; /* Value from parent table row */
  94462. Expr *pRight; /* Column ref to child table */
  94463. Expr *pEq; /* Expression (pLeft = pRight) */
  94464. i16 iCol; /* Index of column in child table */
  94465. const char *zCol; /* Name of column in child table */
  94466. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  94467. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  94468. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  94469. assert( iCol>=0 );
  94470. zCol = pFKey->pFrom->aCol[iCol].zName;
  94471. pRight = sqlite3Expr(db, TK_ID, zCol);
  94472. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  94473. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  94474. }
  94475. /* If the child table is the same as the parent table, then add terms
  94476. ** to the WHERE clause that prevent this entry from being scanned.
  94477. ** The added WHERE clause terms are like this:
  94478. **
  94479. ** $current_rowid!=rowid
  94480. ** NOT( $current_a==a AND $current_b==b AND ... )
  94481. **
  94482. ** The first form is used for rowid tables. The second form is used
  94483. ** for WITHOUT ROWID tables. In the second form, the primary key is
  94484. ** (a,b,...)
  94485. */
  94486. if( pTab==pFKey->pFrom && nIncr>0 ){
  94487. Expr *pNe; /* Expression (pLeft != pRight) */
  94488. Expr *pLeft; /* Value from parent table row */
  94489. Expr *pRight; /* Column ref to child table */
  94490. if( HasRowid(pTab) ){
  94491. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  94492. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  94493. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  94494. }else{
  94495. Expr *pEq, *pAll = 0;
  94496. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  94497. assert( pIdx!=0 );
  94498. for(i=0; i<pPk->nKeyCol; i++){
  94499. i16 iCol = pIdx->aiColumn[i];
  94500. assert( iCol>=0 );
  94501. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  94502. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  94503. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  94504. pAll = sqlite3ExprAnd(db, pAll, pEq);
  94505. }
  94506. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  94507. }
  94508. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  94509. }
  94510. /* Resolve the references in the WHERE clause. */
  94511. memset(&sNameContext, 0, sizeof(NameContext));
  94512. sNameContext.pSrcList = pSrc;
  94513. sNameContext.pParse = pParse;
  94514. sqlite3ResolveExprNames(&sNameContext, pWhere);
  94515. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  94516. ** clause. For each row found, increment either the deferred or immediate
  94517. ** foreign key constraint counter. */
  94518. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  94519. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  94520. if( pWInfo ){
  94521. sqlite3WhereEnd(pWInfo);
  94522. }
  94523. /* Clean up the WHERE clause constructed above. */
  94524. sqlite3ExprDelete(db, pWhere);
  94525. if( iFkIfZero ){
  94526. sqlite3VdbeJumpHere(v, iFkIfZero);
  94527. }
  94528. }
  94529. /*
  94530. ** This function returns a linked list of FKey objects (connected by
  94531. ** FKey.pNextTo) holding all children of table pTab. For example,
  94532. ** given the following schema:
  94533. **
  94534. ** CREATE TABLE t1(a PRIMARY KEY);
  94535. ** CREATE TABLE t2(b REFERENCES t1(a);
  94536. **
  94537. ** Calling this function with table "t1" as an argument returns a pointer
  94538. ** to the FKey structure representing the foreign key constraint on table
  94539. ** "t2". Calling this function with "t2" as the argument would return a
  94540. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  94541. ** table).
  94542. */
  94543. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  94544. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  94545. }
  94546. /*
  94547. ** The second argument is a Trigger structure allocated by the
  94548. ** fkActionTrigger() routine. This function deletes the Trigger structure
  94549. ** and all of its sub-components.
  94550. **
  94551. ** The Trigger structure or any of its sub-components may be allocated from
  94552. ** the lookaside buffer belonging to database handle dbMem.
  94553. */
  94554. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  94555. if( p ){
  94556. TriggerStep *pStep = p->step_list;
  94557. sqlite3ExprDelete(dbMem, pStep->pWhere);
  94558. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  94559. sqlite3SelectDelete(dbMem, pStep->pSelect);
  94560. sqlite3ExprDelete(dbMem, p->pWhen);
  94561. sqlite3DbFree(dbMem, p);
  94562. }
  94563. }
  94564. /*
  94565. ** This function is called to generate code that runs when table pTab is
  94566. ** being dropped from the database. The SrcList passed as the second argument
  94567. ** to this function contains a single entry guaranteed to resolve to
  94568. ** table pTab.
  94569. **
  94570. ** Normally, no code is required. However, if either
  94571. **
  94572. ** (a) The table is the parent table of a FK constraint, or
  94573. ** (b) The table is the child table of a deferred FK constraint and it is
  94574. ** determined at runtime that there are outstanding deferred FK
  94575. ** constraint violations in the database,
  94576. **
  94577. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  94578. ** the table from the database. Triggers are disabled while running this
  94579. ** DELETE, but foreign key actions are not.
  94580. */
  94581. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  94582. sqlite3 *db = pParse->db;
  94583. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  94584. int iSkip = 0;
  94585. Vdbe *v = sqlite3GetVdbe(pParse);
  94586. assert( v ); /* VDBE has already been allocated */
  94587. if( sqlite3FkReferences(pTab)==0 ){
  94588. /* Search for a deferred foreign key constraint for which this table
  94589. ** is the child table. If one cannot be found, return without
  94590. ** generating any VDBE code. If one can be found, then jump over
  94591. ** the entire DELETE if there are no outstanding deferred constraints
  94592. ** when this statement is run. */
  94593. FKey *p;
  94594. for(p=pTab->pFKey; p; p=p->pNextFrom){
  94595. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  94596. }
  94597. if( !p ) return;
  94598. iSkip = sqlite3VdbeMakeLabel(v);
  94599. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  94600. }
  94601. pParse->disableTriggers = 1;
  94602. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  94603. pParse->disableTriggers = 0;
  94604. /* If the DELETE has generated immediate foreign key constraint
  94605. ** violations, halt the VDBE and return an error at this point, before
  94606. ** any modifications to the schema are made. This is because statement
  94607. ** transactions are not able to rollback schema changes.
  94608. **
  94609. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  94610. ** the statement transaction will not be rolled back even if FK
  94611. ** constraints are violated.
  94612. */
  94613. if( (db->flags & SQLITE_DeferFKs)==0 ){
  94614. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  94615. VdbeCoverage(v);
  94616. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  94617. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  94618. }
  94619. if( iSkip ){
  94620. sqlite3VdbeResolveLabel(v, iSkip);
  94621. }
  94622. }
  94623. }
  94624. /*
  94625. ** The second argument points to an FKey object representing a foreign key
  94626. ** for which pTab is the child table. An UPDATE statement against pTab
  94627. ** is currently being processed. For each column of the table that is
  94628. ** actually updated, the corresponding element in the aChange[] array
  94629. ** is zero or greater (if a column is unmodified the corresponding element
  94630. ** is set to -1). If the rowid column is modified by the UPDATE statement
  94631. ** the bChngRowid argument is non-zero.
  94632. **
  94633. ** This function returns true if any of the columns that are part of the
  94634. ** child key for FK constraint *p are modified.
  94635. */
  94636. static int fkChildIsModified(
  94637. Table *pTab, /* Table being updated */
  94638. FKey *p, /* Foreign key for which pTab is the child */
  94639. int *aChange, /* Array indicating modified columns */
  94640. int bChngRowid /* True if rowid is modified by this update */
  94641. ){
  94642. int i;
  94643. for(i=0; i<p->nCol; i++){
  94644. int iChildKey = p->aCol[i].iFrom;
  94645. if( aChange[iChildKey]>=0 ) return 1;
  94646. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  94647. }
  94648. return 0;
  94649. }
  94650. /*
  94651. ** The second argument points to an FKey object representing a foreign key
  94652. ** for which pTab is the parent table. An UPDATE statement against pTab
  94653. ** is currently being processed. For each column of the table that is
  94654. ** actually updated, the corresponding element in the aChange[] array
  94655. ** is zero or greater (if a column is unmodified the corresponding element
  94656. ** is set to -1). If the rowid column is modified by the UPDATE statement
  94657. ** the bChngRowid argument is non-zero.
  94658. **
  94659. ** This function returns true if any of the columns that are part of the
  94660. ** parent key for FK constraint *p are modified.
  94661. */
  94662. static int fkParentIsModified(
  94663. Table *pTab,
  94664. FKey *p,
  94665. int *aChange,
  94666. int bChngRowid
  94667. ){
  94668. int i;
  94669. for(i=0; i<p->nCol; i++){
  94670. char *zKey = p->aCol[i].zCol;
  94671. int iKey;
  94672. for(iKey=0; iKey<pTab->nCol; iKey++){
  94673. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  94674. Column *pCol = &pTab->aCol[iKey];
  94675. if( zKey ){
  94676. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  94677. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  94678. return 1;
  94679. }
  94680. }
  94681. }
  94682. }
  94683. return 0;
  94684. }
  94685. /*
  94686. ** Return true if the parser passed as the first argument is being
  94687. ** used to code a trigger that is really a "SET NULL" action belonging
  94688. ** to trigger pFKey.
  94689. */
  94690. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  94691. Parse *pTop = sqlite3ParseToplevel(pParse);
  94692. if( pTop->pTriggerPrg ){
  94693. Trigger *p = pTop->pTriggerPrg->pTrigger;
  94694. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  94695. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  94696. ){
  94697. return 1;
  94698. }
  94699. }
  94700. return 0;
  94701. }
  94702. /*
  94703. ** This function is called when inserting, deleting or updating a row of
  94704. ** table pTab to generate VDBE code to perform foreign key constraint
  94705. ** processing for the operation.
  94706. **
  94707. ** For a DELETE operation, parameter regOld is passed the index of the
  94708. ** first register in an array of (pTab->nCol+1) registers containing the
  94709. ** rowid of the row being deleted, followed by each of the column values
  94710. ** of the row being deleted, from left to right. Parameter regNew is passed
  94711. ** zero in this case.
  94712. **
  94713. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  94714. ** first register of an array of (pTab->nCol+1) registers containing the new
  94715. ** row data.
  94716. **
  94717. ** For an UPDATE operation, this function is called twice. Once before
  94718. ** the original record is deleted from the table using the calling convention
  94719. ** described for DELETE. Then again after the original record is deleted
  94720. ** but before the new record is inserted using the INSERT convention.
  94721. */
  94722. SQLITE_PRIVATE void sqlite3FkCheck(
  94723. Parse *pParse, /* Parse context */
  94724. Table *pTab, /* Row is being deleted from this table */
  94725. int regOld, /* Previous row data is stored here */
  94726. int regNew, /* New row data is stored here */
  94727. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  94728. int bChngRowid /* True if rowid is UPDATEd */
  94729. ){
  94730. sqlite3 *db = pParse->db; /* Database handle */
  94731. FKey *pFKey; /* Used to iterate through FKs */
  94732. int iDb; /* Index of database containing pTab */
  94733. const char *zDb; /* Name of database containing pTab */
  94734. int isIgnoreErrors = pParse->disableTriggers;
  94735. /* Exactly one of regOld and regNew should be non-zero. */
  94736. assert( (regOld==0)!=(regNew==0) );
  94737. /* If foreign-keys are disabled, this function is a no-op. */
  94738. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  94739. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  94740. zDb = db->aDb[iDb].zName;
  94741. /* Loop through all the foreign key constraints for which pTab is the
  94742. ** child table (the table that the foreign key definition is part of). */
  94743. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  94744. Table *pTo; /* Parent table of foreign key pFKey */
  94745. Index *pIdx = 0; /* Index on key columns in pTo */
  94746. int *aiFree = 0;
  94747. int *aiCol;
  94748. int iCol;
  94749. int i;
  94750. int bIgnore = 0;
  94751. if( aChange
  94752. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  94753. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  94754. ){
  94755. continue;
  94756. }
  94757. /* Find the parent table of this foreign key. Also find a unique index
  94758. ** on the parent key columns in the parent table. If either of these
  94759. ** schema items cannot be located, set an error in pParse and return
  94760. ** early. */
  94761. if( pParse->disableTriggers ){
  94762. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  94763. }else{
  94764. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  94765. }
  94766. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  94767. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  94768. if( !isIgnoreErrors || db->mallocFailed ) return;
  94769. if( pTo==0 ){
  94770. /* If isIgnoreErrors is true, then a table is being dropped. In this
  94771. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  94772. ** before actually dropping it in order to check FK constraints.
  94773. ** If the parent table of an FK constraint on the current table is
  94774. ** missing, behave as if it is empty. i.e. decrement the relevant
  94775. ** FK counter for each row of the current table with non-NULL keys.
  94776. */
  94777. Vdbe *v = sqlite3GetVdbe(pParse);
  94778. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  94779. for(i=0; i<pFKey->nCol; i++){
  94780. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  94781. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  94782. }
  94783. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  94784. }
  94785. continue;
  94786. }
  94787. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  94788. if( aiFree ){
  94789. aiCol = aiFree;
  94790. }else{
  94791. iCol = pFKey->aCol[0].iFrom;
  94792. aiCol = &iCol;
  94793. }
  94794. for(i=0; i<pFKey->nCol; i++){
  94795. if( aiCol[i]==pTab->iPKey ){
  94796. aiCol[i] = -1;
  94797. }
  94798. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  94799. #ifndef SQLITE_OMIT_AUTHORIZATION
  94800. /* Request permission to read the parent key columns. If the
  94801. ** authorization callback returns SQLITE_IGNORE, behave as if any
  94802. ** values read from the parent table are NULL. */
  94803. if( db->xAuth ){
  94804. int rcauth;
  94805. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  94806. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  94807. bIgnore = (rcauth==SQLITE_IGNORE);
  94808. }
  94809. #endif
  94810. }
  94811. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  94812. ** a cursor to use to search the unique index on the parent key columns
  94813. ** in the parent table. */
  94814. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  94815. pParse->nTab++;
  94816. if( regOld!=0 ){
  94817. /* A row is being removed from the child table. Search for the parent.
  94818. ** If the parent does not exist, removing the child row resolves an
  94819. ** outstanding foreign key constraint violation. */
  94820. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  94821. }
  94822. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  94823. /* A row is being added to the child table. If a parent row cannot
  94824. ** be found, adding the child row has violated the FK constraint.
  94825. **
  94826. ** If this operation is being performed as part of a trigger program
  94827. ** that is actually a "SET NULL" action belonging to this very
  94828. ** foreign key, then omit this scan altogether. As all child key
  94829. ** values are guaranteed to be NULL, it is not possible for adding
  94830. ** this row to cause an FK violation. */
  94831. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  94832. }
  94833. sqlite3DbFree(db, aiFree);
  94834. }
  94835. /* Loop through all the foreign key constraints that refer to this table.
  94836. ** (the "child" constraints) */
  94837. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  94838. Index *pIdx = 0; /* Foreign key index for pFKey */
  94839. SrcList *pSrc;
  94840. int *aiCol = 0;
  94841. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  94842. continue;
  94843. }
  94844. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  94845. && !pParse->pToplevel && !pParse->isMultiWrite
  94846. ){
  94847. assert( regOld==0 && regNew!=0 );
  94848. /* Inserting a single row into a parent table cannot cause (or fix)
  94849. ** an immediate foreign key violation. So do nothing in this case. */
  94850. continue;
  94851. }
  94852. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  94853. if( !isIgnoreErrors || db->mallocFailed ) return;
  94854. continue;
  94855. }
  94856. assert( aiCol || pFKey->nCol==1 );
  94857. /* Create a SrcList structure containing the child table. We need the
  94858. ** child table as a SrcList for sqlite3WhereBegin() */
  94859. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  94860. if( pSrc ){
  94861. struct SrcList_item *pItem = pSrc->a;
  94862. pItem->pTab = pFKey->pFrom;
  94863. pItem->zName = pFKey->pFrom->zName;
  94864. pItem->pTab->nRef++;
  94865. pItem->iCursor = pParse->nTab++;
  94866. if( regNew!=0 ){
  94867. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  94868. }
  94869. if( regOld!=0 ){
  94870. int eAction = pFKey->aAction[aChange!=0];
  94871. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  94872. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  94873. ** action applies, then any foreign key violations caused by
  94874. ** removing the parent key will be rectified by the action trigger.
  94875. ** So do not set the "may-abort" flag in this case.
  94876. **
  94877. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  94878. ** may-abort flag will eventually be set on this statement anyway
  94879. ** (when this function is called as part of processing the UPDATE
  94880. ** within the action trigger).
  94881. **
  94882. ** Note 2: At first glance it may seem like SQLite could simply omit
  94883. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  94884. ** applies. The trouble starts if the CASCADE or SET NULL action
  94885. ** trigger causes other triggers or action rules attached to the
  94886. ** child table to fire. In these cases the fk constraint counters
  94887. ** might be set incorrectly if any OP_FkCounter related scans are
  94888. ** omitted. */
  94889. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  94890. sqlite3MayAbort(pParse);
  94891. }
  94892. }
  94893. pItem->zName = 0;
  94894. sqlite3SrcListDelete(db, pSrc);
  94895. }
  94896. sqlite3DbFree(db, aiCol);
  94897. }
  94898. }
  94899. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  94900. /*
  94901. ** This function is called before generating code to update or delete a
  94902. ** row contained in table pTab.
  94903. */
  94904. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  94905. Parse *pParse, /* Parse context */
  94906. Table *pTab /* Table being modified */
  94907. ){
  94908. u32 mask = 0;
  94909. if( pParse->db->flags&SQLITE_ForeignKeys ){
  94910. FKey *p;
  94911. int i;
  94912. for(p=pTab->pFKey; p; p=p->pNextFrom){
  94913. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  94914. }
  94915. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  94916. Index *pIdx = 0;
  94917. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  94918. if( pIdx ){
  94919. for(i=0; i<pIdx->nKeyCol; i++){
  94920. assert( pIdx->aiColumn[i]>=0 );
  94921. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  94922. }
  94923. }
  94924. }
  94925. }
  94926. return mask;
  94927. }
  94928. /*
  94929. ** This function is called before generating code to update or delete a
  94930. ** row contained in table pTab. If the operation is a DELETE, then
  94931. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  94932. ** to an array of size N, where N is the number of columns in table pTab.
  94933. ** If the i'th column is not modified by the UPDATE, then the corresponding
  94934. ** entry in the aChange[] array is set to -1. If the column is modified,
  94935. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  94936. ** UPDATE statement modifies the rowid fields of the table.
  94937. **
  94938. ** If any foreign key processing will be required, this function returns
  94939. ** true. If there is no foreign key related processing, this function
  94940. ** returns false.
  94941. */
  94942. SQLITE_PRIVATE int sqlite3FkRequired(
  94943. Parse *pParse, /* Parse context */
  94944. Table *pTab, /* Table being modified */
  94945. int *aChange, /* Non-NULL for UPDATE operations */
  94946. int chngRowid /* True for UPDATE that affects rowid */
  94947. ){
  94948. if( pParse->db->flags&SQLITE_ForeignKeys ){
  94949. if( !aChange ){
  94950. /* A DELETE operation. Foreign key processing is required if the
  94951. ** table in question is either the child or parent table for any
  94952. ** foreign key constraint. */
  94953. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  94954. }else{
  94955. /* This is an UPDATE. Foreign key processing is only required if the
  94956. ** operation modifies one or more child or parent key columns. */
  94957. FKey *p;
  94958. /* Check if any child key columns are being modified. */
  94959. for(p=pTab->pFKey; p; p=p->pNextFrom){
  94960. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  94961. }
  94962. /* Check if any parent key columns are being modified. */
  94963. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  94964. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  94965. }
  94966. }
  94967. }
  94968. return 0;
  94969. }
  94970. /*
  94971. ** This function is called when an UPDATE or DELETE operation is being
  94972. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  94973. ** If the current operation is an UPDATE, then the pChanges parameter is
  94974. ** passed a pointer to the list of columns being modified. If it is a
  94975. ** DELETE, pChanges is passed a NULL pointer.
  94976. **
  94977. ** It returns a pointer to a Trigger structure containing a trigger
  94978. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  94979. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  94980. ** returned (these actions require no special handling by the triggers
  94981. ** sub-system, code for them is created by fkScanChildren()).
  94982. **
  94983. ** For example, if pFKey is the foreign key and pTab is table "p" in
  94984. ** the following schema:
  94985. **
  94986. ** CREATE TABLE p(pk PRIMARY KEY);
  94987. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  94988. **
  94989. ** then the returned trigger structure is equivalent to:
  94990. **
  94991. ** CREATE TRIGGER ... DELETE ON p BEGIN
  94992. ** DELETE FROM c WHERE ck = old.pk;
  94993. ** END;
  94994. **
  94995. ** The returned pointer is cached as part of the foreign key object. It
  94996. ** is eventually freed along with the rest of the foreign key object by
  94997. ** sqlite3FkDelete().
  94998. */
  94999. static Trigger *fkActionTrigger(
  95000. Parse *pParse, /* Parse context */
  95001. Table *pTab, /* Table being updated or deleted from */
  95002. FKey *pFKey, /* Foreign key to get action for */
  95003. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  95004. ){
  95005. sqlite3 *db = pParse->db; /* Database handle */
  95006. int action; /* One of OE_None, OE_Cascade etc. */
  95007. Trigger *pTrigger; /* Trigger definition to return */
  95008. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  95009. action = pFKey->aAction[iAction];
  95010. pTrigger = pFKey->apTrigger[iAction];
  95011. if( action!=OE_None && !pTrigger ){
  95012. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  95013. char const *zFrom; /* Name of child table */
  95014. int nFrom; /* Length in bytes of zFrom */
  95015. Index *pIdx = 0; /* Parent key index for this FK */
  95016. int *aiCol = 0; /* child table cols -> parent key cols */
  95017. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  95018. Expr *pWhere = 0; /* WHERE clause of trigger step */
  95019. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  95020. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  95021. int i; /* Iterator variable */
  95022. Expr *pWhen = 0; /* WHEN clause for the trigger */
  95023. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  95024. assert( aiCol || pFKey->nCol==1 );
  95025. for(i=0; i<pFKey->nCol; i++){
  95026. Token tOld = { "old", 3 }; /* Literal "old" token */
  95027. Token tNew = { "new", 3 }; /* Literal "new" token */
  95028. Token tFromCol; /* Name of column in child table */
  95029. Token tToCol; /* Name of column in parent table */
  95030. int iFromCol; /* Idx of column in child table */
  95031. Expr *pEq; /* tFromCol = OLD.tToCol */
  95032. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  95033. assert( iFromCol>=0 );
  95034. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  95035. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  95036. tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
  95037. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  95038. tToCol.n = sqlite3Strlen30(tToCol.z);
  95039. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  95040. /* Create the expression "OLD.zToCol = zFromCol". It is important
  95041. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  95042. ** that the affinity and collation sequence associated with the
  95043. ** parent table are used for the comparison. */
  95044. pEq = sqlite3PExpr(pParse, TK_EQ,
  95045. sqlite3PExpr(pParse, TK_DOT,
  95046. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  95047. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  95048. , 0),
  95049. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  95050. , 0);
  95051. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  95052. /* For ON UPDATE, construct the next term of the WHEN clause.
  95053. ** The final WHEN clause will be like this:
  95054. **
  95055. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  95056. */
  95057. if( pChanges ){
  95058. pEq = sqlite3PExpr(pParse, TK_IS,
  95059. sqlite3PExpr(pParse, TK_DOT,
  95060. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  95061. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  95062. 0),
  95063. sqlite3PExpr(pParse, TK_DOT,
  95064. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  95065. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  95066. 0),
  95067. 0);
  95068. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  95069. }
  95070. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  95071. Expr *pNew;
  95072. if( action==OE_Cascade ){
  95073. pNew = sqlite3PExpr(pParse, TK_DOT,
  95074. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  95075. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  95076. , 0);
  95077. }else if( action==OE_SetDflt ){
  95078. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  95079. if( pDflt ){
  95080. pNew = sqlite3ExprDup(db, pDflt, 0);
  95081. }else{
  95082. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  95083. }
  95084. }else{
  95085. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  95086. }
  95087. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  95088. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  95089. }
  95090. }
  95091. sqlite3DbFree(db, aiCol);
  95092. zFrom = pFKey->pFrom->zName;
  95093. nFrom = sqlite3Strlen30(zFrom);
  95094. if( action==OE_Restrict ){
  95095. Token tFrom;
  95096. Expr *pRaise;
  95097. tFrom.z = zFrom;
  95098. tFrom.n = nFrom;
  95099. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  95100. if( pRaise ){
  95101. pRaise->affinity = OE_Abort;
  95102. }
  95103. pSelect = sqlite3SelectNew(pParse,
  95104. sqlite3ExprListAppend(pParse, 0, pRaise),
  95105. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  95106. pWhere,
  95107. 0, 0, 0, 0, 0, 0
  95108. );
  95109. pWhere = 0;
  95110. }
  95111. /* Disable lookaside memory allocation */
  95112. enableLookaside = db->lookaside.bEnabled;
  95113. db->lookaside.bEnabled = 0;
  95114. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  95115. sizeof(Trigger) + /* struct Trigger */
  95116. sizeof(TriggerStep) + /* Single step in trigger program */
  95117. nFrom + 1 /* Space for pStep->zTarget */
  95118. );
  95119. if( pTrigger ){
  95120. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  95121. pStep->zTarget = (char *)&pStep[1];
  95122. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  95123. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  95124. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  95125. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  95126. if( pWhen ){
  95127. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  95128. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  95129. }
  95130. }
  95131. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  95132. db->lookaside.bEnabled = enableLookaside;
  95133. sqlite3ExprDelete(db, pWhere);
  95134. sqlite3ExprDelete(db, pWhen);
  95135. sqlite3ExprListDelete(db, pList);
  95136. sqlite3SelectDelete(db, pSelect);
  95137. if( db->mallocFailed==1 ){
  95138. fkTriggerDelete(db, pTrigger);
  95139. return 0;
  95140. }
  95141. assert( pStep!=0 );
  95142. switch( action ){
  95143. case OE_Restrict:
  95144. pStep->op = TK_SELECT;
  95145. break;
  95146. case OE_Cascade:
  95147. if( !pChanges ){
  95148. pStep->op = TK_DELETE;
  95149. break;
  95150. }
  95151. default:
  95152. pStep->op = TK_UPDATE;
  95153. }
  95154. pStep->pTrig = pTrigger;
  95155. pTrigger->pSchema = pTab->pSchema;
  95156. pTrigger->pTabSchema = pTab->pSchema;
  95157. pFKey->apTrigger[iAction] = pTrigger;
  95158. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  95159. }
  95160. return pTrigger;
  95161. }
  95162. /*
  95163. ** This function is called when deleting or updating a row to implement
  95164. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  95165. */
  95166. SQLITE_PRIVATE void sqlite3FkActions(
  95167. Parse *pParse, /* Parse context */
  95168. Table *pTab, /* Table being updated or deleted from */
  95169. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  95170. int regOld, /* Address of array containing old row */
  95171. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  95172. int bChngRowid /* True if rowid is UPDATEd */
  95173. ){
  95174. /* If foreign-key support is enabled, iterate through all FKs that
  95175. ** refer to table pTab. If there is an action associated with the FK
  95176. ** for this operation (either update or delete), invoke the associated
  95177. ** trigger sub-program. */
  95178. if( pParse->db->flags&SQLITE_ForeignKeys ){
  95179. FKey *pFKey; /* Iterator variable */
  95180. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  95181. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  95182. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  95183. if( pAct ){
  95184. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  95185. }
  95186. }
  95187. }
  95188. }
  95189. }
  95190. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  95191. /*
  95192. ** Free all memory associated with foreign key definitions attached to
  95193. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  95194. ** hash table.
  95195. */
  95196. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  95197. FKey *pFKey; /* Iterator variable */
  95198. FKey *pNext; /* Copy of pFKey->pNextFrom */
  95199. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  95200. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  95201. /* Remove the FK from the fkeyHash hash table. */
  95202. if( !db || db->pnBytesFreed==0 ){
  95203. if( pFKey->pPrevTo ){
  95204. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  95205. }else{
  95206. void *p = (void *)pFKey->pNextTo;
  95207. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  95208. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  95209. }
  95210. if( pFKey->pNextTo ){
  95211. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  95212. }
  95213. }
  95214. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  95215. ** classified as either immediate or deferred.
  95216. */
  95217. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  95218. /* Delete any triggers created to implement actions for this FK. */
  95219. #ifndef SQLITE_OMIT_TRIGGER
  95220. fkTriggerDelete(db, pFKey->apTrigger[0]);
  95221. fkTriggerDelete(db, pFKey->apTrigger[1]);
  95222. #endif
  95223. pNext = pFKey->pNextFrom;
  95224. sqlite3DbFree(db, pFKey);
  95225. }
  95226. }
  95227. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  95228. /************** End of fkey.c ************************************************/
  95229. /************** Begin file insert.c ******************************************/
  95230. /*
  95231. ** 2001 September 15
  95232. **
  95233. ** The author disclaims copyright to this source code. In place of
  95234. ** a legal notice, here is a blessing:
  95235. **
  95236. ** May you do good and not evil.
  95237. ** May you find forgiveness for yourself and forgive others.
  95238. ** May you share freely, never taking more than you give.
  95239. **
  95240. *************************************************************************
  95241. ** This file contains C code routines that are called by the parser
  95242. ** to handle INSERT statements in SQLite.
  95243. */
  95244. /* #include "sqliteInt.h" */
  95245. /*
  95246. ** Generate code that will
  95247. **
  95248. ** (1) acquire a lock for table pTab then
  95249. ** (2) open pTab as cursor iCur.
  95250. **
  95251. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  95252. ** for that table that is actually opened.
  95253. */
  95254. SQLITE_PRIVATE void sqlite3OpenTable(
  95255. Parse *pParse, /* Generate code into this VDBE */
  95256. int iCur, /* The cursor number of the table */
  95257. int iDb, /* The database index in sqlite3.aDb[] */
  95258. Table *pTab, /* The table to be opened */
  95259. int opcode /* OP_OpenRead or OP_OpenWrite */
  95260. ){
  95261. Vdbe *v;
  95262. assert( !IsVirtual(pTab) );
  95263. v = sqlite3GetVdbe(pParse);
  95264. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  95265. sqlite3TableLock(pParse, iDb, pTab->tnum,
  95266. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  95267. if( HasRowid(pTab) ){
  95268. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  95269. VdbeComment((v, "%s", pTab->zName));
  95270. }else{
  95271. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  95272. assert( pPk!=0 );
  95273. assert( pPk->tnum==pTab->tnum );
  95274. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  95275. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  95276. VdbeComment((v, "%s", pTab->zName));
  95277. }
  95278. }
  95279. /*
  95280. ** Return a pointer to the column affinity string associated with index
  95281. ** pIdx. A column affinity string has one character for each column in
  95282. ** the table, according to the affinity of the column:
  95283. **
  95284. ** Character Column affinity
  95285. ** ------------------------------
  95286. ** 'A' BLOB
  95287. ** 'B' TEXT
  95288. ** 'C' NUMERIC
  95289. ** 'D' INTEGER
  95290. ** 'F' REAL
  95291. **
  95292. ** An extra 'D' is appended to the end of the string to cover the
  95293. ** rowid that appears as the last column in every index.
  95294. **
  95295. ** Memory for the buffer containing the column index affinity string
  95296. ** is managed along with the rest of the Index structure. It will be
  95297. ** released when sqlite3DeleteIndex() is called.
  95298. */
  95299. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  95300. if( !pIdx->zColAff ){
  95301. /* The first time a column affinity string for a particular index is
  95302. ** required, it is allocated and populated here. It is then stored as
  95303. ** a member of the Index structure for subsequent use.
  95304. **
  95305. ** The column affinity string will eventually be deleted by
  95306. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  95307. ** up.
  95308. */
  95309. int n;
  95310. Table *pTab = pIdx->pTable;
  95311. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  95312. if( !pIdx->zColAff ){
  95313. db->mallocFailed = 1;
  95314. return 0;
  95315. }
  95316. for(n=0; n<pIdx->nColumn; n++){
  95317. i16 x = pIdx->aiColumn[n];
  95318. if( x>=0 ){
  95319. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  95320. }else if( x==XN_ROWID ){
  95321. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  95322. }else{
  95323. char aff;
  95324. assert( x==XN_EXPR );
  95325. assert( pIdx->aColExpr!=0 );
  95326. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  95327. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  95328. pIdx->zColAff[n] = aff;
  95329. }
  95330. }
  95331. pIdx->zColAff[n] = 0;
  95332. }
  95333. return pIdx->zColAff;
  95334. }
  95335. /*
  95336. ** Compute the affinity string for table pTab, if it has not already been
  95337. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  95338. **
  95339. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  95340. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  95341. ** for register iReg and following. Or if affinities exists and iReg==0,
  95342. ** then just set the P4 operand of the previous opcode (which should be
  95343. ** an OP_MakeRecord) to the affinity string.
  95344. **
  95345. ** A column affinity string has one character per column:
  95346. **
  95347. ** Character Column affinity
  95348. ** ------------------------------
  95349. ** 'A' BLOB
  95350. ** 'B' TEXT
  95351. ** 'C' NUMERIC
  95352. ** 'D' INTEGER
  95353. ** 'E' REAL
  95354. */
  95355. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  95356. int i;
  95357. char *zColAff = pTab->zColAff;
  95358. if( zColAff==0 ){
  95359. sqlite3 *db = sqlite3VdbeDb(v);
  95360. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  95361. if( !zColAff ){
  95362. db->mallocFailed = 1;
  95363. return;
  95364. }
  95365. for(i=0; i<pTab->nCol; i++){
  95366. zColAff[i] = pTab->aCol[i].affinity;
  95367. }
  95368. do{
  95369. zColAff[i--] = 0;
  95370. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  95371. pTab->zColAff = zColAff;
  95372. }
  95373. i = sqlite3Strlen30(zColAff);
  95374. if( i ){
  95375. if( iReg ){
  95376. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  95377. }else{
  95378. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  95379. }
  95380. }
  95381. }
  95382. /*
  95383. ** Return non-zero if the table pTab in database iDb or any of its indices
  95384. ** have been opened at any point in the VDBE program. This is used to see if
  95385. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  95386. ** run without using a temporary table for the results of the SELECT.
  95387. */
  95388. static int readsTable(Parse *p, int iDb, Table *pTab){
  95389. Vdbe *v = sqlite3GetVdbe(p);
  95390. int i;
  95391. int iEnd = sqlite3VdbeCurrentAddr(v);
  95392. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95393. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  95394. #endif
  95395. for(i=1; i<iEnd; i++){
  95396. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  95397. assert( pOp!=0 );
  95398. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  95399. Index *pIndex;
  95400. int tnum = pOp->p2;
  95401. if( tnum==pTab->tnum ){
  95402. return 1;
  95403. }
  95404. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  95405. if( tnum==pIndex->tnum ){
  95406. return 1;
  95407. }
  95408. }
  95409. }
  95410. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95411. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  95412. assert( pOp->p4.pVtab!=0 );
  95413. assert( pOp->p4type==P4_VTAB );
  95414. return 1;
  95415. }
  95416. #endif
  95417. }
  95418. return 0;
  95419. }
  95420. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95421. /*
  95422. ** Locate or create an AutoincInfo structure associated with table pTab
  95423. ** which is in database iDb. Return the register number for the register
  95424. ** that holds the maximum rowid.
  95425. **
  95426. ** There is at most one AutoincInfo structure per table even if the
  95427. ** same table is autoincremented multiple times due to inserts within
  95428. ** triggers. A new AutoincInfo structure is created if this is the
  95429. ** first use of table pTab. On 2nd and subsequent uses, the original
  95430. ** AutoincInfo structure is used.
  95431. **
  95432. ** Three memory locations are allocated:
  95433. **
  95434. ** (1) Register to hold the name of the pTab table.
  95435. ** (2) Register to hold the maximum ROWID of pTab.
  95436. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  95437. **
  95438. ** The 2nd register is the one that is returned. That is all the
  95439. ** insert routine needs to know about.
  95440. */
  95441. static int autoIncBegin(
  95442. Parse *pParse, /* Parsing context */
  95443. int iDb, /* Index of the database holding pTab */
  95444. Table *pTab /* The table we are writing to */
  95445. ){
  95446. int memId = 0; /* Register holding maximum rowid */
  95447. if( pTab->tabFlags & TF_Autoincrement ){
  95448. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  95449. AutoincInfo *pInfo;
  95450. pInfo = pToplevel->pAinc;
  95451. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  95452. if( pInfo==0 ){
  95453. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  95454. if( pInfo==0 ) return 0;
  95455. pInfo->pNext = pToplevel->pAinc;
  95456. pToplevel->pAinc = pInfo;
  95457. pInfo->pTab = pTab;
  95458. pInfo->iDb = iDb;
  95459. pToplevel->nMem++; /* Register to hold name of table */
  95460. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  95461. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  95462. }
  95463. memId = pInfo->regCtr;
  95464. }
  95465. return memId;
  95466. }
  95467. /*
  95468. ** This routine generates code that will initialize all of the
  95469. ** register used by the autoincrement tracker.
  95470. */
  95471. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  95472. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  95473. sqlite3 *db = pParse->db; /* The database connection */
  95474. Db *pDb; /* Database only autoinc table */
  95475. int memId; /* Register holding max rowid */
  95476. int addr; /* A VDBE address */
  95477. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  95478. /* This routine is never called during trigger-generation. It is
  95479. ** only called from the top-level */
  95480. assert( pParse->pTriggerTab==0 );
  95481. assert( sqlite3IsToplevel(pParse) );
  95482. assert( v ); /* We failed long ago if this is not so */
  95483. for(p = pParse->pAinc; p; p = p->pNext){
  95484. pDb = &db->aDb[p->iDb];
  95485. memId = p->regCtr;
  95486. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  95487. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  95488. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  95489. addr = sqlite3VdbeCurrentAddr(v);
  95490. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  95491. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  95492. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  95493. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  95494. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  95495. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  95496. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  95497. sqlite3VdbeGoto(v, addr+9);
  95498. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  95499. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  95500. sqlite3VdbeAddOp0(v, OP_Close);
  95501. }
  95502. }
  95503. /*
  95504. ** Update the maximum rowid for an autoincrement calculation.
  95505. **
  95506. ** This routine should be called when the top of the stack holds a
  95507. ** new rowid that is about to be inserted. If that new rowid is
  95508. ** larger than the maximum rowid in the memId memory cell, then the
  95509. ** memory cell is updated. The stack is unchanged.
  95510. */
  95511. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  95512. if( memId>0 ){
  95513. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  95514. }
  95515. }
  95516. /*
  95517. ** This routine generates the code needed to write autoincrement
  95518. ** maximum rowid values back into the sqlite_sequence register.
  95519. ** Every statement that might do an INSERT into an autoincrement
  95520. ** table (either directly or through triggers) needs to call this
  95521. ** routine just before the "exit" code.
  95522. */
  95523. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  95524. AutoincInfo *p;
  95525. Vdbe *v = pParse->pVdbe;
  95526. sqlite3 *db = pParse->db;
  95527. assert( v );
  95528. for(p = pParse->pAinc; p; p = p->pNext){
  95529. Db *pDb = &db->aDb[p->iDb];
  95530. int addr1;
  95531. int iRec;
  95532. int memId = p->regCtr;
  95533. iRec = sqlite3GetTempReg(pParse);
  95534. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  95535. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  95536. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  95537. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  95538. sqlite3VdbeJumpHere(v, addr1);
  95539. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  95540. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  95541. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95542. sqlite3VdbeAddOp0(v, OP_Close);
  95543. sqlite3ReleaseTempReg(pParse, iRec);
  95544. }
  95545. }
  95546. #else
  95547. /*
  95548. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  95549. ** above are all no-ops
  95550. */
  95551. # define autoIncBegin(A,B,C) (0)
  95552. # define autoIncStep(A,B,C)
  95553. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  95554. /* Forward declaration */
  95555. static int xferOptimization(
  95556. Parse *pParse, /* Parser context */
  95557. Table *pDest, /* The table we are inserting into */
  95558. Select *pSelect, /* A SELECT statement to use as the data source */
  95559. int onError, /* How to handle constraint errors */
  95560. int iDbDest /* The database of pDest */
  95561. );
  95562. /*
  95563. ** This routine is called to handle SQL of the following forms:
  95564. **
  95565. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  95566. ** insert into TABLE (IDLIST) select
  95567. ** insert into TABLE (IDLIST) default values
  95568. **
  95569. ** The IDLIST following the table name is always optional. If omitted,
  95570. ** then a list of all (non-hidden) columns for the table is substituted.
  95571. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  95572. ** is omitted.
  95573. **
  95574. ** For the pSelect parameter holds the values to be inserted for the
  95575. ** first two forms shown above. A VALUES clause is really just short-hand
  95576. ** for a SELECT statement that omits the FROM clause and everything else
  95577. ** that follows. If the pSelect parameter is NULL, that means that the
  95578. ** DEFAULT VALUES form of the INSERT statement is intended.
  95579. **
  95580. ** The code generated follows one of four templates. For a simple
  95581. ** insert with data coming from a single-row VALUES clause, the code executes
  95582. ** once straight down through. Pseudo-code follows (we call this
  95583. ** the "1st template"):
  95584. **
  95585. ** open write cursor to <table> and its indices
  95586. ** put VALUES clause expressions into registers
  95587. ** write the resulting record into <table>
  95588. ** cleanup
  95589. **
  95590. ** The three remaining templates assume the statement is of the form
  95591. **
  95592. ** INSERT INTO <table> SELECT ...
  95593. **
  95594. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  95595. ** in other words if the SELECT pulls all columns from a single table
  95596. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  95597. ** if <table2> and <table1> are distinct tables but have identical
  95598. ** schemas, including all the same indices, then a special optimization
  95599. ** is invoked that copies raw records from <table2> over to <table1>.
  95600. ** See the xferOptimization() function for the implementation of this
  95601. ** template. This is the 2nd template.
  95602. **
  95603. ** open a write cursor to <table>
  95604. ** open read cursor on <table2>
  95605. ** transfer all records in <table2> over to <table>
  95606. ** close cursors
  95607. ** foreach index on <table>
  95608. ** open a write cursor on the <table> index
  95609. ** open a read cursor on the corresponding <table2> index
  95610. ** transfer all records from the read to the write cursors
  95611. ** close cursors
  95612. ** end foreach
  95613. **
  95614. ** The 3rd template is for when the second template does not apply
  95615. ** and the SELECT clause does not read from <table> at any time.
  95616. ** The generated code follows this template:
  95617. **
  95618. ** X <- A
  95619. ** goto B
  95620. ** A: setup for the SELECT
  95621. ** loop over the rows in the SELECT
  95622. ** load values into registers R..R+n
  95623. ** yield X
  95624. ** end loop
  95625. ** cleanup after the SELECT
  95626. ** end-coroutine X
  95627. ** B: open write cursor to <table> and its indices
  95628. ** C: yield X, at EOF goto D
  95629. ** insert the select result into <table> from R..R+n
  95630. ** goto C
  95631. ** D: cleanup
  95632. **
  95633. ** The 4th template is used if the insert statement takes its
  95634. ** values from a SELECT but the data is being inserted into a table
  95635. ** that is also read as part of the SELECT. In the third form,
  95636. ** we have to use an intermediate table to store the results of
  95637. ** the select. The template is like this:
  95638. **
  95639. ** X <- A
  95640. ** goto B
  95641. ** A: setup for the SELECT
  95642. ** loop over the tables in the SELECT
  95643. ** load value into register R..R+n
  95644. ** yield X
  95645. ** end loop
  95646. ** cleanup after the SELECT
  95647. ** end co-routine R
  95648. ** B: open temp table
  95649. ** L: yield X, at EOF goto M
  95650. ** insert row from R..R+n into temp table
  95651. ** goto L
  95652. ** M: open write cursor to <table> and its indices
  95653. ** rewind temp table
  95654. ** C: loop over rows of intermediate table
  95655. ** transfer values form intermediate table into <table>
  95656. ** end loop
  95657. ** D: cleanup
  95658. */
  95659. SQLITE_PRIVATE void sqlite3Insert(
  95660. Parse *pParse, /* Parser context */
  95661. SrcList *pTabList, /* Name of table into which we are inserting */
  95662. Select *pSelect, /* A SELECT statement to use as the data source */
  95663. IdList *pColumn, /* Column names corresponding to IDLIST. */
  95664. int onError /* How to handle constraint errors */
  95665. ){
  95666. sqlite3 *db; /* The main database structure */
  95667. Table *pTab; /* The table to insert into. aka TABLE */
  95668. char *zTab; /* Name of the table into which we are inserting */
  95669. const char *zDb; /* Name of the database holding this table */
  95670. int i, j, idx; /* Loop counters */
  95671. Vdbe *v; /* Generate code into this virtual machine */
  95672. Index *pIdx; /* For looping over indices of the table */
  95673. int nColumn; /* Number of columns in the data */
  95674. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  95675. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  95676. int iIdxCur = 0; /* First index cursor */
  95677. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  95678. int endOfLoop; /* Label for the end of the insertion loop */
  95679. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  95680. int addrInsTop = 0; /* Jump to label "D" */
  95681. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  95682. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  95683. int iDb; /* Index of database holding TABLE */
  95684. Db *pDb; /* The database containing table being inserted into */
  95685. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  95686. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  95687. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  95688. u8 bIdListInOrder; /* True if IDLIST is in table order */
  95689. ExprList *pList = 0; /* List of VALUES() to be inserted */
  95690. /* Register allocations */
  95691. int regFromSelect = 0;/* Base register for data coming from SELECT */
  95692. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  95693. int regRowCount = 0; /* Memory cell used for the row counter */
  95694. int regIns; /* Block of regs holding rowid+data being inserted */
  95695. int regRowid; /* registers holding insert rowid */
  95696. int regData; /* register holding first column to insert */
  95697. int *aRegIdx = 0; /* One register allocated to each index */
  95698. #ifndef SQLITE_OMIT_TRIGGER
  95699. int isView; /* True if attempting to insert into a view */
  95700. Trigger *pTrigger; /* List of triggers on pTab, if required */
  95701. int tmask; /* Mask of trigger times */
  95702. #endif
  95703. db = pParse->db;
  95704. memset(&dest, 0, sizeof(dest));
  95705. if( pParse->nErr || db->mallocFailed ){
  95706. goto insert_cleanup;
  95707. }
  95708. /* If the Select object is really just a simple VALUES() list with a
  95709. ** single row (the common case) then keep that one row of values
  95710. ** and discard the other (unused) parts of the pSelect object
  95711. */
  95712. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  95713. pList = pSelect->pEList;
  95714. pSelect->pEList = 0;
  95715. sqlite3SelectDelete(db, pSelect);
  95716. pSelect = 0;
  95717. }
  95718. /* Locate the table into which we will be inserting new information.
  95719. */
  95720. assert( pTabList->nSrc==1 );
  95721. zTab = pTabList->a[0].zName;
  95722. if( NEVER(zTab==0) ) goto insert_cleanup;
  95723. pTab = sqlite3SrcListLookup(pParse, pTabList);
  95724. if( pTab==0 ){
  95725. goto insert_cleanup;
  95726. }
  95727. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95728. assert( iDb<db->nDb );
  95729. pDb = &db->aDb[iDb];
  95730. zDb = pDb->zName;
  95731. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  95732. goto insert_cleanup;
  95733. }
  95734. withoutRowid = !HasRowid(pTab);
  95735. /* Figure out if we have any triggers and if the table being
  95736. ** inserted into is a view
  95737. */
  95738. #ifndef SQLITE_OMIT_TRIGGER
  95739. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  95740. isView = pTab->pSelect!=0;
  95741. #else
  95742. # define pTrigger 0
  95743. # define tmask 0
  95744. # define isView 0
  95745. #endif
  95746. #ifdef SQLITE_OMIT_VIEW
  95747. # undef isView
  95748. # define isView 0
  95749. #endif
  95750. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  95751. /* If pTab is really a view, make sure it has been initialized.
  95752. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  95753. */
  95754. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  95755. goto insert_cleanup;
  95756. }
  95757. /* Cannot insert into a read-only table.
  95758. */
  95759. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  95760. goto insert_cleanup;
  95761. }
  95762. /* Allocate a VDBE
  95763. */
  95764. v = sqlite3GetVdbe(pParse);
  95765. if( v==0 ) goto insert_cleanup;
  95766. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  95767. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  95768. #ifndef SQLITE_OMIT_XFER_OPT
  95769. /* If the statement is of the form
  95770. **
  95771. ** INSERT INTO <table1> SELECT * FROM <table2>;
  95772. **
  95773. ** Then special optimizations can be applied that make the transfer
  95774. ** very fast and which reduce fragmentation of indices.
  95775. **
  95776. ** This is the 2nd template.
  95777. */
  95778. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  95779. assert( !pTrigger );
  95780. assert( pList==0 );
  95781. goto insert_end;
  95782. }
  95783. #endif /* SQLITE_OMIT_XFER_OPT */
  95784. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  95785. ** sqlite_sequence table and store it in memory cell regAutoinc.
  95786. */
  95787. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  95788. /* Allocate registers for holding the rowid of the new row,
  95789. ** the content of the new row, and the assembled row record.
  95790. */
  95791. regRowid = regIns = pParse->nMem+1;
  95792. pParse->nMem += pTab->nCol + 1;
  95793. if( IsVirtual(pTab) ){
  95794. regRowid++;
  95795. pParse->nMem++;
  95796. }
  95797. regData = regRowid+1;
  95798. /* If the INSERT statement included an IDLIST term, then make sure
  95799. ** all elements of the IDLIST really are columns of the table and
  95800. ** remember the column indices.
  95801. **
  95802. ** If the table has an INTEGER PRIMARY KEY column and that column
  95803. ** is named in the IDLIST, then record in the ipkColumn variable
  95804. ** the index into IDLIST of the primary key column. ipkColumn is
  95805. ** the index of the primary key as it appears in IDLIST, not as
  95806. ** is appears in the original table. (The index of the INTEGER
  95807. ** PRIMARY KEY in the original table is pTab->iPKey.)
  95808. */
  95809. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  95810. if( pColumn ){
  95811. for(i=0; i<pColumn->nId; i++){
  95812. pColumn->a[i].idx = -1;
  95813. }
  95814. for(i=0; i<pColumn->nId; i++){
  95815. for(j=0; j<pTab->nCol; j++){
  95816. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  95817. pColumn->a[i].idx = j;
  95818. if( i!=j ) bIdListInOrder = 0;
  95819. if( j==pTab->iPKey ){
  95820. ipkColumn = i; assert( !withoutRowid );
  95821. }
  95822. break;
  95823. }
  95824. }
  95825. if( j>=pTab->nCol ){
  95826. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  95827. ipkColumn = i;
  95828. bIdListInOrder = 0;
  95829. }else{
  95830. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  95831. pTabList, 0, pColumn->a[i].zName);
  95832. pParse->checkSchema = 1;
  95833. goto insert_cleanup;
  95834. }
  95835. }
  95836. }
  95837. }
  95838. /* Figure out how many columns of data are supplied. If the data
  95839. ** is coming from a SELECT statement, then generate a co-routine that
  95840. ** produces a single row of the SELECT on each invocation. The
  95841. ** co-routine is the common header to the 3rd and 4th templates.
  95842. */
  95843. if( pSelect ){
  95844. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  95845. ** Generate a co-routine to run the SELECT. */
  95846. int regYield; /* Register holding co-routine entry-point */
  95847. int addrTop; /* Top of the co-routine */
  95848. int rc; /* Result code */
  95849. regYield = ++pParse->nMem;
  95850. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  95851. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  95852. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  95853. dest.iSdst = bIdListInOrder ? regData : 0;
  95854. dest.nSdst = pTab->nCol;
  95855. rc = sqlite3Select(pParse, pSelect, &dest);
  95856. regFromSelect = dest.iSdst;
  95857. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  95858. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  95859. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  95860. assert( pSelect->pEList );
  95861. nColumn = pSelect->pEList->nExpr;
  95862. /* Set useTempTable to TRUE if the result of the SELECT statement
  95863. ** should be written into a temporary table (template 4). Set to
  95864. ** FALSE if each output row of the SELECT can be written directly into
  95865. ** the destination table (template 3).
  95866. **
  95867. ** A temp table must be used if the table being updated is also one
  95868. ** of the tables being read by the SELECT statement. Also use a
  95869. ** temp table in the case of row triggers.
  95870. */
  95871. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  95872. useTempTable = 1;
  95873. }
  95874. if( useTempTable ){
  95875. /* Invoke the coroutine to extract information from the SELECT
  95876. ** and add it to a transient table srcTab. The code generated
  95877. ** here is from the 4th template:
  95878. **
  95879. ** B: open temp table
  95880. ** L: yield X, goto M at EOF
  95881. ** insert row from R..R+n into temp table
  95882. ** goto L
  95883. ** M: ...
  95884. */
  95885. int regRec; /* Register to hold packed record */
  95886. int regTempRowid; /* Register to hold temp table ROWID */
  95887. int addrL; /* Label "L" */
  95888. srcTab = pParse->nTab++;
  95889. regRec = sqlite3GetTempReg(pParse);
  95890. regTempRowid = sqlite3GetTempReg(pParse);
  95891. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  95892. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  95893. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  95894. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  95895. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  95896. sqlite3VdbeGoto(v, addrL);
  95897. sqlite3VdbeJumpHere(v, addrL);
  95898. sqlite3ReleaseTempReg(pParse, regRec);
  95899. sqlite3ReleaseTempReg(pParse, regTempRowid);
  95900. }
  95901. }else{
  95902. /* This is the case if the data for the INSERT is coming from a
  95903. ** single-row VALUES clause
  95904. */
  95905. NameContext sNC;
  95906. memset(&sNC, 0, sizeof(sNC));
  95907. sNC.pParse = pParse;
  95908. srcTab = -1;
  95909. assert( useTempTable==0 );
  95910. if( pList ){
  95911. nColumn = pList->nExpr;
  95912. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  95913. goto insert_cleanup;
  95914. }
  95915. }else{
  95916. nColumn = 0;
  95917. }
  95918. }
  95919. /* If there is no IDLIST term but the table has an integer primary
  95920. ** key, the set the ipkColumn variable to the integer primary key
  95921. ** column index in the original table definition.
  95922. */
  95923. if( pColumn==0 && nColumn>0 ){
  95924. ipkColumn = pTab->iPKey;
  95925. }
  95926. /* Make sure the number of columns in the source data matches the number
  95927. ** of columns to be inserted into the table.
  95928. */
  95929. if( IsVirtual(pTab) ){
  95930. for(i=0; i<pTab->nCol; i++){
  95931. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  95932. }
  95933. }
  95934. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  95935. sqlite3ErrorMsg(pParse,
  95936. "table %S has %d columns but %d values were supplied",
  95937. pTabList, 0, pTab->nCol-nHidden, nColumn);
  95938. goto insert_cleanup;
  95939. }
  95940. if( pColumn!=0 && nColumn!=pColumn->nId ){
  95941. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  95942. goto insert_cleanup;
  95943. }
  95944. /* Initialize the count of rows to be inserted
  95945. */
  95946. if( db->flags & SQLITE_CountRows ){
  95947. regRowCount = ++pParse->nMem;
  95948. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  95949. }
  95950. /* If this is not a view, open the table and and all indices */
  95951. if( !isView ){
  95952. int nIdx;
  95953. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
  95954. &iDataCur, &iIdxCur);
  95955. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  95956. if( aRegIdx==0 ){
  95957. goto insert_cleanup;
  95958. }
  95959. for(i=0; i<nIdx; i++){
  95960. aRegIdx[i] = ++pParse->nMem;
  95961. }
  95962. }
  95963. /* This is the top of the main insertion loop */
  95964. if( useTempTable ){
  95965. /* This block codes the top of loop only. The complete loop is the
  95966. ** following pseudocode (template 4):
  95967. **
  95968. ** rewind temp table, if empty goto D
  95969. ** C: loop over rows of intermediate table
  95970. ** transfer values form intermediate table into <table>
  95971. ** end loop
  95972. ** D: ...
  95973. */
  95974. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  95975. addrCont = sqlite3VdbeCurrentAddr(v);
  95976. }else if( pSelect ){
  95977. /* This block codes the top of loop only. The complete loop is the
  95978. ** following pseudocode (template 3):
  95979. **
  95980. ** C: yield X, at EOF goto D
  95981. ** insert the select result into <table> from R..R+n
  95982. ** goto C
  95983. ** D: ...
  95984. */
  95985. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  95986. VdbeCoverage(v);
  95987. }
  95988. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  95989. */
  95990. endOfLoop = sqlite3VdbeMakeLabel(v);
  95991. if( tmask & TRIGGER_BEFORE ){
  95992. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  95993. /* build the NEW.* reference row. Note that if there is an INTEGER
  95994. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  95995. ** translated into a unique ID for the row. But on a BEFORE trigger,
  95996. ** we do not know what the unique ID will be (because the insert has
  95997. ** not happened yet) so we substitute a rowid of -1
  95998. */
  95999. if( ipkColumn<0 ){
  96000. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  96001. }else{
  96002. int addr1;
  96003. assert( !withoutRowid );
  96004. if( useTempTable ){
  96005. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  96006. }else{
  96007. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  96008. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  96009. }
  96010. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  96011. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  96012. sqlite3VdbeJumpHere(v, addr1);
  96013. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  96014. }
  96015. /* Cannot have triggers on a virtual table. If it were possible,
  96016. ** this block would have to account for hidden column.
  96017. */
  96018. assert( !IsVirtual(pTab) );
  96019. /* Create the new column data
  96020. */
  96021. for(i=0; i<pTab->nCol; i++){
  96022. if( pColumn==0 ){
  96023. j = i;
  96024. }else{
  96025. for(j=0; j<pColumn->nId; j++){
  96026. if( pColumn->a[j].idx==i ) break;
  96027. }
  96028. }
  96029. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  96030. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  96031. }else if( useTempTable ){
  96032. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  96033. }else{
  96034. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  96035. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  96036. }
  96037. }
  96038. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  96039. ** do not attempt any conversions before assembling the record.
  96040. ** If this is a real table, attempt conversions as required by the
  96041. ** table column affinities.
  96042. */
  96043. if( !isView ){
  96044. sqlite3TableAffinity(v, pTab, regCols+1);
  96045. }
  96046. /* Fire BEFORE or INSTEAD OF triggers */
  96047. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  96048. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  96049. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  96050. }
  96051. /* Compute the content of the next row to insert into a range of
  96052. ** registers beginning at regIns.
  96053. */
  96054. if( !isView ){
  96055. if( IsVirtual(pTab) ){
  96056. /* The row that the VUpdate opcode will delete: none */
  96057. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  96058. }
  96059. if( ipkColumn>=0 ){
  96060. if( useTempTable ){
  96061. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  96062. }else if( pSelect ){
  96063. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  96064. }else{
  96065. VdbeOp *pOp;
  96066. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  96067. pOp = sqlite3VdbeGetOp(v, -1);
  96068. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  96069. appendFlag = 1;
  96070. pOp->opcode = OP_NewRowid;
  96071. pOp->p1 = iDataCur;
  96072. pOp->p2 = regRowid;
  96073. pOp->p3 = regAutoinc;
  96074. }
  96075. }
  96076. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  96077. ** to generate a unique primary key value.
  96078. */
  96079. if( !appendFlag ){
  96080. int addr1;
  96081. if( !IsVirtual(pTab) ){
  96082. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  96083. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  96084. sqlite3VdbeJumpHere(v, addr1);
  96085. }else{
  96086. addr1 = sqlite3VdbeCurrentAddr(v);
  96087. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  96088. }
  96089. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  96090. }
  96091. }else if( IsVirtual(pTab) || withoutRowid ){
  96092. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  96093. }else{
  96094. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  96095. appendFlag = 1;
  96096. }
  96097. autoIncStep(pParse, regAutoinc, regRowid);
  96098. /* Compute data for all columns of the new entry, beginning
  96099. ** with the first column.
  96100. */
  96101. nHidden = 0;
  96102. for(i=0; i<pTab->nCol; i++){
  96103. int iRegStore = regRowid+1+i;
  96104. if( i==pTab->iPKey ){
  96105. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  96106. ** Whenever this column is read, the rowid will be substituted
  96107. ** in its place. Hence, fill this column with a NULL to avoid
  96108. ** taking up data space with information that will never be used.
  96109. ** As there may be shallow copies of this value, make it a soft-NULL */
  96110. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  96111. continue;
  96112. }
  96113. if( pColumn==0 ){
  96114. if( IsHiddenColumn(&pTab->aCol[i]) ){
  96115. assert( IsVirtual(pTab) );
  96116. j = -1;
  96117. nHidden++;
  96118. }else{
  96119. j = i - nHidden;
  96120. }
  96121. }else{
  96122. for(j=0; j<pColumn->nId; j++){
  96123. if( pColumn->a[j].idx==i ) break;
  96124. }
  96125. }
  96126. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  96127. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  96128. }else if( useTempTable ){
  96129. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  96130. }else if( pSelect ){
  96131. if( regFromSelect!=regData ){
  96132. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  96133. }
  96134. }else{
  96135. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  96136. }
  96137. }
  96138. /* Generate code to check constraints and generate index keys and
  96139. ** do the insertion.
  96140. */
  96141. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96142. if( IsVirtual(pTab) ){
  96143. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  96144. sqlite3VtabMakeWritable(pParse, pTab);
  96145. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  96146. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  96147. sqlite3MayAbort(pParse);
  96148. }else
  96149. #endif
  96150. {
  96151. int isReplace; /* Set to true if constraints may cause a replace */
  96152. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  96153. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  96154. );
  96155. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  96156. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  96157. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  96158. }
  96159. }
  96160. /* Update the count of rows that are inserted
  96161. */
  96162. if( (db->flags & SQLITE_CountRows)!=0 ){
  96163. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  96164. }
  96165. if( pTrigger ){
  96166. /* Code AFTER triggers */
  96167. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  96168. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  96169. }
  96170. /* The bottom of the main insertion loop, if the data source
  96171. ** is a SELECT statement.
  96172. */
  96173. sqlite3VdbeResolveLabel(v, endOfLoop);
  96174. if( useTempTable ){
  96175. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  96176. sqlite3VdbeJumpHere(v, addrInsTop);
  96177. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  96178. }else if( pSelect ){
  96179. sqlite3VdbeGoto(v, addrCont);
  96180. sqlite3VdbeJumpHere(v, addrInsTop);
  96181. }
  96182. if( !IsVirtual(pTab) && !isView ){
  96183. /* Close all tables opened */
  96184. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  96185. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  96186. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  96187. }
  96188. }
  96189. insert_end:
  96190. /* Update the sqlite_sequence table by storing the content of the
  96191. ** maximum rowid counter values recorded while inserting into
  96192. ** autoincrement tables.
  96193. */
  96194. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  96195. sqlite3AutoincrementEnd(pParse);
  96196. }
  96197. /*
  96198. ** Return the number of rows inserted. If this routine is
  96199. ** generating code because of a call to sqlite3NestedParse(), do not
  96200. ** invoke the callback function.
  96201. */
  96202. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  96203. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  96204. sqlite3VdbeSetNumCols(v, 1);
  96205. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  96206. }
  96207. insert_cleanup:
  96208. sqlite3SrcListDelete(db, pTabList);
  96209. sqlite3ExprListDelete(db, pList);
  96210. sqlite3SelectDelete(db, pSelect);
  96211. sqlite3IdListDelete(db, pColumn);
  96212. sqlite3DbFree(db, aRegIdx);
  96213. }
  96214. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  96215. ** they may interfere with compilation of other functions in this file
  96216. ** (or in another file, if this file becomes part of the amalgamation). */
  96217. #ifdef isView
  96218. #undef isView
  96219. #endif
  96220. #ifdef pTrigger
  96221. #undef pTrigger
  96222. #endif
  96223. #ifdef tmask
  96224. #undef tmask
  96225. #endif
  96226. /*
  96227. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  96228. ** on table pTab.
  96229. **
  96230. ** The regNewData parameter is the first register in a range that contains
  96231. ** the data to be inserted or the data after the update. There will be
  96232. ** pTab->nCol+1 registers in this range. The first register (the one
  96233. ** that regNewData points to) will contain the new rowid, or NULL in the
  96234. ** case of a WITHOUT ROWID table. The second register in the range will
  96235. ** contain the content of the first table column. The third register will
  96236. ** contain the content of the second table column. And so forth.
  96237. **
  96238. ** The regOldData parameter is similar to regNewData except that it contains
  96239. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  96240. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  96241. ** checking regOldData for zero.
  96242. **
  96243. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  96244. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  96245. ** might be modified by the UPDATE. If pkChng is false, then the key of
  96246. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  96247. **
  96248. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  96249. ** was explicitly specified as part of the INSERT statement. If pkChng
  96250. ** is zero, it means that the either rowid is computed automatically or
  96251. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  96252. ** pkChng will only be true if the INSERT statement provides an integer
  96253. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  96254. **
  96255. ** The code generated by this routine will store new index entries into
  96256. ** registers identified by aRegIdx[]. No index entry is created for
  96257. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  96258. ** the same as the order of indices on the linked list of indices
  96259. ** at pTab->pIndex.
  96260. **
  96261. ** The caller must have already opened writeable cursors on the main
  96262. ** table and all applicable indices (that is to say, all indices for which
  96263. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  96264. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  96265. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  96266. ** for the first index in the pTab->pIndex list. Cursors for other indices
  96267. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  96268. **
  96269. ** This routine also generates code to check constraints. NOT NULL,
  96270. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  96271. ** then the appropriate action is performed. There are five possible
  96272. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  96273. **
  96274. ** Constraint type Action What Happens
  96275. ** --------------- ---------- ----------------------------------------
  96276. ** any ROLLBACK The current transaction is rolled back and
  96277. ** sqlite3_step() returns immediately with a
  96278. ** return code of SQLITE_CONSTRAINT.
  96279. **
  96280. ** any ABORT Back out changes from the current command
  96281. ** only (do not do a complete rollback) then
  96282. ** cause sqlite3_step() to return immediately
  96283. ** with SQLITE_CONSTRAINT.
  96284. **
  96285. ** any FAIL Sqlite3_step() returns immediately with a
  96286. ** return code of SQLITE_CONSTRAINT. The
  96287. ** transaction is not rolled back and any
  96288. ** changes to prior rows are retained.
  96289. **
  96290. ** any IGNORE The attempt in insert or update the current
  96291. ** row is skipped, without throwing an error.
  96292. ** Processing continues with the next row.
  96293. ** (There is an immediate jump to ignoreDest.)
  96294. **
  96295. ** NOT NULL REPLACE The NULL value is replace by the default
  96296. ** value for that column. If the default value
  96297. ** is NULL, the action is the same as ABORT.
  96298. **
  96299. ** UNIQUE REPLACE The other row that conflicts with the row
  96300. ** being inserted is removed.
  96301. **
  96302. ** CHECK REPLACE Illegal. The results in an exception.
  96303. **
  96304. ** Which action to take is determined by the overrideError parameter.
  96305. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  96306. ** is used. Or if pParse->onError==OE_Default then the onError value
  96307. ** for the constraint is used.
  96308. */
  96309. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  96310. Parse *pParse, /* The parser context */
  96311. Table *pTab, /* The table being inserted or updated */
  96312. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  96313. int iDataCur, /* Canonical data cursor (main table or PK index) */
  96314. int iIdxCur, /* First index cursor */
  96315. int regNewData, /* First register in a range holding values to insert */
  96316. int regOldData, /* Previous content. 0 for INSERTs */
  96317. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  96318. u8 overrideError, /* Override onError to this if not OE_Default */
  96319. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  96320. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  96321. ){
  96322. Vdbe *v; /* VDBE under constrution */
  96323. Index *pIdx; /* Pointer to one of the indices */
  96324. Index *pPk = 0; /* The PRIMARY KEY index */
  96325. sqlite3 *db; /* Database connection */
  96326. int i; /* loop counter */
  96327. int ix; /* Index loop counter */
  96328. int nCol; /* Number of columns */
  96329. int onError; /* Conflict resolution strategy */
  96330. int addr1; /* Address of jump instruction */
  96331. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  96332. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  96333. int ipkTop = 0; /* Top of the rowid change constraint check */
  96334. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  96335. u8 isUpdate; /* True if this is an UPDATE operation */
  96336. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  96337. int regRowid = -1; /* Register holding ROWID value */
  96338. isUpdate = regOldData!=0;
  96339. db = pParse->db;
  96340. v = sqlite3GetVdbe(pParse);
  96341. assert( v!=0 );
  96342. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  96343. nCol = pTab->nCol;
  96344. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  96345. ** normal rowid tables. nPkField is the number of key fields in the
  96346. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  96347. ** number of fields in the true primary key of the table. */
  96348. if( HasRowid(pTab) ){
  96349. pPk = 0;
  96350. nPkField = 1;
  96351. }else{
  96352. pPk = sqlite3PrimaryKeyIndex(pTab);
  96353. nPkField = pPk->nKeyCol;
  96354. }
  96355. /* Record that this module has started */
  96356. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  96357. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  96358. /* Test all NOT NULL constraints.
  96359. */
  96360. for(i=0; i<nCol; i++){
  96361. if( i==pTab->iPKey ){
  96362. continue;
  96363. }
  96364. onError = pTab->aCol[i].notNull;
  96365. if( onError==OE_None ) continue;
  96366. if( overrideError!=OE_Default ){
  96367. onError = overrideError;
  96368. }else if( onError==OE_Default ){
  96369. onError = OE_Abort;
  96370. }
  96371. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  96372. onError = OE_Abort;
  96373. }
  96374. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  96375. || onError==OE_Ignore || onError==OE_Replace );
  96376. switch( onError ){
  96377. case OE_Abort:
  96378. sqlite3MayAbort(pParse);
  96379. /* Fall through */
  96380. case OE_Rollback:
  96381. case OE_Fail: {
  96382. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  96383. pTab->aCol[i].zName);
  96384. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  96385. regNewData+1+i, zMsg, P4_DYNAMIC);
  96386. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  96387. VdbeCoverage(v);
  96388. break;
  96389. }
  96390. case OE_Ignore: {
  96391. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  96392. VdbeCoverage(v);
  96393. break;
  96394. }
  96395. default: {
  96396. assert( onError==OE_Replace );
  96397. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  96398. VdbeCoverage(v);
  96399. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  96400. sqlite3VdbeJumpHere(v, addr1);
  96401. break;
  96402. }
  96403. }
  96404. }
  96405. /* Test all CHECK constraints
  96406. */
  96407. #ifndef SQLITE_OMIT_CHECK
  96408. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  96409. ExprList *pCheck = pTab->pCheck;
  96410. pParse->ckBase = regNewData+1;
  96411. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  96412. for(i=0; i<pCheck->nExpr; i++){
  96413. int allOk = sqlite3VdbeMakeLabel(v);
  96414. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  96415. if( onError==OE_Ignore ){
  96416. sqlite3VdbeGoto(v, ignoreDest);
  96417. }else{
  96418. char *zName = pCheck->a[i].zName;
  96419. if( zName==0 ) zName = pTab->zName;
  96420. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  96421. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  96422. onError, zName, P4_TRANSIENT,
  96423. P5_ConstraintCheck);
  96424. }
  96425. sqlite3VdbeResolveLabel(v, allOk);
  96426. }
  96427. }
  96428. #endif /* !defined(SQLITE_OMIT_CHECK) */
  96429. /* If rowid is changing, make sure the new rowid does not previously
  96430. ** exist in the table.
  96431. */
  96432. if( pkChng && pPk==0 ){
  96433. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  96434. /* Figure out what action to take in case of a rowid collision */
  96435. onError = pTab->keyConf;
  96436. if( overrideError!=OE_Default ){
  96437. onError = overrideError;
  96438. }else if( onError==OE_Default ){
  96439. onError = OE_Abort;
  96440. }
  96441. if( isUpdate ){
  96442. /* pkChng!=0 does not mean that the rowid has change, only that
  96443. ** it might have changed. Skip the conflict logic below if the rowid
  96444. ** is unchanged. */
  96445. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  96446. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  96447. VdbeCoverage(v);
  96448. }
  96449. /* If the response to a rowid conflict is REPLACE but the response
  96450. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  96451. ** to defer the running of the rowid conflict checking until after
  96452. ** the UNIQUE constraints have run.
  96453. */
  96454. if( onError==OE_Replace && overrideError!=OE_Replace ){
  96455. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96456. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  96457. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  96458. break;
  96459. }
  96460. }
  96461. }
  96462. /* Check to see if the new rowid already exists in the table. Skip
  96463. ** the following conflict logic if it does not. */
  96464. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  96465. VdbeCoverage(v);
  96466. /* Generate code that deals with a rowid collision */
  96467. switch( onError ){
  96468. default: {
  96469. onError = OE_Abort;
  96470. /* Fall thru into the next case */
  96471. }
  96472. case OE_Rollback:
  96473. case OE_Abort:
  96474. case OE_Fail: {
  96475. sqlite3RowidConstraint(pParse, onError, pTab);
  96476. break;
  96477. }
  96478. case OE_Replace: {
  96479. /* If there are DELETE triggers on this table and the
  96480. ** recursive-triggers flag is set, call GenerateRowDelete() to
  96481. ** remove the conflicting row from the table. This will fire
  96482. ** the triggers and remove both the table and index b-tree entries.
  96483. **
  96484. ** Otherwise, if there are no triggers or the recursive-triggers
  96485. ** flag is not set, but the table has one or more indexes, call
  96486. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  96487. ** only. The table b-tree entry will be replaced by the new entry
  96488. ** when it is inserted.
  96489. **
  96490. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  96491. ** also invoke MultiWrite() to indicate that this VDBE may require
  96492. ** statement rollback (if the statement is aborted after the delete
  96493. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  96494. ** but being more selective here allows statements like:
  96495. **
  96496. ** REPLACE INTO t(rowid) VALUES($newrowid)
  96497. **
  96498. ** to run without a statement journal if there are no indexes on the
  96499. ** table.
  96500. */
  96501. Trigger *pTrigger = 0;
  96502. if( db->flags&SQLITE_RecTriggers ){
  96503. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  96504. }
  96505. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  96506. sqlite3MultiWrite(pParse);
  96507. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  96508. regNewData, 1, 0, OE_Replace,
  96509. ONEPASS_SINGLE, -1);
  96510. }else{
  96511. if( pTab->pIndex ){
  96512. sqlite3MultiWrite(pParse);
  96513. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  96514. }
  96515. }
  96516. seenReplace = 1;
  96517. break;
  96518. }
  96519. case OE_Ignore: {
  96520. /*assert( seenReplace==0 );*/
  96521. sqlite3VdbeGoto(v, ignoreDest);
  96522. break;
  96523. }
  96524. }
  96525. sqlite3VdbeResolveLabel(v, addrRowidOk);
  96526. if( ipkTop ){
  96527. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  96528. sqlite3VdbeJumpHere(v, ipkTop);
  96529. }
  96530. }
  96531. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  96532. ** index and making sure that duplicate entries do not already exist.
  96533. ** Compute the revised record entries for indices as we go.
  96534. **
  96535. ** This loop also handles the case of the PRIMARY KEY index for a
  96536. ** WITHOUT ROWID table.
  96537. */
  96538. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  96539. int regIdx; /* Range of registers hold conent for pIdx */
  96540. int regR; /* Range of registers holding conflicting PK */
  96541. int iThisCur; /* Cursor for this UNIQUE index */
  96542. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  96543. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  96544. if( bAffinityDone==0 ){
  96545. sqlite3TableAffinity(v, pTab, regNewData+1);
  96546. bAffinityDone = 1;
  96547. }
  96548. iThisCur = iIdxCur+ix;
  96549. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  96550. /* Skip partial indices for which the WHERE clause is not true */
  96551. if( pIdx->pPartIdxWhere ){
  96552. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  96553. pParse->ckBase = regNewData+1;
  96554. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  96555. SQLITE_JUMPIFNULL);
  96556. pParse->ckBase = 0;
  96557. }
  96558. /* Create a record for this index entry as it should appear after
  96559. ** the insert or update. Store that record in the aRegIdx[ix] register
  96560. */
  96561. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  96562. for(i=0; i<pIdx->nColumn; i++){
  96563. int iField = pIdx->aiColumn[i];
  96564. int x;
  96565. if( iField==XN_EXPR ){
  96566. pParse->ckBase = regNewData+1;
  96567. sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  96568. pParse->ckBase = 0;
  96569. VdbeComment((v, "%s column %d", pIdx->zName, i));
  96570. }else{
  96571. if( iField==XN_ROWID || iField==pTab->iPKey ){
  96572. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  96573. x = regNewData;
  96574. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  96575. }else{
  96576. x = iField + regNewData + 1;
  96577. }
  96578. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  96579. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  96580. }
  96581. }
  96582. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  96583. VdbeComment((v, "for %s", pIdx->zName));
  96584. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  96585. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  96586. ** of a WITHOUT ROWID table and there has been no change the
  96587. ** primary key, then no collision is possible. The collision detection
  96588. ** logic below can all be skipped. */
  96589. if( isUpdate && pPk==pIdx && pkChng==0 ){
  96590. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  96591. continue;
  96592. }
  96593. /* Find out what action to take in case there is a uniqueness conflict */
  96594. onError = pIdx->onError;
  96595. if( onError==OE_None ){
  96596. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  96597. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  96598. continue; /* pIdx is not a UNIQUE index */
  96599. }
  96600. if( overrideError!=OE_Default ){
  96601. onError = overrideError;
  96602. }else if( onError==OE_Default ){
  96603. onError = OE_Abort;
  96604. }
  96605. /* Check to see if the new index entry will be unique */
  96606. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  96607. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  96608. /* Generate code to handle collisions */
  96609. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  96610. if( isUpdate || onError==OE_Replace ){
  96611. if( HasRowid(pTab) ){
  96612. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  96613. /* Conflict only if the rowid of the existing index entry
  96614. ** is different from old-rowid */
  96615. if( isUpdate ){
  96616. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  96617. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  96618. VdbeCoverage(v);
  96619. }
  96620. }else{
  96621. int x;
  96622. /* Extract the PRIMARY KEY from the end of the index entry and
  96623. ** store it in registers regR..regR+nPk-1 */
  96624. if( pIdx!=pPk ){
  96625. for(i=0; i<pPk->nKeyCol; i++){
  96626. assert( pPk->aiColumn[i]>=0 );
  96627. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  96628. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  96629. VdbeComment((v, "%s.%s", pTab->zName,
  96630. pTab->aCol[pPk->aiColumn[i]].zName));
  96631. }
  96632. }
  96633. if( isUpdate ){
  96634. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  96635. ** table, only conflict if the new PRIMARY KEY values are actually
  96636. ** different from the old.
  96637. **
  96638. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  96639. ** of the matched index row are different from the original PRIMARY
  96640. ** KEY values of this row before the update. */
  96641. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  96642. int op = OP_Ne;
  96643. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  96644. for(i=0; i<pPk->nKeyCol; i++){
  96645. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  96646. x = pPk->aiColumn[i];
  96647. assert( x>=0 );
  96648. if( i==(pPk->nKeyCol-1) ){
  96649. addrJump = addrUniqueOk;
  96650. op = OP_Eq;
  96651. }
  96652. sqlite3VdbeAddOp4(v, op,
  96653. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  96654. );
  96655. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  96656. VdbeCoverageIf(v, op==OP_Eq);
  96657. VdbeCoverageIf(v, op==OP_Ne);
  96658. }
  96659. }
  96660. }
  96661. }
  96662. /* Generate code that executes if the new index entry is not unique */
  96663. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  96664. || onError==OE_Ignore || onError==OE_Replace );
  96665. switch( onError ){
  96666. case OE_Rollback:
  96667. case OE_Abort:
  96668. case OE_Fail: {
  96669. sqlite3UniqueConstraint(pParse, onError, pIdx);
  96670. break;
  96671. }
  96672. case OE_Ignore: {
  96673. sqlite3VdbeGoto(v, ignoreDest);
  96674. break;
  96675. }
  96676. default: {
  96677. Trigger *pTrigger = 0;
  96678. assert( onError==OE_Replace );
  96679. sqlite3MultiWrite(pParse);
  96680. if( db->flags&SQLITE_RecTriggers ){
  96681. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  96682. }
  96683. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  96684. regR, nPkField, 0, OE_Replace,
  96685. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
  96686. seenReplace = 1;
  96687. break;
  96688. }
  96689. }
  96690. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  96691. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  96692. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  96693. }
  96694. if( ipkTop ){
  96695. sqlite3VdbeGoto(v, ipkTop+1);
  96696. sqlite3VdbeJumpHere(v, ipkBottom);
  96697. }
  96698. *pbMayReplace = seenReplace;
  96699. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  96700. }
  96701. /*
  96702. ** This routine generates code to finish the INSERT or UPDATE operation
  96703. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  96704. ** A consecutive range of registers starting at regNewData contains the
  96705. ** rowid and the content to be inserted.
  96706. **
  96707. ** The arguments to this routine should be the same as the first six
  96708. ** arguments to sqlite3GenerateConstraintChecks.
  96709. */
  96710. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  96711. Parse *pParse, /* The parser context */
  96712. Table *pTab, /* the table into which we are inserting */
  96713. int iDataCur, /* Cursor of the canonical data source */
  96714. int iIdxCur, /* First index cursor */
  96715. int regNewData, /* Range of content */
  96716. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  96717. int isUpdate, /* True for UPDATE, False for INSERT */
  96718. int appendBias, /* True if this is likely to be an append */
  96719. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  96720. ){
  96721. Vdbe *v; /* Prepared statements under construction */
  96722. Index *pIdx; /* An index being inserted or updated */
  96723. u8 pik_flags; /* flag values passed to the btree insert */
  96724. int regData; /* Content registers (after the rowid) */
  96725. int regRec; /* Register holding assembled record for the table */
  96726. int i; /* Loop counter */
  96727. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  96728. v = sqlite3GetVdbe(pParse);
  96729. assert( v!=0 );
  96730. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  96731. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  96732. if( aRegIdx[i]==0 ) continue;
  96733. bAffinityDone = 1;
  96734. if( pIdx->pPartIdxWhere ){
  96735. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  96736. VdbeCoverage(v);
  96737. }
  96738. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  96739. pik_flags = 0;
  96740. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  96741. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  96742. assert( pParse->nested==0 );
  96743. pik_flags |= OPFLAG_NCHANGE;
  96744. }
  96745. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  96746. }
  96747. if( !HasRowid(pTab) ) return;
  96748. regData = regNewData + 1;
  96749. regRec = sqlite3GetTempReg(pParse);
  96750. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  96751. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  96752. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  96753. if( pParse->nested ){
  96754. pik_flags = 0;
  96755. }else{
  96756. pik_flags = OPFLAG_NCHANGE;
  96757. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  96758. }
  96759. if( appendBias ){
  96760. pik_flags |= OPFLAG_APPEND;
  96761. }
  96762. if( useSeekResult ){
  96763. pik_flags |= OPFLAG_USESEEKRESULT;
  96764. }
  96765. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  96766. if( !pParse->nested ){
  96767. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  96768. }
  96769. sqlite3VdbeChangeP5(v, pik_flags);
  96770. }
  96771. /*
  96772. ** Allocate cursors for the pTab table and all its indices and generate
  96773. ** code to open and initialized those cursors.
  96774. **
  96775. ** The cursor for the object that contains the complete data (normally
  96776. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  96777. ** ROWID table) is returned in *piDataCur. The first index cursor is
  96778. ** returned in *piIdxCur. The number of indices is returned.
  96779. **
  96780. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  96781. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  96782. ** If iBase is negative, then allocate the next available cursor.
  96783. **
  96784. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  96785. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  96786. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  96787. ** pTab->pIndex list.
  96788. **
  96789. ** If pTab is a virtual table, then this routine is a no-op and the
  96790. ** *piDataCur and *piIdxCur values are left uninitialized.
  96791. */
  96792. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  96793. Parse *pParse, /* Parsing context */
  96794. Table *pTab, /* Table to be opened */
  96795. int op, /* OP_OpenRead or OP_OpenWrite */
  96796. int iBase, /* Use this for the table cursor, if there is one */
  96797. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  96798. int *piDataCur, /* Write the database source cursor number here */
  96799. int *piIdxCur /* Write the first index cursor number here */
  96800. ){
  96801. int i;
  96802. int iDb;
  96803. int iDataCur;
  96804. Index *pIdx;
  96805. Vdbe *v;
  96806. assert( op==OP_OpenRead || op==OP_OpenWrite );
  96807. if( IsVirtual(pTab) ){
  96808. /* This routine is a no-op for virtual tables. Leave the output
  96809. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  96810. ** can detect if they are used by mistake in the caller. */
  96811. return 0;
  96812. }
  96813. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96814. v = sqlite3GetVdbe(pParse);
  96815. assert( v!=0 );
  96816. if( iBase<0 ) iBase = pParse->nTab;
  96817. iDataCur = iBase++;
  96818. if( piDataCur ) *piDataCur = iDataCur;
  96819. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  96820. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  96821. }else{
  96822. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  96823. }
  96824. if( piIdxCur ) *piIdxCur = iBase;
  96825. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  96826. int iIdxCur = iBase++;
  96827. assert( pIdx->pSchema==pTab->pSchema );
  96828. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  96829. *piDataCur = iIdxCur;
  96830. }
  96831. if( aToOpen==0 || aToOpen[i+1] ){
  96832. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  96833. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  96834. VdbeComment((v, "%s", pIdx->zName));
  96835. }
  96836. }
  96837. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  96838. return i;
  96839. }
  96840. #ifdef SQLITE_TEST
  96841. /*
  96842. ** The following global variable is incremented whenever the
  96843. ** transfer optimization is used. This is used for testing
  96844. ** purposes only - to make sure the transfer optimization really
  96845. ** is happening when it is supposed to.
  96846. */
  96847. SQLITE_API int sqlite3_xferopt_count;
  96848. #endif /* SQLITE_TEST */
  96849. #ifndef SQLITE_OMIT_XFER_OPT
  96850. /*
  96851. ** Check to collation names to see if they are compatible.
  96852. */
  96853. static int xferCompatibleCollation(const char *z1, const char *z2){
  96854. if( z1==0 ){
  96855. return z2==0;
  96856. }
  96857. if( z2==0 ){
  96858. return 0;
  96859. }
  96860. return sqlite3StrICmp(z1, z2)==0;
  96861. }
  96862. /*
  96863. ** Check to see if index pSrc is compatible as a source of data
  96864. ** for index pDest in an insert transfer optimization. The rules
  96865. ** for a compatible index:
  96866. **
  96867. ** * The index is over the same set of columns
  96868. ** * The same DESC and ASC markings occurs on all columns
  96869. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  96870. ** * The same collating sequence on each column
  96871. ** * The index has the exact same WHERE clause
  96872. */
  96873. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  96874. int i;
  96875. assert( pDest && pSrc );
  96876. assert( pDest->pTable!=pSrc->pTable );
  96877. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  96878. return 0; /* Different number of columns */
  96879. }
  96880. if( pDest->onError!=pSrc->onError ){
  96881. return 0; /* Different conflict resolution strategies */
  96882. }
  96883. for(i=0; i<pSrc->nKeyCol; i++){
  96884. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  96885. return 0; /* Different columns indexed */
  96886. }
  96887. if( pSrc->aiColumn[i]==XN_EXPR ){
  96888. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  96889. if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
  96890. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  96891. return 0; /* Different expressions in the index */
  96892. }
  96893. }
  96894. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  96895. return 0; /* Different sort orders */
  96896. }
  96897. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  96898. return 0; /* Different collating sequences */
  96899. }
  96900. }
  96901. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  96902. return 0; /* Different WHERE clauses */
  96903. }
  96904. /* If no test above fails then the indices must be compatible */
  96905. return 1;
  96906. }
  96907. /*
  96908. ** Attempt the transfer optimization on INSERTs of the form
  96909. **
  96910. ** INSERT INTO tab1 SELECT * FROM tab2;
  96911. **
  96912. ** The xfer optimization transfers raw records from tab2 over to tab1.
  96913. ** Columns are not decoded and reassembled, which greatly improves
  96914. ** performance. Raw index records are transferred in the same way.
  96915. **
  96916. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  96917. ** There are lots of rules for determining compatibility - see comments
  96918. ** embedded in the code for details.
  96919. **
  96920. ** This routine returns TRUE if the optimization is guaranteed to be used.
  96921. ** Sometimes the xfer optimization will only work if the destination table
  96922. ** is empty - a factor that can only be determined at run-time. In that
  96923. ** case, this routine generates code for the xfer optimization but also
  96924. ** does a test to see if the destination table is empty and jumps over the
  96925. ** xfer optimization code if the test fails. In that case, this routine
  96926. ** returns FALSE so that the caller will know to go ahead and generate
  96927. ** an unoptimized transfer. This routine also returns FALSE if there
  96928. ** is no chance that the xfer optimization can be applied.
  96929. **
  96930. ** This optimization is particularly useful at making VACUUM run faster.
  96931. */
  96932. static int xferOptimization(
  96933. Parse *pParse, /* Parser context */
  96934. Table *pDest, /* The table we are inserting into */
  96935. Select *pSelect, /* A SELECT statement to use as the data source */
  96936. int onError, /* How to handle constraint errors */
  96937. int iDbDest /* The database of pDest */
  96938. ){
  96939. sqlite3 *db = pParse->db;
  96940. ExprList *pEList; /* The result set of the SELECT */
  96941. Table *pSrc; /* The table in the FROM clause of SELECT */
  96942. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  96943. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  96944. int i; /* Loop counter */
  96945. int iDbSrc; /* The database of pSrc */
  96946. int iSrc, iDest; /* Cursors from source and destination */
  96947. int addr1, addr2; /* Loop addresses */
  96948. int emptyDestTest = 0; /* Address of test for empty pDest */
  96949. int emptySrcTest = 0; /* Address of test for empty pSrc */
  96950. Vdbe *v; /* The VDBE we are building */
  96951. int regAutoinc; /* Memory register used by AUTOINC */
  96952. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  96953. int regData, regRowid; /* Registers holding data and rowid */
  96954. if( pSelect==0 ){
  96955. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  96956. }
  96957. if( pParse->pWith || pSelect->pWith ){
  96958. /* Do not attempt to process this query if there are an WITH clauses
  96959. ** attached to it. Proceeding may generate a false "no such table: xxx"
  96960. ** error if pSelect reads from a CTE named "xxx". */
  96961. return 0;
  96962. }
  96963. if( sqlite3TriggerList(pParse, pDest) ){
  96964. return 0; /* tab1 must not have triggers */
  96965. }
  96966. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96967. if( pDest->tabFlags & TF_Virtual ){
  96968. return 0; /* tab1 must not be a virtual table */
  96969. }
  96970. #endif
  96971. if( onError==OE_Default ){
  96972. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  96973. if( onError==OE_Default ) onError = OE_Abort;
  96974. }
  96975. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  96976. if( pSelect->pSrc->nSrc!=1 ){
  96977. return 0; /* FROM clause must have exactly one term */
  96978. }
  96979. if( pSelect->pSrc->a[0].pSelect ){
  96980. return 0; /* FROM clause cannot contain a subquery */
  96981. }
  96982. if( pSelect->pWhere ){
  96983. return 0; /* SELECT may not have a WHERE clause */
  96984. }
  96985. if( pSelect->pOrderBy ){
  96986. return 0; /* SELECT may not have an ORDER BY clause */
  96987. }
  96988. /* Do not need to test for a HAVING clause. If HAVING is present but
  96989. ** there is no ORDER BY, we will get an error. */
  96990. if( pSelect->pGroupBy ){
  96991. return 0; /* SELECT may not have a GROUP BY clause */
  96992. }
  96993. if( pSelect->pLimit ){
  96994. return 0; /* SELECT may not have a LIMIT clause */
  96995. }
  96996. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  96997. if( pSelect->pPrior ){
  96998. return 0; /* SELECT may not be a compound query */
  96999. }
  97000. if( pSelect->selFlags & SF_Distinct ){
  97001. return 0; /* SELECT may not be DISTINCT */
  97002. }
  97003. pEList = pSelect->pEList;
  97004. assert( pEList!=0 );
  97005. if( pEList->nExpr!=1 ){
  97006. return 0; /* The result set must have exactly one column */
  97007. }
  97008. assert( pEList->a[0].pExpr );
  97009. if( pEList->a[0].pExpr->op!=TK_ALL ){
  97010. return 0; /* The result set must be the special operator "*" */
  97011. }
  97012. /* At this point we have established that the statement is of the
  97013. ** correct syntactic form to participate in this optimization. Now
  97014. ** we have to check the semantics.
  97015. */
  97016. pItem = pSelect->pSrc->a;
  97017. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  97018. if( pSrc==0 ){
  97019. return 0; /* FROM clause does not contain a real table */
  97020. }
  97021. if( pSrc==pDest ){
  97022. return 0; /* tab1 and tab2 may not be the same table */
  97023. }
  97024. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  97025. return 0; /* source and destination must both be WITHOUT ROWID or not */
  97026. }
  97027. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97028. if( pSrc->tabFlags & TF_Virtual ){
  97029. return 0; /* tab2 must not be a virtual table */
  97030. }
  97031. #endif
  97032. if( pSrc->pSelect ){
  97033. return 0; /* tab2 may not be a view */
  97034. }
  97035. if( pDest->nCol!=pSrc->nCol ){
  97036. return 0; /* Number of columns must be the same in tab1 and tab2 */
  97037. }
  97038. if( pDest->iPKey!=pSrc->iPKey ){
  97039. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  97040. }
  97041. for(i=0; i<pDest->nCol; i++){
  97042. Column *pDestCol = &pDest->aCol[i];
  97043. Column *pSrcCol = &pSrc->aCol[i];
  97044. if( pDestCol->affinity!=pSrcCol->affinity ){
  97045. return 0; /* Affinity must be the same on all columns */
  97046. }
  97047. if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
  97048. return 0; /* Collating sequence must be the same on all columns */
  97049. }
  97050. if( pDestCol->notNull && !pSrcCol->notNull ){
  97051. return 0; /* tab2 must be NOT NULL if tab1 is */
  97052. }
  97053. /* Default values for second and subsequent columns need to match. */
  97054. if( i>0
  97055. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  97056. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  97057. ){
  97058. return 0; /* Default values must be the same for all columns */
  97059. }
  97060. }
  97061. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  97062. if( IsUniqueIndex(pDestIdx) ){
  97063. destHasUniqueIdx = 1;
  97064. }
  97065. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  97066. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  97067. }
  97068. if( pSrcIdx==0 ){
  97069. return 0; /* pDestIdx has no corresponding index in pSrc */
  97070. }
  97071. }
  97072. #ifndef SQLITE_OMIT_CHECK
  97073. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  97074. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  97075. }
  97076. #endif
  97077. #ifndef SQLITE_OMIT_FOREIGN_KEY
  97078. /* Disallow the transfer optimization if the destination table constains
  97079. ** any foreign key constraints. This is more restrictive than necessary.
  97080. ** But the main beneficiary of the transfer optimization is the VACUUM
  97081. ** command, and the VACUUM command disables foreign key constraints. So
  97082. ** the extra complication to make this rule less restrictive is probably
  97083. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  97084. */
  97085. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  97086. return 0;
  97087. }
  97088. #endif
  97089. if( (db->flags & SQLITE_CountRows)!=0 ){
  97090. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  97091. }
  97092. /* If we get this far, it means that the xfer optimization is at
  97093. ** least a possibility, though it might only work if the destination
  97094. ** table (tab1) is initially empty.
  97095. */
  97096. #ifdef SQLITE_TEST
  97097. sqlite3_xferopt_count++;
  97098. #endif
  97099. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  97100. v = sqlite3GetVdbe(pParse);
  97101. sqlite3CodeVerifySchema(pParse, iDbSrc);
  97102. iSrc = pParse->nTab++;
  97103. iDest = pParse->nTab++;
  97104. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  97105. regData = sqlite3GetTempReg(pParse);
  97106. regRowid = sqlite3GetTempReg(pParse);
  97107. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  97108. assert( HasRowid(pDest) || destHasUniqueIdx );
  97109. if( (db->flags & SQLITE_Vacuum)==0 && (
  97110. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  97111. || destHasUniqueIdx /* (2) */
  97112. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  97113. )){
  97114. /* In some circumstances, we are able to run the xfer optimization
  97115. ** only if the destination table is initially empty. Unless the
  97116. ** SQLITE_Vacuum flag is set, this block generates code to make
  97117. ** that determination. If SQLITE_Vacuum is set, then the destination
  97118. ** table is always empty.
  97119. **
  97120. ** Conditions under which the destination must be empty:
  97121. **
  97122. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  97123. ** (If the destination is not initially empty, the rowid fields
  97124. ** of index entries might need to change.)
  97125. **
  97126. ** (2) The destination has a unique index. (The xfer optimization
  97127. ** is unable to test uniqueness.)
  97128. **
  97129. ** (3) onError is something other than OE_Abort and OE_Rollback.
  97130. */
  97131. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  97132. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  97133. sqlite3VdbeJumpHere(v, addr1);
  97134. }
  97135. if( HasRowid(pSrc) ){
  97136. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  97137. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  97138. if( pDest->iPKey>=0 ){
  97139. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  97140. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  97141. VdbeCoverage(v);
  97142. sqlite3RowidConstraint(pParse, onError, pDest);
  97143. sqlite3VdbeJumpHere(v, addr2);
  97144. autoIncStep(pParse, regAutoinc, regRowid);
  97145. }else if( pDest->pIndex==0 ){
  97146. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  97147. }else{
  97148. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  97149. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  97150. }
  97151. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  97152. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  97153. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  97154. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  97155. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  97156. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  97157. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  97158. }else{
  97159. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  97160. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  97161. }
  97162. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  97163. u8 idxInsFlags = 0;
  97164. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  97165. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  97166. }
  97167. assert( pSrcIdx );
  97168. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  97169. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  97170. VdbeComment((v, "%s", pSrcIdx->zName));
  97171. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  97172. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  97173. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  97174. VdbeComment((v, "%s", pDestIdx->zName));
  97175. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  97176. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  97177. if( db->flags & SQLITE_Vacuum ){
  97178. /* This INSERT command is part of a VACUUM operation, which guarantees
  97179. ** that the destination table is empty. If all indexed columns use
  97180. ** collation sequence BINARY, then it can also be assumed that the
  97181. ** index will be populated by inserting keys in strictly sorted
  97182. ** order. In this case, instead of seeking within the b-tree as part
  97183. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  97184. ** OP_IdxInsert to seek to the point within the b-tree where each key
  97185. ** should be inserted. This is faster.
  97186. **
  97187. ** If any of the indexed columns use a collation sequence other than
  97188. ** BINARY, this optimization is disabled. This is because the user
  97189. ** might change the definition of a collation sequence and then run
  97190. ** a VACUUM command. In that case keys may not be written in strictly
  97191. ** sorted order. */
  97192. for(i=0; i<pSrcIdx->nColumn; i++){
  97193. char *zColl = pSrcIdx->azColl[i];
  97194. assert( zColl!=0 );
  97195. if( sqlite3_stricmp("BINARY", zColl) ) break;
  97196. }
  97197. if( i==pSrcIdx->nColumn ){
  97198. idxInsFlags = OPFLAG_USESEEKRESULT;
  97199. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  97200. }
  97201. }
  97202. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  97203. idxInsFlags |= OPFLAG_NCHANGE;
  97204. }
  97205. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  97206. sqlite3VdbeChangeP5(v, idxInsFlags);
  97207. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  97208. sqlite3VdbeJumpHere(v, addr1);
  97209. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  97210. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  97211. }
  97212. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  97213. sqlite3ReleaseTempReg(pParse, regRowid);
  97214. sqlite3ReleaseTempReg(pParse, regData);
  97215. if( emptyDestTest ){
  97216. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  97217. sqlite3VdbeJumpHere(v, emptyDestTest);
  97218. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  97219. return 0;
  97220. }else{
  97221. return 1;
  97222. }
  97223. }
  97224. #endif /* SQLITE_OMIT_XFER_OPT */
  97225. /************** End of insert.c **********************************************/
  97226. /************** Begin file legacy.c ******************************************/
  97227. /*
  97228. ** 2001 September 15
  97229. **
  97230. ** The author disclaims copyright to this source code. In place of
  97231. ** a legal notice, here is a blessing:
  97232. **
  97233. ** May you do good and not evil.
  97234. ** May you find forgiveness for yourself and forgive others.
  97235. ** May you share freely, never taking more than you give.
  97236. **
  97237. *************************************************************************
  97238. ** Main file for the SQLite library. The routines in this file
  97239. ** implement the programmer interface to the library. Routines in
  97240. ** other files are for internal use by SQLite and should not be
  97241. ** accessed by users of the library.
  97242. */
  97243. /* #include "sqliteInt.h" */
  97244. /*
  97245. ** Execute SQL code. Return one of the SQLITE_ success/failure
  97246. ** codes. Also write an error message into memory obtained from
  97247. ** malloc() and make *pzErrMsg point to that message.
  97248. **
  97249. ** If the SQL is a query, then for each row in the query result
  97250. ** the xCallback() function is called. pArg becomes the first
  97251. ** argument to xCallback(). If xCallback=NULL then no callback
  97252. ** is invoked, even for queries.
  97253. */
  97254. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  97255. sqlite3 *db, /* The database on which the SQL executes */
  97256. const char *zSql, /* The SQL to be executed */
  97257. sqlite3_callback xCallback, /* Invoke this callback routine */
  97258. void *pArg, /* First argument to xCallback() */
  97259. char **pzErrMsg /* Write error messages here */
  97260. ){
  97261. int rc = SQLITE_OK; /* Return code */
  97262. const char *zLeftover; /* Tail of unprocessed SQL */
  97263. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  97264. char **azCols = 0; /* Names of result columns */
  97265. int callbackIsInit; /* True if callback data is initialized */
  97266. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  97267. if( zSql==0 ) zSql = "";
  97268. sqlite3_mutex_enter(db->mutex);
  97269. sqlite3Error(db, SQLITE_OK);
  97270. while( rc==SQLITE_OK && zSql[0] ){
  97271. int nCol;
  97272. char **azVals = 0;
  97273. pStmt = 0;
  97274. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  97275. assert( rc==SQLITE_OK || pStmt==0 );
  97276. if( rc!=SQLITE_OK ){
  97277. continue;
  97278. }
  97279. if( !pStmt ){
  97280. /* this happens for a comment or white-space */
  97281. zSql = zLeftover;
  97282. continue;
  97283. }
  97284. callbackIsInit = 0;
  97285. nCol = sqlite3_column_count(pStmt);
  97286. while( 1 ){
  97287. int i;
  97288. rc = sqlite3_step(pStmt);
  97289. /* Invoke the callback function if required */
  97290. if( xCallback && (SQLITE_ROW==rc ||
  97291. (SQLITE_DONE==rc && !callbackIsInit
  97292. && db->flags&SQLITE_NullCallback)) ){
  97293. if( !callbackIsInit ){
  97294. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  97295. if( azCols==0 ){
  97296. goto exec_out;
  97297. }
  97298. for(i=0; i<nCol; i++){
  97299. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  97300. /* sqlite3VdbeSetColName() installs column names as UTF8
  97301. ** strings so there is no way for sqlite3_column_name() to fail. */
  97302. assert( azCols[i]!=0 );
  97303. }
  97304. callbackIsInit = 1;
  97305. }
  97306. if( rc==SQLITE_ROW ){
  97307. azVals = &azCols[nCol];
  97308. for(i=0; i<nCol; i++){
  97309. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  97310. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  97311. db->mallocFailed = 1;
  97312. goto exec_out;
  97313. }
  97314. }
  97315. }
  97316. if( xCallback(pArg, nCol, azVals, azCols) ){
  97317. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  97318. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  97319. ** return SQLITE_ABORT. */
  97320. rc = SQLITE_ABORT;
  97321. sqlite3VdbeFinalize((Vdbe *)pStmt);
  97322. pStmt = 0;
  97323. sqlite3Error(db, SQLITE_ABORT);
  97324. goto exec_out;
  97325. }
  97326. }
  97327. if( rc!=SQLITE_ROW ){
  97328. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  97329. pStmt = 0;
  97330. zSql = zLeftover;
  97331. while( sqlite3Isspace(zSql[0]) ) zSql++;
  97332. break;
  97333. }
  97334. }
  97335. sqlite3DbFree(db, azCols);
  97336. azCols = 0;
  97337. }
  97338. exec_out:
  97339. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  97340. sqlite3DbFree(db, azCols);
  97341. rc = sqlite3ApiExit(db, rc);
  97342. if( rc!=SQLITE_OK && pzErrMsg ){
  97343. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  97344. *pzErrMsg = sqlite3Malloc(nErrMsg);
  97345. if( *pzErrMsg ){
  97346. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  97347. }else{
  97348. rc = SQLITE_NOMEM;
  97349. sqlite3Error(db, SQLITE_NOMEM);
  97350. }
  97351. }else if( pzErrMsg ){
  97352. *pzErrMsg = 0;
  97353. }
  97354. assert( (rc&db->errMask)==rc );
  97355. sqlite3_mutex_leave(db->mutex);
  97356. return rc;
  97357. }
  97358. /************** End of legacy.c **********************************************/
  97359. /************** Begin file loadext.c *****************************************/
  97360. /*
  97361. ** 2006 June 7
  97362. **
  97363. ** The author disclaims copyright to this source code. In place of
  97364. ** a legal notice, here is a blessing:
  97365. **
  97366. ** May you do good and not evil.
  97367. ** May you find forgiveness for yourself and forgive others.
  97368. ** May you share freely, never taking more than you give.
  97369. **
  97370. *************************************************************************
  97371. ** This file contains code used to dynamically load extensions into
  97372. ** the SQLite library.
  97373. */
  97374. #ifndef SQLITE_CORE
  97375. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  97376. #endif
  97377. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  97378. /************** Begin file sqlite3ext.h **************************************/
  97379. /*
  97380. ** 2006 June 7
  97381. **
  97382. ** The author disclaims copyright to this source code. In place of
  97383. ** a legal notice, here is a blessing:
  97384. **
  97385. ** May you do good and not evil.
  97386. ** May you find forgiveness for yourself and forgive others.
  97387. ** May you share freely, never taking more than you give.
  97388. **
  97389. *************************************************************************
  97390. ** This header file defines the SQLite interface for use by
  97391. ** shared libraries that want to be imported as extensions into
  97392. ** an SQLite instance. Shared libraries that intend to be loaded
  97393. ** as extensions by SQLite should #include this file instead of
  97394. ** sqlite3.h.
  97395. */
  97396. #ifndef _SQLITE3EXT_H_
  97397. #define _SQLITE3EXT_H_
  97398. /* #include "sqlite3.h" */
  97399. typedef struct sqlite3_api_routines sqlite3_api_routines;
  97400. /*
  97401. ** The following structure holds pointers to all of the SQLite API
  97402. ** routines.
  97403. **
  97404. ** WARNING: In order to maintain backwards compatibility, add new
  97405. ** interfaces to the end of this structure only. If you insert new
  97406. ** interfaces in the middle of this structure, then older different
  97407. ** versions of SQLite will not be able to load each other's shared
  97408. ** libraries!
  97409. */
  97410. struct sqlite3_api_routines {
  97411. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  97412. int (*aggregate_count)(sqlite3_context*);
  97413. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  97414. int (*bind_double)(sqlite3_stmt*,int,double);
  97415. int (*bind_int)(sqlite3_stmt*,int,int);
  97416. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  97417. int (*bind_null)(sqlite3_stmt*,int);
  97418. int (*bind_parameter_count)(sqlite3_stmt*);
  97419. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  97420. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  97421. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  97422. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  97423. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  97424. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  97425. int (*busy_timeout)(sqlite3*,int ms);
  97426. int (*changes)(sqlite3*);
  97427. int (*close)(sqlite3*);
  97428. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  97429. int eTextRep,const char*));
  97430. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  97431. int eTextRep,const void*));
  97432. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  97433. int (*column_bytes)(sqlite3_stmt*,int iCol);
  97434. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  97435. int (*column_count)(sqlite3_stmt*pStmt);
  97436. const char * (*column_database_name)(sqlite3_stmt*,int);
  97437. const void * (*column_database_name16)(sqlite3_stmt*,int);
  97438. const char * (*column_decltype)(sqlite3_stmt*,int i);
  97439. const void * (*column_decltype16)(sqlite3_stmt*,int);
  97440. double (*column_double)(sqlite3_stmt*,int iCol);
  97441. int (*column_int)(sqlite3_stmt*,int iCol);
  97442. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  97443. const char * (*column_name)(sqlite3_stmt*,int);
  97444. const void * (*column_name16)(sqlite3_stmt*,int);
  97445. const char * (*column_origin_name)(sqlite3_stmt*,int);
  97446. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  97447. const char * (*column_table_name)(sqlite3_stmt*,int);
  97448. const void * (*column_table_name16)(sqlite3_stmt*,int);
  97449. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  97450. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  97451. int (*column_type)(sqlite3_stmt*,int iCol);
  97452. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  97453. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  97454. int (*complete)(const char*sql);
  97455. int (*complete16)(const void*sql);
  97456. int (*create_collation)(sqlite3*,const char*,int,void*,
  97457. int(*)(void*,int,const void*,int,const void*));
  97458. int (*create_collation16)(sqlite3*,const void*,int,void*,
  97459. int(*)(void*,int,const void*,int,const void*));
  97460. int (*create_function)(sqlite3*,const char*,int,int,void*,
  97461. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  97462. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  97463. void (*xFinal)(sqlite3_context*));
  97464. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  97465. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  97466. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  97467. void (*xFinal)(sqlite3_context*));
  97468. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  97469. int (*data_count)(sqlite3_stmt*pStmt);
  97470. sqlite3 * (*db_handle)(sqlite3_stmt*);
  97471. int (*declare_vtab)(sqlite3*,const char*);
  97472. int (*enable_shared_cache)(int);
  97473. int (*errcode)(sqlite3*db);
  97474. const char * (*errmsg)(sqlite3*);
  97475. const void * (*errmsg16)(sqlite3*);
  97476. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  97477. int (*expired)(sqlite3_stmt*);
  97478. int (*finalize)(sqlite3_stmt*pStmt);
  97479. void (*free)(void*);
  97480. void (*free_table)(char**result);
  97481. int (*get_autocommit)(sqlite3*);
  97482. void * (*get_auxdata)(sqlite3_context*,int);
  97483. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  97484. int (*global_recover)(void);
  97485. void (*interruptx)(sqlite3*);
  97486. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  97487. const char * (*libversion)(void);
  97488. int (*libversion_number)(void);
  97489. void *(*malloc)(int);
  97490. char * (*mprintf)(const char*,...);
  97491. int (*open)(const char*,sqlite3**);
  97492. int (*open16)(const void*,sqlite3**);
  97493. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  97494. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  97495. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  97496. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  97497. void *(*realloc)(void*,int);
  97498. int (*reset)(sqlite3_stmt*pStmt);
  97499. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  97500. void (*result_double)(sqlite3_context*,double);
  97501. void (*result_error)(sqlite3_context*,const char*,int);
  97502. void (*result_error16)(sqlite3_context*,const void*,int);
  97503. void (*result_int)(sqlite3_context*,int);
  97504. void (*result_int64)(sqlite3_context*,sqlite_int64);
  97505. void (*result_null)(sqlite3_context*);
  97506. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  97507. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  97508. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  97509. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  97510. void (*result_value)(sqlite3_context*,sqlite3_value*);
  97511. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  97512. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  97513. const char*,const char*),void*);
  97514. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  97515. char * (*snprintf)(int,char*,const char*,...);
  97516. int (*step)(sqlite3_stmt*);
  97517. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  97518. char const**,char const**,int*,int*,int*);
  97519. void (*thread_cleanup)(void);
  97520. int (*total_changes)(sqlite3*);
  97521. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  97522. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  97523. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  97524. sqlite_int64),void*);
  97525. void * (*user_data)(sqlite3_context*);
  97526. const void * (*value_blob)(sqlite3_value*);
  97527. int (*value_bytes)(sqlite3_value*);
  97528. int (*value_bytes16)(sqlite3_value*);
  97529. double (*value_double)(sqlite3_value*);
  97530. int (*value_int)(sqlite3_value*);
  97531. sqlite_int64 (*value_int64)(sqlite3_value*);
  97532. int (*value_numeric_type)(sqlite3_value*);
  97533. const unsigned char * (*value_text)(sqlite3_value*);
  97534. const void * (*value_text16)(sqlite3_value*);
  97535. const void * (*value_text16be)(sqlite3_value*);
  97536. const void * (*value_text16le)(sqlite3_value*);
  97537. int (*value_type)(sqlite3_value*);
  97538. char *(*vmprintf)(const char*,va_list);
  97539. /* Added ??? */
  97540. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  97541. /* Added by 3.3.13 */
  97542. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  97543. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  97544. int (*clear_bindings)(sqlite3_stmt*);
  97545. /* Added by 3.4.1 */
  97546. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  97547. void (*xDestroy)(void *));
  97548. /* Added by 3.5.0 */
  97549. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  97550. int (*blob_bytes)(sqlite3_blob*);
  97551. int (*blob_close)(sqlite3_blob*);
  97552. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  97553. int,sqlite3_blob**);
  97554. int (*blob_read)(sqlite3_blob*,void*,int,int);
  97555. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  97556. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  97557. int(*)(void*,int,const void*,int,const void*),
  97558. void(*)(void*));
  97559. int (*file_control)(sqlite3*,const char*,int,void*);
  97560. sqlite3_int64 (*memory_highwater)(int);
  97561. sqlite3_int64 (*memory_used)(void);
  97562. sqlite3_mutex *(*mutex_alloc)(int);
  97563. void (*mutex_enter)(sqlite3_mutex*);
  97564. void (*mutex_free)(sqlite3_mutex*);
  97565. void (*mutex_leave)(sqlite3_mutex*);
  97566. int (*mutex_try)(sqlite3_mutex*);
  97567. int (*open_v2)(const char*,sqlite3**,int,const char*);
  97568. int (*release_memory)(int);
  97569. void (*result_error_nomem)(sqlite3_context*);
  97570. void (*result_error_toobig)(sqlite3_context*);
  97571. int (*sleep)(int);
  97572. void (*soft_heap_limit)(int);
  97573. sqlite3_vfs *(*vfs_find)(const char*);
  97574. int (*vfs_register)(sqlite3_vfs*,int);
  97575. int (*vfs_unregister)(sqlite3_vfs*);
  97576. int (*xthreadsafe)(void);
  97577. void (*result_zeroblob)(sqlite3_context*,int);
  97578. void (*result_error_code)(sqlite3_context*,int);
  97579. int (*test_control)(int, ...);
  97580. void (*randomness)(int,void*);
  97581. sqlite3 *(*context_db_handle)(sqlite3_context*);
  97582. int (*extended_result_codes)(sqlite3*,int);
  97583. int (*limit)(sqlite3*,int,int);
  97584. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  97585. const char *(*sql)(sqlite3_stmt*);
  97586. int (*status)(int,int*,int*,int);
  97587. int (*backup_finish)(sqlite3_backup*);
  97588. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  97589. int (*backup_pagecount)(sqlite3_backup*);
  97590. int (*backup_remaining)(sqlite3_backup*);
  97591. int (*backup_step)(sqlite3_backup*,int);
  97592. const char *(*compileoption_get)(int);
  97593. int (*compileoption_used)(const char*);
  97594. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  97595. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  97596. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  97597. void (*xFinal)(sqlite3_context*),
  97598. void(*xDestroy)(void*));
  97599. int (*db_config)(sqlite3*,int,...);
  97600. sqlite3_mutex *(*db_mutex)(sqlite3*);
  97601. int (*db_status)(sqlite3*,int,int*,int*,int);
  97602. int (*extended_errcode)(sqlite3*);
  97603. void (*log)(int,const char*,...);
  97604. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  97605. const char *(*sourceid)(void);
  97606. int (*stmt_status)(sqlite3_stmt*,int,int);
  97607. int (*strnicmp)(const char*,const char*,int);
  97608. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  97609. int (*wal_autocheckpoint)(sqlite3*,int);
  97610. int (*wal_checkpoint)(sqlite3*,const char*);
  97611. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  97612. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  97613. int (*vtab_config)(sqlite3*,int op,...);
  97614. int (*vtab_on_conflict)(sqlite3*);
  97615. /* Version 3.7.16 and later */
  97616. int (*close_v2)(sqlite3*);
  97617. const char *(*db_filename)(sqlite3*,const char*);
  97618. int (*db_readonly)(sqlite3*,const char*);
  97619. int (*db_release_memory)(sqlite3*);
  97620. const char *(*errstr)(int);
  97621. int (*stmt_busy)(sqlite3_stmt*);
  97622. int (*stmt_readonly)(sqlite3_stmt*);
  97623. int (*stricmp)(const char*,const char*);
  97624. int (*uri_boolean)(const char*,const char*,int);
  97625. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  97626. const char *(*uri_parameter)(const char*,const char*);
  97627. char *(*vsnprintf)(int,char*,const char*,va_list);
  97628. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  97629. /* Version 3.8.7 and later */
  97630. int (*auto_extension)(void(*)(void));
  97631. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  97632. void(*)(void*));
  97633. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  97634. void(*)(void*),unsigned char);
  97635. int (*cancel_auto_extension)(void(*)(void));
  97636. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  97637. void *(*malloc64)(sqlite3_uint64);
  97638. sqlite3_uint64 (*msize)(void*);
  97639. void *(*realloc64)(void*,sqlite3_uint64);
  97640. void (*reset_auto_extension)(void);
  97641. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  97642. void(*)(void*));
  97643. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  97644. void(*)(void*), unsigned char);
  97645. int (*strglob)(const char*,const char*);
  97646. /* Version 3.8.11 and later */
  97647. sqlite3_value *(*value_dup)(const sqlite3_value*);
  97648. void (*value_free)(sqlite3_value*);
  97649. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  97650. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  97651. /* Version 3.9.0 and later */
  97652. unsigned int (*value_subtype)(sqlite3_value*);
  97653. void (*result_subtype)(sqlite3_context*,unsigned int);
  97654. };
  97655. /*
  97656. ** The following macros redefine the API routines so that they are
  97657. ** redirected through the global sqlite3_api structure.
  97658. **
  97659. ** This header file is also used by the loadext.c source file
  97660. ** (part of the main SQLite library - not an extension) so that
  97661. ** it can get access to the sqlite3_api_routines structure
  97662. ** definition. But the main library does not want to redefine
  97663. ** the API. So the redefinition macros are only valid if the
  97664. ** SQLITE_CORE macros is undefined.
  97665. */
  97666. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  97667. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  97668. #ifndef SQLITE_OMIT_DEPRECATED
  97669. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  97670. #endif
  97671. #define sqlite3_bind_blob sqlite3_api->bind_blob
  97672. #define sqlite3_bind_double sqlite3_api->bind_double
  97673. #define sqlite3_bind_int sqlite3_api->bind_int
  97674. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  97675. #define sqlite3_bind_null sqlite3_api->bind_null
  97676. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  97677. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  97678. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  97679. #define sqlite3_bind_text sqlite3_api->bind_text
  97680. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  97681. #define sqlite3_bind_value sqlite3_api->bind_value
  97682. #define sqlite3_busy_handler sqlite3_api->busy_handler
  97683. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  97684. #define sqlite3_changes sqlite3_api->changes
  97685. #define sqlite3_close sqlite3_api->close
  97686. #define sqlite3_collation_needed sqlite3_api->collation_needed
  97687. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  97688. #define sqlite3_column_blob sqlite3_api->column_blob
  97689. #define sqlite3_column_bytes sqlite3_api->column_bytes
  97690. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  97691. #define sqlite3_column_count sqlite3_api->column_count
  97692. #define sqlite3_column_database_name sqlite3_api->column_database_name
  97693. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  97694. #define sqlite3_column_decltype sqlite3_api->column_decltype
  97695. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  97696. #define sqlite3_column_double sqlite3_api->column_double
  97697. #define sqlite3_column_int sqlite3_api->column_int
  97698. #define sqlite3_column_int64 sqlite3_api->column_int64
  97699. #define sqlite3_column_name sqlite3_api->column_name
  97700. #define sqlite3_column_name16 sqlite3_api->column_name16
  97701. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  97702. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  97703. #define sqlite3_column_table_name sqlite3_api->column_table_name
  97704. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  97705. #define sqlite3_column_text sqlite3_api->column_text
  97706. #define sqlite3_column_text16 sqlite3_api->column_text16
  97707. #define sqlite3_column_type sqlite3_api->column_type
  97708. #define sqlite3_column_value sqlite3_api->column_value
  97709. #define sqlite3_commit_hook sqlite3_api->commit_hook
  97710. #define sqlite3_complete sqlite3_api->complete
  97711. #define sqlite3_complete16 sqlite3_api->complete16
  97712. #define sqlite3_create_collation sqlite3_api->create_collation
  97713. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  97714. #define sqlite3_create_function sqlite3_api->create_function
  97715. #define sqlite3_create_function16 sqlite3_api->create_function16
  97716. #define sqlite3_create_module sqlite3_api->create_module
  97717. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  97718. #define sqlite3_data_count sqlite3_api->data_count
  97719. #define sqlite3_db_handle sqlite3_api->db_handle
  97720. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  97721. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  97722. #define sqlite3_errcode sqlite3_api->errcode
  97723. #define sqlite3_errmsg sqlite3_api->errmsg
  97724. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  97725. #define sqlite3_exec sqlite3_api->exec
  97726. #ifndef SQLITE_OMIT_DEPRECATED
  97727. #define sqlite3_expired sqlite3_api->expired
  97728. #endif
  97729. #define sqlite3_finalize sqlite3_api->finalize
  97730. #define sqlite3_free sqlite3_api->free
  97731. #define sqlite3_free_table sqlite3_api->free_table
  97732. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  97733. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  97734. #define sqlite3_get_table sqlite3_api->get_table
  97735. #ifndef SQLITE_OMIT_DEPRECATED
  97736. #define sqlite3_global_recover sqlite3_api->global_recover
  97737. #endif
  97738. #define sqlite3_interrupt sqlite3_api->interruptx
  97739. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  97740. #define sqlite3_libversion sqlite3_api->libversion
  97741. #define sqlite3_libversion_number sqlite3_api->libversion_number
  97742. #define sqlite3_malloc sqlite3_api->malloc
  97743. #define sqlite3_mprintf sqlite3_api->mprintf
  97744. #define sqlite3_open sqlite3_api->open
  97745. #define sqlite3_open16 sqlite3_api->open16
  97746. #define sqlite3_prepare sqlite3_api->prepare
  97747. #define sqlite3_prepare16 sqlite3_api->prepare16
  97748. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  97749. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  97750. #define sqlite3_profile sqlite3_api->profile
  97751. #define sqlite3_progress_handler sqlite3_api->progress_handler
  97752. #define sqlite3_realloc sqlite3_api->realloc
  97753. #define sqlite3_reset sqlite3_api->reset
  97754. #define sqlite3_result_blob sqlite3_api->result_blob
  97755. #define sqlite3_result_double sqlite3_api->result_double
  97756. #define sqlite3_result_error sqlite3_api->result_error
  97757. #define sqlite3_result_error16 sqlite3_api->result_error16
  97758. #define sqlite3_result_int sqlite3_api->result_int
  97759. #define sqlite3_result_int64 sqlite3_api->result_int64
  97760. #define sqlite3_result_null sqlite3_api->result_null
  97761. #define sqlite3_result_text sqlite3_api->result_text
  97762. #define sqlite3_result_text16 sqlite3_api->result_text16
  97763. #define sqlite3_result_text16be sqlite3_api->result_text16be
  97764. #define sqlite3_result_text16le sqlite3_api->result_text16le
  97765. #define sqlite3_result_value sqlite3_api->result_value
  97766. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  97767. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  97768. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  97769. #define sqlite3_snprintf sqlite3_api->snprintf
  97770. #define sqlite3_step sqlite3_api->step
  97771. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  97772. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  97773. #define sqlite3_total_changes sqlite3_api->total_changes
  97774. #define sqlite3_trace sqlite3_api->trace
  97775. #ifndef SQLITE_OMIT_DEPRECATED
  97776. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  97777. #endif
  97778. #define sqlite3_update_hook sqlite3_api->update_hook
  97779. #define sqlite3_user_data sqlite3_api->user_data
  97780. #define sqlite3_value_blob sqlite3_api->value_blob
  97781. #define sqlite3_value_bytes sqlite3_api->value_bytes
  97782. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  97783. #define sqlite3_value_double sqlite3_api->value_double
  97784. #define sqlite3_value_int sqlite3_api->value_int
  97785. #define sqlite3_value_int64 sqlite3_api->value_int64
  97786. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  97787. #define sqlite3_value_text sqlite3_api->value_text
  97788. #define sqlite3_value_text16 sqlite3_api->value_text16
  97789. #define sqlite3_value_text16be sqlite3_api->value_text16be
  97790. #define sqlite3_value_text16le sqlite3_api->value_text16le
  97791. #define sqlite3_value_type sqlite3_api->value_type
  97792. #define sqlite3_vmprintf sqlite3_api->vmprintf
  97793. #define sqlite3_vsnprintf sqlite3_api->vsnprintf
  97794. #define sqlite3_overload_function sqlite3_api->overload_function
  97795. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  97796. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  97797. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  97798. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  97799. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  97800. #define sqlite3_blob_close sqlite3_api->blob_close
  97801. #define sqlite3_blob_open sqlite3_api->blob_open
  97802. #define sqlite3_blob_read sqlite3_api->blob_read
  97803. #define sqlite3_blob_write sqlite3_api->blob_write
  97804. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  97805. #define sqlite3_file_control sqlite3_api->file_control
  97806. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  97807. #define sqlite3_memory_used sqlite3_api->memory_used
  97808. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  97809. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  97810. #define sqlite3_mutex_free sqlite3_api->mutex_free
  97811. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  97812. #define sqlite3_mutex_try sqlite3_api->mutex_try
  97813. #define sqlite3_open_v2 sqlite3_api->open_v2
  97814. #define sqlite3_release_memory sqlite3_api->release_memory
  97815. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  97816. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  97817. #define sqlite3_sleep sqlite3_api->sleep
  97818. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  97819. #define sqlite3_vfs_find sqlite3_api->vfs_find
  97820. #define sqlite3_vfs_register sqlite3_api->vfs_register
  97821. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  97822. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  97823. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  97824. #define sqlite3_result_error_code sqlite3_api->result_error_code
  97825. #define sqlite3_test_control sqlite3_api->test_control
  97826. #define sqlite3_randomness sqlite3_api->randomness
  97827. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  97828. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  97829. #define sqlite3_limit sqlite3_api->limit
  97830. #define sqlite3_next_stmt sqlite3_api->next_stmt
  97831. #define sqlite3_sql sqlite3_api->sql
  97832. #define sqlite3_status sqlite3_api->status
  97833. #define sqlite3_backup_finish sqlite3_api->backup_finish
  97834. #define sqlite3_backup_init sqlite3_api->backup_init
  97835. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  97836. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  97837. #define sqlite3_backup_step sqlite3_api->backup_step
  97838. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  97839. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  97840. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  97841. #define sqlite3_db_config sqlite3_api->db_config
  97842. #define sqlite3_db_mutex sqlite3_api->db_mutex
  97843. #define sqlite3_db_status sqlite3_api->db_status
  97844. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  97845. #define sqlite3_log sqlite3_api->log
  97846. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  97847. #define sqlite3_sourceid sqlite3_api->sourceid
  97848. #define sqlite3_stmt_status sqlite3_api->stmt_status
  97849. #define sqlite3_strnicmp sqlite3_api->strnicmp
  97850. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  97851. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  97852. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  97853. #define sqlite3_wal_hook sqlite3_api->wal_hook
  97854. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  97855. #define sqlite3_vtab_config sqlite3_api->vtab_config
  97856. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  97857. /* Version 3.7.16 and later */
  97858. #define sqlite3_close_v2 sqlite3_api->close_v2
  97859. #define sqlite3_db_filename sqlite3_api->db_filename
  97860. #define sqlite3_db_readonly sqlite3_api->db_readonly
  97861. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  97862. #define sqlite3_errstr sqlite3_api->errstr
  97863. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  97864. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  97865. #define sqlite3_stricmp sqlite3_api->stricmp
  97866. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  97867. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  97868. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  97869. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  97870. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  97871. /* Version 3.8.7 and later */
  97872. #define sqlite3_auto_extension sqlite3_api->auto_extension
  97873. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  97874. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  97875. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  97876. #define sqlite3_load_extension sqlite3_api->load_extension
  97877. #define sqlite3_malloc64 sqlite3_api->malloc64
  97878. #define sqlite3_msize sqlite3_api->msize
  97879. #define sqlite3_realloc64 sqlite3_api->realloc64
  97880. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  97881. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  97882. #define sqlite3_result_text64 sqlite3_api->result_text64
  97883. #define sqlite3_strglob sqlite3_api->strglob
  97884. /* Version 3.8.11 and later */
  97885. #define sqlite3_value_dup sqlite3_api->value_dup
  97886. #define sqlite3_value_free sqlite3_api->value_free
  97887. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  97888. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  97889. /* Version 3.9.0 and later */
  97890. #define sqlite3_value_subtype sqlite3_api->value_subtype
  97891. #define sqlite3_result_subtype sqlite3_api->result_subtype
  97892. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  97893. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  97894. /* This case when the file really is being compiled as a loadable
  97895. ** extension */
  97896. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  97897. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  97898. # define SQLITE_EXTENSION_INIT3 \
  97899. extern const sqlite3_api_routines *sqlite3_api;
  97900. #else
  97901. /* This case when the file is being statically linked into the
  97902. ** application */
  97903. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  97904. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  97905. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  97906. #endif
  97907. #endif /* _SQLITE3EXT_H_ */
  97908. /************** End of sqlite3ext.h ******************************************/
  97909. /************** Continuing where we left off in loadext.c ********************/
  97910. /* #include "sqliteInt.h" */
  97911. /* #include <string.h> */
  97912. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  97913. /*
  97914. ** Some API routines are omitted when various features are
  97915. ** excluded from a build of SQLite. Substitute a NULL pointer
  97916. ** for any missing APIs.
  97917. */
  97918. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  97919. # define sqlite3_column_database_name 0
  97920. # define sqlite3_column_database_name16 0
  97921. # define sqlite3_column_table_name 0
  97922. # define sqlite3_column_table_name16 0
  97923. # define sqlite3_column_origin_name 0
  97924. # define sqlite3_column_origin_name16 0
  97925. #endif
  97926. #ifdef SQLITE_OMIT_AUTHORIZATION
  97927. # define sqlite3_set_authorizer 0
  97928. #endif
  97929. #ifdef SQLITE_OMIT_UTF16
  97930. # define sqlite3_bind_text16 0
  97931. # define sqlite3_collation_needed16 0
  97932. # define sqlite3_column_decltype16 0
  97933. # define sqlite3_column_name16 0
  97934. # define sqlite3_column_text16 0
  97935. # define sqlite3_complete16 0
  97936. # define sqlite3_create_collation16 0
  97937. # define sqlite3_create_function16 0
  97938. # define sqlite3_errmsg16 0
  97939. # define sqlite3_open16 0
  97940. # define sqlite3_prepare16 0
  97941. # define sqlite3_prepare16_v2 0
  97942. # define sqlite3_result_error16 0
  97943. # define sqlite3_result_text16 0
  97944. # define sqlite3_result_text16be 0
  97945. # define sqlite3_result_text16le 0
  97946. # define sqlite3_value_text16 0
  97947. # define sqlite3_value_text16be 0
  97948. # define sqlite3_value_text16le 0
  97949. # define sqlite3_column_database_name16 0
  97950. # define sqlite3_column_table_name16 0
  97951. # define sqlite3_column_origin_name16 0
  97952. #endif
  97953. #ifdef SQLITE_OMIT_COMPLETE
  97954. # define sqlite3_complete 0
  97955. # define sqlite3_complete16 0
  97956. #endif
  97957. #ifdef SQLITE_OMIT_DECLTYPE
  97958. # define sqlite3_column_decltype16 0
  97959. # define sqlite3_column_decltype 0
  97960. #endif
  97961. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  97962. # define sqlite3_progress_handler 0
  97963. #endif
  97964. #ifdef SQLITE_OMIT_VIRTUALTABLE
  97965. # define sqlite3_create_module 0
  97966. # define sqlite3_create_module_v2 0
  97967. # define sqlite3_declare_vtab 0
  97968. # define sqlite3_vtab_config 0
  97969. # define sqlite3_vtab_on_conflict 0
  97970. #endif
  97971. #ifdef SQLITE_OMIT_SHARED_CACHE
  97972. # define sqlite3_enable_shared_cache 0
  97973. #endif
  97974. #ifdef SQLITE_OMIT_TRACE
  97975. # define sqlite3_profile 0
  97976. # define sqlite3_trace 0
  97977. #endif
  97978. #ifdef SQLITE_OMIT_GET_TABLE
  97979. # define sqlite3_free_table 0
  97980. # define sqlite3_get_table 0
  97981. #endif
  97982. #ifdef SQLITE_OMIT_INCRBLOB
  97983. #define sqlite3_bind_zeroblob 0
  97984. #define sqlite3_blob_bytes 0
  97985. #define sqlite3_blob_close 0
  97986. #define sqlite3_blob_open 0
  97987. #define sqlite3_blob_read 0
  97988. #define sqlite3_blob_write 0
  97989. #define sqlite3_blob_reopen 0
  97990. #endif
  97991. /*
  97992. ** The following structure contains pointers to all SQLite API routines.
  97993. ** A pointer to this structure is passed into extensions when they are
  97994. ** loaded so that the extension can make calls back into the SQLite
  97995. ** library.
  97996. **
  97997. ** When adding new APIs, add them to the bottom of this structure
  97998. ** in order to preserve backwards compatibility.
  97999. **
  98000. ** Extensions that use newer APIs should first call the
  98001. ** sqlite3_libversion_number() to make sure that the API they
  98002. ** intend to use is supported by the library. Extensions should
  98003. ** also check to make sure that the pointer to the function is
  98004. ** not NULL before calling it.
  98005. */
  98006. static const sqlite3_api_routines sqlite3Apis = {
  98007. sqlite3_aggregate_context,
  98008. #ifndef SQLITE_OMIT_DEPRECATED
  98009. sqlite3_aggregate_count,
  98010. #else
  98011. 0,
  98012. #endif
  98013. sqlite3_bind_blob,
  98014. sqlite3_bind_double,
  98015. sqlite3_bind_int,
  98016. sqlite3_bind_int64,
  98017. sqlite3_bind_null,
  98018. sqlite3_bind_parameter_count,
  98019. sqlite3_bind_parameter_index,
  98020. sqlite3_bind_parameter_name,
  98021. sqlite3_bind_text,
  98022. sqlite3_bind_text16,
  98023. sqlite3_bind_value,
  98024. sqlite3_busy_handler,
  98025. sqlite3_busy_timeout,
  98026. sqlite3_changes,
  98027. sqlite3_close,
  98028. sqlite3_collation_needed,
  98029. sqlite3_collation_needed16,
  98030. sqlite3_column_blob,
  98031. sqlite3_column_bytes,
  98032. sqlite3_column_bytes16,
  98033. sqlite3_column_count,
  98034. sqlite3_column_database_name,
  98035. sqlite3_column_database_name16,
  98036. sqlite3_column_decltype,
  98037. sqlite3_column_decltype16,
  98038. sqlite3_column_double,
  98039. sqlite3_column_int,
  98040. sqlite3_column_int64,
  98041. sqlite3_column_name,
  98042. sqlite3_column_name16,
  98043. sqlite3_column_origin_name,
  98044. sqlite3_column_origin_name16,
  98045. sqlite3_column_table_name,
  98046. sqlite3_column_table_name16,
  98047. sqlite3_column_text,
  98048. sqlite3_column_text16,
  98049. sqlite3_column_type,
  98050. sqlite3_column_value,
  98051. sqlite3_commit_hook,
  98052. sqlite3_complete,
  98053. sqlite3_complete16,
  98054. sqlite3_create_collation,
  98055. sqlite3_create_collation16,
  98056. sqlite3_create_function,
  98057. sqlite3_create_function16,
  98058. sqlite3_create_module,
  98059. sqlite3_data_count,
  98060. sqlite3_db_handle,
  98061. sqlite3_declare_vtab,
  98062. sqlite3_enable_shared_cache,
  98063. sqlite3_errcode,
  98064. sqlite3_errmsg,
  98065. sqlite3_errmsg16,
  98066. sqlite3_exec,
  98067. #ifndef SQLITE_OMIT_DEPRECATED
  98068. sqlite3_expired,
  98069. #else
  98070. 0,
  98071. #endif
  98072. sqlite3_finalize,
  98073. sqlite3_free,
  98074. sqlite3_free_table,
  98075. sqlite3_get_autocommit,
  98076. sqlite3_get_auxdata,
  98077. sqlite3_get_table,
  98078. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  98079. sqlite3_interrupt,
  98080. sqlite3_last_insert_rowid,
  98081. sqlite3_libversion,
  98082. sqlite3_libversion_number,
  98083. sqlite3_malloc,
  98084. sqlite3_mprintf,
  98085. sqlite3_open,
  98086. sqlite3_open16,
  98087. sqlite3_prepare,
  98088. sqlite3_prepare16,
  98089. sqlite3_profile,
  98090. sqlite3_progress_handler,
  98091. sqlite3_realloc,
  98092. sqlite3_reset,
  98093. sqlite3_result_blob,
  98094. sqlite3_result_double,
  98095. sqlite3_result_error,
  98096. sqlite3_result_error16,
  98097. sqlite3_result_int,
  98098. sqlite3_result_int64,
  98099. sqlite3_result_null,
  98100. sqlite3_result_text,
  98101. sqlite3_result_text16,
  98102. sqlite3_result_text16be,
  98103. sqlite3_result_text16le,
  98104. sqlite3_result_value,
  98105. sqlite3_rollback_hook,
  98106. sqlite3_set_authorizer,
  98107. sqlite3_set_auxdata,
  98108. sqlite3_snprintf,
  98109. sqlite3_step,
  98110. sqlite3_table_column_metadata,
  98111. #ifndef SQLITE_OMIT_DEPRECATED
  98112. sqlite3_thread_cleanup,
  98113. #else
  98114. 0,
  98115. #endif
  98116. sqlite3_total_changes,
  98117. sqlite3_trace,
  98118. #ifndef SQLITE_OMIT_DEPRECATED
  98119. sqlite3_transfer_bindings,
  98120. #else
  98121. 0,
  98122. #endif
  98123. sqlite3_update_hook,
  98124. sqlite3_user_data,
  98125. sqlite3_value_blob,
  98126. sqlite3_value_bytes,
  98127. sqlite3_value_bytes16,
  98128. sqlite3_value_double,
  98129. sqlite3_value_int,
  98130. sqlite3_value_int64,
  98131. sqlite3_value_numeric_type,
  98132. sqlite3_value_text,
  98133. sqlite3_value_text16,
  98134. sqlite3_value_text16be,
  98135. sqlite3_value_text16le,
  98136. sqlite3_value_type,
  98137. sqlite3_vmprintf,
  98138. /*
  98139. ** The original API set ends here. All extensions can call any
  98140. ** of the APIs above provided that the pointer is not NULL. But
  98141. ** before calling APIs that follow, extension should check the
  98142. ** sqlite3_libversion_number() to make sure they are dealing with
  98143. ** a library that is new enough to support that API.
  98144. *************************************************************************
  98145. */
  98146. sqlite3_overload_function,
  98147. /*
  98148. ** Added after 3.3.13
  98149. */
  98150. sqlite3_prepare_v2,
  98151. sqlite3_prepare16_v2,
  98152. sqlite3_clear_bindings,
  98153. /*
  98154. ** Added for 3.4.1
  98155. */
  98156. sqlite3_create_module_v2,
  98157. /*
  98158. ** Added for 3.5.0
  98159. */
  98160. sqlite3_bind_zeroblob,
  98161. sqlite3_blob_bytes,
  98162. sqlite3_blob_close,
  98163. sqlite3_blob_open,
  98164. sqlite3_blob_read,
  98165. sqlite3_blob_write,
  98166. sqlite3_create_collation_v2,
  98167. sqlite3_file_control,
  98168. sqlite3_memory_highwater,
  98169. sqlite3_memory_used,
  98170. #ifdef SQLITE_MUTEX_OMIT
  98171. 0,
  98172. 0,
  98173. 0,
  98174. 0,
  98175. 0,
  98176. #else
  98177. sqlite3_mutex_alloc,
  98178. sqlite3_mutex_enter,
  98179. sqlite3_mutex_free,
  98180. sqlite3_mutex_leave,
  98181. sqlite3_mutex_try,
  98182. #endif
  98183. sqlite3_open_v2,
  98184. sqlite3_release_memory,
  98185. sqlite3_result_error_nomem,
  98186. sqlite3_result_error_toobig,
  98187. sqlite3_sleep,
  98188. sqlite3_soft_heap_limit,
  98189. sqlite3_vfs_find,
  98190. sqlite3_vfs_register,
  98191. sqlite3_vfs_unregister,
  98192. /*
  98193. ** Added for 3.5.8
  98194. */
  98195. sqlite3_threadsafe,
  98196. sqlite3_result_zeroblob,
  98197. sqlite3_result_error_code,
  98198. sqlite3_test_control,
  98199. sqlite3_randomness,
  98200. sqlite3_context_db_handle,
  98201. /*
  98202. ** Added for 3.6.0
  98203. */
  98204. sqlite3_extended_result_codes,
  98205. sqlite3_limit,
  98206. sqlite3_next_stmt,
  98207. sqlite3_sql,
  98208. sqlite3_status,
  98209. /*
  98210. ** Added for 3.7.4
  98211. */
  98212. sqlite3_backup_finish,
  98213. sqlite3_backup_init,
  98214. sqlite3_backup_pagecount,
  98215. sqlite3_backup_remaining,
  98216. sqlite3_backup_step,
  98217. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  98218. sqlite3_compileoption_get,
  98219. sqlite3_compileoption_used,
  98220. #else
  98221. 0,
  98222. 0,
  98223. #endif
  98224. sqlite3_create_function_v2,
  98225. sqlite3_db_config,
  98226. sqlite3_db_mutex,
  98227. sqlite3_db_status,
  98228. sqlite3_extended_errcode,
  98229. sqlite3_log,
  98230. sqlite3_soft_heap_limit64,
  98231. sqlite3_sourceid,
  98232. sqlite3_stmt_status,
  98233. sqlite3_strnicmp,
  98234. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  98235. sqlite3_unlock_notify,
  98236. #else
  98237. 0,
  98238. #endif
  98239. #ifndef SQLITE_OMIT_WAL
  98240. sqlite3_wal_autocheckpoint,
  98241. sqlite3_wal_checkpoint,
  98242. sqlite3_wal_hook,
  98243. #else
  98244. 0,
  98245. 0,
  98246. 0,
  98247. #endif
  98248. sqlite3_blob_reopen,
  98249. sqlite3_vtab_config,
  98250. sqlite3_vtab_on_conflict,
  98251. sqlite3_close_v2,
  98252. sqlite3_db_filename,
  98253. sqlite3_db_readonly,
  98254. sqlite3_db_release_memory,
  98255. sqlite3_errstr,
  98256. sqlite3_stmt_busy,
  98257. sqlite3_stmt_readonly,
  98258. sqlite3_stricmp,
  98259. sqlite3_uri_boolean,
  98260. sqlite3_uri_int64,
  98261. sqlite3_uri_parameter,
  98262. sqlite3_vsnprintf,
  98263. sqlite3_wal_checkpoint_v2,
  98264. /* Version 3.8.7 and later */
  98265. sqlite3_auto_extension,
  98266. sqlite3_bind_blob64,
  98267. sqlite3_bind_text64,
  98268. sqlite3_cancel_auto_extension,
  98269. sqlite3_load_extension,
  98270. sqlite3_malloc64,
  98271. sqlite3_msize,
  98272. sqlite3_realloc64,
  98273. sqlite3_reset_auto_extension,
  98274. sqlite3_result_blob64,
  98275. sqlite3_result_text64,
  98276. sqlite3_strglob,
  98277. /* Version 3.8.11 and later */
  98278. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  98279. sqlite3_value_free,
  98280. sqlite3_result_zeroblob64,
  98281. sqlite3_bind_zeroblob64,
  98282. /* Version 3.9.0 and later */
  98283. sqlite3_value_subtype,
  98284. sqlite3_result_subtype
  98285. };
  98286. /*
  98287. ** Attempt to load an SQLite extension library contained in the file
  98288. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  98289. ** default entry point name (sqlite3_extension_init) is used. Use
  98290. ** of the default name is recommended.
  98291. **
  98292. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  98293. **
  98294. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  98295. ** error message text. The calling function should free this memory
  98296. ** by calling sqlite3DbFree(db, ).
  98297. */
  98298. static int sqlite3LoadExtension(
  98299. sqlite3 *db, /* Load the extension into this database connection */
  98300. const char *zFile, /* Name of the shared library containing extension */
  98301. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  98302. char **pzErrMsg /* Put error message here if not 0 */
  98303. ){
  98304. sqlite3_vfs *pVfs = db->pVfs;
  98305. void *handle;
  98306. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  98307. char *zErrmsg = 0;
  98308. const char *zEntry;
  98309. char *zAltEntry = 0;
  98310. void **aHandle;
  98311. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  98312. int ii;
  98313. /* Shared library endings to try if zFile cannot be loaded as written */
  98314. static const char *azEndings[] = {
  98315. #if SQLITE_OS_WIN
  98316. "dll"
  98317. #elif defined(__APPLE__)
  98318. "dylib"
  98319. #else
  98320. "so"
  98321. #endif
  98322. };
  98323. if( pzErrMsg ) *pzErrMsg = 0;
  98324. /* Ticket #1863. To avoid a creating security problems for older
  98325. ** applications that relink against newer versions of SQLite, the
  98326. ** ability to run load_extension is turned off by default. One
  98327. ** must call sqlite3_enable_load_extension() to turn on extension
  98328. ** loading. Otherwise you get the following error.
  98329. */
  98330. if( (db->flags & SQLITE_LoadExtension)==0 ){
  98331. if( pzErrMsg ){
  98332. *pzErrMsg = sqlite3_mprintf("not authorized");
  98333. }
  98334. return SQLITE_ERROR;
  98335. }
  98336. zEntry = zProc ? zProc : "sqlite3_extension_init";
  98337. handle = sqlite3OsDlOpen(pVfs, zFile);
  98338. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  98339. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  98340. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  98341. if( zAltFile==0 ) return SQLITE_NOMEM;
  98342. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  98343. sqlite3_free(zAltFile);
  98344. }
  98345. #endif
  98346. if( handle==0 ){
  98347. if( pzErrMsg ){
  98348. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  98349. if( zErrmsg ){
  98350. sqlite3_snprintf(nMsg, zErrmsg,
  98351. "unable to open shared library [%s]", zFile);
  98352. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  98353. }
  98354. }
  98355. return SQLITE_ERROR;
  98356. }
  98357. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  98358. sqlite3OsDlSym(pVfs, handle, zEntry);
  98359. /* If no entry point was specified and the default legacy
  98360. ** entry point name "sqlite3_extension_init" was not found, then
  98361. ** construct an entry point name "sqlite3_X_init" where the X is
  98362. ** replaced by the lowercase value of every ASCII alphabetic
  98363. ** character in the filename after the last "/" upto the first ".",
  98364. ** and eliding the first three characters if they are "lib".
  98365. ** Examples:
  98366. **
  98367. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  98368. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  98369. */
  98370. if( xInit==0 && zProc==0 ){
  98371. int iFile, iEntry, c;
  98372. int ncFile = sqlite3Strlen30(zFile);
  98373. zAltEntry = sqlite3_malloc64(ncFile+30);
  98374. if( zAltEntry==0 ){
  98375. sqlite3OsDlClose(pVfs, handle);
  98376. return SQLITE_NOMEM;
  98377. }
  98378. memcpy(zAltEntry, "sqlite3_", 8);
  98379. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  98380. iFile++;
  98381. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  98382. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  98383. if( sqlite3Isalpha(c) ){
  98384. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  98385. }
  98386. }
  98387. memcpy(zAltEntry+iEntry, "_init", 6);
  98388. zEntry = zAltEntry;
  98389. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  98390. sqlite3OsDlSym(pVfs, handle, zEntry);
  98391. }
  98392. if( xInit==0 ){
  98393. if( pzErrMsg ){
  98394. nMsg += sqlite3Strlen30(zEntry);
  98395. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  98396. if( zErrmsg ){
  98397. sqlite3_snprintf(nMsg, zErrmsg,
  98398. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  98399. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  98400. }
  98401. }
  98402. sqlite3OsDlClose(pVfs, handle);
  98403. sqlite3_free(zAltEntry);
  98404. return SQLITE_ERROR;
  98405. }
  98406. sqlite3_free(zAltEntry);
  98407. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  98408. if( pzErrMsg ){
  98409. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  98410. }
  98411. sqlite3_free(zErrmsg);
  98412. sqlite3OsDlClose(pVfs, handle);
  98413. return SQLITE_ERROR;
  98414. }
  98415. /* Append the new shared library handle to the db->aExtension array. */
  98416. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  98417. if( aHandle==0 ){
  98418. return SQLITE_NOMEM;
  98419. }
  98420. if( db->nExtension>0 ){
  98421. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  98422. }
  98423. sqlite3DbFree(db, db->aExtension);
  98424. db->aExtension = aHandle;
  98425. db->aExtension[db->nExtension++] = handle;
  98426. return SQLITE_OK;
  98427. }
  98428. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  98429. sqlite3 *db, /* Load the extension into this database connection */
  98430. const char *zFile, /* Name of the shared library containing extension */
  98431. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  98432. char **pzErrMsg /* Put error message here if not 0 */
  98433. ){
  98434. int rc;
  98435. sqlite3_mutex_enter(db->mutex);
  98436. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  98437. rc = sqlite3ApiExit(db, rc);
  98438. sqlite3_mutex_leave(db->mutex);
  98439. return rc;
  98440. }
  98441. /*
  98442. ** Call this routine when the database connection is closing in order
  98443. ** to clean up loaded extensions
  98444. */
  98445. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  98446. int i;
  98447. assert( sqlite3_mutex_held(db->mutex) );
  98448. for(i=0; i<db->nExtension; i++){
  98449. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  98450. }
  98451. sqlite3DbFree(db, db->aExtension);
  98452. }
  98453. /*
  98454. ** Enable or disable extension loading. Extension loading is disabled by
  98455. ** default so as not to open security holes in older applications.
  98456. */
  98457. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  98458. sqlite3_mutex_enter(db->mutex);
  98459. if( onoff ){
  98460. db->flags |= SQLITE_LoadExtension;
  98461. }else{
  98462. db->flags &= ~SQLITE_LoadExtension;
  98463. }
  98464. sqlite3_mutex_leave(db->mutex);
  98465. return SQLITE_OK;
  98466. }
  98467. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  98468. /*
  98469. ** The auto-extension code added regardless of whether or not extension
  98470. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  98471. ** code if regular extension loading is not available. This is that
  98472. ** dummy pointer.
  98473. */
  98474. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  98475. static const sqlite3_api_routines sqlite3Apis;
  98476. #endif
  98477. /*
  98478. ** The following object holds the list of automatically loaded
  98479. ** extensions.
  98480. **
  98481. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  98482. ** mutex must be held while accessing this list.
  98483. */
  98484. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  98485. static SQLITE_WSD struct sqlite3AutoExtList {
  98486. u32 nExt; /* Number of entries in aExt[] */
  98487. void (**aExt)(void); /* Pointers to the extension init functions */
  98488. } sqlite3Autoext = { 0, 0 };
  98489. /* The "wsdAutoext" macro will resolve to the autoextension
  98490. ** state vector. If writable static data is unsupported on the target,
  98491. ** we have to locate the state vector at run-time. In the more common
  98492. ** case where writable static data is supported, wsdStat can refer directly
  98493. ** to the "sqlite3Autoext" state vector declared above.
  98494. */
  98495. #ifdef SQLITE_OMIT_WSD
  98496. # define wsdAutoextInit \
  98497. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  98498. # define wsdAutoext x[0]
  98499. #else
  98500. # define wsdAutoextInit
  98501. # define wsdAutoext sqlite3Autoext
  98502. #endif
  98503. /*
  98504. ** Register a statically linked extension that is automatically
  98505. ** loaded by every new database connection.
  98506. */
  98507. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
  98508. int rc = SQLITE_OK;
  98509. #ifndef SQLITE_OMIT_AUTOINIT
  98510. rc = sqlite3_initialize();
  98511. if( rc ){
  98512. return rc;
  98513. }else
  98514. #endif
  98515. {
  98516. u32 i;
  98517. #if SQLITE_THREADSAFE
  98518. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  98519. #endif
  98520. wsdAutoextInit;
  98521. sqlite3_mutex_enter(mutex);
  98522. for(i=0; i<wsdAutoext.nExt; i++){
  98523. if( wsdAutoext.aExt[i]==xInit ) break;
  98524. }
  98525. if( i==wsdAutoext.nExt ){
  98526. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  98527. void (**aNew)(void);
  98528. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  98529. if( aNew==0 ){
  98530. rc = SQLITE_NOMEM;
  98531. }else{
  98532. wsdAutoext.aExt = aNew;
  98533. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  98534. wsdAutoext.nExt++;
  98535. }
  98536. }
  98537. sqlite3_mutex_leave(mutex);
  98538. assert( (rc&0xff)==rc );
  98539. return rc;
  98540. }
  98541. }
  98542. /*
  98543. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  98544. ** set of routines that is invoked for each new database connection, if it
  98545. ** is currently on the list. If xInit is not on the list, then this
  98546. ** routine is a no-op.
  98547. **
  98548. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  98549. ** was not on the list.
  98550. */
  98551. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
  98552. #if SQLITE_THREADSAFE
  98553. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  98554. #endif
  98555. int i;
  98556. int n = 0;
  98557. wsdAutoextInit;
  98558. sqlite3_mutex_enter(mutex);
  98559. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  98560. if( wsdAutoext.aExt[i]==xInit ){
  98561. wsdAutoext.nExt--;
  98562. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  98563. n++;
  98564. break;
  98565. }
  98566. }
  98567. sqlite3_mutex_leave(mutex);
  98568. return n;
  98569. }
  98570. /*
  98571. ** Reset the automatic extension loading mechanism.
  98572. */
  98573. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
  98574. #ifndef SQLITE_OMIT_AUTOINIT
  98575. if( sqlite3_initialize()==SQLITE_OK )
  98576. #endif
  98577. {
  98578. #if SQLITE_THREADSAFE
  98579. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  98580. #endif
  98581. wsdAutoextInit;
  98582. sqlite3_mutex_enter(mutex);
  98583. sqlite3_free(wsdAutoext.aExt);
  98584. wsdAutoext.aExt = 0;
  98585. wsdAutoext.nExt = 0;
  98586. sqlite3_mutex_leave(mutex);
  98587. }
  98588. }
  98589. /*
  98590. ** Load all automatic extensions.
  98591. **
  98592. ** If anything goes wrong, set an error in the database connection.
  98593. */
  98594. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  98595. u32 i;
  98596. int go = 1;
  98597. int rc;
  98598. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  98599. wsdAutoextInit;
  98600. if( wsdAutoext.nExt==0 ){
  98601. /* Common case: early out without every having to acquire a mutex */
  98602. return;
  98603. }
  98604. for(i=0; go; i++){
  98605. char *zErrmsg;
  98606. #if SQLITE_THREADSAFE
  98607. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  98608. #endif
  98609. sqlite3_mutex_enter(mutex);
  98610. if( i>=wsdAutoext.nExt ){
  98611. xInit = 0;
  98612. go = 0;
  98613. }else{
  98614. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  98615. wsdAutoext.aExt[i];
  98616. }
  98617. sqlite3_mutex_leave(mutex);
  98618. zErrmsg = 0;
  98619. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  98620. sqlite3ErrorWithMsg(db, rc,
  98621. "automatic extension loading failed: %s", zErrmsg);
  98622. go = 0;
  98623. }
  98624. sqlite3_free(zErrmsg);
  98625. }
  98626. }
  98627. /************** End of loadext.c *********************************************/
  98628. /************** Begin file pragma.c ******************************************/
  98629. /*
  98630. ** 2003 April 6
  98631. **
  98632. ** The author disclaims copyright to this source code. In place of
  98633. ** a legal notice, here is a blessing:
  98634. **
  98635. ** May you do good and not evil.
  98636. ** May you find forgiveness for yourself and forgive others.
  98637. ** May you share freely, never taking more than you give.
  98638. **
  98639. *************************************************************************
  98640. ** This file contains code used to implement the PRAGMA command.
  98641. */
  98642. /* #include "sqliteInt.h" */
  98643. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  98644. # if defined(__APPLE__)
  98645. # define SQLITE_ENABLE_LOCKING_STYLE 1
  98646. # else
  98647. # define SQLITE_ENABLE_LOCKING_STYLE 0
  98648. # endif
  98649. #endif
  98650. /***************************************************************************
  98651. ** The "pragma.h" include file is an automatically generated file that
  98652. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  98653. ** object. This ensures that the aPragmaName[] table is arranged in
  98654. ** lexicographical order to facility a binary search of the pragma name.
  98655. ** Do not edit pragma.h directly. Edit and rerun the script in at
  98656. ** ../tool/mkpragmatab.tcl. */
  98657. /************** Include pragma.h in the middle of pragma.c *******************/
  98658. /************** Begin file pragma.h ******************************************/
  98659. /* DO NOT EDIT!
  98660. ** This file is automatically generated by the script at
  98661. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  98662. ** that script and rerun it.
  98663. */
  98664. #define PragTyp_HEADER_VALUE 0
  98665. #define PragTyp_AUTO_VACUUM 1
  98666. #define PragTyp_FLAG 2
  98667. #define PragTyp_BUSY_TIMEOUT 3
  98668. #define PragTyp_CACHE_SIZE 4
  98669. #define PragTyp_CASE_SENSITIVE_LIKE 5
  98670. #define PragTyp_COLLATION_LIST 6
  98671. #define PragTyp_COMPILE_OPTIONS 7
  98672. #define PragTyp_DATA_STORE_DIRECTORY 8
  98673. #define PragTyp_DATABASE_LIST 9
  98674. #define PragTyp_DEFAULT_CACHE_SIZE 10
  98675. #define PragTyp_ENCODING 11
  98676. #define PragTyp_FOREIGN_KEY_CHECK 12
  98677. #define PragTyp_FOREIGN_KEY_LIST 13
  98678. #define PragTyp_INCREMENTAL_VACUUM 14
  98679. #define PragTyp_INDEX_INFO 15
  98680. #define PragTyp_INDEX_LIST 16
  98681. #define PragTyp_INTEGRITY_CHECK 17
  98682. #define PragTyp_JOURNAL_MODE 18
  98683. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  98684. #define PragTyp_LOCK_PROXY_FILE 20
  98685. #define PragTyp_LOCKING_MODE 21
  98686. #define PragTyp_PAGE_COUNT 22
  98687. #define PragTyp_MMAP_SIZE 23
  98688. #define PragTyp_PAGE_SIZE 24
  98689. #define PragTyp_SECURE_DELETE 25
  98690. #define PragTyp_SHRINK_MEMORY 26
  98691. #define PragTyp_SOFT_HEAP_LIMIT 27
  98692. #define PragTyp_STATS 28
  98693. #define PragTyp_SYNCHRONOUS 29
  98694. #define PragTyp_TABLE_INFO 30
  98695. #define PragTyp_TEMP_STORE 31
  98696. #define PragTyp_TEMP_STORE_DIRECTORY 32
  98697. #define PragTyp_THREADS 33
  98698. #define PragTyp_WAL_AUTOCHECKPOINT 34
  98699. #define PragTyp_WAL_CHECKPOINT 35
  98700. #define PragTyp_ACTIVATE_EXTENSIONS 36
  98701. #define PragTyp_HEXKEY 37
  98702. #define PragTyp_KEY 38
  98703. #define PragTyp_REKEY 39
  98704. #define PragTyp_LOCK_STATUS 40
  98705. #define PragTyp_PARSER_TRACE 41
  98706. #define PragFlag_NeedSchema 0x01
  98707. #define PragFlag_ReadOnly 0x02
  98708. static const struct sPragmaNames {
  98709. const char *const zName; /* Name of pragma */
  98710. u8 ePragTyp; /* PragTyp_XXX value */
  98711. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  98712. u32 iArg; /* Extra argument */
  98713. } aPragmaNames[] = {
  98714. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  98715. { /* zName: */ "activate_extensions",
  98716. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  98717. /* ePragFlag: */ 0,
  98718. /* iArg: */ 0 },
  98719. #endif
  98720. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  98721. { /* zName: */ "application_id",
  98722. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  98723. /* ePragFlag: */ 0,
  98724. /* iArg: */ BTREE_APPLICATION_ID },
  98725. #endif
  98726. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  98727. { /* zName: */ "auto_vacuum",
  98728. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  98729. /* ePragFlag: */ PragFlag_NeedSchema,
  98730. /* iArg: */ 0 },
  98731. #endif
  98732. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98733. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  98734. { /* zName: */ "automatic_index",
  98735. /* ePragTyp: */ PragTyp_FLAG,
  98736. /* ePragFlag: */ 0,
  98737. /* iArg: */ SQLITE_AutoIndex },
  98738. #endif
  98739. #endif
  98740. { /* zName: */ "busy_timeout",
  98741. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  98742. /* ePragFlag: */ 0,
  98743. /* iArg: */ 0 },
  98744. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98745. { /* zName: */ "cache_size",
  98746. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  98747. /* ePragFlag: */ 0,
  98748. /* iArg: */ 0 },
  98749. #endif
  98750. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98751. { /* zName: */ "cache_spill",
  98752. /* ePragTyp: */ PragTyp_FLAG,
  98753. /* ePragFlag: */ 0,
  98754. /* iArg: */ SQLITE_CacheSpill },
  98755. #endif
  98756. { /* zName: */ "case_sensitive_like",
  98757. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  98758. /* ePragFlag: */ 0,
  98759. /* iArg: */ 0 },
  98760. { /* zName: */ "cell_size_check",
  98761. /* ePragTyp: */ PragTyp_FLAG,
  98762. /* ePragFlag: */ 0,
  98763. /* iArg: */ SQLITE_CellSizeCk },
  98764. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98765. { /* zName: */ "checkpoint_fullfsync",
  98766. /* ePragTyp: */ PragTyp_FLAG,
  98767. /* ePragFlag: */ 0,
  98768. /* iArg: */ SQLITE_CkptFullFSync },
  98769. #endif
  98770. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  98771. { /* zName: */ "collation_list",
  98772. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  98773. /* ePragFlag: */ 0,
  98774. /* iArg: */ 0 },
  98775. #endif
  98776. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  98777. { /* zName: */ "compile_options",
  98778. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  98779. /* ePragFlag: */ 0,
  98780. /* iArg: */ 0 },
  98781. #endif
  98782. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98783. { /* zName: */ "count_changes",
  98784. /* ePragTyp: */ PragTyp_FLAG,
  98785. /* ePragFlag: */ 0,
  98786. /* iArg: */ SQLITE_CountRows },
  98787. #endif
  98788. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  98789. { /* zName: */ "data_store_directory",
  98790. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  98791. /* ePragFlag: */ 0,
  98792. /* iArg: */ 0 },
  98793. #endif
  98794. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  98795. { /* zName: */ "data_version",
  98796. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  98797. /* ePragFlag: */ PragFlag_ReadOnly,
  98798. /* iArg: */ BTREE_DATA_VERSION },
  98799. #endif
  98800. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  98801. { /* zName: */ "database_list",
  98802. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  98803. /* ePragFlag: */ PragFlag_NeedSchema,
  98804. /* iArg: */ 0 },
  98805. #endif
  98806. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  98807. { /* zName: */ "default_cache_size",
  98808. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  98809. /* ePragFlag: */ PragFlag_NeedSchema,
  98810. /* iArg: */ 0 },
  98811. #endif
  98812. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98813. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  98814. { /* zName: */ "defer_foreign_keys",
  98815. /* ePragTyp: */ PragTyp_FLAG,
  98816. /* ePragFlag: */ 0,
  98817. /* iArg: */ SQLITE_DeferFKs },
  98818. #endif
  98819. #endif
  98820. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98821. { /* zName: */ "empty_result_callbacks",
  98822. /* ePragTyp: */ PragTyp_FLAG,
  98823. /* ePragFlag: */ 0,
  98824. /* iArg: */ SQLITE_NullCallback },
  98825. #endif
  98826. #if !defined(SQLITE_OMIT_UTF16)
  98827. { /* zName: */ "encoding",
  98828. /* ePragTyp: */ PragTyp_ENCODING,
  98829. /* ePragFlag: */ 0,
  98830. /* iArg: */ 0 },
  98831. #endif
  98832. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  98833. { /* zName: */ "foreign_key_check",
  98834. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  98835. /* ePragFlag: */ PragFlag_NeedSchema,
  98836. /* iArg: */ 0 },
  98837. #endif
  98838. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  98839. { /* zName: */ "foreign_key_list",
  98840. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  98841. /* ePragFlag: */ PragFlag_NeedSchema,
  98842. /* iArg: */ 0 },
  98843. #endif
  98844. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98845. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  98846. { /* zName: */ "foreign_keys",
  98847. /* ePragTyp: */ PragTyp_FLAG,
  98848. /* ePragFlag: */ 0,
  98849. /* iArg: */ SQLITE_ForeignKeys },
  98850. #endif
  98851. #endif
  98852. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  98853. { /* zName: */ "freelist_count",
  98854. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  98855. /* ePragFlag: */ PragFlag_ReadOnly,
  98856. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  98857. #endif
  98858. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98859. { /* zName: */ "full_column_names",
  98860. /* ePragTyp: */ PragTyp_FLAG,
  98861. /* ePragFlag: */ 0,
  98862. /* iArg: */ SQLITE_FullColNames },
  98863. { /* zName: */ "fullfsync",
  98864. /* ePragTyp: */ PragTyp_FLAG,
  98865. /* ePragFlag: */ 0,
  98866. /* iArg: */ SQLITE_FullFSync },
  98867. #endif
  98868. #if defined(SQLITE_HAS_CODEC)
  98869. { /* zName: */ "hexkey",
  98870. /* ePragTyp: */ PragTyp_HEXKEY,
  98871. /* ePragFlag: */ 0,
  98872. /* iArg: */ 0 },
  98873. { /* zName: */ "hexrekey",
  98874. /* ePragTyp: */ PragTyp_HEXKEY,
  98875. /* ePragFlag: */ 0,
  98876. /* iArg: */ 0 },
  98877. #endif
  98878. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98879. #if !defined(SQLITE_OMIT_CHECK)
  98880. { /* zName: */ "ignore_check_constraints",
  98881. /* ePragTyp: */ PragTyp_FLAG,
  98882. /* ePragFlag: */ 0,
  98883. /* iArg: */ SQLITE_IgnoreChecks },
  98884. #endif
  98885. #endif
  98886. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  98887. { /* zName: */ "incremental_vacuum",
  98888. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  98889. /* ePragFlag: */ PragFlag_NeedSchema,
  98890. /* iArg: */ 0 },
  98891. #endif
  98892. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  98893. { /* zName: */ "index_info",
  98894. /* ePragTyp: */ PragTyp_INDEX_INFO,
  98895. /* ePragFlag: */ PragFlag_NeedSchema,
  98896. /* iArg: */ 0 },
  98897. { /* zName: */ "index_list",
  98898. /* ePragTyp: */ PragTyp_INDEX_LIST,
  98899. /* ePragFlag: */ PragFlag_NeedSchema,
  98900. /* iArg: */ 0 },
  98901. { /* zName: */ "index_xinfo",
  98902. /* ePragTyp: */ PragTyp_INDEX_INFO,
  98903. /* ePragFlag: */ PragFlag_NeedSchema,
  98904. /* iArg: */ 1 },
  98905. #endif
  98906. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  98907. { /* zName: */ "integrity_check",
  98908. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  98909. /* ePragFlag: */ PragFlag_NeedSchema,
  98910. /* iArg: */ 0 },
  98911. #endif
  98912. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98913. { /* zName: */ "journal_mode",
  98914. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  98915. /* ePragFlag: */ PragFlag_NeedSchema,
  98916. /* iArg: */ 0 },
  98917. { /* zName: */ "journal_size_limit",
  98918. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  98919. /* ePragFlag: */ 0,
  98920. /* iArg: */ 0 },
  98921. #endif
  98922. #if defined(SQLITE_HAS_CODEC)
  98923. { /* zName: */ "key",
  98924. /* ePragTyp: */ PragTyp_KEY,
  98925. /* ePragFlag: */ 0,
  98926. /* iArg: */ 0 },
  98927. #endif
  98928. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98929. { /* zName: */ "legacy_file_format",
  98930. /* ePragTyp: */ PragTyp_FLAG,
  98931. /* ePragFlag: */ 0,
  98932. /* iArg: */ SQLITE_LegacyFileFmt },
  98933. #endif
  98934. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  98935. { /* zName: */ "lock_proxy_file",
  98936. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  98937. /* ePragFlag: */ 0,
  98938. /* iArg: */ 0 },
  98939. #endif
  98940. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  98941. { /* zName: */ "lock_status",
  98942. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  98943. /* ePragFlag: */ 0,
  98944. /* iArg: */ 0 },
  98945. #endif
  98946. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98947. { /* zName: */ "locking_mode",
  98948. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  98949. /* ePragFlag: */ 0,
  98950. /* iArg: */ 0 },
  98951. { /* zName: */ "max_page_count",
  98952. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  98953. /* ePragFlag: */ PragFlag_NeedSchema,
  98954. /* iArg: */ 0 },
  98955. { /* zName: */ "mmap_size",
  98956. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  98957. /* ePragFlag: */ 0,
  98958. /* iArg: */ 0 },
  98959. { /* zName: */ "page_count",
  98960. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  98961. /* ePragFlag: */ PragFlag_NeedSchema,
  98962. /* iArg: */ 0 },
  98963. { /* zName: */ "page_size",
  98964. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  98965. /* ePragFlag: */ 0,
  98966. /* iArg: */ 0 },
  98967. #endif
  98968. #if defined(SQLITE_DEBUG)
  98969. { /* zName: */ "parser_trace",
  98970. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  98971. /* ePragFlag: */ 0,
  98972. /* iArg: */ 0 },
  98973. #endif
  98974. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98975. { /* zName: */ "query_only",
  98976. /* ePragTyp: */ PragTyp_FLAG,
  98977. /* ePragFlag: */ 0,
  98978. /* iArg: */ SQLITE_QueryOnly },
  98979. #endif
  98980. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  98981. { /* zName: */ "quick_check",
  98982. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  98983. /* ePragFlag: */ PragFlag_NeedSchema,
  98984. /* iArg: */ 0 },
  98985. #endif
  98986. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98987. { /* zName: */ "read_uncommitted",
  98988. /* ePragTyp: */ PragTyp_FLAG,
  98989. /* ePragFlag: */ 0,
  98990. /* iArg: */ SQLITE_ReadUncommitted },
  98991. { /* zName: */ "recursive_triggers",
  98992. /* ePragTyp: */ PragTyp_FLAG,
  98993. /* ePragFlag: */ 0,
  98994. /* iArg: */ SQLITE_RecTriggers },
  98995. #endif
  98996. #if defined(SQLITE_HAS_CODEC)
  98997. { /* zName: */ "rekey",
  98998. /* ePragTyp: */ PragTyp_REKEY,
  98999. /* ePragFlag: */ 0,
  99000. /* iArg: */ 0 },
  99001. #endif
  99002. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99003. { /* zName: */ "reverse_unordered_selects",
  99004. /* ePragTyp: */ PragTyp_FLAG,
  99005. /* ePragFlag: */ 0,
  99006. /* iArg: */ SQLITE_ReverseOrder },
  99007. #endif
  99008. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99009. { /* zName: */ "schema_version",
  99010. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99011. /* ePragFlag: */ 0,
  99012. /* iArg: */ BTREE_SCHEMA_VERSION },
  99013. #endif
  99014. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99015. { /* zName: */ "secure_delete",
  99016. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  99017. /* ePragFlag: */ 0,
  99018. /* iArg: */ 0 },
  99019. #endif
  99020. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99021. { /* zName: */ "short_column_names",
  99022. /* ePragTyp: */ PragTyp_FLAG,
  99023. /* ePragFlag: */ 0,
  99024. /* iArg: */ SQLITE_ShortColNames },
  99025. #endif
  99026. { /* zName: */ "shrink_memory",
  99027. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  99028. /* ePragFlag: */ 0,
  99029. /* iArg: */ 0 },
  99030. { /* zName: */ "soft_heap_limit",
  99031. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  99032. /* ePragFlag: */ 0,
  99033. /* iArg: */ 0 },
  99034. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99035. #if defined(SQLITE_DEBUG)
  99036. { /* zName: */ "sql_trace",
  99037. /* ePragTyp: */ PragTyp_FLAG,
  99038. /* ePragFlag: */ 0,
  99039. /* iArg: */ SQLITE_SqlTrace },
  99040. #endif
  99041. #endif
  99042. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99043. { /* zName: */ "stats",
  99044. /* ePragTyp: */ PragTyp_STATS,
  99045. /* ePragFlag: */ PragFlag_NeedSchema,
  99046. /* iArg: */ 0 },
  99047. #endif
  99048. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99049. { /* zName: */ "synchronous",
  99050. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  99051. /* ePragFlag: */ PragFlag_NeedSchema,
  99052. /* iArg: */ 0 },
  99053. #endif
  99054. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99055. { /* zName: */ "table_info",
  99056. /* ePragTyp: */ PragTyp_TABLE_INFO,
  99057. /* ePragFlag: */ PragFlag_NeedSchema,
  99058. /* iArg: */ 0 },
  99059. #endif
  99060. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99061. { /* zName: */ "temp_store",
  99062. /* ePragTyp: */ PragTyp_TEMP_STORE,
  99063. /* ePragFlag: */ 0,
  99064. /* iArg: */ 0 },
  99065. { /* zName: */ "temp_store_directory",
  99066. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  99067. /* ePragFlag: */ 0,
  99068. /* iArg: */ 0 },
  99069. #endif
  99070. { /* zName: */ "threads",
  99071. /* ePragTyp: */ PragTyp_THREADS,
  99072. /* ePragFlag: */ 0,
  99073. /* iArg: */ 0 },
  99074. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99075. { /* zName: */ "user_version",
  99076. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99077. /* ePragFlag: */ 0,
  99078. /* iArg: */ BTREE_USER_VERSION },
  99079. #endif
  99080. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99081. #if defined(SQLITE_DEBUG)
  99082. { /* zName: */ "vdbe_addoptrace",
  99083. /* ePragTyp: */ PragTyp_FLAG,
  99084. /* ePragFlag: */ 0,
  99085. /* iArg: */ SQLITE_VdbeAddopTrace },
  99086. { /* zName: */ "vdbe_debug",
  99087. /* ePragTyp: */ PragTyp_FLAG,
  99088. /* ePragFlag: */ 0,
  99089. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  99090. { /* zName: */ "vdbe_eqp",
  99091. /* ePragTyp: */ PragTyp_FLAG,
  99092. /* ePragFlag: */ 0,
  99093. /* iArg: */ SQLITE_VdbeEQP },
  99094. { /* zName: */ "vdbe_listing",
  99095. /* ePragTyp: */ PragTyp_FLAG,
  99096. /* ePragFlag: */ 0,
  99097. /* iArg: */ SQLITE_VdbeListing },
  99098. { /* zName: */ "vdbe_trace",
  99099. /* ePragTyp: */ PragTyp_FLAG,
  99100. /* ePragFlag: */ 0,
  99101. /* iArg: */ SQLITE_VdbeTrace },
  99102. #endif
  99103. #endif
  99104. #if !defined(SQLITE_OMIT_WAL)
  99105. { /* zName: */ "wal_autocheckpoint",
  99106. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  99107. /* ePragFlag: */ 0,
  99108. /* iArg: */ 0 },
  99109. { /* zName: */ "wal_checkpoint",
  99110. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  99111. /* ePragFlag: */ PragFlag_NeedSchema,
  99112. /* iArg: */ 0 },
  99113. #endif
  99114. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99115. { /* zName: */ "writable_schema",
  99116. /* ePragTyp: */ PragTyp_FLAG,
  99117. /* ePragFlag: */ 0,
  99118. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  99119. #endif
  99120. };
  99121. /* Number of pragmas: 60 on by default, 73 total. */
  99122. /************** End of pragma.h **********************************************/
  99123. /************** Continuing where we left off in pragma.c *********************/
  99124. /*
  99125. ** Interpret the given string as a safety level. Return 0 for OFF,
  99126. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  99127. ** unrecognized string argument. The FULL option is disallowed
  99128. ** if the omitFull parameter it 1.
  99129. **
  99130. ** Note that the values returned are one less that the values that
  99131. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  99132. ** to support legacy SQL code. The safety level used to be boolean
  99133. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  99134. */
  99135. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  99136. /* 123456789 123456789 */
  99137. static const char zText[] = "onoffalseyestruefull";
  99138. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  99139. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  99140. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  99141. int i, n;
  99142. if( sqlite3Isdigit(*z) ){
  99143. return (u8)sqlite3Atoi(z);
  99144. }
  99145. n = sqlite3Strlen30(z);
  99146. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  99147. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  99148. return iValue[i];
  99149. }
  99150. }
  99151. return dflt;
  99152. }
  99153. /*
  99154. ** Interpret the given string as a boolean value.
  99155. */
  99156. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  99157. return getSafetyLevel(z,1,dflt)!=0;
  99158. }
  99159. /* The sqlite3GetBoolean() function is used by other modules but the
  99160. ** remainder of this file is specific to PRAGMA processing. So omit
  99161. ** the rest of the file if PRAGMAs are omitted from the build.
  99162. */
  99163. #if !defined(SQLITE_OMIT_PRAGMA)
  99164. /*
  99165. ** Interpret the given string as a locking mode value.
  99166. */
  99167. static int getLockingMode(const char *z){
  99168. if( z ){
  99169. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  99170. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  99171. }
  99172. return PAGER_LOCKINGMODE_QUERY;
  99173. }
  99174. #ifndef SQLITE_OMIT_AUTOVACUUM
  99175. /*
  99176. ** Interpret the given string as an auto-vacuum mode value.
  99177. **
  99178. ** The following strings, "none", "full" and "incremental" are
  99179. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  99180. */
  99181. static int getAutoVacuum(const char *z){
  99182. int i;
  99183. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  99184. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  99185. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  99186. i = sqlite3Atoi(z);
  99187. return (u8)((i>=0&&i<=2)?i:0);
  99188. }
  99189. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  99190. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99191. /*
  99192. ** Interpret the given string as a temp db location. Return 1 for file
  99193. ** backed temporary databases, 2 for the Red-Black tree in memory database
  99194. ** and 0 to use the compile-time default.
  99195. */
  99196. static int getTempStore(const char *z){
  99197. if( z[0]>='0' && z[0]<='2' ){
  99198. return z[0] - '0';
  99199. }else if( sqlite3StrICmp(z, "file")==0 ){
  99200. return 1;
  99201. }else if( sqlite3StrICmp(z, "memory")==0 ){
  99202. return 2;
  99203. }else{
  99204. return 0;
  99205. }
  99206. }
  99207. #endif /* SQLITE_PAGER_PRAGMAS */
  99208. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99209. /*
  99210. ** Invalidate temp storage, either when the temp storage is changed
  99211. ** from default, or when 'file' and the temp_store_directory has changed
  99212. */
  99213. static int invalidateTempStorage(Parse *pParse){
  99214. sqlite3 *db = pParse->db;
  99215. if( db->aDb[1].pBt!=0 ){
  99216. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  99217. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  99218. "from within a transaction");
  99219. return SQLITE_ERROR;
  99220. }
  99221. sqlite3BtreeClose(db->aDb[1].pBt);
  99222. db->aDb[1].pBt = 0;
  99223. sqlite3ResetAllSchemasOfConnection(db);
  99224. }
  99225. return SQLITE_OK;
  99226. }
  99227. #endif /* SQLITE_PAGER_PRAGMAS */
  99228. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99229. /*
  99230. ** If the TEMP database is open, close it and mark the database schema
  99231. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  99232. ** or DEFAULT_TEMP_STORE pragmas.
  99233. */
  99234. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  99235. int ts = getTempStore(zStorageType);
  99236. sqlite3 *db = pParse->db;
  99237. if( db->temp_store==ts ) return SQLITE_OK;
  99238. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  99239. return SQLITE_ERROR;
  99240. }
  99241. db->temp_store = (u8)ts;
  99242. return SQLITE_OK;
  99243. }
  99244. #endif /* SQLITE_PAGER_PRAGMAS */
  99245. /*
  99246. ** Set the names of the first N columns to the values in azCol[]
  99247. */
  99248. static void setAllColumnNames(
  99249. Vdbe *v, /* The query under construction */
  99250. int N, /* Number of columns */
  99251. const char **azCol /* Names of columns */
  99252. ){
  99253. int i;
  99254. sqlite3VdbeSetNumCols(v, N);
  99255. for(i=0; i<N; i++){
  99256. sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
  99257. }
  99258. }
  99259. static void setOneColumnName(Vdbe *v, const char *z){
  99260. setAllColumnNames(v, 1, &z);
  99261. }
  99262. /*
  99263. ** Generate code to return a single integer value.
  99264. */
  99265. static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
  99266. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  99267. setOneColumnName(v, zLabel);
  99268. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  99269. }
  99270. /*
  99271. ** Generate code to return a single text value.
  99272. */
  99273. static void returnSingleText(
  99274. Vdbe *v, /* Prepared statement under construction */
  99275. const char *zLabel, /* Name of the result column */
  99276. const char *zValue /* Value to be returned */
  99277. ){
  99278. if( zValue ){
  99279. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  99280. setOneColumnName(v, zLabel);
  99281. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  99282. }
  99283. }
  99284. /*
  99285. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  99286. ** set these values for all pagers.
  99287. */
  99288. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99289. static void setAllPagerFlags(sqlite3 *db){
  99290. if( db->autoCommit ){
  99291. Db *pDb = db->aDb;
  99292. int n = db->nDb;
  99293. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  99294. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  99295. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  99296. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  99297. == PAGER_FLAGS_MASK );
  99298. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  99299. while( (n--) > 0 ){
  99300. if( pDb->pBt ){
  99301. sqlite3BtreeSetPagerFlags(pDb->pBt,
  99302. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  99303. }
  99304. pDb++;
  99305. }
  99306. }
  99307. }
  99308. #else
  99309. # define setAllPagerFlags(X) /* no-op */
  99310. #endif
  99311. /*
  99312. ** Return a human-readable name for a constraint resolution action.
  99313. */
  99314. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99315. static const char *actionName(u8 action){
  99316. const char *zName;
  99317. switch( action ){
  99318. case OE_SetNull: zName = "SET NULL"; break;
  99319. case OE_SetDflt: zName = "SET DEFAULT"; break;
  99320. case OE_Cascade: zName = "CASCADE"; break;
  99321. case OE_Restrict: zName = "RESTRICT"; break;
  99322. default: zName = "NO ACTION";
  99323. assert( action==OE_None ); break;
  99324. }
  99325. return zName;
  99326. }
  99327. #endif
  99328. /*
  99329. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  99330. ** defined in pager.h. This function returns the associated lowercase
  99331. ** journal-mode name.
  99332. */
  99333. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  99334. static char * const azModeName[] = {
  99335. "delete", "persist", "off", "truncate", "memory"
  99336. #ifndef SQLITE_OMIT_WAL
  99337. , "wal"
  99338. #endif
  99339. };
  99340. assert( PAGER_JOURNALMODE_DELETE==0 );
  99341. assert( PAGER_JOURNALMODE_PERSIST==1 );
  99342. assert( PAGER_JOURNALMODE_OFF==2 );
  99343. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  99344. assert( PAGER_JOURNALMODE_MEMORY==4 );
  99345. assert( PAGER_JOURNALMODE_WAL==5 );
  99346. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  99347. if( eMode==ArraySize(azModeName) ) return 0;
  99348. return azModeName[eMode];
  99349. }
  99350. /*
  99351. ** Process a pragma statement.
  99352. **
  99353. ** Pragmas are of this form:
  99354. **
  99355. ** PRAGMA [database.]id [= value]
  99356. **
  99357. ** The identifier might also be a string. The value is a string, and
  99358. ** identifier, or a number. If minusFlag is true, then the value is
  99359. ** a number that was preceded by a minus sign.
  99360. **
  99361. ** If the left side is "database.id" then pId1 is the database name
  99362. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  99363. ** id and pId2 is any empty string.
  99364. */
  99365. SQLITE_PRIVATE void sqlite3Pragma(
  99366. Parse *pParse,
  99367. Token *pId1, /* First part of [database.]id field */
  99368. Token *pId2, /* Second part of [database.]id field, or NULL */
  99369. Token *pValue, /* Token for <value>, or NULL */
  99370. int minusFlag /* True if a '-' sign preceded <value> */
  99371. ){
  99372. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  99373. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  99374. const char *zDb = 0; /* The database name */
  99375. Token *pId; /* Pointer to <id> token */
  99376. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  99377. int iDb; /* Database index for <database> */
  99378. int lwr, upr, mid = 0; /* Binary search bounds */
  99379. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  99380. sqlite3 *db = pParse->db; /* The database connection */
  99381. Db *pDb; /* The specific database being pragmaed */
  99382. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  99383. const struct sPragmaNames *pPragma;
  99384. if( v==0 ) return;
  99385. sqlite3VdbeRunOnlyOnce(v);
  99386. pParse->nMem = 2;
  99387. /* Interpret the [database.] part of the pragma statement. iDb is the
  99388. ** index of the database this pragma is being applied to in db.aDb[]. */
  99389. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  99390. if( iDb<0 ) return;
  99391. pDb = &db->aDb[iDb];
  99392. /* If the temp database has been explicitly named as part of the
  99393. ** pragma, make sure it is open.
  99394. */
  99395. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  99396. return;
  99397. }
  99398. zLeft = sqlite3NameFromToken(db, pId);
  99399. if( !zLeft ) return;
  99400. if( minusFlag ){
  99401. zRight = sqlite3MPrintf(db, "-%T", pValue);
  99402. }else{
  99403. zRight = sqlite3NameFromToken(db, pValue);
  99404. }
  99405. assert( pId2 );
  99406. zDb = pId2->n>0 ? pDb->zName : 0;
  99407. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  99408. goto pragma_out;
  99409. }
  99410. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  99411. ** connection. If it returns SQLITE_OK, then assume that the VFS
  99412. ** handled the pragma and generate a no-op prepared statement.
  99413. **
  99414. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  99415. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  99416. ** object corresponding to the database file to which the pragma
  99417. ** statement refers.
  99418. **
  99419. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  99420. ** file control is an array of pointers to strings (char**) in which the
  99421. ** second element of the array is the name of the pragma and the third
  99422. ** element is the argument to the pragma or NULL if the pragma has no
  99423. ** argument.
  99424. */
  99425. aFcntl[0] = 0;
  99426. aFcntl[1] = zLeft;
  99427. aFcntl[2] = zRight;
  99428. aFcntl[3] = 0;
  99429. db->busyHandler.nBusy = 0;
  99430. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  99431. if( rc==SQLITE_OK ){
  99432. returnSingleText(v, "result", aFcntl[0]);
  99433. sqlite3_free(aFcntl[0]);
  99434. goto pragma_out;
  99435. }
  99436. if( rc!=SQLITE_NOTFOUND ){
  99437. if( aFcntl[0] ){
  99438. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  99439. sqlite3_free(aFcntl[0]);
  99440. }
  99441. pParse->nErr++;
  99442. pParse->rc = rc;
  99443. goto pragma_out;
  99444. }
  99445. /* Locate the pragma in the lookup table */
  99446. lwr = 0;
  99447. upr = ArraySize(aPragmaNames)-1;
  99448. while( lwr<=upr ){
  99449. mid = (lwr+upr)/2;
  99450. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  99451. if( rc==0 ) break;
  99452. if( rc<0 ){
  99453. upr = mid - 1;
  99454. }else{
  99455. lwr = mid + 1;
  99456. }
  99457. }
  99458. if( lwr>upr ) goto pragma_out;
  99459. pPragma = &aPragmaNames[mid];
  99460. /* Make sure the database schema is loaded if the pragma requires that */
  99461. if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
  99462. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  99463. }
  99464. /* Jump to the appropriate pragma handler */
  99465. switch( pPragma->ePragTyp ){
  99466. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  99467. /*
  99468. ** PRAGMA [database.]default_cache_size
  99469. ** PRAGMA [database.]default_cache_size=N
  99470. **
  99471. ** The first form reports the current persistent setting for the
  99472. ** page cache size. The value returned is the maximum number of
  99473. ** pages in the page cache. The second form sets both the current
  99474. ** page cache size value and the persistent page cache size value
  99475. ** stored in the database file.
  99476. **
  99477. ** Older versions of SQLite would set the default cache size to a
  99478. ** negative number to indicate synchronous=OFF. These days, synchronous
  99479. ** is always on by default regardless of the sign of the default cache
  99480. ** size. But continue to take the absolute value of the default cache
  99481. ** size of historical compatibility.
  99482. */
  99483. case PragTyp_DEFAULT_CACHE_SIZE: {
  99484. static const int iLn = VDBE_OFFSET_LINENO(2);
  99485. static const VdbeOpList getCacheSize[] = {
  99486. { OP_Transaction, 0, 0, 0}, /* 0 */
  99487. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  99488. { OP_IfPos, 1, 8, 0},
  99489. { OP_Integer, 0, 2, 0},
  99490. { OP_Subtract, 1, 2, 1},
  99491. { OP_IfPos, 1, 8, 0},
  99492. { OP_Integer, 0, 1, 0}, /* 6 */
  99493. { OP_Noop, 0, 0, 0},
  99494. { OP_ResultRow, 1, 1, 0},
  99495. };
  99496. int addr;
  99497. sqlite3VdbeUsesBtree(v, iDb);
  99498. if( !zRight ){
  99499. setOneColumnName(v, "cache_size");
  99500. pParse->nMem += 2;
  99501. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  99502. sqlite3VdbeChangeP1(v, addr, iDb);
  99503. sqlite3VdbeChangeP1(v, addr+1, iDb);
  99504. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  99505. }else{
  99506. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  99507. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99508. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  99509. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  99510. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99511. pDb->pSchema->cache_size = size;
  99512. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  99513. }
  99514. break;
  99515. }
  99516. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  99517. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99518. /*
  99519. ** PRAGMA [database.]page_size
  99520. ** PRAGMA [database.]page_size=N
  99521. **
  99522. ** The first form reports the current setting for the
  99523. ** database page size in bytes. The second form sets the
  99524. ** database page size value. The value can only be set if
  99525. ** the database has not yet been created.
  99526. */
  99527. case PragTyp_PAGE_SIZE: {
  99528. Btree *pBt = pDb->pBt;
  99529. assert( pBt!=0 );
  99530. if( !zRight ){
  99531. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  99532. returnSingleInt(v, "page_size", size);
  99533. }else{
  99534. /* Malloc may fail when setting the page-size, as there is an internal
  99535. ** buffer that the pager module resizes using sqlite3_realloc().
  99536. */
  99537. db->nextPagesize = sqlite3Atoi(zRight);
  99538. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  99539. db->mallocFailed = 1;
  99540. }
  99541. }
  99542. break;
  99543. }
  99544. /*
  99545. ** PRAGMA [database.]secure_delete
  99546. ** PRAGMA [database.]secure_delete=ON/OFF
  99547. **
  99548. ** The first form reports the current setting for the
  99549. ** secure_delete flag. The second form changes the secure_delete
  99550. ** flag setting and reports thenew value.
  99551. */
  99552. case PragTyp_SECURE_DELETE: {
  99553. Btree *pBt = pDb->pBt;
  99554. int b = -1;
  99555. assert( pBt!=0 );
  99556. if( zRight ){
  99557. b = sqlite3GetBoolean(zRight, 0);
  99558. }
  99559. if( pId2->n==0 && b>=0 ){
  99560. int ii;
  99561. for(ii=0; ii<db->nDb; ii++){
  99562. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  99563. }
  99564. }
  99565. b = sqlite3BtreeSecureDelete(pBt, b);
  99566. returnSingleInt(v, "secure_delete", b);
  99567. break;
  99568. }
  99569. /*
  99570. ** PRAGMA [database.]max_page_count
  99571. ** PRAGMA [database.]max_page_count=N
  99572. **
  99573. ** The first form reports the current setting for the
  99574. ** maximum number of pages in the database file. The
  99575. ** second form attempts to change this setting. Both
  99576. ** forms return the current setting.
  99577. **
  99578. ** The absolute value of N is used. This is undocumented and might
  99579. ** change. The only purpose is to provide an easy way to test
  99580. ** the sqlite3AbsInt32() function.
  99581. **
  99582. ** PRAGMA [database.]page_count
  99583. **
  99584. ** Return the number of pages in the specified database.
  99585. */
  99586. case PragTyp_PAGE_COUNT: {
  99587. int iReg;
  99588. sqlite3CodeVerifySchema(pParse, iDb);
  99589. iReg = ++pParse->nMem;
  99590. if( sqlite3Tolower(zLeft[0])=='p' ){
  99591. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  99592. }else{
  99593. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  99594. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  99595. }
  99596. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  99597. sqlite3VdbeSetNumCols(v, 1);
  99598. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  99599. break;
  99600. }
  99601. /*
  99602. ** PRAGMA [database.]locking_mode
  99603. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  99604. */
  99605. case PragTyp_LOCKING_MODE: {
  99606. const char *zRet = "normal";
  99607. int eMode = getLockingMode(zRight);
  99608. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  99609. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  99610. ** the current default locking mode (which may be different to
  99611. ** the locking-mode of the main database).
  99612. */
  99613. eMode = db->dfltLockMode;
  99614. }else{
  99615. Pager *pPager;
  99616. if( pId2->n==0 ){
  99617. /* This indicates that no database name was specified as part
  99618. ** of the PRAGMA command. In this case the locking-mode must be
  99619. ** set on all attached databases, as well as the main db file.
  99620. **
  99621. ** Also, the sqlite3.dfltLockMode variable is set so that
  99622. ** any subsequently attached databases also use the specified
  99623. ** locking mode.
  99624. */
  99625. int ii;
  99626. assert(pDb==&db->aDb[0]);
  99627. for(ii=2; ii<db->nDb; ii++){
  99628. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  99629. sqlite3PagerLockingMode(pPager, eMode);
  99630. }
  99631. db->dfltLockMode = (u8)eMode;
  99632. }
  99633. pPager = sqlite3BtreePager(pDb->pBt);
  99634. eMode = sqlite3PagerLockingMode(pPager, eMode);
  99635. }
  99636. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  99637. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  99638. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  99639. zRet = "exclusive";
  99640. }
  99641. returnSingleText(v, "locking_mode", zRet);
  99642. break;
  99643. }
  99644. /*
  99645. ** PRAGMA [database.]journal_mode
  99646. ** PRAGMA [database.]journal_mode =
  99647. ** (delete|persist|off|truncate|memory|wal|off)
  99648. */
  99649. case PragTyp_JOURNAL_MODE: {
  99650. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  99651. int ii; /* Loop counter */
  99652. setOneColumnName(v, "journal_mode");
  99653. if( zRight==0 ){
  99654. /* If there is no "=MODE" part of the pragma, do a query for the
  99655. ** current mode */
  99656. eMode = PAGER_JOURNALMODE_QUERY;
  99657. }else{
  99658. const char *zMode;
  99659. int n = sqlite3Strlen30(zRight);
  99660. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  99661. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  99662. }
  99663. if( !zMode ){
  99664. /* If the "=MODE" part does not match any known journal mode,
  99665. ** then do a query */
  99666. eMode = PAGER_JOURNALMODE_QUERY;
  99667. }
  99668. }
  99669. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  99670. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  99671. iDb = 0;
  99672. pId2->n = 1;
  99673. }
  99674. for(ii=db->nDb-1; ii>=0; ii--){
  99675. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  99676. sqlite3VdbeUsesBtree(v, ii);
  99677. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  99678. }
  99679. }
  99680. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  99681. break;
  99682. }
  99683. /*
  99684. ** PRAGMA [database.]journal_size_limit
  99685. ** PRAGMA [database.]journal_size_limit=N
  99686. **
  99687. ** Get or set the size limit on rollback journal files.
  99688. */
  99689. case PragTyp_JOURNAL_SIZE_LIMIT: {
  99690. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  99691. i64 iLimit = -2;
  99692. if( zRight ){
  99693. sqlite3DecOrHexToI64(zRight, &iLimit);
  99694. if( iLimit<-1 ) iLimit = -1;
  99695. }
  99696. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  99697. returnSingleInt(v, "journal_size_limit", iLimit);
  99698. break;
  99699. }
  99700. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  99701. /*
  99702. ** PRAGMA [database.]auto_vacuum
  99703. ** PRAGMA [database.]auto_vacuum=N
  99704. **
  99705. ** Get or set the value of the database 'auto-vacuum' parameter.
  99706. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  99707. */
  99708. #ifndef SQLITE_OMIT_AUTOVACUUM
  99709. case PragTyp_AUTO_VACUUM: {
  99710. Btree *pBt = pDb->pBt;
  99711. assert( pBt!=0 );
  99712. if( !zRight ){
  99713. returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  99714. }else{
  99715. int eAuto = getAutoVacuum(zRight);
  99716. assert( eAuto>=0 && eAuto<=2 );
  99717. db->nextAutovac = (u8)eAuto;
  99718. /* Call SetAutoVacuum() to set initialize the internal auto and
  99719. ** incr-vacuum flags. This is required in case this connection
  99720. ** creates the database file. It is important that it is created
  99721. ** as an auto-vacuum capable db.
  99722. */
  99723. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  99724. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  99725. /* When setting the auto_vacuum mode to either "full" or
  99726. ** "incremental", write the value of meta[6] in the database
  99727. ** file. Before writing to meta[6], check that meta[3] indicates
  99728. ** that this really is an auto-vacuum capable database.
  99729. */
  99730. static const int iLn = VDBE_OFFSET_LINENO(2);
  99731. static const VdbeOpList setMeta6[] = {
  99732. { OP_Transaction, 0, 1, 0}, /* 0 */
  99733. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  99734. { OP_If, 1, 0, 0}, /* 2 */
  99735. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  99736. { OP_Integer, 0, 1, 0}, /* 4 */
  99737. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  99738. };
  99739. int iAddr;
  99740. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  99741. sqlite3VdbeChangeP1(v, iAddr, iDb);
  99742. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  99743. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  99744. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  99745. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  99746. sqlite3VdbeUsesBtree(v, iDb);
  99747. }
  99748. }
  99749. break;
  99750. }
  99751. #endif
  99752. /*
  99753. ** PRAGMA [database.]incremental_vacuum(N)
  99754. **
  99755. ** Do N steps of incremental vacuuming on a database.
  99756. */
  99757. #ifndef SQLITE_OMIT_AUTOVACUUM
  99758. case PragTyp_INCREMENTAL_VACUUM: {
  99759. int iLimit, addr;
  99760. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  99761. iLimit = 0x7fffffff;
  99762. }
  99763. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99764. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  99765. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  99766. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  99767. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  99768. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  99769. sqlite3VdbeJumpHere(v, addr);
  99770. break;
  99771. }
  99772. #endif
  99773. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99774. /*
  99775. ** PRAGMA [database.]cache_size
  99776. ** PRAGMA [database.]cache_size=N
  99777. **
  99778. ** The first form reports the current local setting for the
  99779. ** page cache size. The second form sets the local
  99780. ** page cache size value. If N is positive then that is the
  99781. ** number of pages in the cache. If N is negative, then the
  99782. ** number of pages is adjusted so that the cache uses -N kibibytes
  99783. ** of memory.
  99784. */
  99785. case PragTyp_CACHE_SIZE: {
  99786. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99787. if( !zRight ){
  99788. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  99789. returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
  99790. }else{
  99791. int size = sqlite3Atoi(zRight);
  99792. pDb->pSchema->cache_size = size;
  99793. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  99794. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  99795. }
  99796. break;
  99797. }
  99798. /*
  99799. ** PRAGMA [database.]mmap_size(N)
  99800. **
  99801. ** Used to set mapping size limit. The mapping size limit is
  99802. ** used to limit the aggregate size of all memory mapped regions of the
  99803. ** database file. If this parameter is set to zero, then memory mapping
  99804. ** is not used at all. If N is negative, then the default memory map
  99805. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  99806. ** The parameter N is measured in bytes.
  99807. **
  99808. ** This value is advisory. The underlying VFS is free to memory map
  99809. ** as little or as much as it wants. Except, if N is set to 0 then the
  99810. ** upper layers will never invoke the xFetch interfaces to the VFS.
  99811. */
  99812. case PragTyp_MMAP_SIZE: {
  99813. sqlite3_int64 sz;
  99814. #if SQLITE_MAX_MMAP_SIZE>0
  99815. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99816. if( zRight ){
  99817. int ii;
  99818. sqlite3DecOrHexToI64(zRight, &sz);
  99819. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  99820. if( pId2->n==0 ) db->szMmap = sz;
  99821. for(ii=db->nDb-1; ii>=0; ii--){
  99822. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  99823. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  99824. }
  99825. }
  99826. }
  99827. sz = -1;
  99828. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  99829. #else
  99830. sz = 0;
  99831. rc = SQLITE_OK;
  99832. #endif
  99833. if( rc==SQLITE_OK ){
  99834. returnSingleInt(v, "mmap_size", sz);
  99835. }else if( rc!=SQLITE_NOTFOUND ){
  99836. pParse->nErr++;
  99837. pParse->rc = rc;
  99838. }
  99839. break;
  99840. }
  99841. /*
  99842. ** PRAGMA temp_store
  99843. ** PRAGMA temp_store = "default"|"memory"|"file"
  99844. **
  99845. ** Return or set the local value of the temp_store flag. Changing
  99846. ** the local value does not make changes to the disk file and the default
  99847. ** value will be restored the next time the database is opened.
  99848. **
  99849. ** Note that it is possible for the library compile-time options to
  99850. ** override this setting
  99851. */
  99852. case PragTyp_TEMP_STORE: {
  99853. if( !zRight ){
  99854. returnSingleInt(v, "temp_store", db->temp_store);
  99855. }else{
  99856. changeTempStorage(pParse, zRight);
  99857. }
  99858. break;
  99859. }
  99860. /*
  99861. ** PRAGMA temp_store_directory
  99862. ** PRAGMA temp_store_directory = ""|"directory_name"
  99863. **
  99864. ** Return or set the local value of the temp_store_directory flag. Changing
  99865. ** the value sets a specific directory to be used for temporary files.
  99866. ** Setting to a null string reverts to the default temporary directory search.
  99867. ** If temporary directory is changed, then invalidateTempStorage.
  99868. **
  99869. */
  99870. case PragTyp_TEMP_STORE_DIRECTORY: {
  99871. if( !zRight ){
  99872. returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
  99873. }else{
  99874. #ifndef SQLITE_OMIT_WSD
  99875. if( zRight[0] ){
  99876. int res;
  99877. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  99878. if( rc!=SQLITE_OK || res==0 ){
  99879. sqlite3ErrorMsg(pParse, "not a writable directory");
  99880. goto pragma_out;
  99881. }
  99882. }
  99883. if( SQLITE_TEMP_STORE==0
  99884. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  99885. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  99886. ){
  99887. invalidateTempStorage(pParse);
  99888. }
  99889. sqlite3_free(sqlite3_temp_directory);
  99890. if( zRight[0] ){
  99891. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  99892. }else{
  99893. sqlite3_temp_directory = 0;
  99894. }
  99895. #endif /* SQLITE_OMIT_WSD */
  99896. }
  99897. break;
  99898. }
  99899. #if SQLITE_OS_WIN
  99900. /*
  99901. ** PRAGMA data_store_directory
  99902. ** PRAGMA data_store_directory = ""|"directory_name"
  99903. **
  99904. ** Return or set the local value of the data_store_directory flag. Changing
  99905. ** the value sets a specific directory to be used for database files that
  99906. ** were specified with a relative pathname. Setting to a null string reverts
  99907. ** to the default database directory, which for database files specified with
  99908. ** a relative path will probably be based on the current directory for the
  99909. ** process. Database file specified with an absolute path are not impacted
  99910. ** by this setting, regardless of its value.
  99911. **
  99912. */
  99913. case PragTyp_DATA_STORE_DIRECTORY: {
  99914. if( !zRight ){
  99915. returnSingleText(v, "data_store_directory", sqlite3_data_directory);
  99916. }else{
  99917. #ifndef SQLITE_OMIT_WSD
  99918. if( zRight[0] ){
  99919. int res;
  99920. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  99921. if( rc!=SQLITE_OK || res==0 ){
  99922. sqlite3ErrorMsg(pParse, "not a writable directory");
  99923. goto pragma_out;
  99924. }
  99925. }
  99926. sqlite3_free(sqlite3_data_directory);
  99927. if( zRight[0] ){
  99928. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  99929. }else{
  99930. sqlite3_data_directory = 0;
  99931. }
  99932. #endif /* SQLITE_OMIT_WSD */
  99933. }
  99934. break;
  99935. }
  99936. #endif
  99937. #if SQLITE_ENABLE_LOCKING_STYLE
  99938. /*
  99939. ** PRAGMA [database.]lock_proxy_file
  99940. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  99941. **
  99942. ** Return or set the value of the lock_proxy_file flag. Changing
  99943. ** the value sets a specific file to be used for database access locks.
  99944. **
  99945. */
  99946. case PragTyp_LOCK_PROXY_FILE: {
  99947. if( !zRight ){
  99948. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  99949. char *proxy_file_path = NULL;
  99950. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  99951. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  99952. &proxy_file_path);
  99953. returnSingleText(v, "lock_proxy_file", proxy_file_path);
  99954. }else{
  99955. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  99956. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  99957. int res;
  99958. if( zRight[0] ){
  99959. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  99960. zRight);
  99961. } else {
  99962. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  99963. NULL);
  99964. }
  99965. if( res!=SQLITE_OK ){
  99966. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  99967. goto pragma_out;
  99968. }
  99969. }
  99970. break;
  99971. }
  99972. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  99973. /*
  99974. ** PRAGMA [database.]synchronous
  99975. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  99976. **
  99977. ** Return or set the local value of the synchronous flag. Changing
  99978. ** the local value does not make changes to the disk file and the
  99979. ** default value will be restored the next time the database is
  99980. ** opened.
  99981. */
  99982. case PragTyp_SYNCHRONOUS: {
  99983. if( !zRight ){
  99984. returnSingleInt(v, "synchronous", pDb->safety_level-1);
  99985. }else{
  99986. if( !db->autoCommit ){
  99987. sqlite3ErrorMsg(pParse,
  99988. "Safety level may not be changed inside a transaction");
  99989. }else{
  99990. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  99991. if( iLevel==0 ) iLevel = 1;
  99992. pDb->safety_level = iLevel;
  99993. setAllPagerFlags(db);
  99994. }
  99995. }
  99996. break;
  99997. }
  99998. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  99999. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  100000. case PragTyp_FLAG: {
  100001. if( zRight==0 ){
  100002. returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
  100003. }else{
  100004. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  100005. if( db->autoCommit==0 ){
  100006. /* Foreign key support may not be enabled or disabled while not
  100007. ** in auto-commit mode. */
  100008. mask &= ~(SQLITE_ForeignKeys);
  100009. }
  100010. #if SQLITE_USER_AUTHENTICATION
  100011. if( db->auth.authLevel==UAUTH_User ){
  100012. /* Do not allow non-admin users to modify the schema arbitrarily */
  100013. mask &= ~(SQLITE_WriteSchema);
  100014. }
  100015. #endif
  100016. if( sqlite3GetBoolean(zRight, 0) ){
  100017. db->flags |= mask;
  100018. }else{
  100019. db->flags &= ~mask;
  100020. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  100021. }
  100022. /* Many of the flag-pragmas modify the code generated by the SQL
  100023. ** compiler (eg. count_changes). So add an opcode to expire all
  100024. ** compiled SQL statements after modifying a pragma value.
  100025. */
  100026. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  100027. setAllPagerFlags(db);
  100028. }
  100029. break;
  100030. }
  100031. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  100032. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  100033. /*
  100034. ** PRAGMA table_info(<table>)
  100035. **
  100036. ** Return a single row for each column of the named table. The columns of
  100037. ** the returned data set are:
  100038. **
  100039. ** cid: Column id (numbered from left to right, starting at 0)
  100040. ** name: Column name
  100041. ** type: Column declaration type.
  100042. ** notnull: True if 'NOT NULL' is part of column declaration
  100043. ** dflt_value: The default value for the column, if any.
  100044. */
  100045. case PragTyp_TABLE_INFO: if( zRight ){
  100046. Table *pTab;
  100047. pTab = sqlite3FindTable(db, zRight, zDb);
  100048. if( pTab ){
  100049. static const char *azCol[] = {
  100050. "cid", "name", "type", "notnull", "dflt_value", "pk"
  100051. };
  100052. int i, k;
  100053. int nHidden = 0;
  100054. Column *pCol;
  100055. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  100056. pParse->nMem = 6;
  100057. sqlite3CodeVerifySchema(pParse, iDb);
  100058. setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
  100059. sqlite3ViewGetColumnNames(pParse, pTab);
  100060. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  100061. if( IsHiddenColumn(pCol) ){
  100062. nHidden++;
  100063. continue;
  100064. }
  100065. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  100066. k = 0;
  100067. }else if( pPk==0 ){
  100068. k = 1;
  100069. }else{
  100070. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  100071. }
  100072. sqlite3VdbeMultiLoad(v, 1, "issisi",
  100073. i-nHidden,
  100074. pCol->zName,
  100075. pCol->zType ? pCol->zType : "",
  100076. pCol->notNull ? 1 : 0,
  100077. pCol->zDflt,
  100078. k);
  100079. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  100080. }
  100081. }
  100082. }
  100083. break;
  100084. case PragTyp_STATS: {
  100085. static const char *azCol[] = { "table", "index", "width", "height" };
  100086. Index *pIdx;
  100087. HashElem *i;
  100088. v = sqlite3GetVdbe(pParse);
  100089. pParse->nMem = 4;
  100090. sqlite3CodeVerifySchema(pParse, iDb);
  100091. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  100092. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  100093. Table *pTab = sqliteHashData(i);
  100094. sqlite3VdbeMultiLoad(v, 1, "ssii",
  100095. pTab->zName,
  100096. 0,
  100097. (int)sqlite3LogEstToInt(pTab->szTabRow),
  100098. (int)sqlite3LogEstToInt(pTab->nRowLogEst));
  100099. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  100100. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  100101. sqlite3VdbeMultiLoad(v, 2, "sii",
  100102. pIdx->zName,
  100103. (int)sqlite3LogEstToInt(pIdx->szIdxRow),
  100104. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]));
  100105. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  100106. }
  100107. }
  100108. }
  100109. break;
  100110. case PragTyp_INDEX_INFO: if( zRight ){
  100111. Index *pIdx;
  100112. Table *pTab;
  100113. pIdx = sqlite3FindIndex(db, zRight, zDb);
  100114. if( pIdx ){
  100115. static const char *azCol[] = {
  100116. "seqno", "cid", "name", "desc", "coll", "key"
  100117. };
  100118. int i;
  100119. int mx;
  100120. if( pPragma->iArg ){
  100121. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  100122. mx = pIdx->nColumn;
  100123. pParse->nMem = 6;
  100124. }else{
  100125. /* PRAGMA index_info (legacy version) */
  100126. mx = pIdx->nKeyCol;
  100127. pParse->nMem = 3;
  100128. }
  100129. pTab = pIdx->pTable;
  100130. sqlite3CodeVerifySchema(pParse, iDb);
  100131. assert( pParse->nMem<=ArraySize(azCol) );
  100132. setAllColumnNames(v, pParse->nMem, azCol);
  100133. for(i=0; i<mx; i++){
  100134. i16 cnum = pIdx->aiColumn[i];
  100135. sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
  100136. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  100137. if( pPragma->iArg ){
  100138. sqlite3VdbeMultiLoad(v, 4, "isi",
  100139. pIdx->aSortOrder[i],
  100140. pIdx->azColl[i],
  100141. i<pIdx->nKeyCol);
  100142. }
  100143. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  100144. }
  100145. }
  100146. }
  100147. break;
  100148. case PragTyp_INDEX_LIST: if( zRight ){
  100149. Index *pIdx;
  100150. Table *pTab;
  100151. int i;
  100152. pTab = sqlite3FindTable(db, zRight, zDb);
  100153. if( pTab ){
  100154. static const char *azCol[] = {
  100155. "seq", "name", "unique", "origin", "partial"
  100156. };
  100157. v = sqlite3GetVdbe(pParse);
  100158. pParse->nMem = 5;
  100159. sqlite3CodeVerifySchema(pParse, iDb);
  100160. setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
  100161. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  100162. const char *azOrigin[] = { "c", "u", "pk" };
  100163. sqlite3VdbeMultiLoad(v, 1, "isisi",
  100164. i,
  100165. pIdx->zName,
  100166. IsUniqueIndex(pIdx),
  100167. azOrigin[pIdx->idxType],
  100168. pIdx->pPartIdxWhere!=0);
  100169. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  100170. }
  100171. }
  100172. }
  100173. break;
  100174. case PragTyp_DATABASE_LIST: {
  100175. static const char *azCol[] = { "seq", "name", "file" };
  100176. int i;
  100177. pParse->nMem = 3;
  100178. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  100179. for(i=0; i<db->nDb; i++){
  100180. if( db->aDb[i].pBt==0 ) continue;
  100181. assert( db->aDb[i].zName!=0 );
  100182. sqlite3VdbeMultiLoad(v, 1, "iss",
  100183. i,
  100184. db->aDb[i].zName,
  100185. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  100186. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  100187. }
  100188. }
  100189. break;
  100190. case PragTyp_COLLATION_LIST: {
  100191. static const char *azCol[] = { "seq", "name" };
  100192. int i = 0;
  100193. HashElem *p;
  100194. pParse->nMem = 2;
  100195. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  100196. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  100197. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  100198. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  100199. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  100200. }
  100201. }
  100202. break;
  100203. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  100204. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100205. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  100206. FKey *pFK;
  100207. Table *pTab;
  100208. pTab = sqlite3FindTable(db, zRight, zDb);
  100209. if( pTab ){
  100210. v = sqlite3GetVdbe(pParse);
  100211. pFK = pTab->pFKey;
  100212. if( pFK ){
  100213. static const char *azCol[] = {
  100214. "id", "seq", "table", "from", "to", "on_update", "on_delete",
  100215. "match"
  100216. };
  100217. int i = 0;
  100218. pParse->nMem = 8;
  100219. sqlite3CodeVerifySchema(pParse, iDb);
  100220. setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
  100221. while(pFK){
  100222. int j;
  100223. for(j=0; j<pFK->nCol; j++){
  100224. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  100225. i,
  100226. j,
  100227. pFK->zTo,
  100228. pTab->aCol[pFK->aCol[j].iFrom].zName,
  100229. pFK->aCol[j].zCol,
  100230. actionName(pFK->aAction[1]), /* ON UPDATE */
  100231. actionName(pFK->aAction[0]), /* ON DELETE */
  100232. "NONE");
  100233. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  100234. }
  100235. ++i;
  100236. pFK = pFK->pNextFrom;
  100237. }
  100238. }
  100239. }
  100240. }
  100241. break;
  100242. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  100243. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100244. #ifndef SQLITE_OMIT_TRIGGER
  100245. case PragTyp_FOREIGN_KEY_CHECK: {
  100246. FKey *pFK; /* A foreign key constraint */
  100247. Table *pTab; /* Child table contain "REFERENCES" keyword */
  100248. Table *pParent; /* Parent table that child points to */
  100249. Index *pIdx; /* Index in the parent table */
  100250. int i; /* Loop counter: Foreign key number for pTab */
  100251. int j; /* Loop counter: Field of the foreign key */
  100252. HashElem *k; /* Loop counter: Next table in schema */
  100253. int x; /* result variable */
  100254. int regResult; /* 3 registers to hold a result row */
  100255. int regKey; /* Register to hold key for checking the FK */
  100256. int regRow; /* Registers to hold a row from pTab */
  100257. int addrTop; /* Top of a loop checking foreign keys */
  100258. int addrOk; /* Jump here if the key is OK */
  100259. int *aiCols; /* child to parent column mapping */
  100260. static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
  100261. regResult = pParse->nMem+1;
  100262. pParse->nMem += 4;
  100263. regKey = ++pParse->nMem;
  100264. regRow = ++pParse->nMem;
  100265. v = sqlite3GetVdbe(pParse);
  100266. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  100267. sqlite3CodeVerifySchema(pParse, iDb);
  100268. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  100269. while( k ){
  100270. if( zRight ){
  100271. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  100272. k = 0;
  100273. }else{
  100274. pTab = (Table*)sqliteHashData(k);
  100275. k = sqliteHashNext(k);
  100276. }
  100277. if( pTab==0 || pTab->pFKey==0 ) continue;
  100278. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  100279. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  100280. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  100281. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  100282. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  100283. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  100284. if( pParent==0 ) continue;
  100285. pIdx = 0;
  100286. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  100287. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  100288. if( x==0 ){
  100289. if( pIdx==0 ){
  100290. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  100291. }else{
  100292. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  100293. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  100294. }
  100295. }else{
  100296. k = 0;
  100297. break;
  100298. }
  100299. }
  100300. assert( pParse->nErr>0 || pFK==0 );
  100301. if( pFK ) break;
  100302. if( pParse->nTab<i ) pParse->nTab = i;
  100303. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  100304. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  100305. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  100306. pIdx = 0;
  100307. aiCols = 0;
  100308. if( pParent ){
  100309. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  100310. assert( x==0 );
  100311. }
  100312. addrOk = sqlite3VdbeMakeLabel(v);
  100313. if( pParent && pIdx==0 ){
  100314. int iKey = pFK->aCol[0].iFrom;
  100315. assert( iKey>=0 && iKey<pTab->nCol );
  100316. if( iKey!=pTab->iPKey ){
  100317. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  100318. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  100319. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  100320. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  100321. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  100322. }else{
  100323. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  100324. }
  100325. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  100326. sqlite3VdbeGoto(v, addrOk);
  100327. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  100328. }else{
  100329. for(j=0; j<pFK->nCol; j++){
  100330. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  100331. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  100332. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  100333. }
  100334. if( pParent ){
  100335. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  100336. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  100337. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  100338. VdbeCoverage(v);
  100339. }
  100340. }
  100341. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  100342. sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
  100343. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  100344. sqlite3VdbeResolveLabel(v, addrOk);
  100345. sqlite3DbFree(db, aiCols);
  100346. }
  100347. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  100348. sqlite3VdbeJumpHere(v, addrTop);
  100349. }
  100350. }
  100351. break;
  100352. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  100353. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  100354. #ifndef NDEBUG
  100355. case PragTyp_PARSER_TRACE: {
  100356. if( zRight ){
  100357. if( sqlite3GetBoolean(zRight, 0) ){
  100358. sqlite3ParserTrace(stderr, "parser: ");
  100359. }else{
  100360. sqlite3ParserTrace(0, 0);
  100361. }
  100362. }
  100363. }
  100364. break;
  100365. #endif
  100366. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  100367. ** used will be case sensitive or not depending on the RHS.
  100368. */
  100369. case PragTyp_CASE_SENSITIVE_LIKE: {
  100370. if( zRight ){
  100371. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  100372. }
  100373. }
  100374. break;
  100375. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  100376. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  100377. #endif
  100378. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  100379. /* Pragma "quick_check" is reduced version of
  100380. ** integrity_check designed to detect most database corruption
  100381. ** without most of the overhead of a full integrity-check.
  100382. */
  100383. case PragTyp_INTEGRITY_CHECK: {
  100384. int i, j, addr, mxErr;
  100385. /* Code that appears at the end of the integrity check. If no error
  100386. ** messages have been generated, output OK. Otherwise output the
  100387. ** error message
  100388. */
  100389. static const int iLn = VDBE_OFFSET_LINENO(2);
  100390. static const VdbeOpList endCode[] = {
  100391. { OP_AddImm, 1, 0, 0}, /* 0 */
  100392. { OP_If, 1, 0, 0}, /* 1 */
  100393. { OP_String8, 0, 3, 0}, /* 2 */
  100394. { OP_ResultRow, 3, 1, 0},
  100395. };
  100396. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  100397. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  100398. ** then iDb is set to the index of the database identified by <db>.
  100399. ** In this case, the integrity of database iDb only is verified by
  100400. ** the VDBE created below.
  100401. **
  100402. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  100403. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  100404. ** to -1 here, to indicate that the VDBE should verify the integrity
  100405. ** of all attached databases. */
  100406. assert( iDb>=0 );
  100407. assert( iDb==0 || pId2->z );
  100408. if( pId2->z==0 ) iDb = -1;
  100409. /* Initialize the VDBE program */
  100410. pParse->nMem = 6;
  100411. setOneColumnName(v, "integrity_check");
  100412. /* Set the maximum error count */
  100413. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  100414. if( zRight ){
  100415. sqlite3GetInt32(zRight, &mxErr);
  100416. if( mxErr<=0 ){
  100417. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  100418. }
  100419. }
  100420. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  100421. /* Do an integrity check on each database file */
  100422. for(i=0; i<db->nDb; i++){
  100423. HashElem *x;
  100424. Hash *pTbls;
  100425. int cnt = 0;
  100426. if( OMIT_TEMPDB && i==1 ) continue;
  100427. if( iDb>=0 && i!=iDb ) continue;
  100428. sqlite3CodeVerifySchema(pParse, i);
  100429. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  100430. VdbeCoverage(v);
  100431. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  100432. sqlite3VdbeJumpHere(v, addr);
  100433. /* Do an integrity check of the B-Tree
  100434. **
  100435. ** Begin by filling registers 2, 3, ... with the root pages numbers
  100436. ** for all tables and indices in the database.
  100437. */
  100438. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  100439. pTbls = &db->aDb[i].pSchema->tblHash;
  100440. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  100441. Table *pTab = sqliteHashData(x);
  100442. Index *pIdx;
  100443. if( HasRowid(pTab) ){
  100444. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  100445. VdbeComment((v, "%s", pTab->zName));
  100446. cnt++;
  100447. }
  100448. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  100449. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  100450. VdbeComment((v, "%s", pIdx->zName));
  100451. cnt++;
  100452. }
  100453. }
  100454. /* Make sure sufficient number of registers have been allocated */
  100455. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  100456. /* Do the b-tree integrity checks */
  100457. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  100458. sqlite3VdbeChangeP5(v, (u8)i);
  100459. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  100460. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  100461. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  100462. P4_DYNAMIC);
  100463. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  100464. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  100465. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  100466. sqlite3VdbeJumpHere(v, addr);
  100467. /* Make sure all the indices are constructed correctly.
  100468. */
  100469. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  100470. Table *pTab = sqliteHashData(x);
  100471. Index *pIdx, *pPk;
  100472. Index *pPrior = 0;
  100473. int loopTop;
  100474. int iDataCur, iIdxCur;
  100475. int r1 = -1;
  100476. if( pTab->pIndex==0 ) continue;
  100477. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  100478. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  100479. VdbeCoverage(v);
  100480. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  100481. sqlite3VdbeJumpHere(v, addr);
  100482. sqlite3ExprCacheClear(pParse);
  100483. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  100484. 1, 0, &iDataCur, &iIdxCur);
  100485. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  100486. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  100487. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  100488. }
  100489. pParse->nMem = MAX(pParse->nMem, 8+j);
  100490. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  100491. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  100492. /* Verify that all NOT NULL columns really are NOT NULL */
  100493. for(j=0; j<pTab->nCol; j++){
  100494. char *zErr;
  100495. int jmp2, jmp3;
  100496. if( j==pTab->iPKey ) continue;
  100497. if( pTab->aCol[j].notNull==0 ) continue;
  100498. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  100499. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  100500. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  100501. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  100502. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  100503. pTab->aCol[j].zName);
  100504. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  100505. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  100506. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  100507. sqlite3VdbeAddOp0(v, OP_Halt);
  100508. sqlite3VdbeJumpHere(v, jmp2);
  100509. sqlite3VdbeJumpHere(v, jmp3);
  100510. }
  100511. /* Validate index entries for the current row */
  100512. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  100513. int jmp2, jmp3, jmp4, jmp5;
  100514. int ckUniq = sqlite3VdbeMakeLabel(v);
  100515. if( pPk==pIdx ) continue;
  100516. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  100517. pPrior, r1);
  100518. pPrior = pIdx;
  100519. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  100520. /* Verify that an index entry exists for the current table row */
  100521. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  100522. pIdx->nColumn); VdbeCoverage(v);
  100523. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  100524. sqlite3VdbeLoadString(v, 3, "row ");
  100525. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  100526. sqlite3VdbeLoadString(v, 4, " missing from index ");
  100527. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  100528. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  100529. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  100530. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  100531. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  100532. sqlite3VdbeAddOp0(v, OP_Halt);
  100533. sqlite3VdbeJumpHere(v, jmp2);
  100534. /* For UNIQUE indexes, verify that only one entry exists with the
  100535. ** current key. The entry is unique if (1) any column is NULL
  100536. ** or (2) the next entry has a different key */
  100537. if( IsUniqueIndex(pIdx) ){
  100538. int uniqOk = sqlite3VdbeMakeLabel(v);
  100539. int jmp6;
  100540. int kk;
  100541. for(kk=0; kk<pIdx->nKeyCol; kk++){
  100542. int iCol = pIdx->aiColumn[kk];
  100543. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  100544. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  100545. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  100546. VdbeCoverage(v);
  100547. }
  100548. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  100549. sqlite3VdbeGoto(v, uniqOk);
  100550. sqlite3VdbeJumpHere(v, jmp6);
  100551. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  100552. pIdx->nKeyCol); VdbeCoverage(v);
  100553. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  100554. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  100555. sqlite3VdbeGoto(v, jmp5);
  100556. sqlite3VdbeResolveLabel(v, uniqOk);
  100557. }
  100558. sqlite3VdbeJumpHere(v, jmp4);
  100559. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  100560. }
  100561. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  100562. sqlite3VdbeJumpHere(v, loopTop-1);
  100563. #ifndef SQLITE_OMIT_BTREECOUNT
  100564. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  100565. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  100566. if( pPk==pIdx ) continue;
  100567. addr = sqlite3VdbeCurrentAddr(v);
  100568. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  100569. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  100570. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  100571. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  100572. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  100573. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  100574. sqlite3VdbeLoadString(v, 3, pIdx->zName);
  100575. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  100576. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  100577. }
  100578. #endif /* SQLITE_OMIT_BTREECOUNT */
  100579. }
  100580. }
  100581. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  100582. sqlite3VdbeChangeP2(v, addr, -mxErr);
  100583. sqlite3VdbeJumpHere(v, addr+1);
  100584. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  100585. }
  100586. break;
  100587. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  100588. #ifndef SQLITE_OMIT_UTF16
  100589. /*
  100590. ** PRAGMA encoding
  100591. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  100592. **
  100593. ** In its first form, this pragma returns the encoding of the main
  100594. ** database. If the database is not initialized, it is initialized now.
  100595. **
  100596. ** The second form of this pragma is a no-op if the main database file
  100597. ** has not already been initialized. In this case it sets the default
  100598. ** encoding that will be used for the main database file if a new file
  100599. ** is created. If an existing main database file is opened, then the
  100600. ** default text encoding for the existing database is used.
  100601. **
  100602. ** In all cases new databases created using the ATTACH command are
  100603. ** created to use the same default text encoding as the main database. If
  100604. ** the main database has not been initialized and/or created when ATTACH
  100605. ** is executed, this is done before the ATTACH operation.
  100606. **
  100607. ** In the second form this pragma sets the text encoding to be used in
  100608. ** new database files created using this database handle. It is only
  100609. ** useful if invoked immediately after the main database i
  100610. */
  100611. case PragTyp_ENCODING: {
  100612. static const struct EncName {
  100613. char *zName;
  100614. u8 enc;
  100615. } encnames[] = {
  100616. { "UTF8", SQLITE_UTF8 },
  100617. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  100618. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  100619. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  100620. { "UTF16le", SQLITE_UTF16LE },
  100621. { "UTF16be", SQLITE_UTF16BE },
  100622. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  100623. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  100624. { 0, 0 }
  100625. };
  100626. const struct EncName *pEnc;
  100627. if( !zRight ){ /* "PRAGMA encoding" */
  100628. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  100629. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  100630. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  100631. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  100632. returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
  100633. }else{ /* "PRAGMA encoding = XXX" */
  100634. /* Only change the value of sqlite.enc if the database handle is not
  100635. ** initialized. If the main database exists, the new sqlite.enc value
  100636. ** will be overwritten when the schema is next loaded. If it does not
  100637. ** already exists, it will be created to use the new encoding value.
  100638. */
  100639. if(
  100640. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  100641. DbHasProperty(db, 0, DB_Empty)
  100642. ){
  100643. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  100644. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  100645. SCHEMA_ENC(db) = ENC(db) =
  100646. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  100647. break;
  100648. }
  100649. }
  100650. if( !pEnc->zName ){
  100651. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  100652. }
  100653. }
  100654. }
  100655. }
  100656. break;
  100657. #endif /* SQLITE_OMIT_UTF16 */
  100658. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  100659. /*
  100660. ** PRAGMA [database.]schema_version
  100661. ** PRAGMA [database.]schema_version = <integer>
  100662. **
  100663. ** PRAGMA [database.]user_version
  100664. ** PRAGMA [database.]user_version = <integer>
  100665. **
  100666. ** PRAGMA [database.]freelist_count = <integer>
  100667. **
  100668. ** PRAGMA [database.]application_id
  100669. ** PRAGMA [database.]application_id = <integer>
  100670. **
  100671. ** The pragma's schema_version and user_version are used to set or get
  100672. ** the value of the schema-version and user-version, respectively. Both
  100673. ** the schema-version and the user-version are 32-bit signed integers
  100674. ** stored in the database header.
  100675. **
  100676. ** The schema-cookie is usually only manipulated internally by SQLite. It
  100677. ** is incremented by SQLite whenever the database schema is modified (by
  100678. ** creating or dropping a table or index). The schema version is used by
  100679. ** SQLite each time a query is executed to ensure that the internal cache
  100680. ** of the schema used when compiling the SQL query matches the schema of
  100681. ** the database against which the compiled query is actually executed.
  100682. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  100683. ** the schema-version is potentially dangerous and may lead to program
  100684. ** crashes or database corruption. Use with caution!
  100685. **
  100686. ** The user-version is not used internally by SQLite. It may be used by
  100687. ** applications for any purpose.
  100688. */
  100689. case PragTyp_HEADER_VALUE: {
  100690. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  100691. sqlite3VdbeUsesBtree(v, iDb);
  100692. if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
  100693. /* Write the specified cookie value */
  100694. static const VdbeOpList setCookie[] = {
  100695. { OP_Transaction, 0, 1, 0}, /* 0 */
  100696. { OP_Integer, 0, 1, 0}, /* 1 */
  100697. { OP_SetCookie, 0, 0, 1}, /* 2 */
  100698. };
  100699. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  100700. sqlite3VdbeChangeP1(v, addr, iDb);
  100701. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  100702. sqlite3VdbeChangeP1(v, addr+2, iDb);
  100703. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  100704. }else{
  100705. /* Read the specified cookie value */
  100706. static const VdbeOpList readCookie[] = {
  100707. { OP_Transaction, 0, 0, 0}, /* 0 */
  100708. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  100709. { OP_ResultRow, 1, 1, 0}
  100710. };
  100711. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  100712. sqlite3VdbeChangeP1(v, addr, iDb);
  100713. sqlite3VdbeChangeP1(v, addr+1, iDb);
  100714. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  100715. sqlite3VdbeSetNumCols(v, 1);
  100716. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  100717. }
  100718. }
  100719. break;
  100720. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  100721. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  100722. /*
  100723. ** PRAGMA compile_options
  100724. **
  100725. ** Return the names of all compile-time options used in this build,
  100726. ** one option per row.
  100727. */
  100728. case PragTyp_COMPILE_OPTIONS: {
  100729. int i = 0;
  100730. const char *zOpt;
  100731. pParse->nMem = 1;
  100732. setOneColumnName(v, "compile_option");
  100733. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  100734. sqlite3VdbeLoadString(v, 1, zOpt);
  100735. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  100736. }
  100737. }
  100738. break;
  100739. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  100740. #ifndef SQLITE_OMIT_WAL
  100741. /*
  100742. ** PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
  100743. **
  100744. ** Checkpoint the database.
  100745. */
  100746. case PragTyp_WAL_CHECKPOINT: {
  100747. static const char *azCol[] = { "busy", "log", "checkpointed" };
  100748. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  100749. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  100750. if( zRight ){
  100751. if( sqlite3StrICmp(zRight, "full")==0 ){
  100752. eMode = SQLITE_CHECKPOINT_FULL;
  100753. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  100754. eMode = SQLITE_CHECKPOINT_RESTART;
  100755. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  100756. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  100757. }
  100758. }
  100759. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  100760. pParse->nMem = 3;
  100761. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  100762. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  100763. }
  100764. break;
  100765. /*
  100766. ** PRAGMA wal_autocheckpoint
  100767. ** PRAGMA wal_autocheckpoint = N
  100768. **
  100769. ** Configure a database connection to automatically checkpoint a database
  100770. ** after accumulating N frames in the log. Or query for the current value
  100771. ** of N.
  100772. */
  100773. case PragTyp_WAL_AUTOCHECKPOINT: {
  100774. if( zRight ){
  100775. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  100776. }
  100777. returnSingleInt(v, "wal_autocheckpoint",
  100778. db->xWalCallback==sqlite3WalDefaultHook ?
  100779. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  100780. }
  100781. break;
  100782. #endif
  100783. /*
  100784. ** PRAGMA shrink_memory
  100785. **
  100786. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  100787. ** connection on which it is invoked to free up as much memory as it
  100788. ** can, by calling sqlite3_db_release_memory().
  100789. */
  100790. case PragTyp_SHRINK_MEMORY: {
  100791. sqlite3_db_release_memory(db);
  100792. break;
  100793. }
  100794. /*
  100795. ** PRAGMA busy_timeout
  100796. ** PRAGMA busy_timeout = N
  100797. **
  100798. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  100799. ** if one is set. If no busy handler or a different busy handler is set
  100800. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  100801. ** disables the timeout.
  100802. */
  100803. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  100804. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  100805. if( zRight ){
  100806. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  100807. }
  100808. returnSingleInt(v, "timeout", db->busyTimeout);
  100809. break;
  100810. }
  100811. /*
  100812. ** PRAGMA soft_heap_limit
  100813. ** PRAGMA soft_heap_limit = N
  100814. **
  100815. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  100816. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  100817. ** specified and is a non-negative integer.
  100818. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  100819. ** returns the same integer that would be returned by the
  100820. ** sqlite3_soft_heap_limit64(-1) C-language function.
  100821. */
  100822. case PragTyp_SOFT_HEAP_LIMIT: {
  100823. sqlite3_int64 N;
  100824. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  100825. sqlite3_soft_heap_limit64(N);
  100826. }
  100827. returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  100828. break;
  100829. }
  100830. /*
  100831. ** PRAGMA threads
  100832. ** PRAGMA threads = N
  100833. **
  100834. ** Configure the maximum number of worker threads. Return the new
  100835. ** maximum, which might be less than requested.
  100836. */
  100837. case PragTyp_THREADS: {
  100838. sqlite3_int64 N;
  100839. if( zRight
  100840. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  100841. && N>=0
  100842. ){
  100843. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  100844. }
  100845. returnSingleInt(v, "threads",
  100846. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  100847. break;
  100848. }
  100849. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  100850. /*
  100851. ** Report the current state of file logs for all databases
  100852. */
  100853. case PragTyp_LOCK_STATUS: {
  100854. static const char *const azLockName[] = {
  100855. "unlocked", "shared", "reserved", "pending", "exclusive"
  100856. };
  100857. static const char *azCol[] = { "database", "status" };
  100858. int i;
  100859. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  100860. pParse->nMem = 2;
  100861. for(i=0; i<db->nDb; i++){
  100862. Btree *pBt;
  100863. const char *zState = "unknown";
  100864. int j;
  100865. if( db->aDb[i].zName==0 ) continue;
  100866. pBt = db->aDb[i].pBt;
  100867. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  100868. zState = "closed";
  100869. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  100870. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  100871. zState = azLockName[j];
  100872. }
  100873. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
  100874. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  100875. }
  100876. break;
  100877. }
  100878. #endif
  100879. #ifdef SQLITE_HAS_CODEC
  100880. case PragTyp_KEY: {
  100881. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  100882. break;
  100883. }
  100884. case PragTyp_REKEY: {
  100885. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  100886. break;
  100887. }
  100888. case PragTyp_HEXKEY: {
  100889. if( zRight ){
  100890. u8 iByte;
  100891. int i;
  100892. char zKey[40];
  100893. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  100894. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  100895. if( (i&1)!=0 ) zKey[i/2] = iByte;
  100896. }
  100897. if( (zLeft[3] & 0xf)==0xb ){
  100898. sqlite3_key_v2(db, zDb, zKey, i/2);
  100899. }else{
  100900. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  100901. }
  100902. }
  100903. break;
  100904. }
  100905. #endif
  100906. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  100907. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  100908. #ifdef SQLITE_HAS_CODEC
  100909. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  100910. sqlite3_activate_see(&zRight[4]);
  100911. }
  100912. #endif
  100913. #ifdef SQLITE_ENABLE_CEROD
  100914. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  100915. sqlite3_activate_cerod(&zRight[6]);
  100916. }
  100917. #endif
  100918. }
  100919. break;
  100920. #endif
  100921. } /* End of the PRAGMA switch */
  100922. pragma_out:
  100923. sqlite3DbFree(db, zLeft);
  100924. sqlite3DbFree(db, zRight);
  100925. }
  100926. #endif /* SQLITE_OMIT_PRAGMA */
  100927. /************** End of pragma.c **********************************************/
  100928. /************** Begin file prepare.c *****************************************/
  100929. /*
  100930. ** 2005 May 25
  100931. **
  100932. ** The author disclaims copyright to this source code. In place of
  100933. ** a legal notice, here is a blessing:
  100934. **
  100935. ** May you do good and not evil.
  100936. ** May you find forgiveness for yourself and forgive others.
  100937. ** May you share freely, never taking more than you give.
  100938. **
  100939. *************************************************************************
  100940. ** This file contains the implementation of the sqlite3_prepare()
  100941. ** interface, and routines that contribute to loading the database schema
  100942. ** from disk.
  100943. */
  100944. /* #include "sqliteInt.h" */
  100945. /*
  100946. ** Fill the InitData structure with an error message that indicates
  100947. ** that the database is corrupt.
  100948. */
  100949. static void corruptSchema(
  100950. InitData *pData, /* Initialization context */
  100951. const char *zObj, /* Object being parsed at the point of error */
  100952. const char *zExtra /* Error information */
  100953. ){
  100954. sqlite3 *db = pData->db;
  100955. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  100956. char *z;
  100957. if( zObj==0 ) zObj = "?";
  100958. z = sqlite3_mprintf("malformed database schema (%s)", zObj);
  100959. if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
  100960. sqlite3DbFree(db, *pData->pzErrMsg);
  100961. *pData->pzErrMsg = z;
  100962. if( z==0 ) db->mallocFailed = 1;
  100963. }
  100964. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  100965. }
  100966. /*
  100967. ** This is the callback routine for the code that initializes the
  100968. ** database. See sqlite3Init() below for additional information.
  100969. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  100970. **
  100971. ** Each callback contains the following information:
  100972. **
  100973. ** argv[0] = name of thing being created
  100974. ** argv[1] = root page number for table or index. 0 for trigger or view.
  100975. ** argv[2] = SQL text for the CREATE statement.
  100976. **
  100977. */
  100978. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  100979. InitData *pData = (InitData*)pInit;
  100980. sqlite3 *db = pData->db;
  100981. int iDb = pData->iDb;
  100982. assert( argc==3 );
  100983. UNUSED_PARAMETER2(NotUsed, argc);
  100984. assert( sqlite3_mutex_held(db->mutex) );
  100985. DbClearProperty(db, iDb, DB_Empty);
  100986. if( db->mallocFailed ){
  100987. corruptSchema(pData, argv[0], 0);
  100988. return 1;
  100989. }
  100990. assert( iDb>=0 && iDb<db->nDb );
  100991. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  100992. if( argv[1]==0 ){
  100993. corruptSchema(pData, argv[0], 0);
  100994. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  100995. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  100996. ** But because db->init.busy is set to 1, no VDBE code is generated
  100997. ** or executed. All the parser does is build the internal data
  100998. ** structures that describe the table, index, or view.
  100999. */
  101000. int rc;
  101001. sqlite3_stmt *pStmt;
  101002. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  101003. assert( db->init.busy );
  101004. db->init.iDb = iDb;
  101005. db->init.newTnum = sqlite3Atoi(argv[1]);
  101006. db->init.orphanTrigger = 0;
  101007. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  101008. rc = db->errCode;
  101009. assert( (rc&0xFF)==(rcp&0xFF) );
  101010. db->init.iDb = 0;
  101011. if( SQLITE_OK!=rc ){
  101012. if( db->init.orphanTrigger ){
  101013. assert( iDb==1 );
  101014. }else{
  101015. pData->rc = rc;
  101016. if( rc==SQLITE_NOMEM ){
  101017. db->mallocFailed = 1;
  101018. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  101019. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  101020. }
  101021. }
  101022. }
  101023. sqlite3_finalize(pStmt);
  101024. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  101025. corruptSchema(pData, argv[0], 0);
  101026. }else{
  101027. /* If the SQL column is blank it means this is an index that
  101028. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  101029. ** constraint for a CREATE TABLE. The index should have already
  101030. ** been created when we processed the CREATE TABLE. All we have
  101031. ** to do here is record the root page number for that index.
  101032. */
  101033. Index *pIndex;
  101034. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  101035. if( pIndex==0 ){
  101036. /* This can occur if there exists an index on a TEMP table which
  101037. ** has the same name as another index on a permanent index. Since
  101038. ** the permanent table is hidden by the TEMP table, we can also
  101039. ** safely ignore the index on the permanent table.
  101040. */
  101041. /* Do Nothing */;
  101042. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  101043. corruptSchema(pData, argv[0], "invalid rootpage");
  101044. }
  101045. }
  101046. return 0;
  101047. }
  101048. /*
  101049. ** Attempt to read the database schema and initialize internal
  101050. ** data structures for a single database file. The index of the
  101051. ** database file is given by iDb. iDb==0 is used for the main
  101052. ** database. iDb==1 should never be used. iDb>=2 is used for
  101053. ** auxiliary databases. Return one of the SQLITE_ error codes to
  101054. ** indicate success or failure.
  101055. */
  101056. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  101057. int rc;
  101058. int i;
  101059. #ifndef SQLITE_OMIT_DEPRECATED
  101060. int size;
  101061. #endif
  101062. Table *pTab;
  101063. Db *pDb;
  101064. char const *azArg[4];
  101065. int meta[5];
  101066. InitData initData;
  101067. char const *zMasterSchema;
  101068. char const *zMasterName;
  101069. int openedTransaction = 0;
  101070. /*
  101071. ** The master database table has a structure like this
  101072. */
  101073. static const char master_schema[] =
  101074. "CREATE TABLE sqlite_master(\n"
  101075. " type text,\n"
  101076. " name text,\n"
  101077. " tbl_name text,\n"
  101078. " rootpage integer,\n"
  101079. " sql text\n"
  101080. ")"
  101081. ;
  101082. #ifndef SQLITE_OMIT_TEMPDB
  101083. static const char temp_master_schema[] =
  101084. "CREATE TEMP TABLE sqlite_temp_master(\n"
  101085. " type text,\n"
  101086. " name text,\n"
  101087. " tbl_name text,\n"
  101088. " rootpage integer,\n"
  101089. " sql text\n"
  101090. ")"
  101091. ;
  101092. #else
  101093. #define temp_master_schema 0
  101094. #endif
  101095. assert( iDb>=0 && iDb<db->nDb );
  101096. assert( db->aDb[iDb].pSchema );
  101097. assert( sqlite3_mutex_held(db->mutex) );
  101098. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  101099. /* zMasterSchema and zInitScript are set to point at the master schema
  101100. ** and initialisation script appropriate for the database being
  101101. ** initialized. zMasterName is the name of the master table.
  101102. */
  101103. if( !OMIT_TEMPDB && iDb==1 ){
  101104. zMasterSchema = temp_master_schema;
  101105. }else{
  101106. zMasterSchema = master_schema;
  101107. }
  101108. zMasterName = SCHEMA_TABLE(iDb);
  101109. /* Construct the schema tables. */
  101110. azArg[0] = zMasterName;
  101111. azArg[1] = "1";
  101112. azArg[2] = zMasterSchema;
  101113. azArg[3] = 0;
  101114. initData.db = db;
  101115. initData.iDb = iDb;
  101116. initData.rc = SQLITE_OK;
  101117. initData.pzErrMsg = pzErrMsg;
  101118. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  101119. if( initData.rc ){
  101120. rc = initData.rc;
  101121. goto error_out;
  101122. }
  101123. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  101124. if( ALWAYS(pTab) ){
  101125. pTab->tabFlags |= TF_Readonly;
  101126. }
  101127. /* Create a cursor to hold the database open
  101128. */
  101129. pDb = &db->aDb[iDb];
  101130. if( pDb->pBt==0 ){
  101131. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  101132. DbSetProperty(db, 1, DB_SchemaLoaded);
  101133. }
  101134. return SQLITE_OK;
  101135. }
  101136. /* If there is not already a read-only (or read-write) transaction opened
  101137. ** on the b-tree database, open one now. If a transaction is opened, it
  101138. ** will be closed before this function returns. */
  101139. sqlite3BtreeEnter(pDb->pBt);
  101140. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  101141. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  101142. if( rc!=SQLITE_OK ){
  101143. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  101144. goto initone_error_out;
  101145. }
  101146. openedTransaction = 1;
  101147. }
  101148. /* Get the database meta information.
  101149. **
  101150. ** Meta values are as follows:
  101151. ** meta[0] Schema cookie. Changes with each schema change.
  101152. ** meta[1] File format of schema layer.
  101153. ** meta[2] Size of the page cache.
  101154. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  101155. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  101156. ** meta[5] User version
  101157. ** meta[6] Incremental vacuum mode
  101158. ** meta[7] unused
  101159. ** meta[8] unused
  101160. ** meta[9] unused
  101161. **
  101162. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  101163. ** the possible values of meta[4].
  101164. */
  101165. for(i=0; i<ArraySize(meta); i++){
  101166. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  101167. }
  101168. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  101169. /* If opening a non-empty database, check the text encoding. For the
  101170. ** main database, set sqlite3.enc to the encoding of the main database.
  101171. ** For an attached db, it is an error if the encoding is not the same
  101172. ** as sqlite3.enc.
  101173. */
  101174. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  101175. if( iDb==0 ){
  101176. #ifndef SQLITE_OMIT_UTF16
  101177. u8 encoding;
  101178. /* If opening the main database, set ENC(db). */
  101179. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  101180. if( encoding==0 ) encoding = SQLITE_UTF8;
  101181. ENC(db) = encoding;
  101182. #else
  101183. ENC(db) = SQLITE_UTF8;
  101184. #endif
  101185. }else{
  101186. /* If opening an attached database, the encoding much match ENC(db) */
  101187. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  101188. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  101189. " text encoding as main database");
  101190. rc = SQLITE_ERROR;
  101191. goto initone_error_out;
  101192. }
  101193. }
  101194. }else{
  101195. DbSetProperty(db, iDb, DB_Empty);
  101196. }
  101197. pDb->pSchema->enc = ENC(db);
  101198. if( pDb->pSchema->cache_size==0 ){
  101199. #ifndef SQLITE_OMIT_DEPRECATED
  101200. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  101201. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  101202. pDb->pSchema->cache_size = size;
  101203. #else
  101204. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  101205. #endif
  101206. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  101207. }
  101208. /*
  101209. ** file_format==1 Version 3.0.0.
  101210. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  101211. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  101212. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  101213. */
  101214. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  101215. if( pDb->pSchema->file_format==0 ){
  101216. pDb->pSchema->file_format = 1;
  101217. }
  101218. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  101219. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  101220. rc = SQLITE_ERROR;
  101221. goto initone_error_out;
  101222. }
  101223. /* Ticket #2804: When we open a database in the newer file format,
  101224. ** clear the legacy_file_format pragma flag so that a VACUUM will
  101225. ** not downgrade the database and thus invalidate any descending
  101226. ** indices that the user might have created.
  101227. */
  101228. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  101229. db->flags &= ~SQLITE_LegacyFileFmt;
  101230. }
  101231. /* Read the schema information out of the schema tables
  101232. */
  101233. assert( db->init.busy );
  101234. {
  101235. char *zSql;
  101236. zSql = sqlite3MPrintf(db,
  101237. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  101238. db->aDb[iDb].zName, zMasterName);
  101239. #ifndef SQLITE_OMIT_AUTHORIZATION
  101240. {
  101241. sqlite3_xauth xAuth;
  101242. xAuth = db->xAuth;
  101243. db->xAuth = 0;
  101244. #endif
  101245. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  101246. #ifndef SQLITE_OMIT_AUTHORIZATION
  101247. db->xAuth = xAuth;
  101248. }
  101249. #endif
  101250. if( rc==SQLITE_OK ) rc = initData.rc;
  101251. sqlite3DbFree(db, zSql);
  101252. #ifndef SQLITE_OMIT_ANALYZE
  101253. if( rc==SQLITE_OK ){
  101254. sqlite3AnalysisLoad(db, iDb);
  101255. }
  101256. #endif
  101257. }
  101258. if( db->mallocFailed ){
  101259. rc = SQLITE_NOMEM;
  101260. sqlite3ResetAllSchemasOfConnection(db);
  101261. }
  101262. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  101263. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  101264. ** the schema loaded, even if errors occurred. In this situation the
  101265. ** current sqlite3_prepare() operation will fail, but the following one
  101266. ** will attempt to compile the supplied statement against whatever subset
  101267. ** of the schema was loaded before the error occurred. The primary
  101268. ** purpose of this is to allow access to the sqlite_master table
  101269. ** even when its contents have been corrupted.
  101270. */
  101271. DbSetProperty(db, iDb, DB_SchemaLoaded);
  101272. rc = SQLITE_OK;
  101273. }
  101274. /* Jump here for an error that occurs after successfully allocating
  101275. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  101276. ** before that point, jump to error_out.
  101277. */
  101278. initone_error_out:
  101279. if( openedTransaction ){
  101280. sqlite3BtreeCommit(pDb->pBt);
  101281. }
  101282. sqlite3BtreeLeave(pDb->pBt);
  101283. error_out:
  101284. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  101285. db->mallocFailed = 1;
  101286. }
  101287. return rc;
  101288. }
  101289. /*
  101290. ** Initialize all database files - the main database file, the file
  101291. ** used to store temporary tables, and any additional database files
  101292. ** created using ATTACH statements. Return a success code. If an
  101293. ** error occurs, write an error message into *pzErrMsg.
  101294. **
  101295. ** After a database is initialized, the DB_SchemaLoaded bit is set
  101296. ** bit is set in the flags field of the Db structure. If the database
  101297. ** file was of zero-length, then the DB_Empty flag is also set.
  101298. */
  101299. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  101300. int i, rc;
  101301. int commit_internal = !(db->flags&SQLITE_InternChanges);
  101302. assert( sqlite3_mutex_held(db->mutex) );
  101303. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  101304. assert( db->init.busy==0 );
  101305. rc = SQLITE_OK;
  101306. db->init.busy = 1;
  101307. ENC(db) = SCHEMA_ENC(db);
  101308. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  101309. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  101310. rc = sqlite3InitOne(db, i, pzErrMsg);
  101311. if( rc ){
  101312. sqlite3ResetOneSchema(db, i);
  101313. }
  101314. }
  101315. /* Once all the other databases have been initialized, load the schema
  101316. ** for the TEMP database. This is loaded last, as the TEMP database
  101317. ** schema may contain references to objects in other databases.
  101318. */
  101319. #ifndef SQLITE_OMIT_TEMPDB
  101320. assert( db->nDb>1 );
  101321. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  101322. rc = sqlite3InitOne(db, 1, pzErrMsg);
  101323. if( rc ){
  101324. sqlite3ResetOneSchema(db, 1);
  101325. }
  101326. }
  101327. #endif
  101328. db->init.busy = 0;
  101329. if( rc==SQLITE_OK && commit_internal ){
  101330. sqlite3CommitInternalChanges(db);
  101331. }
  101332. return rc;
  101333. }
  101334. /*
  101335. ** This routine is a no-op if the database schema is already initialized.
  101336. ** Otherwise, the schema is loaded. An error code is returned.
  101337. */
  101338. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  101339. int rc = SQLITE_OK;
  101340. sqlite3 *db = pParse->db;
  101341. assert( sqlite3_mutex_held(db->mutex) );
  101342. if( !db->init.busy ){
  101343. rc = sqlite3Init(db, &pParse->zErrMsg);
  101344. }
  101345. if( rc!=SQLITE_OK ){
  101346. pParse->rc = rc;
  101347. pParse->nErr++;
  101348. }
  101349. return rc;
  101350. }
  101351. /*
  101352. ** Check schema cookies in all databases. If any cookie is out
  101353. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  101354. ** make no changes to pParse->rc.
  101355. */
  101356. static void schemaIsValid(Parse *pParse){
  101357. sqlite3 *db = pParse->db;
  101358. int iDb;
  101359. int rc;
  101360. int cookie;
  101361. assert( pParse->checkSchema );
  101362. assert( sqlite3_mutex_held(db->mutex) );
  101363. for(iDb=0; iDb<db->nDb; iDb++){
  101364. int openedTransaction = 0; /* True if a transaction is opened */
  101365. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  101366. if( pBt==0 ) continue;
  101367. /* If there is not already a read-only (or read-write) transaction opened
  101368. ** on the b-tree database, open one now. If a transaction is opened, it
  101369. ** will be closed immediately after reading the meta-value. */
  101370. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  101371. rc = sqlite3BtreeBeginTrans(pBt, 0);
  101372. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  101373. db->mallocFailed = 1;
  101374. }
  101375. if( rc!=SQLITE_OK ) return;
  101376. openedTransaction = 1;
  101377. }
  101378. /* Read the schema cookie from the database. If it does not match the
  101379. ** value stored as part of the in-memory schema representation,
  101380. ** set Parse.rc to SQLITE_SCHEMA. */
  101381. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  101382. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101383. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  101384. sqlite3ResetOneSchema(db, iDb);
  101385. pParse->rc = SQLITE_SCHEMA;
  101386. }
  101387. /* Close the transaction, if one was opened. */
  101388. if( openedTransaction ){
  101389. sqlite3BtreeCommit(pBt);
  101390. }
  101391. }
  101392. }
  101393. /*
  101394. ** Convert a schema pointer into the iDb index that indicates
  101395. ** which database file in db->aDb[] the schema refers to.
  101396. **
  101397. ** If the same database is attached more than once, the first
  101398. ** attached database is returned.
  101399. */
  101400. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  101401. int i = -1000000;
  101402. /* If pSchema is NULL, then return -1000000. This happens when code in
  101403. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  101404. ** created by a sub-select). In this case the return value of this
  101405. ** function should never be used.
  101406. **
  101407. ** We return -1000000 instead of the more usual -1 simply because using
  101408. ** -1000000 as the incorrect index into db->aDb[] is much
  101409. ** more likely to cause a segfault than -1 (of course there are assert()
  101410. ** statements too, but it never hurts to play the odds).
  101411. */
  101412. assert( sqlite3_mutex_held(db->mutex) );
  101413. if( pSchema ){
  101414. for(i=0; ALWAYS(i<db->nDb); i++){
  101415. if( db->aDb[i].pSchema==pSchema ){
  101416. break;
  101417. }
  101418. }
  101419. assert( i>=0 && i<db->nDb );
  101420. }
  101421. return i;
  101422. }
  101423. /*
  101424. ** Free all memory allocations in the pParse object
  101425. */
  101426. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  101427. if( pParse ){
  101428. sqlite3 *db = pParse->db;
  101429. sqlite3DbFree(db, pParse->aLabel);
  101430. sqlite3ExprListDelete(db, pParse->pConstExpr);
  101431. }
  101432. }
  101433. /*
  101434. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  101435. */
  101436. static int sqlite3Prepare(
  101437. sqlite3 *db, /* Database handle. */
  101438. const char *zSql, /* UTF-8 encoded SQL statement. */
  101439. int nBytes, /* Length of zSql in bytes. */
  101440. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  101441. Vdbe *pReprepare, /* VM being reprepared */
  101442. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101443. const char **pzTail /* OUT: End of parsed string */
  101444. ){
  101445. Parse *pParse; /* Parsing context */
  101446. char *zErrMsg = 0; /* Error message */
  101447. int rc = SQLITE_OK; /* Result code */
  101448. int i; /* Loop counter */
  101449. /* Allocate the parsing context */
  101450. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  101451. if( pParse==0 ){
  101452. rc = SQLITE_NOMEM;
  101453. goto end_prepare;
  101454. }
  101455. pParse->pReprepare = pReprepare;
  101456. assert( ppStmt && *ppStmt==0 );
  101457. assert( !db->mallocFailed );
  101458. assert( sqlite3_mutex_held(db->mutex) );
  101459. /* Check to verify that it is possible to get a read lock on all
  101460. ** database schemas. The inability to get a read lock indicates that
  101461. ** some other database connection is holding a write-lock, which in
  101462. ** turn means that the other connection has made uncommitted changes
  101463. ** to the schema.
  101464. **
  101465. ** Were we to proceed and prepare the statement against the uncommitted
  101466. ** schema changes and if those schema changes are subsequently rolled
  101467. ** back and different changes are made in their place, then when this
  101468. ** prepared statement goes to run the schema cookie would fail to detect
  101469. ** the schema change. Disaster would follow.
  101470. **
  101471. ** This thread is currently holding mutexes on all Btrees (because
  101472. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  101473. ** is not possible for another thread to start a new schema change
  101474. ** while this routine is running. Hence, we do not need to hold
  101475. ** locks on the schema, we just need to make sure nobody else is
  101476. ** holding them.
  101477. **
  101478. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  101479. ** but it does *not* override schema lock detection, so this all still
  101480. ** works even if READ_UNCOMMITTED is set.
  101481. */
  101482. for(i=0; i<db->nDb; i++) {
  101483. Btree *pBt = db->aDb[i].pBt;
  101484. if( pBt ){
  101485. assert( sqlite3BtreeHoldsMutex(pBt) );
  101486. rc = sqlite3BtreeSchemaLocked(pBt);
  101487. if( rc ){
  101488. const char *zDb = db->aDb[i].zName;
  101489. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  101490. testcase( db->flags & SQLITE_ReadUncommitted );
  101491. goto end_prepare;
  101492. }
  101493. }
  101494. }
  101495. sqlite3VtabUnlockList(db);
  101496. pParse->db = db;
  101497. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  101498. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  101499. char *zSqlCopy;
  101500. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  101501. testcase( nBytes==mxLen );
  101502. testcase( nBytes==mxLen+1 );
  101503. if( nBytes>mxLen ){
  101504. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  101505. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  101506. goto end_prepare;
  101507. }
  101508. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  101509. if( zSqlCopy ){
  101510. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  101511. sqlite3DbFree(db, zSqlCopy);
  101512. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  101513. }else{
  101514. pParse->zTail = &zSql[nBytes];
  101515. }
  101516. }else{
  101517. sqlite3RunParser(pParse, zSql, &zErrMsg);
  101518. }
  101519. assert( 0==pParse->nQueryLoop );
  101520. if( db->mallocFailed ){
  101521. pParse->rc = SQLITE_NOMEM;
  101522. }
  101523. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  101524. if( pParse->checkSchema ){
  101525. schemaIsValid(pParse);
  101526. }
  101527. if( db->mallocFailed ){
  101528. pParse->rc = SQLITE_NOMEM;
  101529. }
  101530. if( pzTail ){
  101531. *pzTail = pParse->zTail;
  101532. }
  101533. rc = pParse->rc;
  101534. #ifndef SQLITE_OMIT_EXPLAIN
  101535. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  101536. static const char * const azColName[] = {
  101537. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  101538. "selectid", "order", "from", "detail"
  101539. };
  101540. int iFirst, mx;
  101541. if( pParse->explain==2 ){
  101542. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  101543. iFirst = 8;
  101544. mx = 12;
  101545. }else{
  101546. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  101547. iFirst = 0;
  101548. mx = 8;
  101549. }
  101550. for(i=iFirst; i<mx; i++){
  101551. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  101552. azColName[i], SQLITE_STATIC);
  101553. }
  101554. }
  101555. #endif
  101556. if( db->init.busy==0 ){
  101557. Vdbe *pVdbe = pParse->pVdbe;
  101558. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  101559. }
  101560. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  101561. sqlite3VdbeFinalize(pParse->pVdbe);
  101562. assert(!(*ppStmt));
  101563. }else{
  101564. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  101565. }
  101566. if( zErrMsg ){
  101567. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  101568. sqlite3DbFree(db, zErrMsg);
  101569. }else{
  101570. sqlite3Error(db, rc);
  101571. }
  101572. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  101573. while( pParse->pTriggerPrg ){
  101574. TriggerPrg *pT = pParse->pTriggerPrg;
  101575. pParse->pTriggerPrg = pT->pNext;
  101576. sqlite3DbFree(db, pT);
  101577. }
  101578. end_prepare:
  101579. sqlite3ParserReset(pParse);
  101580. sqlite3StackFree(db, pParse);
  101581. rc = sqlite3ApiExit(db, rc);
  101582. assert( (rc&db->errMask)==rc );
  101583. return rc;
  101584. }
  101585. static int sqlite3LockAndPrepare(
  101586. sqlite3 *db, /* Database handle. */
  101587. const char *zSql, /* UTF-8 encoded SQL statement. */
  101588. int nBytes, /* Length of zSql in bytes. */
  101589. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  101590. Vdbe *pOld, /* VM being reprepared */
  101591. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101592. const char **pzTail /* OUT: End of parsed string */
  101593. ){
  101594. int rc;
  101595. #ifdef SQLITE_ENABLE_API_ARMOR
  101596. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  101597. #endif
  101598. *ppStmt = 0;
  101599. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  101600. return SQLITE_MISUSE_BKPT;
  101601. }
  101602. sqlite3_mutex_enter(db->mutex);
  101603. sqlite3BtreeEnterAll(db);
  101604. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  101605. if( rc==SQLITE_SCHEMA ){
  101606. sqlite3_finalize(*ppStmt);
  101607. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  101608. }
  101609. sqlite3BtreeLeaveAll(db);
  101610. sqlite3_mutex_leave(db->mutex);
  101611. assert( rc==SQLITE_OK || *ppStmt==0 );
  101612. return rc;
  101613. }
  101614. /*
  101615. ** Rerun the compilation of a statement after a schema change.
  101616. **
  101617. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  101618. ** if the statement cannot be recompiled because another connection has
  101619. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  101620. ** occurs, return SQLITE_SCHEMA.
  101621. */
  101622. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  101623. int rc;
  101624. sqlite3_stmt *pNew;
  101625. const char *zSql;
  101626. sqlite3 *db;
  101627. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  101628. zSql = sqlite3_sql((sqlite3_stmt *)p);
  101629. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  101630. db = sqlite3VdbeDb(p);
  101631. assert( sqlite3_mutex_held(db->mutex) );
  101632. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  101633. if( rc ){
  101634. if( rc==SQLITE_NOMEM ){
  101635. db->mallocFailed = 1;
  101636. }
  101637. assert( pNew==0 );
  101638. return rc;
  101639. }else{
  101640. assert( pNew!=0 );
  101641. }
  101642. sqlite3VdbeSwap((Vdbe*)pNew, p);
  101643. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  101644. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  101645. sqlite3VdbeFinalize((Vdbe*)pNew);
  101646. return SQLITE_OK;
  101647. }
  101648. /*
  101649. ** Two versions of the official API. Legacy and new use. In the legacy
  101650. ** version, the original SQL text is not saved in the prepared statement
  101651. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  101652. ** sqlite3_step(). In the new version, the original SQL text is retained
  101653. ** and the statement is automatically recompiled if an schema change
  101654. ** occurs.
  101655. */
  101656. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  101657. sqlite3 *db, /* Database handle. */
  101658. const char *zSql, /* UTF-8 encoded SQL statement. */
  101659. int nBytes, /* Length of zSql in bytes. */
  101660. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101661. const char **pzTail /* OUT: End of parsed string */
  101662. ){
  101663. int rc;
  101664. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  101665. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  101666. return rc;
  101667. }
  101668. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  101669. sqlite3 *db, /* Database handle. */
  101670. const char *zSql, /* UTF-8 encoded SQL statement. */
  101671. int nBytes, /* Length of zSql in bytes. */
  101672. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101673. const char **pzTail /* OUT: End of parsed string */
  101674. ){
  101675. int rc;
  101676. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  101677. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  101678. return rc;
  101679. }
  101680. #ifndef SQLITE_OMIT_UTF16
  101681. /*
  101682. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  101683. */
  101684. static int sqlite3Prepare16(
  101685. sqlite3 *db, /* Database handle. */
  101686. const void *zSql, /* UTF-16 encoded SQL statement. */
  101687. int nBytes, /* Length of zSql in bytes. */
  101688. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  101689. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101690. const void **pzTail /* OUT: End of parsed string */
  101691. ){
  101692. /* This function currently works by first transforming the UTF-16
  101693. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  101694. ** tricky bit is figuring out the pointer to return in *pzTail.
  101695. */
  101696. char *zSql8;
  101697. const char *zTail8 = 0;
  101698. int rc = SQLITE_OK;
  101699. #ifdef SQLITE_ENABLE_API_ARMOR
  101700. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  101701. #endif
  101702. *ppStmt = 0;
  101703. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  101704. return SQLITE_MISUSE_BKPT;
  101705. }
  101706. if( nBytes>=0 ){
  101707. int sz;
  101708. const char *z = (const char*)zSql;
  101709. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  101710. nBytes = sz;
  101711. }
  101712. sqlite3_mutex_enter(db->mutex);
  101713. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  101714. if( zSql8 ){
  101715. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  101716. }
  101717. if( zTail8 && pzTail ){
  101718. /* If sqlite3_prepare returns a tail pointer, we calculate the
  101719. ** equivalent pointer into the UTF-16 string by counting the unicode
  101720. ** characters between zSql8 and zTail8, and then returning a pointer
  101721. ** the same number of characters into the UTF-16 string.
  101722. */
  101723. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  101724. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  101725. }
  101726. sqlite3DbFree(db, zSql8);
  101727. rc = sqlite3ApiExit(db, rc);
  101728. sqlite3_mutex_leave(db->mutex);
  101729. return rc;
  101730. }
  101731. /*
  101732. ** Two versions of the official API. Legacy and new use. In the legacy
  101733. ** version, the original SQL text is not saved in the prepared statement
  101734. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  101735. ** sqlite3_step(). In the new version, the original SQL text is retained
  101736. ** and the statement is automatically recompiled if an schema change
  101737. ** occurs.
  101738. */
  101739. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  101740. sqlite3 *db, /* Database handle. */
  101741. const void *zSql, /* UTF-16 encoded SQL statement. */
  101742. int nBytes, /* Length of zSql in bytes. */
  101743. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101744. const void **pzTail /* OUT: End of parsed string */
  101745. ){
  101746. int rc;
  101747. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  101748. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  101749. return rc;
  101750. }
  101751. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  101752. sqlite3 *db, /* Database handle. */
  101753. const void *zSql, /* UTF-16 encoded SQL statement. */
  101754. int nBytes, /* Length of zSql in bytes. */
  101755. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  101756. const void **pzTail /* OUT: End of parsed string */
  101757. ){
  101758. int rc;
  101759. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  101760. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  101761. return rc;
  101762. }
  101763. #endif /* SQLITE_OMIT_UTF16 */
  101764. /************** End of prepare.c *********************************************/
  101765. /************** Begin file select.c ******************************************/
  101766. /*
  101767. ** 2001 September 15
  101768. **
  101769. ** The author disclaims copyright to this source code. In place of
  101770. ** a legal notice, here is a blessing:
  101771. **
  101772. ** May you do good and not evil.
  101773. ** May you find forgiveness for yourself and forgive others.
  101774. ** May you share freely, never taking more than you give.
  101775. **
  101776. *************************************************************************
  101777. ** This file contains C code routines that are called by the parser
  101778. ** to handle SELECT statements in SQLite.
  101779. */
  101780. /* #include "sqliteInt.h" */
  101781. /*
  101782. ** Trace output macros
  101783. */
  101784. #if SELECTTRACE_ENABLED
  101785. /***/ int sqlite3SelectTrace = 0;
  101786. # define SELECTTRACE(K,P,S,X) \
  101787. if(sqlite3SelectTrace&(K)) \
  101788. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  101789. (S)->zSelName,(S)),\
  101790. sqlite3DebugPrintf X
  101791. #else
  101792. # define SELECTTRACE(K,P,S,X)
  101793. #endif
  101794. /*
  101795. ** An instance of the following object is used to record information about
  101796. ** how to process the DISTINCT keyword, to simplify passing that information
  101797. ** into the selectInnerLoop() routine.
  101798. */
  101799. typedef struct DistinctCtx DistinctCtx;
  101800. struct DistinctCtx {
  101801. u8 isTnct; /* True if the DISTINCT keyword is present */
  101802. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  101803. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  101804. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  101805. };
  101806. /*
  101807. ** An instance of the following object is used to record information about
  101808. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  101809. */
  101810. typedef struct SortCtx SortCtx;
  101811. struct SortCtx {
  101812. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  101813. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  101814. int iECursor; /* Cursor number for the sorter */
  101815. int regReturn; /* Register holding block-output return address */
  101816. int labelBkOut; /* Start label for the block-output subroutine */
  101817. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  101818. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  101819. };
  101820. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  101821. /*
  101822. ** Delete all the content of a Select structure. Deallocate the structure
  101823. ** itself only if bFree is true.
  101824. */
  101825. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  101826. while( p ){
  101827. Select *pPrior = p->pPrior;
  101828. sqlite3ExprListDelete(db, p->pEList);
  101829. sqlite3SrcListDelete(db, p->pSrc);
  101830. sqlite3ExprDelete(db, p->pWhere);
  101831. sqlite3ExprListDelete(db, p->pGroupBy);
  101832. sqlite3ExprDelete(db, p->pHaving);
  101833. sqlite3ExprListDelete(db, p->pOrderBy);
  101834. sqlite3ExprDelete(db, p->pLimit);
  101835. sqlite3ExprDelete(db, p->pOffset);
  101836. sqlite3WithDelete(db, p->pWith);
  101837. if( bFree ) sqlite3DbFree(db, p);
  101838. p = pPrior;
  101839. bFree = 1;
  101840. }
  101841. }
  101842. /*
  101843. ** Initialize a SelectDest structure.
  101844. */
  101845. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  101846. pDest->eDest = (u8)eDest;
  101847. pDest->iSDParm = iParm;
  101848. pDest->affSdst = 0;
  101849. pDest->iSdst = 0;
  101850. pDest->nSdst = 0;
  101851. }
  101852. /*
  101853. ** Allocate a new Select structure and return a pointer to that
  101854. ** structure.
  101855. */
  101856. SQLITE_PRIVATE Select *sqlite3SelectNew(
  101857. Parse *pParse, /* Parsing context */
  101858. ExprList *pEList, /* which columns to include in the result */
  101859. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  101860. Expr *pWhere, /* the WHERE clause */
  101861. ExprList *pGroupBy, /* the GROUP BY clause */
  101862. Expr *pHaving, /* the HAVING clause */
  101863. ExprList *pOrderBy, /* the ORDER BY clause */
  101864. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  101865. Expr *pLimit, /* LIMIT value. NULL means not used */
  101866. Expr *pOffset /* OFFSET value. NULL means no offset */
  101867. ){
  101868. Select *pNew;
  101869. Select standin;
  101870. sqlite3 *db = pParse->db;
  101871. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  101872. if( pNew==0 ){
  101873. assert( db->mallocFailed );
  101874. pNew = &standin;
  101875. memset(pNew, 0, sizeof(*pNew));
  101876. }
  101877. if( pEList==0 ){
  101878. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  101879. }
  101880. pNew->pEList = pEList;
  101881. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  101882. pNew->pSrc = pSrc;
  101883. pNew->pWhere = pWhere;
  101884. pNew->pGroupBy = pGroupBy;
  101885. pNew->pHaving = pHaving;
  101886. pNew->pOrderBy = pOrderBy;
  101887. pNew->selFlags = selFlags;
  101888. pNew->op = TK_SELECT;
  101889. pNew->pLimit = pLimit;
  101890. pNew->pOffset = pOffset;
  101891. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
  101892. pNew->addrOpenEphm[0] = -1;
  101893. pNew->addrOpenEphm[1] = -1;
  101894. if( db->mallocFailed ) {
  101895. clearSelect(db, pNew, pNew!=&standin);
  101896. pNew = 0;
  101897. }else{
  101898. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  101899. }
  101900. assert( pNew!=&standin );
  101901. return pNew;
  101902. }
  101903. #if SELECTTRACE_ENABLED
  101904. /*
  101905. ** Set the name of a Select object
  101906. */
  101907. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  101908. if( p && zName ){
  101909. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  101910. }
  101911. }
  101912. #endif
  101913. /*
  101914. ** Delete the given Select structure and all of its substructures.
  101915. */
  101916. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  101917. clearSelect(db, p, 1);
  101918. }
  101919. /*
  101920. ** Return a pointer to the right-most SELECT statement in a compound.
  101921. */
  101922. static Select *findRightmost(Select *p){
  101923. while( p->pNext ) p = p->pNext;
  101924. return p;
  101925. }
  101926. /*
  101927. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  101928. ** type of join. Return an integer constant that expresses that type
  101929. ** in terms of the following bit values:
  101930. **
  101931. ** JT_INNER
  101932. ** JT_CROSS
  101933. ** JT_OUTER
  101934. ** JT_NATURAL
  101935. ** JT_LEFT
  101936. ** JT_RIGHT
  101937. **
  101938. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  101939. **
  101940. ** If an illegal or unsupported join type is seen, then still return
  101941. ** a join type, but put an error in the pParse structure.
  101942. */
  101943. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  101944. int jointype = 0;
  101945. Token *apAll[3];
  101946. Token *p;
  101947. /* 0123456789 123456789 123456789 123 */
  101948. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  101949. static const struct {
  101950. u8 i; /* Beginning of keyword text in zKeyText[] */
  101951. u8 nChar; /* Length of the keyword in characters */
  101952. u8 code; /* Join type mask */
  101953. } aKeyword[] = {
  101954. /* natural */ { 0, 7, JT_NATURAL },
  101955. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  101956. /* outer */ { 10, 5, JT_OUTER },
  101957. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  101958. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  101959. /* inner */ { 23, 5, JT_INNER },
  101960. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  101961. };
  101962. int i, j;
  101963. apAll[0] = pA;
  101964. apAll[1] = pB;
  101965. apAll[2] = pC;
  101966. for(i=0; i<3 && apAll[i]; i++){
  101967. p = apAll[i];
  101968. for(j=0; j<ArraySize(aKeyword); j++){
  101969. if( p->n==aKeyword[j].nChar
  101970. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  101971. jointype |= aKeyword[j].code;
  101972. break;
  101973. }
  101974. }
  101975. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  101976. if( j>=ArraySize(aKeyword) ){
  101977. jointype |= JT_ERROR;
  101978. break;
  101979. }
  101980. }
  101981. if(
  101982. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  101983. (jointype & JT_ERROR)!=0
  101984. ){
  101985. const char *zSp = " ";
  101986. assert( pB!=0 );
  101987. if( pC==0 ){ zSp++; }
  101988. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  101989. "%T %T%s%T", pA, pB, zSp, pC);
  101990. jointype = JT_INNER;
  101991. }else if( (jointype & JT_OUTER)!=0
  101992. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  101993. sqlite3ErrorMsg(pParse,
  101994. "RIGHT and FULL OUTER JOINs are not currently supported");
  101995. jointype = JT_INNER;
  101996. }
  101997. return jointype;
  101998. }
  101999. /*
  102000. ** Return the index of a column in a table. Return -1 if the column
  102001. ** is not contained in the table.
  102002. */
  102003. static int columnIndex(Table *pTab, const char *zCol){
  102004. int i;
  102005. for(i=0; i<pTab->nCol; i++){
  102006. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  102007. }
  102008. return -1;
  102009. }
  102010. /*
  102011. ** Search the first N tables in pSrc, from left to right, looking for a
  102012. ** table that has a column named zCol.
  102013. **
  102014. ** When found, set *piTab and *piCol to the table index and column index
  102015. ** of the matching column and return TRUE.
  102016. **
  102017. ** If not found, return FALSE.
  102018. */
  102019. static int tableAndColumnIndex(
  102020. SrcList *pSrc, /* Array of tables to search */
  102021. int N, /* Number of tables in pSrc->a[] to search */
  102022. const char *zCol, /* Name of the column we are looking for */
  102023. int *piTab, /* Write index of pSrc->a[] here */
  102024. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  102025. ){
  102026. int i; /* For looping over tables in pSrc */
  102027. int iCol; /* Index of column matching zCol */
  102028. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  102029. for(i=0; i<N; i++){
  102030. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  102031. if( iCol>=0 ){
  102032. if( piTab ){
  102033. *piTab = i;
  102034. *piCol = iCol;
  102035. }
  102036. return 1;
  102037. }
  102038. }
  102039. return 0;
  102040. }
  102041. /*
  102042. ** This function is used to add terms implied by JOIN syntax to the
  102043. ** WHERE clause expression of a SELECT statement. The new term, which
  102044. ** is ANDed with the existing WHERE clause, is of the form:
  102045. **
  102046. ** (tab1.col1 = tab2.col2)
  102047. **
  102048. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  102049. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  102050. ** column iColRight of tab2.
  102051. */
  102052. static void addWhereTerm(
  102053. Parse *pParse, /* Parsing context */
  102054. SrcList *pSrc, /* List of tables in FROM clause */
  102055. int iLeft, /* Index of first table to join in pSrc */
  102056. int iColLeft, /* Index of column in first table */
  102057. int iRight, /* Index of second table in pSrc */
  102058. int iColRight, /* Index of column in second table */
  102059. int isOuterJoin, /* True if this is an OUTER join */
  102060. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  102061. ){
  102062. sqlite3 *db = pParse->db;
  102063. Expr *pE1;
  102064. Expr *pE2;
  102065. Expr *pEq;
  102066. assert( iLeft<iRight );
  102067. assert( pSrc->nSrc>iRight );
  102068. assert( pSrc->a[iLeft].pTab );
  102069. assert( pSrc->a[iRight].pTab );
  102070. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  102071. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  102072. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  102073. if( pEq && isOuterJoin ){
  102074. ExprSetProperty(pEq, EP_FromJoin);
  102075. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  102076. ExprSetVVAProperty(pEq, EP_NoReduce);
  102077. pEq->iRightJoinTable = (i16)pE2->iTable;
  102078. }
  102079. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  102080. }
  102081. /*
  102082. ** Set the EP_FromJoin property on all terms of the given expression.
  102083. ** And set the Expr.iRightJoinTable to iTable for every term in the
  102084. ** expression.
  102085. **
  102086. ** The EP_FromJoin property is used on terms of an expression to tell
  102087. ** the LEFT OUTER JOIN processing logic that this term is part of the
  102088. ** join restriction specified in the ON or USING clause and not a part
  102089. ** of the more general WHERE clause. These terms are moved over to the
  102090. ** WHERE clause during join processing but we need to remember that they
  102091. ** originated in the ON or USING clause.
  102092. **
  102093. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  102094. ** expression depends on table iRightJoinTable even if that table is not
  102095. ** explicitly mentioned in the expression. That information is needed
  102096. ** for cases like this:
  102097. **
  102098. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  102099. **
  102100. ** The where clause needs to defer the handling of the t1.x=5
  102101. ** term until after the t2 loop of the join. In that way, a
  102102. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  102103. ** defer the handling of t1.x=5, it will be processed immediately
  102104. ** after the t1 loop and rows with t1.x!=5 will never appear in
  102105. ** the output, which is incorrect.
  102106. */
  102107. static void setJoinExpr(Expr *p, int iTable){
  102108. while( p ){
  102109. ExprSetProperty(p, EP_FromJoin);
  102110. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  102111. ExprSetVVAProperty(p, EP_NoReduce);
  102112. p->iRightJoinTable = (i16)iTable;
  102113. if( p->op==TK_FUNCTION && p->x.pList ){
  102114. int i;
  102115. for(i=0; i<p->x.pList->nExpr; i++){
  102116. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  102117. }
  102118. }
  102119. setJoinExpr(p->pLeft, iTable);
  102120. p = p->pRight;
  102121. }
  102122. }
  102123. /*
  102124. ** This routine processes the join information for a SELECT statement.
  102125. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  102126. ** NATURAL joins also create extra WHERE clause terms.
  102127. **
  102128. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  102129. ** The left most table is the first entry in Select.pSrc. The right-most
  102130. ** table is the last entry. The join operator is held in the entry to
  102131. ** the left. Thus entry 0 contains the join operator for the join between
  102132. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  102133. ** also attached to the left entry.
  102134. **
  102135. ** This routine returns the number of errors encountered.
  102136. */
  102137. static int sqliteProcessJoin(Parse *pParse, Select *p){
  102138. SrcList *pSrc; /* All tables in the FROM clause */
  102139. int i, j; /* Loop counters */
  102140. struct SrcList_item *pLeft; /* Left table being joined */
  102141. struct SrcList_item *pRight; /* Right table being joined */
  102142. pSrc = p->pSrc;
  102143. pLeft = &pSrc->a[0];
  102144. pRight = &pLeft[1];
  102145. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  102146. Table *pLeftTab = pLeft->pTab;
  102147. Table *pRightTab = pRight->pTab;
  102148. int isOuter;
  102149. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  102150. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  102151. /* When the NATURAL keyword is present, add WHERE clause terms for
  102152. ** every column that the two tables have in common.
  102153. */
  102154. if( pRight->fg.jointype & JT_NATURAL ){
  102155. if( pRight->pOn || pRight->pUsing ){
  102156. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  102157. "an ON or USING clause", 0);
  102158. return 1;
  102159. }
  102160. for(j=0; j<pRightTab->nCol; j++){
  102161. char *zName; /* Name of column in the right table */
  102162. int iLeft; /* Matching left table */
  102163. int iLeftCol; /* Matching column in the left table */
  102164. zName = pRightTab->aCol[j].zName;
  102165. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  102166. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  102167. isOuter, &p->pWhere);
  102168. }
  102169. }
  102170. }
  102171. /* Disallow both ON and USING clauses in the same join
  102172. */
  102173. if( pRight->pOn && pRight->pUsing ){
  102174. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  102175. "clauses in the same join");
  102176. return 1;
  102177. }
  102178. /* Add the ON clause to the end of the WHERE clause, connected by
  102179. ** an AND operator.
  102180. */
  102181. if( pRight->pOn ){
  102182. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  102183. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  102184. pRight->pOn = 0;
  102185. }
  102186. /* Create extra terms on the WHERE clause for each column named
  102187. ** in the USING clause. Example: If the two tables to be joined are
  102188. ** A and B and the USING clause names X, Y, and Z, then add this
  102189. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  102190. ** Report an error if any column mentioned in the USING clause is
  102191. ** not contained in both tables to be joined.
  102192. */
  102193. if( pRight->pUsing ){
  102194. IdList *pList = pRight->pUsing;
  102195. for(j=0; j<pList->nId; j++){
  102196. char *zName; /* Name of the term in the USING clause */
  102197. int iLeft; /* Table on the left with matching column name */
  102198. int iLeftCol; /* Column number of matching column on the left */
  102199. int iRightCol; /* Column number of matching column on the right */
  102200. zName = pList->a[j].zName;
  102201. iRightCol = columnIndex(pRightTab, zName);
  102202. if( iRightCol<0
  102203. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  102204. ){
  102205. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  102206. "not present in both tables", zName);
  102207. return 1;
  102208. }
  102209. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  102210. isOuter, &p->pWhere);
  102211. }
  102212. }
  102213. }
  102214. return 0;
  102215. }
  102216. /* Forward reference */
  102217. static KeyInfo *keyInfoFromExprList(
  102218. Parse *pParse, /* Parsing context */
  102219. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  102220. int iStart, /* Begin with this column of pList */
  102221. int nExtra /* Add this many extra columns to the end */
  102222. );
  102223. /*
  102224. ** Generate code that will push the record in registers regData
  102225. ** through regData+nData-1 onto the sorter.
  102226. */
  102227. static void pushOntoSorter(
  102228. Parse *pParse, /* Parser context */
  102229. SortCtx *pSort, /* Information about the ORDER BY clause */
  102230. Select *pSelect, /* The whole SELECT statement */
  102231. int regData, /* First register holding data to be sorted */
  102232. int regOrigData, /* First register holding data before packing */
  102233. int nData, /* Number of elements in the data array */
  102234. int nPrefixReg /* No. of reg prior to regData available for use */
  102235. ){
  102236. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  102237. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  102238. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  102239. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  102240. int regBase; /* Regs for sorter record */
  102241. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  102242. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  102243. int op; /* Opcode to add sorter record to sorter */
  102244. assert( bSeq==0 || bSeq==1 );
  102245. assert( nData==1 || regData==regOrigData );
  102246. if( nPrefixReg ){
  102247. assert( nPrefixReg==nExpr+bSeq );
  102248. regBase = regData - nExpr - bSeq;
  102249. }else{
  102250. regBase = pParse->nMem + 1;
  102251. pParse->nMem += nBase;
  102252. }
  102253. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  102254. SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
  102255. if( bSeq ){
  102256. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  102257. }
  102258. if( nPrefixReg==0 ){
  102259. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  102260. }
  102261. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  102262. if( nOBSat>0 ){
  102263. int regPrevKey; /* The first nOBSat columns of the previous row */
  102264. int addrFirst; /* Address of the OP_IfNot opcode */
  102265. int addrJmp; /* Address of the OP_Jump opcode */
  102266. VdbeOp *pOp; /* Opcode that opens the sorter */
  102267. int nKey; /* Number of sorting key columns, including OP_Sequence */
  102268. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  102269. regPrevKey = pParse->nMem+1;
  102270. pParse->nMem += pSort->nOBSat;
  102271. nKey = nExpr - pSort->nOBSat + bSeq;
  102272. if( bSeq ){
  102273. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  102274. }else{
  102275. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  102276. }
  102277. VdbeCoverage(v);
  102278. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  102279. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  102280. if( pParse->db->mallocFailed ) return;
  102281. pOp->p2 = nKey + nData;
  102282. pKI = pOp->p4.pKeyInfo;
  102283. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  102284. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  102285. testcase( pKI->nXField>2 );
  102286. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  102287. pKI->nXField-1);
  102288. addrJmp = sqlite3VdbeCurrentAddr(v);
  102289. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  102290. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  102291. pSort->regReturn = ++pParse->nMem;
  102292. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  102293. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  102294. sqlite3VdbeJumpHere(v, addrFirst);
  102295. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  102296. sqlite3VdbeJumpHere(v, addrJmp);
  102297. }
  102298. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  102299. op = OP_SorterInsert;
  102300. }else{
  102301. op = OP_IdxInsert;
  102302. }
  102303. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  102304. if( pSelect->iLimit ){
  102305. int addr;
  102306. int iLimit;
  102307. if( pSelect->iOffset ){
  102308. iLimit = pSelect->iOffset+1;
  102309. }else{
  102310. iLimit = pSelect->iLimit;
  102311. }
  102312. addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
  102313. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  102314. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  102315. sqlite3VdbeJumpHere(v, addr);
  102316. }
  102317. }
  102318. /*
  102319. ** Add code to implement the OFFSET
  102320. */
  102321. static void codeOffset(
  102322. Vdbe *v, /* Generate code into this VM */
  102323. int iOffset, /* Register holding the offset counter */
  102324. int iContinue /* Jump here to skip the current record */
  102325. ){
  102326. if( iOffset>0 ){
  102327. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  102328. VdbeComment((v, "OFFSET"));
  102329. }
  102330. }
  102331. /*
  102332. ** Add code that will check to make sure the N registers starting at iMem
  102333. ** form a distinct entry. iTab is a sorting index that holds previously
  102334. ** seen combinations of the N values. A new entry is made in iTab
  102335. ** if the current N values are new.
  102336. **
  102337. ** A jump to addrRepeat is made and the N+1 values are popped from the
  102338. ** stack if the top N elements are not distinct.
  102339. */
  102340. static void codeDistinct(
  102341. Parse *pParse, /* Parsing and code generating context */
  102342. int iTab, /* A sorting index used to test for distinctness */
  102343. int addrRepeat, /* Jump to here if not distinct */
  102344. int N, /* Number of elements */
  102345. int iMem /* First element */
  102346. ){
  102347. Vdbe *v;
  102348. int r1;
  102349. v = pParse->pVdbe;
  102350. r1 = sqlite3GetTempReg(pParse);
  102351. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  102352. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  102353. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  102354. sqlite3ReleaseTempReg(pParse, r1);
  102355. }
  102356. #ifndef SQLITE_OMIT_SUBQUERY
  102357. /*
  102358. ** Generate an error message when a SELECT is used within a subexpression
  102359. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  102360. ** column. We do this in a subroutine because the error used to occur
  102361. ** in multiple places. (The error only occurs in one place now, but we
  102362. ** retain the subroutine to minimize code disruption.)
  102363. */
  102364. static int checkForMultiColumnSelectError(
  102365. Parse *pParse, /* Parse context. */
  102366. SelectDest *pDest, /* Destination of SELECT results */
  102367. int nExpr /* Number of result columns returned by SELECT */
  102368. ){
  102369. int eDest = pDest->eDest;
  102370. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  102371. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  102372. "a SELECT that is part of an expression");
  102373. return 1;
  102374. }else{
  102375. return 0;
  102376. }
  102377. }
  102378. #endif
  102379. /*
  102380. ** This routine generates the code for the inside of the inner loop
  102381. ** of a SELECT.
  102382. **
  102383. ** If srcTab is negative, then the pEList expressions
  102384. ** are evaluated in order to get the data for this row. If srcTab is
  102385. ** zero or more, then data is pulled from srcTab and pEList is used only
  102386. ** to get number columns and the datatype for each column.
  102387. */
  102388. static void selectInnerLoop(
  102389. Parse *pParse, /* The parser context */
  102390. Select *p, /* The complete select statement being coded */
  102391. ExprList *pEList, /* List of values being extracted */
  102392. int srcTab, /* Pull data from this table */
  102393. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  102394. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  102395. SelectDest *pDest, /* How to dispose of the results */
  102396. int iContinue, /* Jump here to continue with next row */
  102397. int iBreak /* Jump here to break out of the inner loop */
  102398. ){
  102399. Vdbe *v = pParse->pVdbe;
  102400. int i;
  102401. int hasDistinct; /* True if the DISTINCT keyword is present */
  102402. int regResult; /* Start of memory holding result set */
  102403. int eDest = pDest->eDest; /* How to dispose of results */
  102404. int iParm = pDest->iSDParm; /* First argument to disposal method */
  102405. int nResultCol; /* Number of result columns */
  102406. int nPrefixReg = 0; /* Number of extra registers before regResult */
  102407. assert( v );
  102408. assert( pEList!=0 );
  102409. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  102410. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  102411. if( pSort==0 && !hasDistinct ){
  102412. assert( iContinue!=0 );
  102413. codeOffset(v, p->iOffset, iContinue);
  102414. }
  102415. /* Pull the requested columns.
  102416. */
  102417. nResultCol = pEList->nExpr;
  102418. if( pDest->iSdst==0 ){
  102419. if( pSort ){
  102420. nPrefixReg = pSort->pOrderBy->nExpr;
  102421. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  102422. pParse->nMem += nPrefixReg;
  102423. }
  102424. pDest->iSdst = pParse->nMem+1;
  102425. pParse->nMem += nResultCol;
  102426. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  102427. /* This is an error condition that can result, for example, when a SELECT
  102428. ** on the right-hand side of an INSERT contains more result columns than
  102429. ** there are columns in the table on the left. The error will be caught
  102430. ** and reported later. But we need to make sure enough memory is allocated
  102431. ** to avoid other spurious errors in the meantime. */
  102432. pParse->nMem += nResultCol;
  102433. }
  102434. pDest->nSdst = nResultCol;
  102435. regResult = pDest->iSdst;
  102436. if( srcTab>=0 ){
  102437. for(i=0; i<nResultCol; i++){
  102438. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  102439. VdbeComment((v, "%s", pEList->a[i].zName));
  102440. }
  102441. }else if( eDest!=SRT_Exists ){
  102442. /* If the destination is an EXISTS(...) expression, the actual
  102443. ** values returned by the SELECT are not required.
  102444. */
  102445. u8 ecelFlags;
  102446. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  102447. ecelFlags = SQLITE_ECEL_DUP;
  102448. }else{
  102449. ecelFlags = 0;
  102450. }
  102451. sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
  102452. }
  102453. /* If the DISTINCT keyword was present on the SELECT statement
  102454. ** and this row has been seen before, then do not make this row
  102455. ** part of the result.
  102456. */
  102457. if( hasDistinct ){
  102458. switch( pDistinct->eTnctType ){
  102459. case WHERE_DISTINCT_ORDERED: {
  102460. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  102461. int iJump; /* Jump destination */
  102462. int regPrev; /* Previous row content */
  102463. /* Allocate space for the previous row */
  102464. regPrev = pParse->nMem+1;
  102465. pParse->nMem += nResultCol;
  102466. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  102467. ** sets the MEM_Cleared bit on the first register of the
  102468. ** previous value. This will cause the OP_Ne below to always
  102469. ** fail on the first iteration of the loop even if the first
  102470. ** row is all NULLs.
  102471. */
  102472. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  102473. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  102474. pOp->opcode = OP_Null;
  102475. pOp->p1 = 1;
  102476. pOp->p2 = regPrev;
  102477. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  102478. for(i=0; i<nResultCol; i++){
  102479. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  102480. if( i<nResultCol-1 ){
  102481. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  102482. VdbeCoverage(v);
  102483. }else{
  102484. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  102485. VdbeCoverage(v);
  102486. }
  102487. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  102488. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  102489. }
  102490. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  102491. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  102492. break;
  102493. }
  102494. case WHERE_DISTINCT_UNIQUE: {
  102495. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  102496. break;
  102497. }
  102498. default: {
  102499. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  102500. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  102501. regResult);
  102502. break;
  102503. }
  102504. }
  102505. if( pSort==0 ){
  102506. codeOffset(v, p->iOffset, iContinue);
  102507. }
  102508. }
  102509. switch( eDest ){
  102510. /* In this mode, write each query result to the key of the temporary
  102511. ** table iParm.
  102512. */
  102513. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  102514. case SRT_Union: {
  102515. int r1;
  102516. r1 = sqlite3GetTempReg(pParse);
  102517. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  102518. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  102519. sqlite3ReleaseTempReg(pParse, r1);
  102520. break;
  102521. }
  102522. /* Construct a record from the query result, but instead of
  102523. ** saving that record, use it as a key to delete elements from
  102524. ** the temporary table iParm.
  102525. */
  102526. case SRT_Except: {
  102527. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  102528. break;
  102529. }
  102530. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  102531. /* Store the result as data using a unique key.
  102532. */
  102533. case SRT_Fifo:
  102534. case SRT_DistFifo:
  102535. case SRT_Table:
  102536. case SRT_EphemTab: {
  102537. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  102538. testcase( eDest==SRT_Table );
  102539. testcase( eDest==SRT_EphemTab );
  102540. testcase( eDest==SRT_Fifo );
  102541. testcase( eDest==SRT_DistFifo );
  102542. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  102543. #ifndef SQLITE_OMIT_CTE
  102544. if( eDest==SRT_DistFifo ){
  102545. /* If the destination is DistFifo, then cursor (iParm+1) is open
  102546. ** on an ephemeral index. If the current row is already present
  102547. ** in the index, do not write it to the output. If not, add the
  102548. ** current row to the index and proceed with writing it to the
  102549. ** output table as well. */
  102550. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  102551. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  102552. VdbeCoverage(v);
  102553. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  102554. assert( pSort==0 );
  102555. }
  102556. #endif
  102557. if( pSort ){
  102558. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  102559. }else{
  102560. int r2 = sqlite3GetTempReg(pParse);
  102561. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  102562. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  102563. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  102564. sqlite3ReleaseTempReg(pParse, r2);
  102565. }
  102566. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  102567. break;
  102568. }
  102569. #ifndef SQLITE_OMIT_SUBQUERY
  102570. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  102571. ** then there should be a single item on the stack. Write this
  102572. ** item into the set table with bogus data.
  102573. */
  102574. case SRT_Set: {
  102575. assert( nResultCol==1 );
  102576. pDest->affSdst =
  102577. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  102578. if( pSort ){
  102579. /* At first glance you would think we could optimize out the
  102580. ** ORDER BY in this case since the order of entries in the set
  102581. ** does not matter. But there might be a LIMIT clause, in which
  102582. ** case the order does matter */
  102583. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  102584. }else{
  102585. int r1 = sqlite3GetTempReg(pParse);
  102586. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  102587. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  102588. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  102589. sqlite3ReleaseTempReg(pParse, r1);
  102590. }
  102591. break;
  102592. }
  102593. /* If any row exist in the result set, record that fact and abort.
  102594. */
  102595. case SRT_Exists: {
  102596. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  102597. /* The LIMIT clause will terminate the loop for us */
  102598. break;
  102599. }
  102600. /* If this is a scalar select that is part of an expression, then
  102601. ** store the results in the appropriate memory cell and break out
  102602. ** of the scan loop.
  102603. */
  102604. case SRT_Mem: {
  102605. assert( nResultCol==1 );
  102606. if( pSort ){
  102607. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  102608. }else{
  102609. assert( regResult==iParm );
  102610. /* The LIMIT clause will jump out of the loop for us */
  102611. }
  102612. break;
  102613. }
  102614. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  102615. case SRT_Coroutine: /* Send data to a co-routine */
  102616. case SRT_Output: { /* Return the results */
  102617. testcase( eDest==SRT_Coroutine );
  102618. testcase( eDest==SRT_Output );
  102619. if( pSort ){
  102620. pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
  102621. nPrefixReg);
  102622. }else if( eDest==SRT_Coroutine ){
  102623. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  102624. }else{
  102625. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  102626. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  102627. }
  102628. break;
  102629. }
  102630. #ifndef SQLITE_OMIT_CTE
  102631. /* Write the results into a priority queue that is order according to
  102632. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  102633. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  102634. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  102635. ** final OP_Sequence column. The last column is the record as a blob.
  102636. */
  102637. case SRT_DistQueue:
  102638. case SRT_Queue: {
  102639. int nKey;
  102640. int r1, r2, r3;
  102641. int addrTest = 0;
  102642. ExprList *pSO;
  102643. pSO = pDest->pOrderBy;
  102644. assert( pSO );
  102645. nKey = pSO->nExpr;
  102646. r1 = sqlite3GetTempReg(pParse);
  102647. r2 = sqlite3GetTempRange(pParse, nKey+2);
  102648. r3 = r2+nKey+1;
  102649. if( eDest==SRT_DistQueue ){
  102650. /* If the destination is DistQueue, then cursor (iParm+1) is open
  102651. ** on a second ephemeral index that holds all values every previously
  102652. ** added to the queue. */
  102653. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  102654. regResult, nResultCol);
  102655. VdbeCoverage(v);
  102656. }
  102657. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  102658. if( eDest==SRT_DistQueue ){
  102659. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  102660. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  102661. }
  102662. for(i=0; i<nKey; i++){
  102663. sqlite3VdbeAddOp2(v, OP_SCopy,
  102664. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  102665. r2+i);
  102666. }
  102667. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  102668. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  102669. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  102670. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  102671. sqlite3ReleaseTempReg(pParse, r1);
  102672. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  102673. break;
  102674. }
  102675. #endif /* SQLITE_OMIT_CTE */
  102676. #if !defined(SQLITE_OMIT_TRIGGER)
  102677. /* Discard the results. This is used for SELECT statements inside
  102678. ** the body of a TRIGGER. The purpose of such selects is to call
  102679. ** user-defined functions that have side effects. We do not care
  102680. ** about the actual results of the select.
  102681. */
  102682. default: {
  102683. assert( eDest==SRT_Discard );
  102684. break;
  102685. }
  102686. #endif
  102687. }
  102688. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  102689. ** there is a sorter, in which case the sorter has already limited
  102690. ** the output for us.
  102691. */
  102692. if( pSort==0 && p->iLimit ){
  102693. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  102694. }
  102695. }
  102696. /*
  102697. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  102698. ** X extra columns.
  102699. */
  102700. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  102701. KeyInfo *p = sqlite3DbMallocZero(0,
  102702. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  102703. if( p ){
  102704. p->aSortOrder = (u8*)&p->aColl[N+X];
  102705. p->nField = (u16)N;
  102706. p->nXField = (u16)X;
  102707. p->enc = ENC(db);
  102708. p->db = db;
  102709. p->nRef = 1;
  102710. }else{
  102711. db->mallocFailed = 1;
  102712. }
  102713. return p;
  102714. }
  102715. /*
  102716. ** Deallocate a KeyInfo object
  102717. */
  102718. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  102719. if( p ){
  102720. assert( p->nRef>0 );
  102721. p->nRef--;
  102722. if( p->nRef==0 ) sqlite3DbFree(0, p);
  102723. }
  102724. }
  102725. /*
  102726. ** Make a new pointer to a KeyInfo object
  102727. */
  102728. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  102729. if( p ){
  102730. assert( p->nRef>0 );
  102731. p->nRef++;
  102732. }
  102733. return p;
  102734. }
  102735. #ifdef SQLITE_DEBUG
  102736. /*
  102737. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  102738. ** can only be changed if this is just a single reference to the object.
  102739. **
  102740. ** This routine is used only inside of assert() statements.
  102741. */
  102742. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  102743. #endif /* SQLITE_DEBUG */
  102744. /*
  102745. ** Given an expression list, generate a KeyInfo structure that records
  102746. ** the collating sequence for each expression in that expression list.
  102747. **
  102748. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  102749. ** KeyInfo structure is appropriate for initializing a virtual index to
  102750. ** implement that clause. If the ExprList is the result set of a SELECT
  102751. ** then the KeyInfo structure is appropriate for initializing a virtual
  102752. ** index to implement a DISTINCT test.
  102753. **
  102754. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  102755. ** function is responsible for seeing that this structure is eventually
  102756. ** freed.
  102757. */
  102758. static KeyInfo *keyInfoFromExprList(
  102759. Parse *pParse, /* Parsing context */
  102760. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  102761. int iStart, /* Begin with this column of pList */
  102762. int nExtra /* Add this many extra columns to the end */
  102763. ){
  102764. int nExpr;
  102765. KeyInfo *pInfo;
  102766. struct ExprList_item *pItem;
  102767. sqlite3 *db = pParse->db;
  102768. int i;
  102769. nExpr = pList->nExpr;
  102770. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  102771. if( pInfo ){
  102772. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  102773. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  102774. CollSeq *pColl;
  102775. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  102776. if( !pColl ) pColl = db->pDfltColl;
  102777. pInfo->aColl[i-iStart] = pColl;
  102778. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  102779. }
  102780. }
  102781. return pInfo;
  102782. }
  102783. /*
  102784. ** Name of the connection operator, used for error messages.
  102785. */
  102786. static const char *selectOpName(int id){
  102787. char *z;
  102788. switch( id ){
  102789. case TK_ALL: z = "UNION ALL"; break;
  102790. case TK_INTERSECT: z = "INTERSECT"; break;
  102791. case TK_EXCEPT: z = "EXCEPT"; break;
  102792. default: z = "UNION"; break;
  102793. }
  102794. return z;
  102795. }
  102796. #ifndef SQLITE_OMIT_EXPLAIN
  102797. /*
  102798. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  102799. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  102800. ** where the caption is of the form:
  102801. **
  102802. ** "USE TEMP B-TREE FOR xxx"
  102803. **
  102804. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  102805. ** is determined by the zUsage argument.
  102806. */
  102807. static void explainTempTable(Parse *pParse, const char *zUsage){
  102808. if( pParse->explain==2 ){
  102809. Vdbe *v = pParse->pVdbe;
  102810. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  102811. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  102812. }
  102813. }
  102814. /*
  102815. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  102816. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  102817. ** in sqlite3Select() to assign values to structure member variables that
  102818. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  102819. ** code with #ifndef directives.
  102820. */
  102821. # define explainSetInteger(a, b) a = b
  102822. #else
  102823. /* No-op versions of the explainXXX() functions and macros. */
  102824. # define explainTempTable(y,z)
  102825. # define explainSetInteger(y,z)
  102826. #endif
  102827. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  102828. /*
  102829. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  102830. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  102831. ** where the caption is of one of the two forms:
  102832. **
  102833. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  102834. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  102835. **
  102836. ** where iSub1 and iSub2 are the integers passed as the corresponding
  102837. ** function parameters, and op is the text representation of the parameter
  102838. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  102839. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  102840. ** false, or the second form if it is true.
  102841. */
  102842. static void explainComposite(
  102843. Parse *pParse, /* Parse context */
  102844. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  102845. int iSub1, /* Subquery id 1 */
  102846. int iSub2, /* Subquery id 2 */
  102847. int bUseTmp /* True if a temp table was used */
  102848. ){
  102849. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  102850. if( pParse->explain==2 ){
  102851. Vdbe *v = pParse->pVdbe;
  102852. char *zMsg = sqlite3MPrintf(
  102853. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  102854. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  102855. );
  102856. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  102857. }
  102858. }
  102859. #else
  102860. /* No-op versions of the explainXXX() functions and macros. */
  102861. # define explainComposite(v,w,x,y,z)
  102862. #endif
  102863. /*
  102864. ** If the inner loop was generated using a non-null pOrderBy argument,
  102865. ** then the results were placed in a sorter. After the loop is terminated
  102866. ** we need to run the sorter and output the results. The following
  102867. ** routine generates the code needed to do that.
  102868. */
  102869. static void generateSortTail(
  102870. Parse *pParse, /* Parsing context */
  102871. Select *p, /* The SELECT statement */
  102872. SortCtx *pSort, /* Information on the ORDER BY clause */
  102873. int nColumn, /* Number of columns of data */
  102874. SelectDest *pDest /* Write the sorted results here */
  102875. ){
  102876. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  102877. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  102878. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  102879. int addr;
  102880. int addrOnce = 0;
  102881. int iTab;
  102882. ExprList *pOrderBy = pSort->pOrderBy;
  102883. int eDest = pDest->eDest;
  102884. int iParm = pDest->iSDParm;
  102885. int regRow;
  102886. int regRowid;
  102887. int nKey;
  102888. int iSortTab; /* Sorter cursor to read from */
  102889. int nSortData; /* Trailing values to read from sorter */
  102890. int i;
  102891. int bSeq; /* True if sorter record includes seq. no. */
  102892. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  102893. struct ExprList_item *aOutEx = p->pEList->a;
  102894. #endif
  102895. if( pSort->labelBkOut ){
  102896. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  102897. sqlite3VdbeGoto(v, addrBreak);
  102898. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  102899. }
  102900. iTab = pSort->iECursor;
  102901. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  102902. regRowid = 0;
  102903. regRow = pDest->iSdst;
  102904. nSortData = nColumn;
  102905. }else{
  102906. regRowid = sqlite3GetTempReg(pParse);
  102907. regRow = sqlite3GetTempReg(pParse);
  102908. nSortData = 1;
  102909. }
  102910. nKey = pOrderBy->nExpr - pSort->nOBSat;
  102911. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  102912. int regSortOut = ++pParse->nMem;
  102913. iSortTab = pParse->nTab++;
  102914. if( pSort->labelBkOut ){
  102915. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  102916. }
  102917. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  102918. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  102919. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  102920. VdbeCoverage(v);
  102921. codeOffset(v, p->iOffset, addrContinue);
  102922. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  102923. bSeq = 0;
  102924. }else{
  102925. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  102926. codeOffset(v, p->iOffset, addrContinue);
  102927. iSortTab = iTab;
  102928. bSeq = 1;
  102929. }
  102930. for(i=0; i<nSortData; i++){
  102931. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  102932. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  102933. }
  102934. switch( eDest ){
  102935. case SRT_EphemTab: {
  102936. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  102937. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  102938. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  102939. break;
  102940. }
  102941. #ifndef SQLITE_OMIT_SUBQUERY
  102942. case SRT_Set: {
  102943. assert( nColumn==1 );
  102944. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  102945. &pDest->affSdst, 1);
  102946. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  102947. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  102948. break;
  102949. }
  102950. case SRT_Mem: {
  102951. assert( nColumn==1 );
  102952. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  102953. /* The LIMIT clause will terminate the loop for us */
  102954. break;
  102955. }
  102956. #endif
  102957. default: {
  102958. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  102959. testcase( eDest==SRT_Output );
  102960. testcase( eDest==SRT_Coroutine );
  102961. if( eDest==SRT_Output ){
  102962. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  102963. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  102964. }else{
  102965. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  102966. }
  102967. break;
  102968. }
  102969. }
  102970. if( regRowid ){
  102971. sqlite3ReleaseTempReg(pParse, regRow);
  102972. sqlite3ReleaseTempReg(pParse, regRowid);
  102973. }
  102974. /* The bottom of the loop
  102975. */
  102976. sqlite3VdbeResolveLabel(v, addrContinue);
  102977. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  102978. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  102979. }else{
  102980. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  102981. }
  102982. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  102983. sqlite3VdbeResolveLabel(v, addrBreak);
  102984. }
  102985. /*
  102986. ** Return a pointer to a string containing the 'declaration type' of the
  102987. ** expression pExpr. The string may be treated as static by the caller.
  102988. **
  102989. ** Also try to estimate the size of the returned value and return that
  102990. ** result in *pEstWidth.
  102991. **
  102992. ** The declaration type is the exact datatype definition extracted from the
  102993. ** original CREATE TABLE statement if the expression is a column. The
  102994. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  102995. ** is considered a column can be complex in the presence of subqueries. The
  102996. ** result-set expression in all of the following SELECT statements is
  102997. ** considered a column by this function.
  102998. **
  102999. ** SELECT col FROM tbl;
  103000. ** SELECT (SELECT col FROM tbl;
  103001. ** SELECT (SELECT col FROM tbl);
  103002. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  103003. **
  103004. ** The declaration type for any expression other than a column is NULL.
  103005. **
  103006. ** This routine has either 3 or 6 parameters depending on whether or not
  103007. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  103008. */
  103009. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103010. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  103011. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  103012. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  103013. #endif
  103014. static const char *columnTypeImpl(
  103015. NameContext *pNC,
  103016. Expr *pExpr,
  103017. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103018. const char **pzOrigDb,
  103019. const char **pzOrigTab,
  103020. const char **pzOrigCol,
  103021. #endif
  103022. u8 *pEstWidth
  103023. ){
  103024. char const *zType = 0;
  103025. int j;
  103026. u8 estWidth = 1;
  103027. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103028. char const *zOrigDb = 0;
  103029. char const *zOrigTab = 0;
  103030. char const *zOrigCol = 0;
  103031. #endif
  103032. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  103033. switch( pExpr->op ){
  103034. case TK_AGG_COLUMN:
  103035. case TK_COLUMN: {
  103036. /* The expression is a column. Locate the table the column is being
  103037. ** extracted from in NameContext.pSrcList. This table may be real
  103038. ** database table or a subquery.
  103039. */
  103040. Table *pTab = 0; /* Table structure column is extracted from */
  103041. Select *pS = 0; /* Select the column is extracted from */
  103042. int iCol = pExpr->iColumn; /* Index of column in pTab */
  103043. testcase( pExpr->op==TK_AGG_COLUMN );
  103044. testcase( pExpr->op==TK_COLUMN );
  103045. while( pNC && !pTab ){
  103046. SrcList *pTabList = pNC->pSrcList;
  103047. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  103048. if( j<pTabList->nSrc ){
  103049. pTab = pTabList->a[j].pTab;
  103050. pS = pTabList->a[j].pSelect;
  103051. }else{
  103052. pNC = pNC->pNext;
  103053. }
  103054. }
  103055. if( pTab==0 ){
  103056. /* At one time, code such as "SELECT new.x" within a trigger would
  103057. ** cause this condition to run. Since then, we have restructured how
  103058. ** trigger code is generated and so this condition is no longer
  103059. ** possible. However, it can still be true for statements like
  103060. ** the following:
  103061. **
  103062. ** CREATE TABLE t1(col INTEGER);
  103063. ** SELECT (SELECT t1.col) FROM FROM t1;
  103064. **
  103065. ** when columnType() is called on the expression "t1.col" in the
  103066. ** sub-select. In this case, set the column type to NULL, even
  103067. ** though it should really be "INTEGER".
  103068. **
  103069. ** This is not a problem, as the column type of "t1.col" is never
  103070. ** used. When columnType() is called on the expression
  103071. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  103072. ** branch below. */
  103073. break;
  103074. }
  103075. assert( pTab && pExpr->pTab==pTab );
  103076. if( pS ){
  103077. /* The "table" is actually a sub-select or a view in the FROM clause
  103078. ** of the SELECT statement. Return the declaration type and origin
  103079. ** data for the result-set column of the sub-select.
  103080. */
  103081. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  103082. /* If iCol is less than zero, then the expression requests the
  103083. ** rowid of the sub-select or view. This expression is legal (see
  103084. ** test case misc2.2.2) - it always evaluates to NULL.
  103085. **
  103086. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  103087. ** caught already by name resolution.
  103088. */
  103089. NameContext sNC;
  103090. Expr *p = pS->pEList->a[iCol].pExpr;
  103091. sNC.pSrcList = pS->pSrc;
  103092. sNC.pNext = pNC;
  103093. sNC.pParse = pNC->pParse;
  103094. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  103095. }
  103096. }else if( pTab->pSchema ){
  103097. /* A real table */
  103098. assert( !pS );
  103099. if( iCol<0 ) iCol = pTab->iPKey;
  103100. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  103101. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103102. if( iCol<0 ){
  103103. zType = "INTEGER";
  103104. zOrigCol = "rowid";
  103105. }else{
  103106. zType = pTab->aCol[iCol].zType;
  103107. zOrigCol = pTab->aCol[iCol].zName;
  103108. estWidth = pTab->aCol[iCol].szEst;
  103109. }
  103110. zOrigTab = pTab->zName;
  103111. if( pNC->pParse ){
  103112. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  103113. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  103114. }
  103115. #else
  103116. if( iCol<0 ){
  103117. zType = "INTEGER";
  103118. }else{
  103119. zType = pTab->aCol[iCol].zType;
  103120. estWidth = pTab->aCol[iCol].szEst;
  103121. }
  103122. #endif
  103123. }
  103124. break;
  103125. }
  103126. #ifndef SQLITE_OMIT_SUBQUERY
  103127. case TK_SELECT: {
  103128. /* The expression is a sub-select. Return the declaration type and
  103129. ** origin info for the single column in the result set of the SELECT
  103130. ** statement.
  103131. */
  103132. NameContext sNC;
  103133. Select *pS = pExpr->x.pSelect;
  103134. Expr *p = pS->pEList->a[0].pExpr;
  103135. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  103136. sNC.pSrcList = pS->pSrc;
  103137. sNC.pNext = pNC;
  103138. sNC.pParse = pNC->pParse;
  103139. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  103140. break;
  103141. }
  103142. #endif
  103143. }
  103144. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103145. if( pzOrigDb ){
  103146. assert( pzOrigTab && pzOrigCol );
  103147. *pzOrigDb = zOrigDb;
  103148. *pzOrigTab = zOrigTab;
  103149. *pzOrigCol = zOrigCol;
  103150. }
  103151. #endif
  103152. if( pEstWidth ) *pEstWidth = estWidth;
  103153. return zType;
  103154. }
  103155. /*
  103156. ** Generate code that will tell the VDBE the declaration types of columns
  103157. ** in the result set.
  103158. */
  103159. static void generateColumnTypes(
  103160. Parse *pParse, /* Parser context */
  103161. SrcList *pTabList, /* List of tables */
  103162. ExprList *pEList /* Expressions defining the result set */
  103163. ){
  103164. #ifndef SQLITE_OMIT_DECLTYPE
  103165. Vdbe *v = pParse->pVdbe;
  103166. int i;
  103167. NameContext sNC;
  103168. sNC.pSrcList = pTabList;
  103169. sNC.pParse = pParse;
  103170. for(i=0; i<pEList->nExpr; i++){
  103171. Expr *p = pEList->a[i].pExpr;
  103172. const char *zType;
  103173. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103174. const char *zOrigDb = 0;
  103175. const char *zOrigTab = 0;
  103176. const char *zOrigCol = 0;
  103177. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  103178. /* The vdbe must make its own copy of the column-type and other
  103179. ** column specific strings, in case the schema is reset before this
  103180. ** virtual machine is deleted.
  103181. */
  103182. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  103183. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  103184. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  103185. #else
  103186. zType = columnType(&sNC, p, 0, 0, 0, 0);
  103187. #endif
  103188. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  103189. }
  103190. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  103191. }
  103192. /*
  103193. ** Generate code that will tell the VDBE the names of columns
  103194. ** in the result set. This information is used to provide the
  103195. ** azCol[] values in the callback.
  103196. */
  103197. static void generateColumnNames(
  103198. Parse *pParse, /* Parser context */
  103199. SrcList *pTabList, /* List of tables */
  103200. ExprList *pEList /* Expressions defining the result set */
  103201. ){
  103202. Vdbe *v = pParse->pVdbe;
  103203. int i, j;
  103204. sqlite3 *db = pParse->db;
  103205. int fullNames, shortNames;
  103206. #ifndef SQLITE_OMIT_EXPLAIN
  103207. /* If this is an EXPLAIN, skip this step */
  103208. if( pParse->explain ){
  103209. return;
  103210. }
  103211. #endif
  103212. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  103213. pParse->colNamesSet = 1;
  103214. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  103215. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  103216. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  103217. for(i=0; i<pEList->nExpr; i++){
  103218. Expr *p;
  103219. p = pEList->a[i].pExpr;
  103220. if( NEVER(p==0) ) continue;
  103221. if( pEList->a[i].zName ){
  103222. char *zName = pEList->a[i].zName;
  103223. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  103224. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  103225. Table *pTab;
  103226. char *zCol;
  103227. int iCol = p->iColumn;
  103228. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  103229. if( pTabList->a[j].iCursor==p->iTable ) break;
  103230. }
  103231. assert( j<pTabList->nSrc );
  103232. pTab = pTabList->a[j].pTab;
  103233. if( iCol<0 ) iCol = pTab->iPKey;
  103234. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  103235. if( iCol<0 ){
  103236. zCol = "rowid";
  103237. }else{
  103238. zCol = pTab->aCol[iCol].zName;
  103239. }
  103240. if( !shortNames && !fullNames ){
  103241. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  103242. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  103243. }else if( fullNames ){
  103244. char *zName = 0;
  103245. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  103246. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  103247. }else{
  103248. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  103249. }
  103250. }else{
  103251. const char *z = pEList->a[i].zSpan;
  103252. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  103253. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  103254. }
  103255. }
  103256. generateColumnTypes(pParse, pTabList, pEList);
  103257. }
  103258. /*
  103259. ** Given an expression list (which is really the list of expressions
  103260. ** that form the result set of a SELECT statement) compute appropriate
  103261. ** column names for a table that would hold the expression list.
  103262. **
  103263. ** All column names will be unique.
  103264. **
  103265. ** Only the column names are computed. Column.zType, Column.zColl,
  103266. ** and other fields of Column are zeroed.
  103267. **
  103268. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  103269. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  103270. */
  103271. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  103272. Parse *pParse, /* Parsing context */
  103273. ExprList *pEList, /* Expr list from which to derive column names */
  103274. i16 *pnCol, /* Write the number of columns here */
  103275. Column **paCol /* Write the new column list here */
  103276. ){
  103277. sqlite3 *db = pParse->db; /* Database connection */
  103278. int i, j; /* Loop counters */
  103279. int cnt; /* Index added to make the name unique */
  103280. Column *aCol, *pCol; /* For looping over result columns */
  103281. int nCol; /* Number of columns in the result set */
  103282. Expr *p; /* Expression for a single result column */
  103283. char *zName; /* Column name */
  103284. int nName; /* Size of name in zName[] */
  103285. if( pEList ){
  103286. nCol = pEList->nExpr;
  103287. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  103288. testcase( aCol==0 );
  103289. }else{
  103290. nCol = 0;
  103291. aCol = 0;
  103292. }
  103293. *pnCol = nCol;
  103294. *paCol = aCol;
  103295. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  103296. /* Get an appropriate name for the column
  103297. */
  103298. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  103299. if( (zName = pEList->a[i].zName)!=0 ){
  103300. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  103301. zName = sqlite3DbStrDup(db, zName);
  103302. }else{
  103303. Expr *pColExpr = p; /* The expression that is the result column name */
  103304. Table *pTab; /* Table associated with this expression */
  103305. while( pColExpr->op==TK_DOT ){
  103306. pColExpr = pColExpr->pRight;
  103307. assert( pColExpr!=0 );
  103308. }
  103309. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  103310. /* For columns use the column name name */
  103311. int iCol = pColExpr->iColumn;
  103312. pTab = pColExpr->pTab;
  103313. if( iCol<0 ) iCol = pTab->iPKey;
  103314. zName = sqlite3MPrintf(db, "%s",
  103315. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  103316. }else if( pColExpr->op==TK_ID ){
  103317. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  103318. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  103319. }else{
  103320. /* Use the original text of the column expression as its name */
  103321. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  103322. }
  103323. }
  103324. if( db->mallocFailed ){
  103325. sqlite3DbFree(db, zName);
  103326. break;
  103327. }
  103328. /* Make sure the column name is unique. If the name is not unique,
  103329. ** append an integer to the name so that it becomes unique.
  103330. */
  103331. nName = sqlite3Strlen30(zName);
  103332. for(j=cnt=0; j<i; j++){
  103333. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  103334. char *zNewName;
  103335. int k;
  103336. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  103337. if( k>=0 && zName[k]==':' ) nName = k;
  103338. zName[nName] = 0;
  103339. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  103340. sqlite3DbFree(db, zName);
  103341. zName = zNewName;
  103342. j = -1;
  103343. if( zName==0 ) break;
  103344. }
  103345. }
  103346. pCol->zName = zName;
  103347. }
  103348. if( db->mallocFailed ){
  103349. for(j=0; j<i; j++){
  103350. sqlite3DbFree(db, aCol[j].zName);
  103351. }
  103352. sqlite3DbFree(db, aCol);
  103353. *paCol = 0;
  103354. *pnCol = 0;
  103355. return SQLITE_NOMEM;
  103356. }
  103357. return SQLITE_OK;
  103358. }
  103359. /*
  103360. ** Add type and collation information to a column list based on
  103361. ** a SELECT statement.
  103362. **
  103363. ** The column list presumably came from selectColumnNamesFromExprList().
  103364. ** The column list has only names, not types or collations. This
  103365. ** routine goes through and adds the types and collations.
  103366. **
  103367. ** This routine requires that all identifiers in the SELECT
  103368. ** statement be resolved.
  103369. */
  103370. static void selectAddColumnTypeAndCollation(
  103371. Parse *pParse, /* Parsing contexts */
  103372. Table *pTab, /* Add column type information to this table */
  103373. Select *pSelect /* SELECT used to determine types and collations */
  103374. ){
  103375. sqlite3 *db = pParse->db;
  103376. NameContext sNC;
  103377. Column *pCol;
  103378. CollSeq *pColl;
  103379. int i;
  103380. Expr *p;
  103381. struct ExprList_item *a;
  103382. u64 szAll = 0;
  103383. assert( pSelect!=0 );
  103384. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  103385. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  103386. if( db->mallocFailed ) return;
  103387. memset(&sNC, 0, sizeof(sNC));
  103388. sNC.pSrcList = pSelect->pSrc;
  103389. a = pSelect->pEList->a;
  103390. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  103391. p = a[i].pExpr;
  103392. if( pCol->zType==0 ){
  103393. pCol->zType = sqlite3DbStrDup(db,
  103394. columnType(&sNC, p,0,0,0, &pCol->szEst));
  103395. }
  103396. szAll += pCol->szEst;
  103397. pCol->affinity = sqlite3ExprAffinity(p);
  103398. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  103399. pColl = sqlite3ExprCollSeq(pParse, p);
  103400. if( pColl && pCol->zColl==0 ){
  103401. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  103402. }
  103403. }
  103404. pTab->szTabRow = sqlite3LogEst(szAll*4);
  103405. }
  103406. /*
  103407. ** Given a SELECT statement, generate a Table structure that describes
  103408. ** the result set of that SELECT.
  103409. */
  103410. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  103411. Table *pTab;
  103412. sqlite3 *db = pParse->db;
  103413. int savedFlags;
  103414. savedFlags = db->flags;
  103415. db->flags &= ~SQLITE_FullColNames;
  103416. db->flags |= SQLITE_ShortColNames;
  103417. sqlite3SelectPrep(pParse, pSelect, 0);
  103418. if( pParse->nErr ) return 0;
  103419. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  103420. db->flags = savedFlags;
  103421. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  103422. if( pTab==0 ){
  103423. return 0;
  103424. }
  103425. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  103426. ** is disabled */
  103427. assert( db->lookaside.bEnabled==0 );
  103428. pTab->nRef = 1;
  103429. pTab->zName = 0;
  103430. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  103431. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  103432. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  103433. pTab->iPKey = -1;
  103434. if( db->mallocFailed ){
  103435. sqlite3DeleteTable(db, pTab);
  103436. return 0;
  103437. }
  103438. return pTab;
  103439. }
  103440. /*
  103441. ** Get a VDBE for the given parser context. Create a new one if necessary.
  103442. ** If an error occurs, return NULL and leave a message in pParse.
  103443. */
  103444. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  103445. Vdbe *v = pParse->pVdbe;
  103446. if( v==0 ){
  103447. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  103448. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  103449. if( pParse->pToplevel==0
  103450. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  103451. ){
  103452. pParse->okConstFactor = 1;
  103453. }
  103454. }
  103455. return v;
  103456. }
  103457. /*
  103458. ** Compute the iLimit and iOffset fields of the SELECT based on the
  103459. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  103460. ** that appear in the original SQL statement after the LIMIT and OFFSET
  103461. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  103462. ** are the integer memory register numbers for counters used to compute
  103463. ** the limit and offset. If there is no limit and/or offset, then
  103464. ** iLimit and iOffset are negative.
  103465. **
  103466. ** This routine changes the values of iLimit and iOffset only if
  103467. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  103468. ** iOffset should have been preset to appropriate default values (zero)
  103469. ** prior to calling this routine.
  103470. **
  103471. ** The iOffset register (if it exists) is initialized to the value
  103472. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  103473. ** iOffset+1 is initialized to LIMIT+OFFSET.
  103474. **
  103475. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  103476. ** redefined. The UNION ALL operator uses this property to force
  103477. ** the reuse of the same limit and offset registers across multiple
  103478. ** SELECT statements.
  103479. */
  103480. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  103481. Vdbe *v = 0;
  103482. int iLimit = 0;
  103483. int iOffset;
  103484. int n;
  103485. if( p->iLimit ) return;
  103486. /*
  103487. ** "LIMIT -1" always shows all rows. There is some
  103488. ** controversy about what the correct behavior should be.
  103489. ** The current implementation interprets "LIMIT 0" to mean
  103490. ** no rows.
  103491. */
  103492. sqlite3ExprCacheClear(pParse);
  103493. assert( p->pOffset==0 || p->pLimit!=0 );
  103494. if( p->pLimit ){
  103495. p->iLimit = iLimit = ++pParse->nMem;
  103496. v = sqlite3GetVdbe(pParse);
  103497. assert( v!=0 );
  103498. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  103499. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  103500. VdbeComment((v, "LIMIT counter"));
  103501. if( n==0 ){
  103502. sqlite3VdbeGoto(v, iBreak);
  103503. }else if( n>=0 && p->nSelectRow>(u64)n ){
  103504. p->nSelectRow = n;
  103505. }
  103506. }else{
  103507. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  103508. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  103509. VdbeComment((v, "LIMIT counter"));
  103510. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  103511. }
  103512. if( p->pOffset ){
  103513. p->iOffset = iOffset = ++pParse->nMem;
  103514. pParse->nMem++; /* Allocate an extra register for limit+offset */
  103515. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  103516. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  103517. VdbeComment((v, "OFFSET counter"));
  103518. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
  103519. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  103520. VdbeComment((v, "LIMIT+OFFSET"));
  103521. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
  103522. }
  103523. }
  103524. }
  103525. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  103526. /*
  103527. ** Return the appropriate collating sequence for the iCol-th column of
  103528. ** the result set for the compound-select statement "p". Return NULL if
  103529. ** the column has no default collating sequence.
  103530. **
  103531. ** The collating sequence for the compound select is taken from the
  103532. ** left-most term of the select that has a collating sequence.
  103533. */
  103534. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  103535. CollSeq *pRet;
  103536. if( p->pPrior ){
  103537. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  103538. }else{
  103539. pRet = 0;
  103540. }
  103541. assert( iCol>=0 );
  103542. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  103543. ** have been thrown during name resolution and we would not have gotten
  103544. ** this far */
  103545. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  103546. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  103547. }
  103548. return pRet;
  103549. }
  103550. /*
  103551. ** The select statement passed as the second parameter is a compound SELECT
  103552. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  103553. ** structure suitable for implementing the ORDER BY.
  103554. **
  103555. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  103556. ** function is responsible for ensuring that this structure is eventually
  103557. ** freed.
  103558. */
  103559. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  103560. ExprList *pOrderBy = p->pOrderBy;
  103561. int nOrderBy = p->pOrderBy->nExpr;
  103562. sqlite3 *db = pParse->db;
  103563. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  103564. if( pRet ){
  103565. int i;
  103566. for(i=0; i<nOrderBy; i++){
  103567. struct ExprList_item *pItem = &pOrderBy->a[i];
  103568. Expr *pTerm = pItem->pExpr;
  103569. CollSeq *pColl;
  103570. if( pTerm->flags & EP_Collate ){
  103571. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  103572. }else{
  103573. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  103574. if( pColl==0 ) pColl = db->pDfltColl;
  103575. pOrderBy->a[i].pExpr =
  103576. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  103577. }
  103578. assert( sqlite3KeyInfoIsWriteable(pRet) );
  103579. pRet->aColl[i] = pColl;
  103580. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  103581. }
  103582. }
  103583. return pRet;
  103584. }
  103585. #ifndef SQLITE_OMIT_CTE
  103586. /*
  103587. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  103588. ** query of the form:
  103589. **
  103590. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  103591. ** \___________/ \_______________/
  103592. ** p->pPrior p
  103593. **
  103594. **
  103595. ** There is exactly one reference to the recursive-table in the FROM clause
  103596. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  103597. **
  103598. ** The setup-query runs once to generate an initial set of rows that go
  103599. ** into a Queue table. Rows are extracted from the Queue table one by
  103600. ** one. Each row extracted from Queue is output to pDest. Then the single
  103601. ** extracted row (now in the iCurrent table) becomes the content of the
  103602. ** recursive-table for a recursive-query run. The output of the recursive-query
  103603. ** is added back into the Queue table. Then another row is extracted from Queue
  103604. ** and the iteration continues until the Queue table is empty.
  103605. **
  103606. ** If the compound query operator is UNION then no duplicate rows are ever
  103607. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  103608. ** that have ever been inserted into Queue and causes duplicates to be
  103609. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  103610. **
  103611. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  103612. ** ORDER BY order and the first entry is extracted for each cycle. Without
  103613. ** an ORDER BY, the Queue table is just a FIFO.
  103614. **
  103615. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  103616. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  103617. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  103618. ** with a positive value, then the first OFFSET outputs are discarded rather
  103619. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  103620. ** rows have been skipped.
  103621. */
  103622. static void generateWithRecursiveQuery(
  103623. Parse *pParse, /* Parsing context */
  103624. Select *p, /* The recursive SELECT to be coded */
  103625. SelectDest *pDest /* What to do with query results */
  103626. ){
  103627. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  103628. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  103629. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  103630. Select *pSetup = p->pPrior; /* The setup query */
  103631. int addrTop; /* Top of the loop */
  103632. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  103633. int iCurrent = 0; /* The Current table */
  103634. int regCurrent; /* Register holding Current table */
  103635. int iQueue; /* The Queue table */
  103636. int iDistinct = 0; /* To ensure unique results if UNION */
  103637. int eDest = SRT_Fifo; /* How to write to Queue */
  103638. SelectDest destQueue; /* SelectDest targetting the Queue table */
  103639. int i; /* Loop counter */
  103640. int rc; /* Result code */
  103641. ExprList *pOrderBy; /* The ORDER BY clause */
  103642. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  103643. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  103644. /* Obtain authorization to do a recursive query */
  103645. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  103646. /* Process the LIMIT and OFFSET clauses, if they exist */
  103647. addrBreak = sqlite3VdbeMakeLabel(v);
  103648. computeLimitRegisters(pParse, p, addrBreak);
  103649. pLimit = p->pLimit;
  103650. pOffset = p->pOffset;
  103651. regLimit = p->iLimit;
  103652. regOffset = p->iOffset;
  103653. p->pLimit = p->pOffset = 0;
  103654. p->iLimit = p->iOffset = 0;
  103655. pOrderBy = p->pOrderBy;
  103656. /* Locate the cursor number of the Current table */
  103657. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  103658. if( pSrc->a[i].fg.isRecursive ){
  103659. iCurrent = pSrc->a[i].iCursor;
  103660. break;
  103661. }
  103662. }
  103663. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  103664. ** the Distinct table must be exactly one greater than Queue in order
  103665. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  103666. iQueue = pParse->nTab++;
  103667. if( p->op==TK_UNION ){
  103668. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  103669. iDistinct = pParse->nTab++;
  103670. }else{
  103671. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  103672. }
  103673. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  103674. /* Allocate cursors for Current, Queue, and Distinct. */
  103675. regCurrent = ++pParse->nMem;
  103676. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  103677. if( pOrderBy ){
  103678. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  103679. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  103680. (char*)pKeyInfo, P4_KEYINFO);
  103681. destQueue.pOrderBy = pOrderBy;
  103682. }else{
  103683. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  103684. }
  103685. VdbeComment((v, "Queue table"));
  103686. if( iDistinct ){
  103687. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  103688. p->selFlags |= SF_UsesEphemeral;
  103689. }
  103690. /* Detach the ORDER BY clause from the compound SELECT */
  103691. p->pOrderBy = 0;
  103692. /* Store the results of the setup-query in Queue. */
  103693. pSetup->pNext = 0;
  103694. rc = sqlite3Select(pParse, pSetup, &destQueue);
  103695. pSetup->pNext = p;
  103696. if( rc ) goto end_of_recursive_query;
  103697. /* Find the next row in the Queue and output that row */
  103698. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  103699. /* Transfer the next row in Queue over to Current */
  103700. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  103701. if( pOrderBy ){
  103702. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  103703. }else{
  103704. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  103705. }
  103706. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  103707. /* Output the single row in Current */
  103708. addrCont = sqlite3VdbeMakeLabel(v);
  103709. codeOffset(v, regOffset, addrCont);
  103710. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  103711. 0, 0, pDest, addrCont, addrBreak);
  103712. if( regLimit ){
  103713. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  103714. VdbeCoverage(v);
  103715. }
  103716. sqlite3VdbeResolveLabel(v, addrCont);
  103717. /* Execute the recursive SELECT taking the single row in Current as
  103718. ** the value for the recursive-table. Store the results in the Queue.
  103719. */
  103720. if( p->selFlags & SF_Aggregate ){
  103721. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  103722. }else{
  103723. p->pPrior = 0;
  103724. sqlite3Select(pParse, p, &destQueue);
  103725. assert( p->pPrior==0 );
  103726. p->pPrior = pSetup;
  103727. }
  103728. /* Keep running the loop until the Queue is empty */
  103729. sqlite3VdbeGoto(v, addrTop);
  103730. sqlite3VdbeResolveLabel(v, addrBreak);
  103731. end_of_recursive_query:
  103732. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  103733. p->pOrderBy = pOrderBy;
  103734. p->pLimit = pLimit;
  103735. p->pOffset = pOffset;
  103736. return;
  103737. }
  103738. #endif /* SQLITE_OMIT_CTE */
  103739. /* Forward references */
  103740. static int multiSelectOrderBy(
  103741. Parse *pParse, /* Parsing context */
  103742. Select *p, /* The right-most of SELECTs to be coded */
  103743. SelectDest *pDest /* What to do with query results */
  103744. );
  103745. /*
  103746. ** Handle the special case of a compound-select that originates from a
  103747. ** VALUES clause. By handling this as a special case, we avoid deep
  103748. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  103749. ** on a VALUES clause.
  103750. **
  103751. ** Because the Select object originates from a VALUES clause:
  103752. ** (1) It has no LIMIT or OFFSET
  103753. ** (2) All terms are UNION ALL
  103754. ** (3) There is no ORDER BY clause
  103755. */
  103756. static int multiSelectValues(
  103757. Parse *pParse, /* Parsing context */
  103758. Select *p, /* The right-most of SELECTs to be coded */
  103759. SelectDest *pDest /* What to do with query results */
  103760. ){
  103761. Select *pPrior;
  103762. int nRow = 1;
  103763. int rc = 0;
  103764. assert( p->selFlags & SF_MultiValue );
  103765. do{
  103766. assert( p->selFlags & SF_Values );
  103767. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  103768. assert( p->pLimit==0 );
  103769. assert( p->pOffset==0 );
  103770. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  103771. if( p->pPrior==0 ) break;
  103772. assert( p->pPrior->pNext==p );
  103773. p = p->pPrior;
  103774. nRow++;
  103775. }while(1);
  103776. while( p ){
  103777. pPrior = p->pPrior;
  103778. p->pPrior = 0;
  103779. rc = sqlite3Select(pParse, p, pDest);
  103780. p->pPrior = pPrior;
  103781. if( rc ) break;
  103782. p->nSelectRow = nRow;
  103783. p = p->pNext;
  103784. }
  103785. return rc;
  103786. }
  103787. /*
  103788. ** This routine is called to process a compound query form from
  103789. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  103790. ** INTERSECT
  103791. **
  103792. ** "p" points to the right-most of the two queries. the query on the
  103793. ** left is p->pPrior. The left query could also be a compound query
  103794. ** in which case this routine will be called recursively.
  103795. **
  103796. ** The results of the total query are to be written into a destination
  103797. ** of type eDest with parameter iParm.
  103798. **
  103799. ** Example 1: Consider a three-way compound SQL statement.
  103800. **
  103801. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  103802. **
  103803. ** This statement is parsed up as follows:
  103804. **
  103805. ** SELECT c FROM t3
  103806. ** |
  103807. ** `-----> SELECT b FROM t2
  103808. ** |
  103809. ** `------> SELECT a FROM t1
  103810. **
  103811. ** The arrows in the diagram above represent the Select.pPrior pointer.
  103812. ** So if this routine is called with p equal to the t3 query, then
  103813. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  103814. **
  103815. ** Notice that because of the way SQLite parses compound SELECTs, the
  103816. ** individual selects always group from left to right.
  103817. */
  103818. static int multiSelect(
  103819. Parse *pParse, /* Parsing context */
  103820. Select *p, /* The right-most of SELECTs to be coded */
  103821. SelectDest *pDest /* What to do with query results */
  103822. ){
  103823. int rc = SQLITE_OK; /* Success code from a subroutine */
  103824. Select *pPrior; /* Another SELECT immediately to our left */
  103825. Vdbe *v; /* Generate code to this VDBE */
  103826. SelectDest dest; /* Alternative data destination */
  103827. Select *pDelete = 0; /* Chain of simple selects to delete */
  103828. sqlite3 *db; /* Database connection */
  103829. #ifndef SQLITE_OMIT_EXPLAIN
  103830. int iSub1 = 0; /* EQP id of left-hand query */
  103831. int iSub2 = 0; /* EQP id of right-hand query */
  103832. #endif
  103833. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  103834. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  103835. */
  103836. assert( p && p->pPrior ); /* Calling function guarantees this much */
  103837. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  103838. db = pParse->db;
  103839. pPrior = p->pPrior;
  103840. dest = *pDest;
  103841. if( pPrior->pOrderBy ){
  103842. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  103843. selectOpName(p->op));
  103844. rc = 1;
  103845. goto multi_select_end;
  103846. }
  103847. if( pPrior->pLimit ){
  103848. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  103849. selectOpName(p->op));
  103850. rc = 1;
  103851. goto multi_select_end;
  103852. }
  103853. v = sqlite3GetVdbe(pParse);
  103854. assert( v!=0 ); /* The VDBE already created by calling function */
  103855. /* Create the destination temporary table if necessary
  103856. */
  103857. if( dest.eDest==SRT_EphemTab ){
  103858. assert( p->pEList );
  103859. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  103860. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  103861. dest.eDest = SRT_Table;
  103862. }
  103863. /* Special handling for a compound-select that originates as a VALUES clause.
  103864. */
  103865. if( p->selFlags & SF_MultiValue ){
  103866. rc = multiSelectValues(pParse, p, &dest);
  103867. goto multi_select_end;
  103868. }
  103869. /* Make sure all SELECTs in the statement have the same number of elements
  103870. ** in their result sets.
  103871. */
  103872. assert( p->pEList && pPrior->pEList );
  103873. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  103874. #ifndef SQLITE_OMIT_CTE
  103875. if( p->selFlags & SF_Recursive ){
  103876. generateWithRecursiveQuery(pParse, p, &dest);
  103877. }else
  103878. #endif
  103879. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  103880. */
  103881. if( p->pOrderBy ){
  103882. return multiSelectOrderBy(pParse, p, pDest);
  103883. }else
  103884. /* Generate code for the left and right SELECT statements.
  103885. */
  103886. switch( p->op ){
  103887. case TK_ALL: {
  103888. int addr = 0;
  103889. int nLimit;
  103890. assert( !pPrior->pLimit );
  103891. pPrior->iLimit = p->iLimit;
  103892. pPrior->iOffset = p->iOffset;
  103893. pPrior->pLimit = p->pLimit;
  103894. pPrior->pOffset = p->pOffset;
  103895. explainSetInteger(iSub1, pParse->iNextSelectId);
  103896. rc = sqlite3Select(pParse, pPrior, &dest);
  103897. p->pLimit = 0;
  103898. p->pOffset = 0;
  103899. if( rc ){
  103900. goto multi_select_end;
  103901. }
  103902. p->pPrior = 0;
  103903. p->iLimit = pPrior->iLimit;
  103904. p->iOffset = pPrior->iOffset;
  103905. if( p->iLimit ){
  103906. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  103907. VdbeComment((v, "Jump ahead if LIMIT reached"));
  103908. if( p->iOffset ){
  103909. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
  103910. sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
  103911. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
  103912. }
  103913. }
  103914. explainSetInteger(iSub2, pParse->iNextSelectId);
  103915. rc = sqlite3Select(pParse, p, &dest);
  103916. testcase( rc!=SQLITE_OK );
  103917. pDelete = p->pPrior;
  103918. p->pPrior = pPrior;
  103919. p->nSelectRow += pPrior->nSelectRow;
  103920. if( pPrior->pLimit
  103921. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  103922. && nLimit>0 && p->nSelectRow > (u64)nLimit
  103923. ){
  103924. p->nSelectRow = nLimit;
  103925. }
  103926. if( addr ){
  103927. sqlite3VdbeJumpHere(v, addr);
  103928. }
  103929. break;
  103930. }
  103931. case TK_EXCEPT:
  103932. case TK_UNION: {
  103933. int unionTab; /* Cursor number of the temporary table holding result */
  103934. u8 op = 0; /* One of the SRT_ operations to apply to self */
  103935. int priorOp; /* The SRT_ operation to apply to prior selects */
  103936. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  103937. int addr;
  103938. SelectDest uniondest;
  103939. testcase( p->op==TK_EXCEPT );
  103940. testcase( p->op==TK_UNION );
  103941. priorOp = SRT_Union;
  103942. if( dest.eDest==priorOp ){
  103943. /* We can reuse a temporary table generated by a SELECT to our
  103944. ** right.
  103945. */
  103946. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  103947. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  103948. unionTab = dest.iSDParm;
  103949. }else{
  103950. /* We will need to create our own temporary table to hold the
  103951. ** intermediate results.
  103952. */
  103953. unionTab = pParse->nTab++;
  103954. assert( p->pOrderBy==0 );
  103955. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  103956. assert( p->addrOpenEphm[0] == -1 );
  103957. p->addrOpenEphm[0] = addr;
  103958. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  103959. assert( p->pEList );
  103960. }
  103961. /* Code the SELECT statements to our left
  103962. */
  103963. assert( !pPrior->pOrderBy );
  103964. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  103965. explainSetInteger(iSub1, pParse->iNextSelectId);
  103966. rc = sqlite3Select(pParse, pPrior, &uniondest);
  103967. if( rc ){
  103968. goto multi_select_end;
  103969. }
  103970. /* Code the current SELECT statement
  103971. */
  103972. if( p->op==TK_EXCEPT ){
  103973. op = SRT_Except;
  103974. }else{
  103975. assert( p->op==TK_UNION );
  103976. op = SRT_Union;
  103977. }
  103978. p->pPrior = 0;
  103979. pLimit = p->pLimit;
  103980. p->pLimit = 0;
  103981. pOffset = p->pOffset;
  103982. p->pOffset = 0;
  103983. uniondest.eDest = op;
  103984. explainSetInteger(iSub2, pParse->iNextSelectId);
  103985. rc = sqlite3Select(pParse, p, &uniondest);
  103986. testcase( rc!=SQLITE_OK );
  103987. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  103988. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  103989. sqlite3ExprListDelete(db, p->pOrderBy);
  103990. pDelete = p->pPrior;
  103991. p->pPrior = pPrior;
  103992. p->pOrderBy = 0;
  103993. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  103994. sqlite3ExprDelete(db, p->pLimit);
  103995. p->pLimit = pLimit;
  103996. p->pOffset = pOffset;
  103997. p->iLimit = 0;
  103998. p->iOffset = 0;
  103999. /* Convert the data in the temporary table into whatever form
  104000. ** it is that we currently need.
  104001. */
  104002. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  104003. if( dest.eDest!=priorOp ){
  104004. int iCont, iBreak, iStart;
  104005. assert( p->pEList );
  104006. if( dest.eDest==SRT_Output ){
  104007. Select *pFirst = p;
  104008. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  104009. generateColumnNames(pParse, 0, pFirst->pEList);
  104010. }
  104011. iBreak = sqlite3VdbeMakeLabel(v);
  104012. iCont = sqlite3VdbeMakeLabel(v);
  104013. computeLimitRegisters(pParse, p, iBreak);
  104014. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  104015. iStart = sqlite3VdbeCurrentAddr(v);
  104016. selectInnerLoop(pParse, p, p->pEList, unionTab,
  104017. 0, 0, &dest, iCont, iBreak);
  104018. sqlite3VdbeResolveLabel(v, iCont);
  104019. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  104020. sqlite3VdbeResolveLabel(v, iBreak);
  104021. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  104022. }
  104023. break;
  104024. }
  104025. default: assert( p->op==TK_INTERSECT ); {
  104026. int tab1, tab2;
  104027. int iCont, iBreak, iStart;
  104028. Expr *pLimit, *pOffset;
  104029. int addr;
  104030. SelectDest intersectdest;
  104031. int r1;
  104032. /* INTERSECT is different from the others since it requires
  104033. ** two temporary tables. Hence it has its own case. Begin
  104034. ** by allocating the tables we will need.
  104035. */
  104036. tab1 = pParse->nTab++;
  104037. tab2 = pParse->nTab++;
  104038. assert( p->pOrderBy==0 );
  104039. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  104040. assert( p->addrOpenEphm[0] == -1 );
  104041. p->addrOpenEphm[0] = addr;
  104042. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  104043. assert( p->pEList );
  104044. /* Code the SELECTs to our left into temporary table "tab1".
  104045. */
  104046. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  104047. explainSetInteger(iSub1, pParse->iNextSelectId);
  104048. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  104049. if( rc ){
  104050. goto multi_select_end;
  104051. }
  104052. /* Code the current SELECT into temporary table "tab2"
  104053. */
  104054. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  104055. assert( p->addrOpenEphm[1] == -1 );
  104056. p->addrOpenEphm[1] = addr;
  104057. p->pPrior = 0;
  104058. pLimit = p->pLimit;
  104059. p->pLimit = 0;
  104060. pOffset = p->pOffset;
  104061. p->pOffset = 0;
  104062. intersectdest.iSDParm = tab2;
  104063. explainSetInteger(iSub2, pParse->iNextSelectId);
  104064. rc = sqlite3Select(pParse, p, &intersectdest);
  104065. testcase( rc!=SQLITE_OK );
  104066. pDelete = p->pPrior;
  104067. p->pPrior = pPrior;
  104068. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  104069. sqlite3ExprDelete(db, p->pLimit);
  104070. p->pLimit = pLimit;
  104071. p->pOffset = pOffset;
  104072. /* Generate code to take the intersection of the two temporary
  104073. ** tables.
  104074. */
  104075. assert( p->pEList );
  104076. if( dest.eDest==SRT_Output ){
  104077. Select *pFirst = p;
  104078. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  104079. generateColumnNames(pParse, 0, pFirst->pEList);
  104080. }
  104081. iBreak = sqlite3VdbeMakeLabel(v);
  104082. iCont = sqlite3VdbeMakeLabel(v);
  104083. computeLimitRegisters(pParse, p, iBreak);
  104084. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  104085. r1 = sqlite3GetTempReg(pParse);
  104086. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  104087. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  104088. sqlite3ReleaseTempReg(pParse, r1);
  104089. selectInnerLoop(pParse, p, p->pEList, tab1,
  104090. 0, 0, &dest, iCont, iBreak);
  104091. sqlite3VdbeResolveLabel(v, iCont);
  104092. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  104093. sqlite3VdbeResolveLabel(v, iBreak);
  104094. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  104095. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  104096. break;
  104097. }
  104098. }
  104099. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  104100. /* Compute collating sequences used by
  104101. ** temporary tables needed to implement the compound select.
  104102. ** Attach the KeyInfo structure to all temporary tables.
  104103. **
  104104. ** This section is run by the right-most SELECT statement only.
  104105. ** SELECT statements to the left always skip this part. The right-most
  104106. ** SELECT might also skip this part if it has no ORDER BY clause and
  104107. ** no temp tables are required.
  104108. */
  104109. if( p->selFlags & SF_UsesEphemeral ){
  104110. int i; /* Loop counter */
  104111. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  104112. Select *pLoop; /* For looping through SELECT statements */
  104113. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  104114. int nCol; /* Number of columns in result set */
  104115. assert( p->pNext==0 );
  104116. nCol = p->pEList->nExpr;
  104117. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  104118. if( !pKeyInfo ){
  104119. rc = SQLITE_NOMEM;
  104120. goto multi_select_end;
  104121. }
  104122. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  104123. *apColl = multiSelectCollSeq(pParse, p, i);
  104124. if( 0==*apColl ){
  104125. *apColl = db->pDfltColl;
  104126. }
  104127. }
  104128. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  104129. for(i=0; i<2; i++){
  104130. int addr = pLoop->addrOpenEphm[i];
  104131. if( addr<0 ){
  104132. /* If [0] is unused then [1] is also unused. So we can
  104133. ** always safely abort as soon as the first unused slot is found */
  104134. assert( pLoop->addrOpenEphm[1]<0 );
  104135. break;
  104136. }
  104137. sqlite3VdbeChangeP2(v, addr, nCol);
  104138. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  104139. P4_KEYINFO);
  104140. pLoop->addrOpenEphm[i] = -1;
  104141. }
  104142. }
  104143. sqlite3KeyInfoUnref(pKeyInfo);
  104144. }
  104145. multi_select_end:
  104146. pDest->iSdst = dest.iSdst;
  104147. pDest->nSdst = dest.nSdst;
  104148. sqlite3SelectDelete(db, pDelete);
  104149. return rc;
  104150. }
  104151. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  104152. /*
  104153. ** Error message for when two or more terms of a compound select have different
  104154. ** size result sets.
  104155. */
  104156. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  104157. if( p->selFlags & SF_Values ){
  104158. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  104159. }else{
  104160. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  104161. " do not have the same number of result columns", selectOpName(p->op));
  104162. }
  104163. }
  104164. /*
  104165. ** Code an output subroutine for a coroutine implementation of a
  104166. ** SELECT statment.
  104167. **
  104168. ** The data to be output is contained in pIn->iSdst. There are
  104169. ** pIn->nSdst columns to be output. pDest is where the output should
  104170. ** be sent.
  104171. **
  104172. ** regReturn is the number of the register holding the subroutine
  104173. ** return address.
  104174. **
  104175. ** If regPrev>0 then it is the first register in a vector that
  104176. ** records the previous output. mem[regPrev] is a flag that is false
  104177. ** if there has been no previous output. If regPrev>0 then code is
  104178. ** generated to suppress duplicates. pKeyInfo is used for comparing
  104179. ** keys.
  104180. **
  104181. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  104182. ** iBreak.
  104183. */
  104184. static int generateOutputSubroutine(
  104185. Parse *pParse, /* Parsing context */
  104186. Select *p, /* The SELECT statement */
  104187. SelectDest *pIn, /* Coroutine supplying data */
  104188. SelectDest *pDest, /* Where to send the data */
  104189. int regReturn, /* The return address register */
  104190. int regPrev, /* Previous result register. No uniqueness if 0 */
  104191. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  104192. int iBreak /* Jump here if we hit the LIMIT */
  104193. ){
  104194. Vdbe *v = pParse->pVdbe;
  104195. int iContinue;
  104196. int addr;
  104197. addr = sqlite3VdbeCurrentAddr(v);
  104198. iContinue = sqlite3VdbeMakeLabel(v);
  104199. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  104200. */
  104201. if( regPrev ){
  104202. int addr1, addr2;
  104203. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  104204. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  104205. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  104206. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  104207. sqlite3VdbeJumpHere(v, addr1);
  104208. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  104209. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  104210. }
  104211. if( pParse->db->mallocFailed ) return 0;
  104212. /* Suppress the first OFFSET entries if there is an OFFSET clause
  104213. */
  104214. codeOffset(v, p->iOffset, iContinue);
  104215. assert( pDest->eDest!=SRT_Exists );
  104216. assert( pDest->eDest!=SRT_Table );
  104217. switch( pDest->eDest ){
  104218. /* Store the result as data using a unique key.
  104219. */
  104220. case SRT_EphemTab: {
  104221. int r1 = sqlite3GetTempReg(pParse);
  104222. int r2 = sqlite3GetTempReg(pParse);
  104223. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  104224. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  104225. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  104226. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  104227. sqlite3ReleaseTempReg(pParse, r2);
  104228. sqlite3ReleaseTempReg(pParse, r1);
  104229. break;
  104230. }
  104231. #ifndef SQLITE_OMIT_SUBQUERY
  104232. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  104233. ** then there should be a single item on the stack. Write this
  104234. ** item into the set table with bogus data.
  104235. */
  104236. case SRT_Set: {
  104237. int r1;
  104238. assert( pIn->nSdst==1 || pParse->nErr>0 );
  104239. pDest->affSdst =
  104240. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  104241. r1 = sqlite3GetTempReg(pParse);
  104242. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  104243. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  104244. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  104245. sqlite3ReleaseTempReg(pParse, r1);
  104246. break;
  104247. }
  104248. /* If this is a scalar select that is part of an expression, then
  104249. ** store the results in the appropriate memory cell and break out
  104250. ** of the scan loop.
  104251. */
  104252. case SRT_Mem: {
  104253. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  104254. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  104255. /* The LIMIT clause will jump out of the loop for us */
  104256. break;
  104257. }
  104258. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  104259. /* The results are stored in a sequence of registers
  104260. ** starting at pDest->iSdst. Then the co-routine yields.
  104261. */
  104262. case SRT_Coroutine: {
  104263. if( pDest->iSdst==0 ){
  104264. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  104265. pDest->nSdst = pIn->nSdst;
  104266. }
  104267. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  104268. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  104269. break;
  104270. }
  104271. /* If none of the above, then the result destination must be
  104272. ** SRT_Output. This routine is never called with any other
  104273. ** destination other than the ones handled above or SRT_Output.
  104274. **
  104275. ** For SRT_Output, results are stored in a sequence of registers.
  104276. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  104277. ** return the next row of result.
  104278. */
  104279. default: {
  104280. assert( pDest->eDest==SRT_Output );
  104281. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  104282. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  104283. break;
  104284. }
  104285. }
  104286. /* Jump to the end of the loop if the LIMIT is reached.
  104287. */
  104288. if( p->iLimit ){
  104289. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  104290. }
  104291. /* Generate the subroutine return
  104292. */
  104293. sqlite3VdbeResolveLabel(v, iContinue);
  104294. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  104295. return addr;
  104296. }
  104297. /*
  104298. ** Alternative compound select code generator for cases when there
  104299. ** is an ORDER BY clause.
  104300. **
  104301. ** We assume a query of the following form:
  104302. **
  104303. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  104304. **
  104305. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  104306. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  104307. ** co-routines. Then run the co-routines in parallel and merge the results
  104308. ** into the output. In addition to the two coroutines (called selectA and
  104309. ** selectB) there are 7 subroutines:
  104310. **
  104311. ** outA: Move the output of the selectA coroutine into the output
  104312. ** of the compound query.
  104313. **
  104314. ** outB: Move the output of the selectB coroutine into the output
  104315. ** of the compound query. (Only generated for UNION and
  104316. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  104317. ** appears only in B.)
  104318. **
  104319. ** AltB: Called when there is data from both coroutines and A<B.
  104320. **
  104321. ** AeqB: Called when there is data from both coroutines and A==B.
  104322. **
  104323. ** AgtB: Called when there is data from both coroutines and A>B.
  104324. **
  104325. ** EofA: Called when data is exhausted from selectA.
  104326. **
  104327. ** EofB: Called when data is exhausted from selectB.
  104328. **
  104329. ** The implementation of the latter five subroutines depend on which
  104330. ** <operator> is used:
  104331. **
  104332. **
  104333. ** UNION ALL UNION EXCEPT INTERSECT
  104334. ** ------------- ----------------- -------------- -----------------
  104335. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  104336. **
  104337. ** AeqB: outA, nextA nextA nextA outA, nextA
  104338. **
  104339. ** AgtB: outB, nextB outB, nextB nextB nextB
  104340. **
  104341. ** EofA: outB, nextB outB, nextB halt halt
  104342. **
  104343. ** EofB: outA, nextA outA, nextA outA, nextA halt
  104344. **
  104345. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  104346. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  104347. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  104348. ** following nextX causes a jump to the end of the select processing.
  104349. **
  104350. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  104351. ** within the output subroutine. The regPrev register set holds the previously
  104352. ** output value. A comparison is made against this value and the output
  104353. ** is skipped if the next results would be the same as the previous.
  104354. **
  104355. ** The implementation plan is to implement the two coroutines and seven
  104356. ** subroutines first, then put the control logic at the bottom. Like this:
  104357. **
  104358. ** goto Init
  104359. ** coA: coroutine for left query (A)
  104360. ** coB: coroutine for right query (B)
  104361. ** outA: output one row of A
  104362. ** outB: output one row of B (UNION and UNION ALL only)
  104363. ** EofA: ...
  104364. ** EofB: ...
  104365. ** AltB: ...
  104366. ** AeqB: ...
  104367. ** AgtB: ...
  104368. ** Init: initialize coroutine registers
  104369. ** yield coA
  104370. ** if eof(A) goto EofA
  104371. ** yield coB
  104372. ** if eof(B) goto EofB
  104373. ** Cmpr: Compare A, B
  104374. ** Jump AltB, AeqB, AgtB
  104375. ** End: ...
  104376. **
  104377. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  104378. ** actually called using Gosub and they do not Return. EofA and EofB loop
  104379. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  104380. ** and AgtB jump to either L2 or to one of EofA or EofB.
  104381. */
  104382. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  104383. static int multiSelectOrderBy(
  104384. Parse *pParse, /* Parsing context */
  104385. Select *p, /* The right-most of SELECTs to be coded */
  104386. SelectDest *pDest /* What to do with query results */
  104387. ){
  104388. int i, j; /* Loop counters */
  104389. Select *pPrior; /* Another SELECT immediately to our left */
  104390. Vdbe *v; /* Generate code to this VDBE */
  104391. SelectDest destA; /* Destination for coroutine A */
  104392. SelectDest destB; /* Destination for coroutine B */
  104393. int regAddrA; /* Address register for select-A coroutine */
  104394. int regAddrB; /* Address register for select-B coroutine */
  104395. int addrSelectA; /* Address of the select-A coroutine */
  104396. int addrSelectB; /* Address of the select-B coroutine */
  104397. int regOutA; /* Address register for the output-A subroutine */
  104398. int regOutB; /* Address register for the output-B subroutine */
  104399. int addrOutA; /* Address of the output-A subroutine */
  104400. int addrOutB = 0; /* Address of the output-B subroutine */
  104401. int addrEofA; /* Address of the select-A-exhausted subroutine */
  104402. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  104403. int addrEofB; /* Address of the select-B-exhausted subroutine */
  104404. int addrAltB; /* Address of the A<B subroutine */
  104405. int addrAeqB; /* Address of the A==B subroutine */
  104406. int addrAgtB; /* Address of the A>B subroutine */
  104407. int regLimitA; /* Limit register for select-A */
  104408. int regLimitB; /* Limit register for select-A */
  104409. int regPrev; /* A range of registers to hold previous output */
  104410. int savedLimit; /* Saved value of p->iLimit */
  104411. int savedOffset; /* Saved value of p->iOffset */
  104412. int labelCmpr; /* Label for the start of the merge algorithm */
  104413. int labelEnd; /* Label for the end of the overall SELECT stmt */
  104414. int addr1; /* Jump instructions that get retargetted */
  104415. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  104416. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  104417. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  104418. sqlite3 *db; /* Database connection */
  104419. ExprList *pOrderBy; /* The ORDER BY clause */
  104420. int nOrderBy; /* Number of terms in the ORDER BY clause */
  104421. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  104422. #ifndef SQLITE_OMIT_EXPLAIN
  104423. int iSub1; /* EQP id of left-hand query */
  104424. int iSub2; /* EQP id of right-hand query */
  104425. #endif
  104426. assert( p->pOrderBy!=0 );
  104427. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  104428. db = pParse->db;
  104429. v = pParse->pVdbe;
  104430. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  104431. labelEnd = sqlite3VdbeMakeLabel(v);
  104432. labelCmpr = sqlite3VdbeMakeLabel(v);
  104433. /* Patch up the ORDER BY clause
  104434. */
  104435. op = p->op;
  104436. pPrior = p->pPrior;
  104437. assert( pPrior->pOrderBy==0 );
  104438. pOrderBy = p->pOrderBy;
  104439. assert( pOrderBy );
  104440. nOrderBy = pOrderBy->nExpr;
  104441. /* For operators other than UNION ALL we have to make sure that
  104442. ** the ORDER BY clause covers every term of the result set. Add
  104443. ** terms to the ORDER BY clause as necessary.
  104444. */
  104445. if( op!=TK_ALL ){
  104446. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  104447. struct ExprList_item *pItem;
  104448. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  104449. assert( pItem->u.x.iOrderByCol>0 );
  104450. if( pItem->u.x.iOrderByCol==i ) break;
  104451. }
  104452. if( j==nOrderBy ){
  104453. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  104454. if( pNew==0 ) return SQLITE_NOMEM;
  104455. pNew->flags |= EP_IntValue;
  104456. pNew->u.iValue = i;
  104457. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  104458. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  104459. }
  104460. }
  104461. }
  104462. /* Compute the comparison permutation and keyinfo that is used with
  104463. ** the permutation used to determine if the next
  104464. ** row of results comes from selectA or selectB. Also add explicit
  104465. ** collations to the ORDER BY clause terms so that when the subqueries
  104466. ** to the right and the left are evaluated, they use the correct
  104467. ** collation.
  104468. */
  104469. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  104470. if( aPermute ){
  104471. struct ExprList_item *pItem;
  104472. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  104473. assert( pItem->u.x.iOrderByCol>0 );
  104474. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  104475. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  104476. }
  104477. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  104478. }else{
  104479. pKeyMerge = 0;
  104480. }
  104481. /* Reattach the ORDER BY clause to the query.
  104482. */
  104483. p->pOrderBy = pOrderBy;
  104484. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  104485. /* Allocate a range of temporary registers and the KeyInfo needed
  104486. ** for the logic that removes duplicate result rows when the
  104487. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  104488. */
  104489. if( op==TK_ALL ){
  104490. regPrev = 0;
  104491. }else{
  104492. int nExpr = p->pEList->nExpr;
  104493. assert( nOrderBy>=nExpr || db->mallocFailed );
  104494. regPrev = pParse->nMem+1;
  104495. pParse->nMem += nExpr+1;
  104496. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  104497. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  104498. if( pKeyDup ){
  104499. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  104500. for(i=0; i<nExpr; i++){
  104501. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  104502. pKeyDup->aSortOrder[i] = 0;
  104503. }
  104504. }
  104505. }
  104506. /* Separate the left and the right query from one another
  104507. */
  104508. p->pPrior = 0;
  104509. pPrior->pNext = 0;
  104510. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  104511. if( pPrior->pPrior==0 ){
  104512. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  104513. }
  104514. /* Compute the limit registers */
  104515. computeLimitRegisters(pParse, p, labelEnd);
  104516. if( p->iLimit && op==TK_ALL ){
  104517. regLimitA = ++pParse->nMem;
  104518. regLimitB = ++pParse->nMem;
  104519. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  104520. regLimitA);
  104521. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  104522. }else{
  104523. regLimitA = regLimitB = 0;
  104524. }
  104525. sqlite3ExprDelete(db, p->pLimit);
  104526. p->pLimit = 0;
  104527. sqlite3ExprDelete(db, p->pOffset);
  104528. p->pOffset = 0;
  104529. regAddrA = ++pParse->nMem;
  104530. regAddrB = ++pParse->nMem;
  104531. regOutA = ++pParse->nMem;
  104532. regOutB = ++pParse->nMem;
  104533. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  104534. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  104535. /* Generate a coroutine to evaluate the SELECT statement to the
  104536. ** left of the compound operator - the "A" select.
  104537. */
  104538. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  104539. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  104540. VdbeComment((v, "left SELECT"));
  104541. pPrior->iLimit = regLimitA;
  104542. explainSetInteger(iSub1, pParse->iNextSelectId);
  104543. sqlite3Select(pParse, pPrior, &destA);
  104544. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  104545. sqlite3VdbeJumpHere(v, addr1);
  104546. /* Generate a coroutine to evaluate the SELECT statement on
  104547. ** the right - the "B" select
  104548. */
  104549. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  104550. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  104551. VdbeComment((v, "right SELECT"));
  104552. savedLimit = p->iLimit;
  104553. savedOffset = p->iOffset;
  104554. p->iLimit = regLimitB;
  104555. p->iOffset = 0;
  104556. explainSetInteger(iSub2, pParse->iNextSelectId);
  104557. sqlite3Select(pParse, p, &destB);
  104558. p->iLimit = savedLimit;
  104559. p->iOffset = savedOffset;
  104560. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  104561. /* Generate a subroutine that outputs the current row of the A
  104562. ** select as the next output row of the compound select.
  104563. */
  104564. VdbeNoopComment((v, "Output routine for A"));
  104565. addrOutA = generateOutputSubroutine(pParse,
  104566. p, &destA, pDest, regOutA,
  104567. regPrev, pKeyDup, labelEnd);
  104568. /* Generate a subroutine that outputs the current row of the B
  104569. ** select as the next output row of the compound select.
  104570. */
  104571. if( op==TK_ALL || op==TK_UNION ){
  104572. VdbeNoopComment((v, "Output routine for B"));
  104573. addrOutB = generateOutputSubroutine(pParse,
  104574. p, &destB, pDest, regOutB,
  104575. regPrev, pKeyDup, labelEnd);
  104576. }
  104577. sqlite3KeyInfoUnref(pKeyDup);
  104578. /* Generate a subroutine to run when the results from select A
  104579. ** are exhausted and only data in select B remains.
  104580. */
  104581. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  104582. addrEofA_noB = addrEofA = labelEnd;
  104583. }else{
  104584. VdbeNoopComment((v, "eof-A subroutine"));
  104585. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  104586. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  104587. VdbeCoverage(v);
  104588. sqlite3VdbeGoto(v, addrEofA);
  104589. p->nSelectRow += pPrior->nSelectRow;
  104590. }
  104591. /* Generate a subroutine to run when the results from select B
  104592. ** are exhausted and only data in select A remains.
  104593. */
  104594. if( op==TK_INTERSECT ){
  104595. addrEofB = addrEofA;
  104596. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  104597. }else{
  104598. VdbeNoopComment((v, "eof-B subroutine"));
  104599. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  104600. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  104601. sqlite3VdbeGoto(v, addrEofB);
  104602. }
  104603. /* Generate code to handle the case of A<B
  104604. */
  104605. VdbeNoopComment((v, "A-lt-B subroutine"));
  104606. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  104607. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  104608. sqlite3VdbeGoto(v, labelCmpr);
  104609. /* Generate code to handle the case of A==B
  104610. */
  104611. if( op==TK_ALL ){
  104612. addrAeqB = addrAltB;
  104613. }else if( op==TK_INTERSECT ){
  104614. addrAeqB = addrAltB;
  104615. addrAltB++;
  104616. }else{
  104617. VdbeNoopComment((v, "A-eq-B subroutine"));
  104618. addrAeqB =
  104619. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  104620. sqlite3VdbeGoto(v, labelCmpr);
  104621. }
  104622. /* Generate code to handle the case of A>B
  104623. */
  104624. VdbeNoopComment((v, "A-gt-B subroutine"));
  104625. addrAgtB = sqlite3VdbeCurrentAddr(v);
  104626. if( op==TK_ALL || op==TK_UNION ){
  104627. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  104628. }
  104629. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  104630. sqlite3VdbeGoto(v, labelCmpr);
  104631. /* This code runs once to initialize everything.
  104632. */
  104633. sqlite3VdbeJumpHere(v, addr1);
  104634. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  104635. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  104636. /* Implement the main merge loop
  104637. */
  104638. sqlite3VdbeResolveLabel(v, labelCmpr);
  104639. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  104640. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  104641. (char*)pKeyMerge, P4_KEYINFO);
  104642. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  104643. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  104644. /* Jump to the this point in order to terminate the query.
  104645. */
  104646. sqlite3VdbeResolveLabel(v, labelEnd);
  104647. /* Set the number of output columns
  104648. */
  104649. if( pDest->eDest==SRT_Output ){
  104650. Select *pFirst = pPrior;
  104651. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  104652. generateColumnNames(pParse, 0, pFirst->pEList);
  104653. }
  104654. /* Reassembly the compound query so that it will be freed correctly
  104655. ** by the calling function */
  104656. if( p->pPrior ){
  104657. sqlite3SelectDelete(db, p->pPrior);
  104658. }
  104659. p->pPrior = pPrior;
  104660. pPrior->pNext = p;
  104661. /*** TBD: Insert subroutine calls to close cursors on incomplete
  104662. **** subqueries ****/
  104663. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  104664. return pParse->nErr!=0;
  104665. }
  104666. #endif
  104667. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  104668. /* Forward Declarations */
  104669. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  104670. static void substSelect(sqlite3*, Select *, int, ExprList*, int);
  104671. /*
  104672. ** Scan through the expression pExpr. Replace every reference to
  104673. ** a column in table number iTable with a copy of the iColumn-th
  104674. ** entry in pEList. (But leave references to the ROWID column
  104675. ** unchanged.)
  104676. **
  104677. ** This routine is part of the flattening procedure. A subquery
  104678. ** whose result set is defined by pEList appears as entry in the
  104679. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  104680. ** FORM clause entry is iTable. This routine make the necessary
  104681. ** changes to pExpr so that it refers directly to the source table
  104682. ** of the subquery rather the result set of the subquery.
  104683. */
  104684. static Expr *substExpr(
  104685. sqlite3 *db, /* Report malloc errors to this connection */
  104686. Expr *pExpr, /* Expr in which substitution occurs */
  104687. int iTable, /* Table to be substituted */
  104688. ExprList *pEList /* Substitute expressions */
  104689. ){
  104690. if( pExpr==0 ) return 0;
  104691. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  104692. if( pExpr->iColumn<0 ){
  104693. pExpr->op = TK_NULL;
  104694. }else{
  104695. Expr *pNew;
  104696. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  104697. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  104698. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  104699. sqlite3ExprDelete(db, pExpr);
  104700. pExpr = pNew;
  104701. }
  104702. }else{
  104703. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  104704. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  104705. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  104706. substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
  104707. }else{
  104708. substExprList(db, pExpr->x.pList, iTable, pEList);
  104709. }
  104710. }
  104711. return pExpr;
  104712. }
  104713. static void substExprList(
  104714. sqlite3 *db, /* Report malloc errors here */
  104715. ExprList *pList, /* List to scan and in which to make substitutes */
  104716. int iTable, /* Table to be substituted */
  104717. ExprList *pEList /* Substitute values */
  104718. ){
  104719. int i;
  104720. if( pList==0 ) return;
  104721. for(i=0; i<pList->nExpr; i++){
  104722. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  104723. }
  104724. }
  104725. static void substSelect(
  104726. sqlite3 *db, /* Report malloc errors here */
  104727. Select *p, /* SELECT statement in which to make substitutions */
  104728. int iTable, /* Table to be replaced */
  104729. ExprList *pEList, /* Substitute values */
  104730. int doPrior /* Do substitutes on p->pPrior too */
  104731. ){
  104732. SrcList *pSrc;
  104733. struct SrcList_item *pItem;
  104734. int i;
  104735. if( !p ) return;
  104736. do{
  104737. substExprList(db, p->pEList, iTable, pEList);
  104738. substExprList(db, p->pGroupBy, iTable, pEList);
  104739. substExprList(db, p->pOrderBy, iTable, pEList);
  104740. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  104741. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  104742. pSrc = p->pSrc;
  104743. assert( pSrc!=0 );
  104744. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  104745. substSelect(db, pItem->pSelect, iTable, pEList, 1);
  104746. if( pItem->fg.isTabFunc ){
  104747. substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
  104748. }
  104749. }
  104750. }while( doPrior && (p = p->pPrior)!=0 );
  104751. }
  104752. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  104753. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  104754. /*
  104755. ** This routine attempts to flatten subqueries as a performance optimization.
  104756. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  104757. **
  104758. ** To understand the concept of flattening, consider the following
  104759. ** query:
  104760. **
  104761. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  104762. **
  104763. ** The default way of implementing this query is to execute the
  104764. ** subquery first and store the results in a temporary table, then
  104765. ** run the outer query on that temporary table. This requires two
  104766. ** passes over the data. Furthermore, because the temporary table
  104767. ** has no indices, the WHERE clause on the outer query cannot be
  104768. ** optimized.
  104769. **
  104770. ** This routine attempts to rewrite queries such as the above into
  104771. ** a single flat select, like this:
  104772. **
  104773. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  104774. **
  104775. ** The code generated for this simplification gives the same result
  104776. ** but only has to scan the data once. And because indices might
  104777. ** exist on the table t1, a complete scan of the data might be
  104778. ** avoided.
  104779. **
  104780. ** Flattening is only attempted if all of the following are true:
  104781. **
  104782. ** (1) The subquery and the outer query do not both use aggregates.
  104783. **
  104784. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  104785. ** and (2b) the outer query does not use subqueries other than the one
  104786. ** FROM-clause subquery that is a candidate for flattening. (2b is
  104787. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  104788. **
  104789. ** (3) The subquery is not the right operand of a left outer join
  104790. ** (Originally ticket #306. Strengthened by ticket #3300)
  104791. **
  104792. ** (4) The subquery is not DISTINCT.
  104793. **
  104794. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  104795. ** sub-queries that were excluded from this optimization. Restriction
  104796. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  104797. **
  104798. ** (6) The subquery does not use aggregates or the outer query is not
  104799. ** DISTINCT.
  104800. **
  104801. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  104802. ** A FROM clause, consider adding a FROM close with the special
  104803. ** table sqlite_once that consists of a single row containing a
  104804. ** single NULL.
  104805. **
  104806. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  104807. **
  104808. ** (9) The subquery does not use LIMIT or the outer query does not use
  104809. ** aggregates.
  104810. **
  104811. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  104812. ** accidently carried the comment forward until 2014-09-15. Original
  104813. ** text: "The subquery does not use aggregates or the outer query
  104814. ** does not use LIMIT."
  104815. **
  104816. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  104817. **
  104818. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  104819. ** a separate restriction deriving from ticket #350.
  104820. **
  104821. ** (13) The subquery and outer query do not both use LIMIT.
  104822. **
  104823. ** (14) The subquery does not use OFFSET.
  104824. **
  104825. ** (15) The outer query is not part of a compound select or the
  104826. ** subquery does not have a LIMIT clause.
  104827. ** (See ticket #2339 and ticket [02a8e81d44]).
  104828. **
  104829. ** (16) The outer query is not an aggregate or the subquery does
  104830. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  104831. ** until we introduced the group_concat() function.
  104832. **
  104833. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  104834. ** compound clause made up entirely of non-aggregate queries, and
  104835. ** the parent query:
  104836. **
  104837. ** * is not itself part of a compound select,
  104838. ** * is not an aggregate or DISTINCT query, and
  104839. ** * is not a join
  104840. **
  104841. ** The parent and sub-query may contain WHERE clauses. Subject to
  104842. ** rules (11), (13) and (14), they may also contain ORDER BY,
  104843. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  104844. ** operator other than UNION ALL because all the other compound
  104845. ** operators have an implied DISTINCT which is disallowed by
  104846. ** restriction (4).
  104847. **
  104848. ** Also, each component of the sub-query must return the same number
  104849. ** of result columns. This is actually a requirement for any compound
  104850. ** SELECT statement, but all the code here does is make sure that no
  104851. ** such (illegal) sub-query is flattened. The caller will detect the
  104852. ** syntax error and return a detailed message.
  104853. **
  104854. ** (18) If the sub-query is a compound select, then all terms of the
  104855. ** ORDER by clause of the parent must be simple references to
  104856. ** columns of the sub-query.
  104857. **
  104858. ** (19) The subquery does not use LIMIT or the outer query does not
  104859. ** have a WHERE clause.
  104860. **
  104861. ** (20) If the sub-query is a compound select, then it must not use
  104862. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  104863. ** somewhat by saying that the terms of the ORDER BY clause must
  104864. ** appear as unmodified result columns in the outer query. But we
  104865. ** have other optimizations in mind to deal with that case.
  104866. **
  104867. ** (21) The subquery does not use LIMIT or the outer query is not
  104868. ** DISTINCT. (See ticket [752e1646fc]).
  104869. **
  104870. ** (22) The subquery is not a recursive CTE.
  104871. **
  104872. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  104873. ** compound query. This restriction is because transforming the
  104874. ** parent to a compound query confuses the code that handles
  104875. ** recursive queries in multiSelect().
  104876. **
  104877. ** (24) The subquery is not an aggregate that uses the built-in min() or
  104878. ** or max() functions. (Without this restriction, a query like:
  104879. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  104880. ** return the value X for which Y was maximal.)
  104881. **
  104882. **
  104883. ** In this routine, the "p" parameter is a pointer to the outer query.
  104884. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  104885. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  104886. **
  104887. ** If flattening is not attempted, this routine is a no-op and returns 0.
  104888. ** If flattening is attempted this routine returns 1.
  104889. **
  104890. ** All of the expression analysis must occur on both the outer query and
  104891. ** the subquery before this routine runs.
  104892. */
  104893. static int flattenSubquery(
  104894. Parse *pParse, /* Parsing context */
  104895. Select *p, /* The parent or outer SELECT statement */
  104896. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  104897. int isAgg, /* True if outer SELECT uses aggregate functions */
  104898. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  104899. ){
  104900. const char *zSavedAuthContext = pParse->zAuthContext;
  104901. Select *pParent; /* Current UNION ALL term of the other query */
  104902. Select *pSub; /* The inner query or "subquery" */
  104903. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  104904. SrcList *pSrc; /* The FROM clause of the outer query */
  104905. SrcList *pSubSrc; /* The FROM clause of the subquery */
  104906. ExprList *pList; /* The result set of the outer query */
  104907. int iParent; /* VDBE cursor number of the pSub result set temp table */
  104908. int i; /* Loop counter */
  104909. Expr *pWhere; /* The WHERE clause */
  104910. struct SrcList_item *pSubitem; /* The subquery */
  104911. sqlite3 *db = pParse->db;
  104912. /* Check to see if flattening is permitted. Return 0 if not.
  104913. */
  104914. assert( p!=0 );
  104915. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  104916. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  104917. pSrc = p->pSrc;
  104918. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  104919. pSubitem = &pSrc->a[iFrom];
  104920. iParent = pSubitem->iCursor;
  104921. pSub = pSubitem->pSelect;
  104922. assert( pSub!=0 );
  104923. if( subqueryIsAgg ){
  104924. if( isAgg ) return 0; /* Restriction (1) */
  104925. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  104926. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  104927. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  104928. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  104929. ){
  104930. return 0; /* Restriction (2b) */
  104931. }
  104932. }
  104933. pSubSrc = pSub->pSrc;
  104934. assert( pSubSrc );
  104935. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  104936. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  104937. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  104938. ** became arbitrary expressions, we were forced to add restrictions (13)
  104939. ** and (14). */
  104940. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  104941. if( pSub->pOffset ) return 0; /* Restriction (14) */
  104942. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  104943. return 0; /* Restriction (15) */
  104944. }
  104945. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  104946. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  104947. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  104948. return 0; /* Restrictions (8)(9) */
  104949. }
  104950. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  104951. return 0; /* Restriction (6) */
  104952. }
  104953. if( p->pOrderBy && pSub->pOrderBy ){
  104954. return 0; /* Restriction (11) */
  104955. }
  104956. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  104957. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  104958. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  104959. return 0; /* Restriction (21) */
  104960. }
  104961. testcase( pSub->selFlags & SF_Recursive );
  104962. testcase( pSub->selFlags & SF_MinMaxAgg );
  104963. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  104964. return 0; /* Restrictions (22) and (24) */
  104965. }
  104966. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  104967. return 0; /* Restriction (23) */
  104968. }
  104969. /* OBSOLETE COMMENT 1:
  104970. ** Restriction 3: If the subquery is a join, make sure the subquery is
  104971. ** not used as the right operand of an outer join. Examples of why this
  104972. ** is not allowed:
  104973. **
  104974. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  104975. **
  104976. ** If we flatten the above, we would get
  104977. **
  104978. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  104979. **
  104980. ** which is not at all the same thing.
  104981. **
  104982. ** OBSOLETE COMMENT 2:
  104983. ** Restriction 12: If the subquery is the right operand of a left outer
  104984. ** join, make sure the subquery has no WHERE clause.
  104985. ** An examples of why this is not allowed:
  104986. **
  104987. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  104988. **
  104989. ** If we flatten the above, we would get
  104990. **
  104991. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  104992. **
  104993. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  104994. ** effectively converts the OUTER JOIN into an INNER JOIN.
  104995. **
  104996. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  104997. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  104998. ** is fraught with danger. Best to avoid the whole thing. If the
  104999. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  105000. */
  105001. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  105002. return 0;
  105003. }
  105004. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  105005. ** use only the UNION ALL operator. And none of the simple select queries
  105006. ** that make up the compound SELECT are allowed to be aggregate or distinct
  105007. ** queries.
  105008. */
  105009. if( pSub->pPrior ){
  105010. if( pSub->pOrderBy ){
  105011. return 0; /* Restriction 20 */
  105012. }
  105013. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  105014. return 0;
  105015. }
  105016. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  105017. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  105018. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  105019. assert( pSub->pSrc!=0 );
  105020. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  105021. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  105022. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  105023. || pSub1->pSrc->nSrc<1
  105024. ){
  105025. return 0;
  105026. }
  105027. testcase( pSub1->pSrc->nSrc>1 );
  105028. }
  105029. /* Restriction 18. */
  105030. if( p->pOrderBy ){
  105031. int ii;
  105032. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  105033. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  105034. }
  105035. }
  105036. }
  105037. /***** If we reach this point, flattening is permitted. *****/
  105038. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  105039. pSub->zSelName, pSub, iFrom));
  105040. /* Authorize the subquery */
  105041. pParse->zAuthContext = pSubitem->zName;
  105042. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  105043. testcase( i==SQLITE_DENY );
  105044. pParse->zAuthContext = zSavedAuthContext;
  105045. /* If the sub-query is a compound SELECT statement, then (by restrictions
  105046. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  105047. ** be of the form:
  105048. **
  105049. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  105050. **
  105051. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  105052. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  105053. ** OFFSET clauses and joins them to the left-hand-side of the original
  105054. ** using UNION ALL operators. In this case N is the number of simple
  105055. ** select statements in the compound sub-query.
  105056. **
  105057. ** Example:
  105058. **
  105059. ** SELECT a+1 FROM (
  105060. ** SELECT x FROM tab
  105061. ** UNION ALL
  105062. ** SELECT y FROM tab
  105063. ** UNION ALL
  105064. ** SELECT abs(z*2) FROM tab2
  105065. ** ) WHERE a!=5 ORDER BY 1
  105066. **
  105067. ** Transformed into:
  105068. **
  105069. ** SELECT x+1 FROM tab WHERE x+1!=5
  105070. ** UNION ALL
  105071. ** SELECT y+1 FROM tab WHERE y+1!=5
  105072. ** UNION ALL
  105073. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  105074. ** ORDER BY 1
  105075. **
  105076. ** We call this the "compound-subquery flattening".
  105077. */
  105078. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  105079. Select *pNew;
  105080. ExprList *pOrderBy = p->pOrderBy;
  105081. Expr *pLimit = p->pLimit;
  105082. Expr *pOffset = p->pOffset;
  105083. Select *pPrior = p->pPrior;
  105084. p->pOrderBy = 0;
  105085. p->pSrc = 0;
  105086. p->pPrior = 0;
  105087. p->pLimit = 0;
  105088. p->pOffset = 0;
  105089. pNew = sqlite3SelectDup(db, p, 0);
  105090. sqlite3SelectSetName(pNew, pSub->zSelName);
  105091. p->pOffset = pOffset;
  105092. p->pLimit = pLimit;
  105093. p->pOrderBy = pOrderBy;
  105094. p->pSrc = pSrc;
  105095. p->op = TK_ALL;
  105096. if( pNew==0 ){
  105097. p->pPrior = pPrior;
  105098. }else{
  105099. pNew->pPrior = pPrior;
  105100. if( pPrior ) pPrior->pNext = pNew;
  105101. pNew->pNext = p;
  105102. p->pPrior = pNew;
  105103. SELECTTRACE(2,pParse,p,
  105104. ("compound-subquery flattener creates %s.%p as peer\n",
  105105. pNew->zSelName, pNew));
  105106. }
  105107. if( db->mallocFailed ) return 1;
  105108. }
  105109. /* Begin flattening the iFrom-th entry of the FROM clause
  105110. ** in the outer query.
  105111. */
  105112. pSub = pSub1 = pSubitem->pSelect;
  105113. /* Delete the transient table structure associated with the
  105114. ** subquery
  105115. */
  105116. sqlite3DbFree(db, pSubitem->zDatabase);
  105117. sqlite3DbFree(db, pSubitem->zName);
  105118. sqlite3DbFree(db, pSubitem->zAlias);
  105119. pSubitem->zDatabase = 0;
  105120. pSubitem->zName = 0;
  105121. pSubitem->zAlias = 0;
  105122. pSubitem->pSelect = 0;
  105123. /* Defer deleting the Table object associated with the
  105124. ** subquery until code generation is
  105125. ** complete, since there may still exist Expr.pTab entries that
  105126. ** refer to the subquery even after flattening. Ticket #3346.
  105127. **
  105128. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  105129. */
  105130. if( ALWAYS(pSubitem->pTab!=0) ){
  105131. Table *pTabToDel = pSubitem->pTab;
  105132. if( pTabToDel->nRef==1 ){
  105133. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  105134. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  105135. pToplevel->pZombieTab = pTabToDel;
  105136. }else{
  105137. pTabToDel->nRef--;
  105138. }
  105139. pSubitem->pTab = 0;
  105140. }
  105141. /* The following loop runs once for each term in a compound-subquery
  105142. ** flattening (as described above). If we are doing a different kind
  105143. ** of flattening - a flattening other than a compound-subquery flattening -
  105144. ** then this loop only runs once.
  105145. **
  105146. ** This loop moves all of the FROM elements of the subquery into the
  105147. ** the FROM clause of the outer query. Before doing this, remember
  105148. ** the cursor number for the original outer query FROM element in
  105149. ** iParent. The iParent cursor will never be used. Subsequent code
  105150. ** will scan expressions looking for iParent references and replace
  105151. ** those references with expressions that resolve to the subquery FROM
  105152. ** elements we are now copying in.
  105153. */
  105154. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  105155. int nSubSrc;
  105156. u8 jointype = 0;
  105157. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  105158. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  105159. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  105160. if( pSrc ){
  105161. assert( pParent==p ); /* First time through the loop */
  105162. jointype = pSubitem->fg.jointype;
  105163. }else{
  105164. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  105165. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  105166. if( pSrc==0 ){
  105167. assert( db->mallocFailed );
  105168. break;
  105169. }
  105170. }
  105171. /* The subquery uses a single slot of the FROM clause of the outer
  105172. ** query. If the subquery has more than one element in its FROM clause,
  105173. ** then expand the outer query to make space for it to hold all elements
  105174. ** of the subquery.
  105175. **
  105176. ** Example:
  105177. **
  105178. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  105179. **
  105180. ** The outer query has 3 slots in its FROM clause. One slot of the
  105181. ** outer query (the middle slot) is used by the subquery. The next
  105182. ** block of code will expand the outer query FROM clause to 4 slots.
  105183. ** The middle slot is expanded to two slots in order to make space
  105184. ** for the two elements in the FROM clause of the subquery.
  105185. */
  105186. if( nSubSrc>1 ){
  105187. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  105188. if( db->mallocFailed ){
  105189. break;
  105190. }
  105191. }
  105192. /* Transfer the FROM clause terms from the subquery into the
  105193. ** outer query.
  105194. */
  105195. for(i=0; i<nSubSrc; i++){
  105196. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  105197. pSrc->a[i+iFrom] = pSubSrc->a[i];
  105198. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  105199. }
  105200. pSrc->a[iFrom].fg.jointype = jointype;
  105201. /* Now begin substituting subquery result set expressions for
  105202. ** references to the iParent in the outer query.
  105203. **
  105204. ** Example:
  105205. **
  105206. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  105207. ** \ \_____________ subquery __________/ /
  105208. ** \_____________________ outer query ______________________________/
  105209. **
  105210. ** We look at every expression in the outer query and every place we see
  105211. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  105212. */
  105213. pList = pParent->pEList;
  105214. for(i=0; i<pList->nExpr; i++){
  105215. if( pList->a[i].zName==0 ){
  105216. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  105217. sqlite3Dequote(zName);
  105218. pList->a[i].zName = zName;
  105219. }
  105220. }
  105221. if( pSub->pOrderBy ){
  105222. /* At this point, any non-zero iOrderByCol values indicate that the
  105223. ** ORDER BY column expression is identical to the iOrderByCol'th
  105224. ** expression returned by SELECT statement pSub. Since these values
  105225. ** do not necessarily correspond to columns in SELECT statement pParent,
  105226. ** zero them before transfering the ORDER BY clause.
  105227. **
  105228. ** Not doing this may cause an error if a subsequent call to this
  105229. ** function attempts to flatten a compound sub-query into pParent
  105230. ** (the only way this can happen is if the compound sub-query is
  105231. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  105232. ExprList *pOrderBy = pSub->pOrderBy;
  105233. for(i=0; i<pOrderBy->nExpr; i++){
  105234. pOrderBy->a[i].u.x.iOrderByCol = 0;
  105235. }
  105236. assert( pParent->pOrderBy==0 );
  105237. assert( pSub->pPrior==0 );
  105238. pParent->pOrderBy = pOrderBy;
  105239. pSub->pOrderBy = 0;
  105240. }
  105241. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  105242. if( subqueryIsAgg ){
  105243. assert( pParent->pHaving==0 );
  105244. pParent->pHaving = pParent->pWhere;
  105245. pParent->pWhere = pWhere;
  105246. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  105247. sqlite3ExprDup(db, pSub->pHaving, 0));
  105248. assert( pParent->pGroupBy==0 );
  105249. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  105250. }else{
  105251. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  105252. }
  105253. substSelect(db, pParent, iParent, pSub->pEList, 0);
  105254. /* The flattened query is distinct if either the inner or the
  105255. ** outer query is distinct.
  105256. */
  105257. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  105258. /*
  105259. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  105260. **
  105261. ** One is tempted to try to add a and b to combine the limits. But this
  105262. ** does not work if either limit is negative.
  105263. */
  105264. if( pSub->pLimit ){
  105265. pParent->pLimit = pSub->pLimit;
  105266. pSub->pLimit = 0;
  105267. }
  105268. }
  105269. /* Finially, delete what is left of the subquery and return
  105270. ** success.
  105271. */
  105272. sqlite3SelectDelete(db, pSub1);
  105273. #if SELECTTRACE_ENABLED
  105274. if( sqlite3SelectTrace & 0x100 ){
  105275. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  105276. sqlite3TreeViewSelect(0, p, 0);
  105277. }
  105278. #endif
  105279. return 1;
  105280. }
  105281. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  105282. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  105283. /*
  105284. ** Make copies of relevant WHERE clause terms of the outer query into
  105285. ** the WHERE clause of subquery. Example:
  105286. **
  105287. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  105288. **
  105289. ** Transformed into:
  105290. **
  105291. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  105292. ** WHERE x=5 AND y=10;
  105293. **
  105294. ** The hope is that the terms added to the inner query will make it more
  105295. ** efficient.
  105296. **
  105297. ** Do not attempt this optimization if:
  105298. **
  105299. ** (1) The inner query is an aggregate. (In that case, we'd really want
  105300. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  105301. ** inner query. But they probably won't help there so do not bother.)
  105302. **
  105303. ** (2) The inner query is the recursive part of a common table expression.
  105304. **
  105305. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  105306. ** close would change the meaning of the LIMIT).
  105307. **
  105308. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  105309. ** enforces this restriction since this routine does not have enough
  105310. ** information to know.)
  105311. **
  105312. ** (5) The WHERE clause expression originates in the ON or USING clause
  105313. ** of a LEFT JOIN.
  105314. **
  105315. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  105316. ** terms are duplicated into the subquery.
  105317. */
  105318. static int pushDownWhereTerms(
  105319. sqlite3 *db, /* The database connection (for malloc()) */
  105320. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  105321. Expr *pWhere, /* The WHERE clause of the outer query */
  105322. int iCursor /* Cursor number of the subquery */
  105323. ){
  105324. Expr *pNew;
  105325. int nChng = 0;
  105326. if( pWhere==0 ) return 0;
  105327. if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  105328. return 0; /* restrictions (1) and (2) */
  105329. }
  105330. if( pSubq->pLimit!=0 ){
  105331. return 0; /* restriction (3) */
  105332. }
  105333. while( pWhere->op==TK_AND ){
  105334. nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
  105335. pWhere = pWhere->pLeft;
  105336. }
  105337. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
  105338. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  105339. nChng++;
  105340. while( pSubq ){
  105341. pNew = sqlite3ExprDup(db, pWhere, 0);
  105342. pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
  105343. pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
  105344. pSubq = pSubq->pPrior;
  105345. }
  105346. }
  105347. return nChng;
  105348. }
  105349. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  105350. /*
  105351. ** Based on the contents of the AggInfo structure indicated by the first
  105352. ** argument, this function checks if the following are true:
  105353. **
  105354. ** * the query contains just a single aggregate function,
  105355. ** * the aggregate function is either min() or max(), and
  105356. ** * the argument to the aggregate function is a column value.
  105357. **
  105358. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  105359. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  105360. ** list of arguments passed to the aggregate before returning.
  105361. **
  105362. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  105363. ** WHERE_ORDERBY_NORMAL is returned.
  105364. */
  105365. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  105366. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  105367. *ppMinMax = 0;
  105368. if( pAggInfo->nFunc==1 ){
  105369. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  105370. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  105371. assert( pExpr->op==TK_AGG_FUNCTION );
  105372. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  105373. const char *zFunc = pExpr->u.zToken;
  105374. if( sqlite3StrICmp(zFunc, "min")==0 ){
  105375. eRet = WHERE_ORDERBY_MIN;
  105376. *ppMinMax = pEList;
  105377. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  105378. eRet = WHERE_ORDERBY_MAX;
  105379. *ppMinMax = pEList;
  105380. }
  105381. }
  105382. }
  105383. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  105384. return eRet;
  105385. }
  105386. /*
  105387. ** The select statement passed as the first argument is an aggregate query.
  105388. ** The second argument is the associated aggregate-info object. This
  105389. ** function tests if the SELECT is of the form:
  105390. **
  105391. ** SELECT count(*) FROM <tbl>
  105392. **
  105393. ** where table is a database table, not a sub-select or view. If the query
  105394. ** does match this pattern, then a pointer to the Table object representing
  105395. ** <tbl> is returned. Otherwise, 0 is returned.
  105396. */
  105397. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  105398. Table *pTab;
  105399. Expr *pExpr;
  105400. assert( !p->pGroupBy );
  105401. if( p->pWhere || p->pEList->nExpr!=1
  105402. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  105403. ){
  105404. return 0;
  105405. }
  105406. pTab = p->pSrc->a[0].pTab;
  105407. pExpr = p->pEList->a[0].pExpr;
  105408. assert( pTab && !pTab->pSelect && pExpr );
  105409. if( IsVirtual(pTab) ) return 0;
  105410. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  105411. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  105412. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  105413. if( pExpr->flags&EP_Distinct ) return 0;
  105414. return pTab;
  105415. }
  105416. /*
  105417. ** If the source-list item passed as an argument was augmented with an
  105418. ** INDEXED BY clause, then try to locate the specified index. If there
  105419. ** was such a clause and the named index cannot be found, return
  105420. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  105421. ** pFrom->pIndex and return SQLITE_OK.
  105422. */
  105423. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  105424. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  105425. Table *pTab = pFrom->pTab;
  105426. char *zIndexedBy = pFrom->u1.zIndexedBy;
  105427. Index *pIdx;
  105428. for(pIdx=pTab->pIndex;
  105429. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  105430. pIdx=pIdx->pNext
  105431. );
  105432. if( !pIdx ){
  105433. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  105434. pParse->checkSchema = 1;
  105435. return SQLITE_ERROR;
  105436. }
  105437. pFrom->pIBIndex = pIdx;
  105438. }
  105439. return SQLITE_OK;
  105440. }
  105441. /*
  105442. ** Detect compound SELECT statements that use an ORDER BY clause with
  105443. ** an alternative collating sequence.
  105444. **
  105445. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  105446. **
  105447. ** These are rewritten as a subquery:
  105448. **
  105449. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  105450. ** ORDER BY ... COLLATE ...
  105451. **
  105452. ** This transformation is necessary because the multiSelectOrderBy() routine
  105453. ** above that generates the code for a compound SELECT with an ORDER BY clause
  105454. ** uses a merge algorithm that requires the same collating sequence on the
  105455. ** result columns as on the ORDER BY clause. See ticket
  105456. ** http://www.sqlite.org/src/info/6709574d2a
  105457. **
  105458. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  105459. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  105460. ** there are COLLATE terms in the ORDER BY.
  105461. */
  105462. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  105463. int i;
  105464. Select *pNew;
  105465. Select *pX;
  105466. sqlite3 *db;
  105467. struct ExprList_item *a;
  105468. SrcList *pNewSrc;
  105469. Parse *pParse;
  105470. Token dummy;
  105471. if( p->pPrior==0 ) return WRC_Continue;
  105472. if( p->pOrderBy==0 ) return WRC_Continue;
  105473. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  105474. if( pX==0 ) return WRC_Continue;
  105475. a = p->pOrderBy->a;
  105476. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  105477. if( a[i].pExpr->flags & EP_Collate ) break;
  105478. }
  105479. if( i<0 ) return WRC_Continue;
  105480. /* If we reach this point, that means the transformation is required. */
  105481. pParse = pWalker->pParse;
  105482. db = pParse->db;
  105483. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  105484. if( pNew==0 ) return WRC_Abort;
  105485. memset(&dummy, 0, sizeof(dummy));
  105486. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  105487. if( pNewSrc==0 ) return WRC_Abort;
  105488. *pNew = *p;
  105489. p->pSrc = pNewSrc;
  105490. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  105491. p->op = TK_SELECT;
  105492. p->pWhere = 0;
  105493. pNew->pGroupBy = 0;
  105494. pNew->pHaving = 0;
  105495. pNew->pOrderBy = 0;
  105496. p->pPrior = 0;
  105497. p->pNext = 0;
  105498. p->pWith = 0;
  105499. p->selFlags &= ~SF_Compound;
  105500. assert( (p->selFlags & SF_Converted)==0 );
  105501. p->selFlags |= SF_Converted;
  105502. assert( pNew->pPrior!=0 );
  105503. pNew->pPrior->pNext = pNew;
  105504. pNew->pLimit = 0;
  105505. pNew->pOffset = 0;
  105506. return WRC_Continue;
  105507. }
  105508. #ifndef SQLITE_OMIT_CTE
  105509. /*
  105510. ** Argument pWith (which may be NULL) points to a linked list of nested
  105511. ** WITH contexts, from inner to outermost. If the table identified by
  105512. ** FROM clause element pItem is really a common-table-expression (CTE)
  105513. ** then return a pointer to the CTE definition for that table. Otherwise
  105514. ** return NULL.
  105515. **
  105516. ** If a non-NULL value is returned, set *ppContext to point to the With
  105517. ** object that the returned CTE belongs to.
  105518. */
  105519. static struct Cte *searchWith(
  105520. With *pWith, /* Current outermost WITH clause */
  105521. struct SrcList_item *pItem, /* FROM clause element to resolve */
  105522. With **ppContext /* OUT: WITH clause return value belongs to */
  105523. ){
  105524. const char *zName;
  105525. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  105526. With *p;
  105527. for(p=pWith; p; p=p->pOuter){
  105528. int i;
  105529. for(i=0; i<p->nCte; i++){
  105530. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  105531. *ppContext = p;
  105532. return &p->a[i];
  105533. }
  105534. }
  105535. }
  105536. }
  105537. return 0;
  105538. }
  105539. /* The code generator maintains a stack of active WITH clauses
  105540. ** with the inner-most WITH clause being at the top of the stack.
  105541. **
  105542. ** This routine pushes the WITH clause passed as the second argument
  105543. ** onto the top of the stack. If argument bFree is true, then this
  105544. ** WITH clause will never be popped from the stack. In this case it
  105545. ** should be freed along with the Parse object. In other cases, when
  105546. ** bFree==0, the With object will be freed along with the SELECT
  105547. ** statement with which it is associated.
  105548. */
  105549. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  105550. assert( bFree==0 || pParse->pWith==0 );
  105551. if( pWith ){
  105552. pWith->pOuter = pParse->pWith;
  105553. pParse->pWith = pWith;
  105554. pParse->bFreeWith = bFree;
  105555. }
  105556. }
  105557. /*
  105558. ** This function checks if argument pFrom refers to a CTE declared by
  105559. ** a WITH clause on the stack currently maintained by the parser. And,
  105560. ** if currently processing a CTE expression, if it is a recursive
  105561. ** reference to the current CTE.
  105562. **
  105563. ** If pFrom falls into either of the two categories above, pFrom->pTab
  105564. ** and other fields are populated accordingly. The caller should check
  105565. ** (pFrom->pTab!=0) to determine whether or not a successful match
  105566. ** was found.
  105567. **
  105568. ** Whether or not a match is found, SQLITE_OK is returned if no error
  105569. ** occurs. If an error does occur, an error message is stored in the
  105570. ** parser and some error code other than SQLITE_OK returned.
  105571. */
  105572. static int withExpand(
  105573. Walker *pWalker,
  105574. struct SrcList_item *pFrom
  105575. ){
  105576. Parse *pParse = pWalker->pParse;
  105577. sqlite3 *db = pParse->db;
  105578. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  105579. With *pWith; /* WITH clause that pCte belongs to */
  105580. assert( pFrom->pTab==0 );
  105581. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  105582. if( pCte ){
  105583. Table *pTab;
  105584. ExprList *pEList;
  105585. Select *pSel;
  105586. Select *pLeft; /* Left-most SELECT statement */
  105587. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  105588. With *pSavedWith; /* Initial value of pParse->pWith */
  105589. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  105590. ** recursive reference to CTE pCte. Leave an error in pParse and return
  105591. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  105592. ** In this case, proceed. */
  105593. if( pCte->zCteErr ){
  105594. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  105595. return SQLITE_ERROR;
  105596. }
  105597. assert( pFrom->pTab==0 );
  105598. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  105599. if( pTab==0 ) return WRC_Abort;
  105600. pTab->nRef = 1;
  105601. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  105602. pTab->iPKey = -1;
  105603. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  105604. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  105605. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  105606. if( db->mallocFailed ) return SQLITE_NOMEM;
  105607. assert( pFrom->pSelect );
  105608. /* Check if this is a recursive CTE. */
  105609. pSel = pFrom->pSelect;
  105610. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  105611. if( bMayRecursive ){
  105612. int i;
  105613. SrcList *pSrc = pFrom->pSelect->pSrc;
  105614. for(i=0; i<pSrc->nSrc; i++){
  105615. struct SrcList_item *pItem = &pSrc->a[i];
  105616. if( pItem->zDatabase==0
  105617. && pItem->zName!=0
  105618. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  105619. ){
  105620. pItem->pTab = pTab;
  105621. pItem->fg.isRecursive = 1;
  105622. pTab->nRef++;
  105623. pSel->selFlags |= SF_Recursive;
  105624. }
  105625. }
  105626. }
  105627. /* Only one recursive reference is permitted. */
  105628. if( pTab->nRef>2 ){
  105629. sqlite3ErrorMsg(
  105630. pParse, "multiple references to recursive table: %s", pCte->zName
  105631. );
  105632. return SQLITE_ERROR;
  105633. }
  105634. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  105635. pCte->zCteErr = "circular reference: %s";
  105636. pSavedWith = pParse->pWith;
  105637. pParse->pWith = pWith;
  105638. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  105639. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  105640. pEList = pLeft->pEList;
  105641. if( pCte->pCols ){
  105642. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  105643. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  105644. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  105645. );
  105646. pParse->pWith = pSavedWith;
  105647. return SQLITE_ERROR;
  105648. }
  105649. pEList = pCte->pCols;
  105650. }
  105651. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  105652. if( bMayRecursive ){
  105653. if( pSel->selFlags & SF_Recursive ){
  105654. pCte->zCteErr = "multiple recursive references: %s";
  105655. }else{
  105656. pCte->zCteErr = "recursive reference in a subquery: %s";
  105657. }
  105658. sqlite3WalkSelect(pWalker, pSel);
  105659. }
  105660. pCte->zCteErr = 0;
  105661. pParse->pWith = pSavedWith;
  105662. }
  105663. return SQLITE_OK;
  105664. }
  105665. #endif
  105666. #ifndef SQLITE_OMIT_CTE
  105667. /*
  105668. ** If the SELECT passed as the second argument has an associated WITH
  105669. ** clause, pop it from the stack stored as part of the Parse object.
  105670. **
  105671. ** This function is used as the xSelectCallback2() callback by
  105672. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  105673. ** names and other FROM clause elements.
  105674. */
  105675. static void selectPopWith(Walker *pWalker, Select *p){
  105676. Parse *pParse = pWalker->pParse;
  105677. With *pWith = findRightmost(p)->pWith;
  105678. if( pWith!=0 ){
  105679. assert( pParse->pWith==pWith );
  105680. pParse->pWith = pWith->pOuter;
  105681. }
  105682. }
  105683. #else
  105684. #define selectPopWith 0
  105685. #endif
  105686. /*
  105687. ** This routine is a Walker callback for "expanding" a SELECT statement.
  105688. ** "Expanding" means to do the following:
  105689. **
  105690. ** (1) Make sure VDBE cursor numbers have been assigned to every
  105691. ** element of the FROM clause.
  105692. **
  105693. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  105694. ** defines FROM clause. When views appear in the FROM clause,
  105695. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  105696. ** that implements the view. A copy is made of the view's SELECT
  105697. ** statement so that we can freely modify or delete that statement
  105698. ** without worrying about messing up the persistent representation
  105699. ** of the view.
  105700. **
  105701. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  105702. ** on joins and the ON and USING clause of joins.
  105703. **
  105704. ** (4) Scan the list of columns in the result set (pEList) looking
  105705. ** for instances of the "*" operator or the TABLE.* operator.
  105706. ** If found, expand each "*" to be every column in every table
  105707. ** and TABLE.* to be every column in TABLE.
  105708. **
  105709. */
  105710. static int selectExpander(Walker *pWalker, Select *p){
  105711. Parse *pParse = pWalker->pParse;
  105712. int i, j, k;
  105713. SrcList *pTabList;
  105714. ExprList *pEList;
  105715. struct SrcList_item *pFrom;
  105716. sqlite3 *db = pParse->db;
  105717. Expr *pE, *pRight, *pExpr;
  105718. u16 selFlags = p->selFlags;
  105719. p->selFlags |= SF_Expanded;
  105720. if( db->mallocFailed ){
  105721. return WRC_Abort;
  105722. }
  105723. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  105724. return WRC_Prune;
  105725. }
  105726. pTabList = p->pSrc;
  105727. pEList = p->pEList;
  105728. if( pWalker->xSelectCallback2==selectPopWith ){
  105729. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  105730. }
  105731. /* Make sure cursor numbers have been assigned to all entries in
  105732. ** the FROM clause of the SELECT statement.
  105733. */
  105734. sqlite3SrcListAssignCursors(pParse, pTabList);
  105735. /* Look up every table named in the FROM clause of the select. If
  105736. ** an entry of the FROM clause is a subquery instead of a table or view,
  105737. ** then create a transient table structure to describe the subquery.
  105738. */
  105739. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  105740. Table *pTab;
  105741. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  105742. if( pFrom->fg.isRecursive ) continue;
  105743. assert( pFrom->pTab==0 );
  105744. #ifndef SQLITE_OMIT_CTE
  105745. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  105746. if( pFrom->pTab ) {} else
  105747. #endif
  105748. if( pFrom->zName==0 ){
  105749. #ifndef SQLITE_OMIT_SUBQUERY
  105750. Select *pSel = pFrom->pSelect;
  105751. /* A sub-query in the FROM clause of a SELECT */
  105752. assert( pSel!=0 );
  105753. assert( pFrom->pTab==0 );
  105754. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  105755. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  105756. if( pTab==0 ) return WRC_Abort;
  105757. pTab->nRef = 1;
  105758. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  105759. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  105760. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  105761. pTab->iPKey = -1;
  105762. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  105763. pTab->tabFlags |= TF_Ephemeral;
  105764. #endif
  105765. }else{
  105766. /* An ordinary table or view name in the FROM clause */
  105767. assert( pFrom->pTab==0 );
  105768. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  105769. if( pTab==0 ) return WRC_Abort;
  105770. if( pTab->nRef==0xffff ){
  105771. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  105772. pTab->zName);
  105773. pFrom->pTab = 0;
  105774. return WRC_Abort;
  105775. }
  105776. pTab->nRef++;
  105777. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  105778. if( pTab->pSelect || IsVirtual(pTab) ){
  105779. i16 nCol;
  105780. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  105781. assert( pFrom->pSelect==0 );
  105782. if( pFrom->fg.isTabFunc && !IsVirtual(pTab) ){
  105783. sqlite3ErrorMsg(pParse, "'%s' is not a function", pTab->zName);
  105784. return WRC_Abort;
  105785. }
  105786. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  105787. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  105788. nCol = pTab->nCol;
  105789. pTab->nCol = -1;
  105790. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  105791. pTab->nCol = nCol;
  105792. }
  105793. #endif
  105794. }
  105795. /* Locate the index named by the INDEXED BY clause, if any. */
  105796. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  105797. return WRC_Abort;
  105798. }
  105799. }
  105800. /* Process NATURAL keywords, and ON and USING clauses of joins.
  105801. */
  105802. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  105803. return WRC_Abort;
  105804. }
  105805. /* For every "*" that occurs in the column list, insert the names of
  105806. ** all columns in all tables. And for every TABLE.* insert the names
  105807. ** of all columns in TABLE. The parser inserted a special expression
  105808. ** with the TK_ALL operator for each "*" that it found in the column list.
  105809. ** The following code just has to locate the TK_ALL expressions and expand
  105810. ** each one to the list of all columns in all tables.
  105811. **
  105812. ** The first loop just checks to see if there are any "*" operators
  105813. ** that need expanding.
  105814. */
  105815. for(k=0; k<pEList->nExpr; k++){
  105816. pE = pEList->a[k].pExpr;
  105817. if( pE->op==TK_ALL ) break;
  105818. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  105819. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  105820. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  105821. }
  105822. if( k<pEList->nExpr ){
  105823. /*
  105824. ** If we get here it means the result set contains one or more "*"
  105825. ** operators that need to be expanded. Loop through each expression
  105826. ** in the result set and expand them one by one.
  105827. */
  105828. struct ExprList_item *a = pEList->a;
  105829. ExprList *pNew = 0;
  105830. int flags = pParse->db->flags;
  105831. int longNames = (flags & SQLITE_FullColNames)!=0
  105832. && (flags & SQLITE_ShortColNames)==0;
  105833. for(k=0; k<pEList->nExpr; k++){
  105834. pE = a[k].pExpr;
  105835. pRight = pE->pRight;
  105836. assert( pE->op!=TK_DOT || pRight!=0 );
  105837. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  105838. /* This particular expression does not need to be expanded.
  105839. */
  105840. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  105841. if( pNew ){
  105842. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  105843. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  105844. a[k].zName = 0;
  105845. a[k].zSpan = 0;
  105846. }
  105847. a[k].pExpr = 0;
  105848. }else{
  105849. /* This expression is a "*" or a "TABLE.*" and needs to be
  105850. ** expanded. */
  105851. int tableSeen = 0; /* Set to 1 when TABLE matches */
  105852. char *zTName = 0; /* text of name of TABLE */
  105853. if( pE->op==TK_DOT ){
  105854. assert( pE->pLeft!=0 );
  105855. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  105856. zTName = pE->pLeft->u.zToken;
  105857. }
  105858. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  105859. Table *pTab = pFrom->pTab;
  105860. Select *pSub = pFrom->pSelect;
  105861. char *zTabName = pFrom->zAlias;
  105862. const char *zSchemaName = 0;
  105863. int iDb;
  105864. if( zTabName==0 ){
  105865. zTabName = pTab->zName;
  105866. }
  105867. if( db->mallocFailed ) break;
  105868. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  105869. pSub = 0;
  105870. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  105871. continue;
  105872. }
  105873. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105874. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  105875. }
  105876. for(j=0; j<pTab->nCol; j++){
  105877. char *zName = pTab->aCol[j].zName;
  105878. char *zColname; /* The computed column name */
  105879. char *zToFree; /* Malloced string that needs to be freed */
  105880. Token sColname; /* Computed column name as a token */
  105881. assert( zName );
  105882. if( zTName && pSub
  105883. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  105884. ){
  105885. continue;
  105886. }
  105887. /* If a column is marked as 'hidden' (currently only possible
  105888. ** for virtual tables), do not include it in the expanded
  105889. ** result-set list.
  105890. */
  105891. if( IsHiddenColumn(&pTab->aCol[j]) ){
  105892. assert(IsVirtual(pTab));
  105893. continue;
  105894. }
  105895. tableSeen = 1;
  105896. if( i>0 && zTName==0 ){
  105897. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  105898. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  105899. ){
  105900. /* In a NATURAL join, omit the join columns from the
  105901. ** table to the right of the join */
  105902. continue;
  105903. }
  105904. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  105905. /* In a join with a USING clause, omit columns in the
  105906. ** using clause from the table on the right. */
  105907. continue;
  105908. }
  105909. }
  105910. pRight = sqlite3Expr(db, TK_ID, zName);
  105911. zColname = zName;
  105912. zToFree = 0;
  105913. if( longNames || pTabList->nSrc>1 ){
  105914. Expr *pLeft;
  105915. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  105916. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  105917. if( zSchemaName ){
  105918. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  105919. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  105920. }
  105921. if( longNames ){
  105922. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  105923. zToFree = zColname;
  105924. }
  105925. }else{
  105926. pExpr = pRight;
  105927. }
  105928. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  105929. sColname.z = zColname;
  105930. sColname.n = sqlite3Strlen30(zColname);
  105931. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  105932. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  105933. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  105934. if( pSub ){
  105935. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  105936. testcase( pX->zSpan==0 );
  105937. }else{
  105938. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  105939. zSchemaName, zTabName, zColname);
  105940. testcase( pX->zSpan==0 );
  105941. }
  105942. pX->bSpanIsTab = 1;
  105943. }
  105944. sqlite3DbFree(db, zToFree);
  105945. }
  105946. }
  105947. if( !tableSeen ){
  105948. if( zTName ){
  105949. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  105950. }else{
  105951. sqlite3ErrorMsg(pParse, "no tables specified");
  105952. }
  105953. }
  105954. }
  105955. }
  105956. sqlite3ExprListDelete(db, pEList);
  105957. p->pEList = pNew;
  105958. }
  105959. #if SQLITE_MAX_COLUMN
  105960. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  105961. sqlite3ErrorMsg(pParse, "too many columns in result set");
  105962. }
  105963. #endif
  105964. return WRC_Continue;
  105965. }
  105966. /*
  105967. ** No-op routine for the parse-tree walker.
  105968. **
  105969. ** When this routine is the Walker.xExprCallback then expression trees
  105970. ** are walked without any actions being taken at each node. Presumably,
  105971. ** when this routine is used for Walker.xExprCallback then
  105972. ** Walker.xSelectCallback is set to do something useful for every
  105973. ** subquery in the parser tree.
  105974. */
  105975. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  105976. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105977. return WRC_Continue;
  105978. }
  105979. /*
  105980. ** This routine "expands" a SELECT statement and all of its subqueries.
  105981. ** For additional information on what it means to "expand" a SELECT
  105982. ** statement, see the comment on the selectExpand worker callback above.
  105983. **
  105984. ** Expanding a SELECT statement is the first step in processing a
  105985. ** SELECT statement. The SELECT statement must be expanded before
  105986. ** name resolution is performed.
  105987. **
  105988. ** If anything goes wrong, an error message is written into pParse.
  105989. ** The calling function can detect the problem by looking at pParse->nErr
  105990. ** and/or pParse->db->mallocFailed.
  105991. */
  105992. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  105993. Walker w;
  105994. memset(&w, 0, sizeof(w));
  105995. w.xExprCallback = exprWalkNoop;
  105996. w.pParse = pParse;
  105997. if( pParse->hasCompound ){
  105998. w.xSelectCallback = convertCompoundSelectToSubquery;
  105999. sqlite3WalkSelect(&w, pSelect);
  106000. }
  106001. w.xSelectCallback = selectExpander;
  106002. if( (pSelect->selFlags & SF_MultiValue)==0 ){
  106003. w.xSelectCallback2 = selectPopWith;
  106004. }
  106005. sqlite3WalkSelect(&w, pSelect);
  106006. }
  106007. #ifndef SQLITE_OMIT_SUBQUERY
  106008. /*
  106009. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  106010. ** interface.
  106011. **
  106012. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  106013. ** information to the Table structure that represents the result set
  106014. ** of that subquery.
  106015. **
  106016. ** The Table structure that represents the result set was constructed
  106017. ** by selectExpander() but the type and collation information was omitted
  106018. ** at that point because identifiers had not yet been resolved. This
  106019. ** routine is called after identifier resolution.
  106020. */
  106021. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  106022. Parse *pParse;
  106023. int i;
  106024. SrcList *pTabList;
  106025. struct SrcList_item *pFrom;
  106026. assert( p->selFlags & SF_Resolved );
  106027. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  106028. p->selFlags |= SF_HasTypeInfo;
  106029. pParse = pWalker->pParse;
  106030. pTabList = p->pSrc;
  106031. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  106032. Table *pTab = pFrom->pTab;
  106033. assert( pTab!=0 );
  106034. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  106035. /* A sub-query in the FROM clause of a SELECT */
  106036. Select *pSel = pFrom->pSelect;
  106037. if( pSel ){
  106038. while( pSel->pPrior ) pSel = pSel->pPrior;
  106039. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  106040. }
  106041. }
  106042. }
  106043. }
  106044. #endif
  106045. /*
  106046. ** This routine adds datatype and collating sequence information to
  106047. ** the Table structures of all FROM-clause subqueries in a
  106048. ** SELECT statement.
  106049. **
  106050. ** Use this routine after name resolution.
  106051. */
  106052. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  106053. #ifndef SQLITE_OMIT_SUBQUERY
  106054. Walker w;
  106055. memset(&w, 0, sizeof(w));
  106056. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  106057. w.xExprCallback = exprWalkNoop;
  106058. w.pParse = pParse;
  106059. sqlite3WalkSelect(&w, pSelect);
  106060. #endif
  106061. }
  106062. /*
  106063. ** This routine sets up a SELECT statement for processing. The
  106064. ** following is accomplished:
  106065. **
  106066. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  106067. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  106068. ** * ON and USING clauses are shifted into WHERE statements
  106069. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  106070. ** * Identifiers in expression are matched to tables.
  106071. **
  106072. ** This routine acts recursively on all subqueries within the SELECT.
  106073. */
  106074. SQLITE_PRIVATE void sqlite3SelectPrep(
  106075. Parse *pParse, /* The parser context */
  106076. Select *p, /* The SELECT statement being coded. */
  106077. NameContext *pOuterNC /* Name context for container */
  106078. ){
  106079. sqlite3 *db;
  106080. if( NEVER(p==0) ) return;
  106081. db = pParse->db;
  106082. if( db->mallocFailed ) return;
  106083. if( p->selFlags & SF_HasTypeInfo ) return;
  106084. sqlite3SelectExpand(pParse, p);
  106085. if( pParse->nErr || db->mallocFailed ) return;
  106086. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  106087. if( pParse->nErr || db->mallocFailed ) return;
  106088. sqlite3SelectAddTypeInfo(pParse, p);
  106089. }
  106090. /*
  106091. ** Reset the aggregate accumulator.
  106092. **
  106093. ** The aggregate accumulator is a set of memory cells that hold
  106094. ** intermediate results while calculating an aggregate. This
  106095. ** routine generates code that stores NULLs in all of those memory
  106096. ** cells.
  106097. */
  106098. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  106099. Vdbe *v = pParse->pVdbe;
  106100. int i;
  106101. struct AggInfo_func *pFunc;
  106102. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  106103. if( nReg==0 ) return;
  106104. #ifdef SQLITE_DEBUG
  106105. /* Verify that all AggInfo registers are within the range specified by
  106106. ** AggInfo.mnReg..AggInfo.mxReg */
  106107. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  106108. for(i=0; i<pAggInfo->nColumn; i++){
  106109. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  106110. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  106111. }
  106112. for(i=0; i<pAggInfo->nFunc; i++){
  106113. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  106114. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  106115. }
  106116. #endif
  106117. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  106118. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  106119. if( pFunc->iDistinct>=0 ){
  106120. Expr *pE = pFunc->pExpr;
  106121. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  106122. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  106123. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  106124. "argument");
  106125. pFunc->iDistinct = -1;
  106126. }else{
  106127. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  106128. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  106129. (char*)pKeyInfo, P4_KEYINFO);
  106130. }
  106131. }
  106132. }
  106133. }
  106134. /*
  106135. ** Invoke the OP_AggFinalize opcode for every aggregate function
  106136. ** in the AggInfo structure.
  106137. */
  106138. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  106139. Vdbe *v = pParse->pVdbe;
  106140. int i;
  106141. struct AggInfo_func *pF;
  106142. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  106143. ExprList *pList = pF->pExpr->x.pList;
  106144. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  106145. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  106146. (void*)pF->pFunc, P4_FUNCDEF);
  106147. }
  106148. }
  106149. /*
  106150. ** Update the accumulator memory cells for an aggregate based on
  106151. ** the current cursor position.
  106152. */
  106153. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  106154. Vdbe *v = pParse->pVdbe;
  106155. int i;
  106156. int regHit = 0;
  106157. int addrHitTest = 0;
  106158. struct AggInfo_func *pF;
  106159. struct AggInfo_col *pC;
  106160. pAggInfo->directMode = 1;
  106161. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  106162. int nArg;
  106163. int addrNext = 0;
  106164. int regAgg;
  106165. ExprList *pList = pF->pExpr->x.pList;
  106166. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  106167. if( pList ){
  106168. nArg = pList->nExpr;
  106169. regAgg = sqlite3GetTempRange(pParse, nArg);
  106170. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  106171. }else{
  106172. nArg = 0;
  106173. regAgg = 0;
  106174. }
  106175. if( pF->iDistinct>=0 ){
  106176. addrNext = sqlite3VdbeMakeLabel(v);
  106177. testcase( nArg==0 ); /* Error condition */
  106178. testcase( nArg>1 ); /* Also an error */
  106179. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  106180. }
  106181. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  106182. CollSeq *pColl = 0;
  106183. struct ExprList_item *pItem;
  106184. int j;
  106185. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  106186. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  106187. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  106188. }
  106189. if( !pColl ){
  106190. pColl = pParse->db->pDfltColl;
  106191. }
  106192. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  106193. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  106194. }
  106195. sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
  106196. (void*)pF->pFunc, P4_FUNCDEF);
  106197. sqlite3VdbeChangeP5(v, (u8)nArg);
  106198. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  106199. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  106200. if( addrNext ){
  106201. sqlite3VdbeResolveLabel(v, addrNext);
  106202. sqlite3ExprCacheClear(pParse);
  106203. }
  106204. }
  106205. /* Before populating the accumulator registers, clear the column cache.
  106206. ** Otherwise, if any of the required column values are already present
  106207. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  106208. ** to pC->iMem. But by the time the value is used, the original register
  106209. ** may have been used, invalidating the underlying buffer holding the
  106210. ** text or blob value. See ticket [883034dcb5].
  106211. **
  106212. ** Another solution would be to change the OP_SCopy used to copy cached
  106213. ** values to an OP_Copy.
  106214. */
  106215. if( regHit ){
  106216. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  106217. }
  106218. sqlite3ExprCacheClear(pParse);
  106219. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  106220. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  106221. }
  106222. pAggInfo->directMode = 0;
  106223. sqlite3ExprCacheClear(pParse);
  106224. if( addrHitTest ){
  106225. sqlite3VdbeJumpHere(v, addrHitTest);
  106226. }
  106227. }
  106228. /*
  106229. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  106230. ** count(*) query ("SELECT count(*) FROM pTab").
  106231. */
  106232. #ifndef SQLITE_OMIT_EXPLAIN
  106233. static void explainSimpleCount(
  106234. Parse *pParse, /* Parse context */
  106235. Table *pTab, /* Table being queried */
  106236. Index *pIdx /* Index used to optimize scan, or NULL */
  106237. ){
  106238. if( pParse->explain==2 ){
  106239. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  106240. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  106241. pTab->zName,
  106242. bCover ? " USING COVERING INDEX " : "",
  106243. bCover ? pIdx->zName : ""
  106244. );
  106245. sqlite3VdbeAddOp4(
  106246. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  106247. );
  106248. }
  106249. }
  106250. #else
  106251. # define explainSimpleCount(a,b,c)
  106252. #endif
  106253. /*
  106254. ** Generate code for the SELECT statement given in the p argument.
  106255. **
  106256. ** The results are returned according to the SelectDest structure.
  106257. ** See comments in sqliteInt.h for further information.
  106258. **
  106259. ** This routine returns the number of errors. If any errors are
  106260. ** encountered, then an appropriate error message is left in
  106261. ** pParse->zErrMsg.
  106262. **
  106263. ** This routine does NOT free the Select structure passed in. The
  106264. ** calling function needs to do that.
  106265. */
  106266. SQLITE_PRIVATE int sqlite3Select(
  106267. Parse *pParse, /* The parser context */
  106268. Select *p, /* The SELECT statement being coded. */
  106269. SelectDest *pDest /* What to do with the query results */
  106270. ){
  106271. int i, j; /* Loop counters */
  106272. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  106273. Vdbe *v; /* The virtual machine under construction */
  106274. int isAgg; /* True for select lists like "count(*)" */
  106275. ExprList *pEList = 0; /* List of columns to extract. */
  106276. SrcList *pTabList; /* List of tables to select from */
  106277. Expr *pWhere; /* The WHERE clause. May be NULL */
  106278. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  106279. Expr *pHaving; /* The HAVING clause. May be NULL */
  106280. int rc = 1; /* Value to return from this function */
  106281. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  106282. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  106283. AggInfo sAggInfo; /* Information used by aggregate queries */
  106284. int iEnd; /* Address of the end of the query */
  106285. sqlite3 *db; /* The database connection */
  106286. #ifndef SQLITE_OMIT_EXPLAIN
  106287. int iRestoreSelectId = pParse->iSelectId;
  106288. pParse->iSelectId = pParse->iNextSelectId++;
  106289. #endif
  106290. db = pParse->db;
  106291. if( p==0 || db->mallocFailed || pParse->nErr ){
  106292. return 1;
  106293. }
  106294. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  106295. memset(&sAggInfo, 0, sizeof(sAggInfo));
  106296. #if SELECTTRACE_ENABLED
  106297. pParse->nSelectIndent++;
  106298. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  106299. if( sqlite3SelectTrace & 0x100 ){
  106300. sqlite3TreeViewSelect(0, p, 0);
  106301. }
  106302. #endif
  106303. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  106304. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  106305. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  106306. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  106307. if( IgnorableOrderby(pDest) ){
  106308. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  106309. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  106310. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  106311. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  106312. /* If ORDER BY makes no difference in the output then neither does
  106313. ** DISTINCT so it can be removed too. */
  106314. sqlite3ExprListDelete(db, p->pOrderBy);
  106315. p->pOrderBy = 0;
  106316. p->selFlags &= ~SF_Distinct;
  106317. }
  106318. sqlite3SelectPrep(pParse, p, 0);
  106319. memset(&sSort, 0, sizeof(sSort));
  106320. sSort.pOrderBy = p->pOrderBy;
  106321. pTabList = p->pSrc;
  106322. if( pParse->nErr || db->mallocFailed ){
  106323. goto select_end;
  106324. }
  106325. assert( p->pEList!=0 );
  106326. isAgg = (p->selFlags & SF_Aggregate)!=0;
  106327. #if SELECTTRACE_ENABLED
  106328. if( sqlite3SelectTrace & 0x100 ){
  106329. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  106330. sqlite3TreeViewSelect(0, p, 0);
  106331. }
  106332. #endif
  106333. /* If writing to memory or generating a set
  106334. ** only a single column may be output.
  106335. */
  106336. #ifndef SQLITE_OMIT_SUBQUERY
  106337. if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
  106338. goto select_end;
  106339. }
  106340. #endif
  106341. /* Try to flatten subqueries in the FROM clause up into the main query
  106342. */
  106343. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  106344. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  106345. struct SrcList_item *pItem = &pTabList->a[i];
  106346. Select *pSub = pItem->pSelect;
  106347. int isAggSub;
  106348. Table *pTab = pItem->pTab;
  106349. if( pSub==0 ) continue;
  106350. /* Catch mismatch in the declared columns of a view and the number of
  106351. ** columns in the SELECT on the RHS */
  106352. if( pTab->nCol!=pSub->pEList->nExpr ){
  106353. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  106354. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  106355. goto select_end;
  106356. }
  106357. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  106358. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  106359. /* This subquery can be absorbed into its parent. */
  106360. if( isAggSub ){
  106361. isAgg = 1;
  106362. p->selFlags |= SF_Aggregate;
  106363. }
  106364. i = -1;
  106365. }
  106366. pTabList = p->pSrc;
  106367. if( db->mallocFailed ) goto select_end;
  106368. if( !IgnorableOrderby(pDest) ){
  106369. sSort.pOrderBy = p->pOrderBy;
  106370. }
  106371. }
  106372. #endif
  106373. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  106374. ** does not already exist */
  106375. v = sqlite3GetVdbe(pParse);
  106376. if( v==0 ) goto select_end;
  106377. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  106378. /* Handle compound SELECT statements using the separate multiSelect()
  106379. ** procedure.
  106380. */
  106381. if( p->pPrior ){
  106382. rc = multiSelect(pParse, p, pDest);
  106383. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  106384. #if SELECTTRACE_ENABLED
  106385. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  106386. pParse->nSelectIndent--;
  106387. #endif
  106388. return rc;
  106389. }
  106390. #endif
  106391. /* Generate code for all sub-queries in the FROM clause
  106392. */
  106393. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  106394. for(i=0; i<pTabList->nSrc; i++){
  106395. struct SrcList_item *pItem = &pTabList->a[i];
  106396. SelectDest dest;
  106397. Select *pSub = pItem->pSelect;
  106398. if( pSub==0 ) continue;
  106399. /* Sometimes the code for a subquery will be generated more than
  106400. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  106401. ** for example. In that case, do not regenerate the code to manifest
  106402. ** a view or the co-routine to implement a view. The first instance
  106403. ** is sufficient, though the subroutine to manifest the view does need
  106404. ** to be invoked again. */
  106405. if( pItem->addrFillSub ){
  106406. if( pItem->fg.viaCoroutine==0 ){
  106407. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  106408. }
  106409. continue;
  106410. }
  106411. /* Increment Parse.nHeight by the height of the largest expression
  106412. ** tree referred to by this, the parent select. The child select
  106413. ** may contain expression trees of at most
  106414. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  106415. ** more conservative than necessary, but much easier than enforcing
  106416. ** an exact limit.
  106417. */
  106418. pParse->nHeight += sqlite3SelectExprHeight(p);
  106419. /* Make copies of constant WHERE-clause terms in the outer query down
  106420. ** inside the subquery. This can help the subquery to run more efficiently.
  106421. */
  106422. if( (pItem->fg.jointype & JT_OUTER)==0
  106423. && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
  106424. ){
  106425. #if SELECTTRACE_ENABLED
  106426. if( sqlite3SelectTrace & 0x100 ){
  106427. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  106428. sqlite3TreeViewSelect(0, p, 0);
  106429. }
  106430. #endif
  106431. }
  106432. /* Generate code to implement the subquery
  106433. */
  106434. if( pTabList->nSrc==1
  106435. && (p->selFlags & SF_All)==0
  106436. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  106437. ){
  106438. /* Implement a co-routine that will return a single row of the result
  106439. ** set on each invocation.
  106440. */
  106441. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  106442. pItem->regReturn = ++pParse->nMem;
  106443. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  106444. VdbeComment((v, "%s", pItem->pTab->zName));
  106445. pItem->addrFillSub = addrTop;
  106446. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  106447. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  106448. sqlite3Select(pParse, pSub, &dest);
  106449. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  106450. pItem->fg.viaCoroutine = 1;
  106451. pItem->regResult = dest.iSdst;
  106452. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  106453. sqlite3VdbeJumpHere(v, addrTop-1);
  106454. sqlite3ClearTempRegCache(pParse);
  106455. }else{
  106456. /* Generate a subroutine that will fill an ephemeral table with
  106457. ** the content of this subquery. pItem->addrFillSub will point
  106458. ** to the address of the generated subroutine. pItem->regReturn
  106459. ** is a register allocated to hold the subroutine return address
  106460. */
  106461. int topAddr;
  106462. int onceAddr = 0;
  106463. int retAddr;
  106464. assert( pItem->addrFillSub==0 );
  106465. pItem->regReturn = ++pParse->nMem;
  106466. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  106467. pItem->addrFillSub = topAddr+1;
  106468. if( pItem->fg.isCorrelated==0 ){
  106469. /* If the subquery is not correlated and if we are not inside of
  106470. ** a trigger, then we only need to compute the value of the subquery
  106471. ** once. */
  106472. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  106473. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  106474. }else{
  106475. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  106476. }
  106477. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  106478. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  106479. sqlite3Select(pParse, pSub, &dest);
  106480. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  106481. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  106482. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  106483. VdbeComment((v, "end %s", pItem->pTab->zName));
  106484. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  106485. sqlite3ClearTempRegCache(pParse);
  106486. }
  106487. if( db->mallocFailed ) goto select_end;
  106488. pParse->nHeight -= sqlite3SelectExprHeight(p);
  106489. }
  106490. #endif
  106491. /* Various elements of the SELECT copied into local variables for
  106492. ** convenience */
  106493. pEList = p->pEList;
  106494. pWhere = p->pWhere;
  106495. pGroupBy = p->pGroupBy;
  106496. pHaving = p->pHaving;
  106497. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  106498. #if SELECTTRACE_ENABLED
  106499. if( sqlite3SelectTrace & 0x400 ){
  106500. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  106501. sqlite3TreeViewSelect(0, p, 0);
  106502. }
  106503. #endif
  106504. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  106505. ** if the select-list is the same as the ORDER BY list, then this query
  106506. ** can be rewritten as a GROUP BY. In other words, this:
  106507. **
  106508. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  106509. **
  106510. ** is transformed to:
  106511. **
  106512. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  106513. **
  106514. ** The second form is preferred as a single index (or temp-table) may be
  106515. ** used for both the ORDER BY and DISTINCT processing. As originally
  106516. ** written the query must use a temp-table for at least one of the ORDER
  106517. ** BY and DISTINCT, and an index or separate temp-table for the other.
  106518. */
  106519. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  106520. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  106521. ){
  106522. p->selFlags &= ~SF_Distinct;
  106523. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  106524. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  106525. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  106526. ** original setting of the SF_Distinct flag, not the current setting */
  106527. assert( sDistinct.isTnct );
  106528. }
  106529. /* If there is an ORDER BY clause, then create an ephemeral index to
  106530. ** do the sorting. But this sorting ephemeral index might end up
  106531. ** being unused if the data can be extracted in pre-sorted order.
  106532. ** If that is the case, then the OP_OpenEphemeral instruction will be
  106533. ** changed to an OP_Noop once we figure out that the sorting index is
  106534. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  106535. ** that change.
  106536. */
  106537. if( sSort.pOrderBy ){
  106538. KeyInfo *pKeyInfo;
  106539. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  106540. sSort.iECursor = pParse->nTab++;
  106541. sSort.addrSortIndex =
  106542. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  106543. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  106544. (char*)pKeyInfo, P4_KEYINFO
  106545. );
  106546. }else{
  106547. sSort.addrSortIndex = -1;
  106548. }
  106549. /* If the output is destined for a temporary table, open that table.
  106550. */
  106551. if( pDest->eDest==SRT_EphemTab ){
  106552. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  106553. }
  106554. /* Set the limiter.
  106555. */
  106556. iEnd = sqlite3VdbeMakeLabel(v);
  106557. p->nSelectRow = LARGEST_INT64;
  106558. computeLimitRegisters(pParse, p, iEnd);
  106559. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  106560. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  106561. sSort.sortFlags |= SORTFLAG_UseSorter;
  106562. }
  106563. /* Open an ephemeral index to use for the distinct set.
  106564. */
  106565. if( p->selFlags & SF_Distinct ){
  106566. sDistinct.tabTnct = pParse->nTab++;
  106567. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  106568. sDistinct.tabTnct, 0, 0,
  106569. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  106570. P4_KEYINFO);
  106571. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  106572. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  106573. }else{
  106574. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  106575. }
  106576. if( !isAgg && pGroupBy==0 ){
  106577. /* No aggregate functions and no GROUP BY clause */
  106578. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  106579. /* Begin the database scan. */
  106580. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  106581. p->pEList, wctrlFlags, 0);
  106582. if( pWInfo==0 ) goto select_end;
  106583. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  106584. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  106585. }
  106586. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  106587. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  106588. }
  106589. if( sSort.pOrderBy ){
  106590. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  106591. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  106592. sSort.pOrderBy = 0;
  106593. }
  106594. }
  106595. /* If sorting index that was created by a prior OP_OpenEphemeral
  106596. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  106597. ** into an OP_Noop.
  106598. */
  106599. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  106600. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  106601. }
  106602. /* Use the standard inner loop. */
  106603. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  106604. sqlite3WhereContinueLabel(pWInfo),
  106605. sqlite3WhereBreakLabel(pWInfo));
  106606. /* End the database scan loop.
  106607. */
  106608. sqlite3WhereEnd(pWInfo);
  106609. }else{
  106610. /* This case when there exist aggregate functions or a GROUP BY clause
  106611. ** or both */
  106612. NameContext sNC; /* Name context for processing aggregate information */
  106613. int iAMem; /* First Mem address for storing current GROUP BY */
  106614. int iBMem; /* First Mem address for previous GROUP BY */
  106615. int iUseFlag; /* Mem address holding flag indicating that at least
  106616. ** one row of the input to the aggregator has been
  106617. ** processed */
  106618. int iAbortFlag; /* Mem address which causes query abort if positive */
  106619. int groupBySort; /* Rows come from source in GROUP BY order */
  106620. int addrEnd; /* End of processing for this SELECT */
  106621. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  106622. int sortOut = 0; /* Output register from the sorter */
  106623. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  106624. /* Remove any and all aliases between the result set and the
  106625. ** GROUP BY clause.
  106626. */
  106627. if( pGroupBy ){
  106628. int k; /* Loop counter */
  106629. struct ExprList_item *pItem; /* For looping over expression in a list */
  106630. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  106631. pItem->u.x.iAlias = 0;
  106632. }
  106633. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  106634. pItem->u.x.iAlias = 0;
  106635. }
  106636. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  106637. }else{
  106638. p->nSelectRow = 1;
  106639. }
  106640. /* If there is both a GROUP BY and an ORDER BY clause and they are
  106641. ** identical, then it may be possible to disable the ORDER BY clause
  106642. ** on the grounds that the GROUP BY will cause elements to come out
  106643. ** in the correct order. It also may not - the GROUP BY might use a
  106644. ** database index that causes rows to be grouped together as required
  106645. ** but not actually sorted. Either way, record the fact that the
  106646. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  106647. ** variable. */
  106648. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  106649. orderByGrp = 1;
  106650. }
  106651. /* Create a label to jump to when we want to abort the query */
  106652. addrEnd = sqlite3VdbeMakeLabel(v);
  106653. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  106654. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  106655. ** SELECT statement.
  106656. */
  106657. memset(&sNC, 0, sizeof(sNC));
  106658. sNC.pParse = pParse;
  106659. sNC.pSrcList = pTabList;
  106660. sNC.pAggInfo = &sAggInfo;
  106661. sAggInfo.mnReg = pParse->nMem+1;
  106662. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  106663. sAggInfo.pGroupBy = pGroupBy;
  106664. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  106665. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  106666. if( pHaving ){
  106667. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  106668. }
  106669. sAggInfo.nAccumulator = sAggInfo.nColumn;
  106670. for(i=0; i<sAggInfo.nFunc; i++){
  106671. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  106672. sNC.ncFlags |= NC_InAggFunc;
  106673. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  106674. sNC.ncFlags &= ~NC_InAggFunc;
  106675. }
  106676. sAggInfo.mxReg = pParse->nMem;
  106677. if( db->mallocFailed ) goto select_end;
  106678. /* Processing for aggregates with GROUP BY is very different and
  106679. ** much more complex than aggregates without a GROUP BY.
  106680. */
  106681. if( pGroupBy ){
  106682. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  106683. int addr1; /* A-vs-B comparision jump */
  106684. int addrOutputRow; /* Start of subroutine that outputs a result row */
  106685. int regOutputRow; /* Return address register for output subroutine */
  106686. int addrSetAbort; /* Set the abort flag and return */
  106687. int addrTopOfLoop; /* Top of the input loop */
  106688. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  106689. int addrReset; /* Subroutine for resetting the accumulator */
  106690. int regReset; /* Return address register for reset subroutine */
  106691. /* If there is a GROUP BY clause we might need a sorting index to
  106692. ** implement it. Allocate that sorting index now. If it turns out
  106693. ** that we do not need it after all, the OP_SorterOpen instruction
  106694. ** will be converted into a Noop.
  106695. */
  106696. sAggInfo.sortingIdx = pParse->nTab++;
  106697. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  106698. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  106699. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  106700. 0, (char*)pKeyInfo, P4_KEYINFO);
  106701. /* Initialize memory locations used by GROUP BY aggregate processing
  106702. */
  106703. iUseFlag = ++pParse->nMem;
  106704. iAbortFlag = ++pParse->nMem;
  106705. regOutputRow = ++pParse->nMem;
  106706. addrOutputRow = sqlite3VdbeMakeLabel(v);
  106707. regReset = ++pParse->nMem;
  106708. addrReset = sqlite3VdbeMakeLabel(v);
  106709. iAMem = pParse->nMem + 1;
  106710. pParse->nMem += pGroupBy->nExpr;
  106711. iBMem = pParse->nMem + 1;
  106712. pParse->nMem += pGroupBy->nExpr;
  106713. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  106714. VdbeComment((v, "clear abort flag"));
  106715. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  106716. VdbeComment((v, "indicate accumulator empty"));
  106717. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  106718. /* Begin a loop that will extract all source rows in GROUP BY order.
  106719. ** This might involve two separate loops with an OP_Sort in between, or
  106720. ** it might be a single loop that uses an index to extract information
  106721. ** in the right order to begin with.
  106722. */
  106723. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  106724. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  106725. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  106726. );
  106727. if( pWInfo==0 ) goto select_end;
  106728. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  106729. /* The optimizer is able to deliver rows in group by order so
  106730. ** we do not have to sort. The OP_OpenEphemeral table will be
  106731. ** cancelled later because we still need to use the pKeyInfo
  106732. */
  106733. groupBySort = 0;
  106734. }else{
  106735. /* Rows are coming out in undetermined order. We have to push
  106736. ** each row into a sorting index, terminate the first loop,
  106737. ** then loop over the sorting index in order to get the output
  106738. ** in sorted order
  106739. */
  106740. int regBase;
  106741. int regRecord;
  106742. int nCol;
  106743. int nGroupBy;
  106744. explainTempTable(pParse,
  106745. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  106746. "DISTINCT" : "GROUP BY");
  106747. groupBySort = 1;
  106748. nGroupBy = pGroupBy->nExpr;
  106749. nCol = nGroupBy;
  106750. j = nGroupBy;
  106751. for(i=0; i<sAggInfo.nColumn; i++){
  106752. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  106753. nCol++;
  106754. j++;
  106755. }
  106756. }
  106757. regBase = sqlite3GetTempRange(pParse, nCol);
  106758. sqlite3ExprCacheClear(pParse);
  106759. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  106760. j = nGroupBy;
  106761. for(i=0; i<sAggInfo.nColumn; i++){
  106762. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  106763. if( pCol->iSorterColumn>=j ){
  106764. int r1 = j + regBase;
  106765. int r2;
  106766. r2 = sqlite3ExprCodeGetColumn(pParse,
  106767. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  106768. if( r1!=r2 ){
  106769. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  106770. }
  106771. j++;
  106772. }
  106773. }
  106774. regRecord = sqlite3GetTempReg(pParse);
  106775. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  106776. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  106777. sqlite3ReleaseTempReg(pParse, regRecord);
  106778. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  106779. sqlite3WhereEnd(pWInfo);
  106780. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  106781. sortOut = sqlite3GetTempReg(pParse);
  106782. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  106783. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  106784. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  106785. sAggInfo.useSortingIdx = 1;
  106786. sqlite3ExprCacheClear(pParse);
  106787. }
  106788. /* If the index or temporary table used by the GROUP BY sort
  106789. ** will naturally deliver rows in the order required by the ORDER BY
  106790. ** clause, cancel the ephemeral table open coded earlier.
  106791. **
  106792. ** This is an optimization - the correct answer should result regardless.
  106793. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  106794. ** disable this optimization for testing purposes. */
  106795. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  106796. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  106797. ){
  106798. sSort.pOrderBy = 0;
  106799. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  106800. }
  106801. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  106802. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  106803. ** Then compare the current GROUP BY terms against the GROUP BY terms
  106804. ** from the previous row currently stored in a0, a1, a2...
  106805. */
  106806. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  106807. sqlite3ExprCacheClear(pParse);
  106808. if( groupBySort ){
  106809. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  106810. sortOut, sortPTab);
  106811. }
  106812. for(j=0; j<pGroupBy->nExpr; j++){
  106813. if( groupBySort ){
  106814. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  106815. }else{
  106816. sAggInfo.directMode = 1;
  106817. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  106818. }
  106819. }
  106820. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  106821. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  106822. addr1 = sqlite3VdbeCurrentAddr(v);
  106823. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  106824. /* Generate code that runs whenever the GROUP BY changes.
  106825. ** Changes in the GROUP BY are detected by the previous code
  106826. ** block. If there were no changes, this block is skipped.
  106827. **
  106828. ** This code copies current group by terms in b0,b1,b2,...
  106829. ** over to a0,a1,a2. It then calls the output subroutine
  106830. ** and resets the aggregate accumulator registers in preparation
  106831. ** for the next GROUP BY batch.
  106832. */
  106833. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  106834. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  106835. VdbeComment((v, "output one row"));
  106836. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  106837. VdbeComment((v, "check abort flag"));
  106838. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  106839. VdbeComment((v, "reset accumulator"));
  106840. /* Update the aggregate accumulators based on the content of
  106841. ** the current row
  106842. */
  106843. sqlite3VdbeJumpHere(v, addr1);
  106844. updateAccumulator(pParse, &sAggInfo);
  106845. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  106846. VdbeComment((v, "indicate data in accumulator"));
  106847. /* End of the loop
  106848. */
  106849. if( groupBySort ){
  106850. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  106851. VdbeCoverage(v);
  106852. }else{
  106853. sqlite3WhereEnd(pWInfo);
  106854. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  106855. }
  106856. /* Output the final row of result
  106857. */
  106858. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  106859. VdbeComment((v, "output final row"));
  106860. /* Jump over the subroutines
  106861. */
  106862. sqlite3VdbeGoto(v, addrEnd);
  106863. /* Generate a subroutine that outputs a single row of the result
  106864. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  106865. ** is less than or equal to zero, the subroutine is a no-op. If
  106866. ** the processing calls for the query to abort, this subroutine
  106867. ** increments the iAbortFlag memory location before returning in
  106868. ** order to signal the caller to abort.
  106869. */
  106870. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  106871. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  106872. VdbeComment((v, "set abort flag"));
  106873. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  106874. sqlite3VdbeResolveLabel(v, addrOutputRow);
  106875. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  106876. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  106877. VdbeCoverage(v);
  106878. VdbeComment((v, "Groupby result generator entry point"));
  106879. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  106880. finalizeAggFunctions(pParse, &sAggInfo);
  106881. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  106882. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  106883. &sDistinct, pDest,
  106884. addrOutputRow+1, addrSetAbort);
  106885. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  106886. VdbeComment((v, "end groupby result generator"));
  106887. /* Generate a subroutine that will reset the group-by accumulator
  106888. */
  106889. sqlite3VdbeResolveLabel(v, addrReset);
  106890. resetAccumulator(pParse, &sAggInfo);
  106891. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  106892. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  106893. else {
  106894. ExprList *pDel = 0;
  106895. #ifndef SQLITE_OMIT_BTREECOUNT
  106896. Table *pTab;
  106897. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  106898. /* If isSimpleCount() returns a pointer to a Table structure, then
  106899. ** the SQL statement is of the form:
  106900. **
  106901. ** SELECT count(*) FROM <tbl>
  106902. **
  106903. ** where the Table structure returned represents table <tbl>.
  106904. **
  106905. ** This statement is so common that it is optimized specially. The
  106906. ** OP_Count instruction is executed either on the intkey table that
  106907. ** contains the data for table <tbl> or on one of its indexes. It
  106908. ** is better to execute the op on an index, as indexes are almost
  106909. ** always spread across less pages than their corresponding tables.
  106910. */
  106911. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  106912. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  106913. Index *pIdx; /* Iterator variable */
  106914. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  106915. Index *pBest = 0; /* Best index found so far */
  106916. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  106917. sqlite3CodeVerifySchema(pParse, iDb);
  106918. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  106919. /* Search for the index that has the lowest scan cost.
  106920. **
  106921. ** (2011-04-15) Do not do a full scan of an unordered index.
  106922. **
  106923. ** (2013-10-03) Do not count the entries in a partial index.
  106924. **
  106925. ** In practice the KeyInfo structure will not be used. It is only
  106926. ** passed to keep OP_OpenRead happy.
  106927. */
  106928. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  106929. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  106930. if( pIdx->bUnordered==0
  106931. && pIdx->szIdxRow<pTab->szTabRow
  106932. && pIdx->pPartIdxWhere==0
  106933. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  106934. ){
  106935. pBest = pIdx;
  106936. }
  106937. }
  106938. if( pBest ){
  106939. iRoot = pBest->tnum;
  106940. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  106941. }
  106942. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  106943. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  106944. if( pKeyInfo ){
  106945. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  106946. }
  106947. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  106948. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  106949. explainSimpleCount(pParse, pTab, pBest);
  106950. }else
  106951. #endif /* SQLITE_OMIT_BTREECOUNT */
  106952. {
  106953. /* Check if the query is of one of the following forms:
  106954. **
  106955. ** SELECT min(x) FROM ...
  106956. ** SELECT max(x) FROM ...
  106957. **
  106958. ** If it is, then ask the code in where.c to attempt to sort results
  106959. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  106960. ** If where.c is able to produce results sorted in this order, then
  106961. ** add vdbe code to break out of the processing loop after the
  106962. ** first iteration (since the first iteration of the loop is
  106963. ** guaranteed to operate on the row with the minimum or maximum
  106964. ** value of x, the only row required).
  106965. **
  106966. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  106967. ** modify behavior as follows:
  106968. **
  106969. ** + If the query is a "SELECT min(x)", then the loop coded by
  106970. ** where.c should not iterate over any values with a NULL value
  106971. ** for x.
  106972. **
  106973. ** + The optimizer code in where.c (the thing that decides which
  106974. ** index or indices to use) should place a different priority on
  106975. ** satisfying the 'ORDER BY' clause than it does in other cases.
  106976. ** Refer to code and comments in where.c for details.
  106977. */
  106978. ExprList *pMinMax = 0;
  106979. u8 flag = WHERE_ORDERBY_NORMAL;
  106980. assert( p->pGroupBy==0 );
  106981. assert( flag==0 );
  106982. if( p->pHaving==0 ){
  106983. flag = minMaxQuery(&sAggInfo, &pMinMax);
  106984. }
  106985. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  106986. if( flag ){
  106987. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  106988. pDel = pMinMax;
  106989. if( pMinMax && !db->mallocFailed ){
  106990. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  106991. pMinMax->a[0].pExpr->op = TK_COLUMN;
  106992. }
  106993. }
  106994. /* This case runs if the aggregate has no GROUP BY clause. The
  106995. ** processing is much simpler since there is only a single row
  106996. ** of output.
  106997. */
  106998. resetAccumulator(pParse, &sAggInfo);
  106999. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  107000. if( pWInfo==0 ){
  107001. sqlite3ExprListDelete(db, pDel);
  107002. goto select_end;
  107003. }
  107004. updateAccumulator(pParse, &sAggInfo);
  107005. assert( pMinMax==0 || pMinMax->nExpr==1 );
  107006. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  107007. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  107008. VdbeComment((v, "%s() by index",
  107009. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  107010. }
  107011. sqlite3WhereEnd(pWInfo);
  107012. finalizeAggFunctions(pParse, &sAggInfo);
  107013. }
  107014. sSort.pOrderBy = 0;
  107015. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  107016. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  107017. pDest, addrEnd, addrEnd);
  107018. sqlite3ExprListDelete(db, pDel);
  107019. }
  107020. sqlite3VdbeResolveLabel(v, addrEnd);
  107021. } /* endif aggregate query */
  107022. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  107023. explainTempTable(pParse, "DISTINCT");
  107024. }
  107025. /* If there is an ORDER BY clause, then we need to sort the results
  107026. ** and send them to the callback one by one.
  107027. */
  107028. if( sSort.pOrderBy ){
  107029. explainTempTable(pParse,
  107030. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  107031. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  107032. }
  107033. /* Jump here to skip this query
  107034. */
  107035. sqlite3VdbeResolveLabel(v, iEnd);
  107036. /* The SELECT has been coded. If there is an error in the Parse structure,
  107037. ** set the return code to 1. Otherwise 0. */
  107038. rc = (pParse->nErr>0);
  107039. /* Control jumps to here if an error is encountered above, or upon
  107040. ** successful coding of the SELECT.
  107041. */
  107042. select_end:
  107043. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  107044. /* Identify column names if results of the SELECT are to be output.
  107045. */
  107046. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  107047. generateColumnNames(pParse, pTabList, pEList);
  107048. }
  107049. sqlite3DbFree(db, sAggInfo.aCol);
  107050. sqlite3DbFree(db, sAggInfo.aFunc);
  107051. #if SELECTTRACE_ENABLED
  107052. SELECTTRACE(1,pParse,p,("end processing\n"));
  107053. pParse->nSelectIndent--;
  107054. #endif
  107055. return rc;
  107056. }
  107057. /************** End of select.c **********************************************/
  107058. /************** Begin file table.c *******************************************/
  107059. /*
  107060. ** 2001 September 15
  107061. **
  107062. ** The author disclaims copyright to this source code. In place of
  107063. ** a legal notice, here is a blessing:
  107064. **
  107065. ** May you do good and not evil.
  107066. ** May you find forgiveness for yourself and forgive others.
  107067. ** May you share freely, never taking more than you give.
  107068. **
  107069. *************************************************************************
  107070. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  107071. ** interface routines. These are just wrappers around the main
  107072. ** interface routine of sqlite3_exec().
  107073. **
  107074. ** These routines are in a separate files so that they will not be linked
  107075. ** if they are not used.
  107076. */
  107077. /* #include "sqliteInt.h" */
  107078. /* #include <stdlib.h> */
  107079. /* #include <string.h> */
  107080. #ifndef SQLITE_OMIT_GET_TABLE
  107081. /*
  107082. ** This structure is used to pass data from sqlite3_get_table() through
  107083. ** to the callback function is uses to build the result.
  107084. */
  107085. typedef struct TabResult {
  107086. char **azResult; /* Accumulated output */
  107087. char *zErrMsg; /* Error message text, if an error occurs */
  107088. u32 nAlloc; /* Slots allocated for azResult[] */
  107089. u32 nRow; /* Number of rows in the result */
  107090. u32 nColumn; /* Number of columns in the result */
  107091. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  107092. int rc; /* Return code from sqlite3_exec() */
  107093. } TabResult;
  107094. /*
  107095. ** This routine is called once for each row in the result table. Its job
  107096. ** is to fill in the TabResult structure appropriately, allocating new
  107097. ** memory as necessary.
  107098. */
  107099. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  107100. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  107101. int need; /* Slots needed in p->azResult[] */
  107102. int i; /* Loop counter */
  107103. char *z; /* A single column of result */
  107104. /* Make sure there is enough space in p->azResult to hold everything
  107105. ** we need to remember from this invocation of the callback.
  107106. */
  107107. if( p->nRow==0 && argv!=0 ){
  107108. need = nCol*2;
  107109. }else{
  107110. need = nCol;
  107111. }
  107112. if( p->nData + need > p->nAlloc ){
  107113. char **azNew;
  107114. p->nAlloc = p->nAlloc*2 + need;
  107115. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  107116. if( azNew==0 ) goto malloc_failed;
  107117. p->azResult = azNew;
  107118. }
  107119. /* If this is the first row, then generate an extra row containing
  107120. ** the names of all columns.
  107121. */
  107122. if( p->nRow==0 ){
  107123. p->nColumn = nCol;
  107124. for(i=0; i<nCol; i++){
  107125. z = sqlite3_mprintf("%s", colv[i]);
  107126. if( z==0 ) goto malloc_failed;
  107127. p->azResult[p->nData++] = z;
  107128. }
  107129. }else if( (int)p->nColumn!=nCol ){
  107130. sqlite3_free(p->zErrMsg);
  107131. p->zErrMsg = sqlite3_mprintf(
  107132. "sqlite3_get_table() called with two or more incompatible queries"
  107133. );
  107134. p->rc = SQLITE_ERROR;
  107135. return 1;
  107136. }
  107137. /* Copy over the row data
  107138. */
  107139. if( argv!=0 ){
  107140. for(i=0; i<nCol; i++){
  107141. if( argv[i]==0 ){
  107142. z = 0;
  107143. }else{
  107144. int n = sqlite3Strlen30(argv[i])+1;
  107145. z = sqlite3_malloc64( n );
  107146. if( z==0 ) goto malloc_failed;
  107147. memcpy(z, argv[i], n);
  107148. }
  107149. p->azResult[p->nData++] = z;
  107150. }
  107151. p->nRow++;
  107152. }
  107153. return 0;
  107154. malloc_failed:
  107155. p->rc = SQLITE_NOMEM;
  107156. return 1;
  107157. }
  107158. /*
  107159. ** Query the database. But instead of invoking a callback for each row,
  107160. ** malloc() for space to hold the result and return the entire results
  107161. ** at the conclusion of the call.
  107162. **
  107163. ** The result that is written to ***pazResult is held in memory obtained
  107164. ** from malloc(). But the caller cannot free this memory directly.
  107165. ** Instead, the entire table should be passed to sqlite3_free_table() when
  107166. ** the calling procedure is finished using it.
  107167. */
  107168. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  107169. sqlite3 *db, /* The database on which the SQL executes */
  107170. const char *zSql, /* The SQL to be executed */
  107171. char ***pazResult, /* Write the result table here */
  107172. int *pnRow, /* Write the number of rows in the result here */
  107173. int *pnColumn, /* Write the number of columns of result here */
  107174. char **pzErrMsg /* Write error messages here */
  107175. ){
  107176. int rc;
  107177. TabResult res;
  107178. #ifdef SQLITE_ENABLE_API_ARMOR
  107179. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  107180. #endif
  107181. *pazResult = 0;
  107182. if( pnColumn ) *pnColumn = 0;
  107183. if( pnRow ) *pnRow = 0;
  107184. if( pzErrMsg ) *pzErrMsg = 0;
  107185. res.zErrMsg = 0;
  107186. res.nRow = 0;
  107187. res.nColumn = 0;
  107188. res.nData = 1;
  107189. res.nAlloc = 20;
  107190. res.rc = SQLITE_OK;
  107191. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  107192. if( res.azResult==0 ){
  107193. db->errCode = SQLITE_NOMEM;
  107194. return SQLITE_NOMEM;
  107195. }
  107196. res.azResult[0] = 0;
  107197. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  107198. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  107199. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  107200. if( (rc&0xff)==SQLITE_ABORT ){
  107201. sqlite3_free_table(&res.azResult[1]);
  107202. if( res.zErrMsg ){
  107203. if( pzErrMsg ){
  107204. sqlite3_free(*pzErrMsg);
  107205. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  107206. }
  107207. sqlite3_free(res.zErrMsg);
  107208. }
  107209. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  107210. return res.rc;
  107211. }
  107212. sqlite3_free(res.zErrMsg);
  107213. if( rc!=SQLITE_OK ){
  107214. sqlite3_free_table(&res.azResult[1]);
  107215. return rc;
  107216. }
  107217. if( res.nAlloc>res.nData ){
  107218. char **azNew;
  107219. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  107220. if( azNew==0 ){
  107221. sqlite3_free_table(&res.azResult[1]);
  107222. db->errCode = SQLITE_NOMEM;
  107223. return SQLITE_NOMEM;
  107224. }
  107225. res.azResult = azNew;
  107226. }
  107227. *pazResult = &res.azResult[1];
  107228. if( pnColumn ) *pnColumn = res.nColumn;
  107229. if( pnRow ) *pnRow = res.nRow;
  107230. return rc;
  107231. }
  107232. /*
  107233. ** This routine frees the space the sqlite3_get_table() malloced.
  107234. */
  107235. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
  107236. char **azResult /* Result returned from sqlite3_get_table() */
  107237. ){
  107238. if( azResult ){
  107239. int i, n;
  107240. azResult--;
  107241. assert( azResult!=0 );
  107242. n = SQLITE_PTR_TO_INT(azResult[0]);
  107243. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  107244. sqlite3_free(azResult);
  107245. }
  107246. }
  107247. #endif /* SQLITE_OMIT_GET_TABLE */
  107248. /************** End of table.c ***********************************************/
  107249. /************** Begin file trigger.c *****************************************/
  107250. /*
  107251. **
  107252. ** The author disclaims copyright to this source code. In place of
  107253. ** a legal notice, here is a blessing:
  107254. **
  107255. ** May you do good and not evil.
  107256. ** May you find forgiveness for yourself and forgive others.
  107257. ** May you share freely, never taking more than you give.
  107258. **
  107259. *************************************************************************
  107260. ** This file contains the implementation for TRIGGERs
  107261. */
  107262. /* #include "sqliteInt.h" */
  107263. #ifndef SQLITE_OMIT_TRIGGER
  107264. /*
  107265. ** Delete a linked list of TriggerStep structures.
  107266. */
  107267. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  107268. while( pTriggerStep ){
  107269. TriggerStep * pTmp = pTriggerStep;
  107270. pTriggerStep = pTriggerStep->pNext;
  107271. sqlite3ExprDelete(db, pTmp->pWhere);
  107272. sqlite3ExprListDelete(db, pTmp->pExprList);
  107273. sqlite3SelectDelete(db, pTmp->pSelect);
  107274. sqlite3IdListDelete(db, pTmp->pIdList);
  107275. sqlite3DbFree(db, pTmp);
  107276. }
  107277. }
  107278. /*
  107279. ** Given table pTab, return a list of all the triggers attached to
  107280. ** the table. The list is connected by Trigger.pNext pointers.
  107281. **
  107282. ** All of the triggers on pTab that are in the same database as pTab
  107283. ** are already attached to pTab->pTrigger. But there might be additional
  107284. ** triggers on pTab in the TEMP schema. This routine prepends all
  107285. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  107286. ** and returns the combined list.
  107287. **
  107288. ** To state it another way: This routine returns a list of all triggers
  107289. ** that fire off of pTab. The list will include any TEMP triggers on
  107290. ** pTab as well as the triggers lised in pTab->pTrigger.
  107291. */
  107292. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  107293. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  107294. Trigger *pList = 0; /* List of triggers to return */
  107295. if( pParse->disableTriggers ){
  107296. return 0;
  107297. }
  107298. if( pTmpSchema!=pTab->pSchema ){
  107299. HashElem *p;
  107300. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  107301. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  107302. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  107303. if( pTrig->pTabSchema==pTab->pSchema
  107304. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  107305. ){
  107306. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  107307. pList = pTrig;
  107308. }
  107309. }
  107310. }
  107311. return (pList ? pList : pTab->pTrigger);
  107312. }
  107313. /*
  107314. ** This is called by the parser when it sees a CREATE TRIGGER statement
  107315. ** up to the point of the BEGIN before the trigger actions. A Trigger
  107316. ** structure is generated based on the information available and stored
  107317. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  107318. ** sqlite3FinishTrigger() function is called to complete the trigger
  107319. ** construction process.
  107320. */
  107321. SQLITE_PRIVATE void sqlite3BeginTrigger(
  107322. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  107323. Token *pName1, /* The name of the trigger */
  107324. Token *pName2, /* The name of the trigger */
  107325. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  107326. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  107327. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  107328. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  107329. Expr *pWhen, /* WHEN clause */
  107330. int isTemp, /* True if the TEMPORARY keyword is present */
  107331. int noErr /* Suppress errors if the trigger already exists */
  107332. ){
  107333. Trigger *pTrigger = 0; /* The new trigger */
  107334. Table *pTab; /* Table that the trigger fires off of */
  107335. char *zName = 0; /* Name of the trigger */
  107336. sqlite3 *db = pParse->db; /* The database connection */
  107337. int iDb; /* The database to store the trigger in */
  107338. Token *pName; /* The unqualified db name */
  107339. DbFixer sFix; /* State vector for the DB fixer */
  107340. int iTabDb; /* Index of the database holding pTab */
  107341. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  107342. assert( pName2!=0 );
  107343. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  107344. assert( op>0 && op<0xff );
  107345. if( isTemp ){
  107346. /* If TEMP was specified, then the trigger name may not be qualified. */
  107347. if( pName2->n>0 ){
  107348. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  107349. goto trigger_cleanup;
  107350. }
  107351. iDb = 1;
  107352. pName = pName1;
  107353. }else{
  107354. /* Figure out the db that the trigger will be created in */
  107355. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  107356. if( iDb<0 ){
  107357. goto trigger_cleanup;
  107358. }
  107359. }
  107360. if( !pTableName || db->mallocFailed ){
  107361. goto trigger_cleanup;
  107362. }
  107363. /* A long-standing parser bug is that this syntax was allowed:
  107364. **
  107365. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  107366. ** ^^^^^^^^
  107367. **
  107368. ** To maintain backwards compatibility, ignore the database
  107369. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  107370. */
  107371. if( db->init.busy && iDb!=1 ){
  107372. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  107373. pTableName->a[0].zDatabase = 0;
  107374. }
  107375. /* If the trigger name was unqualified, and the table is a temp table,
  107376. ** then set iDb to 1 to create the trigger in the temporary database.
  107377. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  107378. ** exist, the error is caught by the block below.
  107379. */
  107380. pTab = sqlite3SrcListLookup(pParse, pTableName);
  107381. if( db->init.busy==0 && pName2->n==0 && pTab
  107382. && pTab->pSchema==db->aDb[1].pSchema ){
  107383. iDb = 1;
  107384. }
  107385. /* Ensure the table name matches database name and that the table exists */
  107386. if( db->mallocFailed ) goto trigger_cleanup;
  107387. assert( pTableName->nSrc==1 );
  107388. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  107389. if( sqlite3FixSrcList(&sFix, pTableName) ){
  107390. goto trigger_cleanup;
  107391. }
  107392. pTab = sqlite3SrcListLookup(pParse, pTableName);
  107393. if( !pTab ){
  107394. /* The table does not exist. */
  107395. if( db->init.iDb==1 ){
  107396. /* Ticket #3810.
  107397. ** Normally, whenever a table is dropped, all associated triggers are
  107398. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  107399. ** and the table is dropped by a different database connection, the
  107400. ** trigger is not visible to the database connection that does the
  107401. ** drop so the trigger cannot be dropped. This results in an
  107402. ** "orphaned trigger" - a trigger whose associated table is missing.
  107403. */
  107404. db->init.orphanTrigger = 1;
  107405. }
  107406. goto trigger_cleanup;
  107407. }
  107408. if( IsVirtual(pTab) ){
  107409. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  107410. goto trigger_cleanup;
  107411. }
  107412. /* Check that the trigger name is not reserved and that no trigger of the
  107413. ** specified name exists */
  107414. zName = sqlite3NameFromToken(db, pName);
  107415. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  107416. goto trigger_cleanup;
  107417. }
  107418. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107419. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  107420. if( !noErr ){
  107421. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  107422. }else{
  107423. assert( !db->init.busy );
  107424. sqlite3CodeVerifySchema(pParse, iDb);
  107425. }
  107426. goto trigger_cleanup;
  107427. }
  107428. /* Do not create a trigger on a system table */
  107429. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  107430. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  107431. goto trigger_cleanup;
  107432. }
  107433. /* INSTEAD of triggers are only for views and views only support INSTEAD
  107434. ** of triggers.
  107435. */
  107436. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  107437. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  107438. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  107439. goto trigger_cleanup;
  107440. }
  107441. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  107442. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  107443. " trigger on table: %S", pTableName, 0);
  107444. goto trigger_cleanup;
  107445. }
  107446. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  107447. #ifndef SQLITE_OMIT_AUTHORIZATION
  107448. {
  107449. int code = SQLITE_CREATE_TRIGGER;
  107450. const char *zDb = db->aDb[iTabDb].zName;
  107451. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  107452. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  107453. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  107454. goto trigger_cleanup;
  107455. }
  107456. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  107457. goto trigger_cleanup;
  107458. }
  107459. }
  107460. #endif
  107461. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  107462. ** cannot appear on views. So we might as well translate every
  107463. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  107464. ** elsewhere.
  107465. */
  107466. if (tr_tm == TK_INSTEAD){
  107467. tr_tm = TK_BEFORE;
  107468. }
  107469. /* Build the Trigger object */
  107470. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  107471. if( pTrigger==0 ) goto trigger_cleanup;
  107472. pTrigger->zName = zName;
  107473. zName = 0;
  107474. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  107475. pTrigger->pSchema = db->aDb[iDb].pSchema;
  107476. pTrigger->pTabSchema = pTab->pSchema;
  107477. pTrigger->op = (u8)op;
  107478. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  107479. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  107480. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  107481. assert( pParse->pNewTrigger==0 );
  107482. pParse->pNewTrigger = pTrigger;
  107483. trigger_cleanup:
  107484. sqlite3DbFree(db, zName);
  107485. sqlite3SrcListDelete(db, pTableName);
  107486. sqlite3IdListDelete(db, pColumns);
  107487. sqlite3ExprDelete(db, pWhen);
  107488. if( !pParse->pNewTrigger ){
  107489. sqlite3DeleteTrigger(db, pTrigger);
  107490. }else{
  107491. assert( pParse->pNewTrigger==pTrigger );
  107492. }
  107493. }
  107494. /*
  107495. ** This routine is called after all of the trigger actions have been parsed
  107496. ** in order to complete the process of building the trigger.
  107497. */
  107498. SQLITE_PRIVATE void sqlite3FinishTrigger(
  107499. Parse *pParse, /* Parser context */
  107500. TriggerStep *pStepList, /* The triggered program */
  107501. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  107502. ){
  107503. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  107504. char *zName; /* Name of trigger */
  107505. sqlite3 *db = pParse->db; /* The database */
  107506. DbFixer sFix; /* Fixer object */
  107507. int iDb; /* Database containing the trigger */
  107508. Token nameToken; /* Trigger name for error reporting */
  107509. pParse->pNewTrigger = 0;
  107510. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  107511. zName = pTrig->zName;
  107512. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  107513. pTrig->step_list = pStepList;
  107514. while( pStepList ){
  107515. pStepList->pTrig = pTrig;
  107516. pStepList = pStepList->pNext;
  107517. }
  107518. nameToken.z = pTrig->zName;
  107519. nameToken.n = sqlite3Strlen30(nameToken.z);
  107520. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  107521. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  107522. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  107523. ){
  107524. goto triggerfinish_cleanup;
  107525. }
  107526. /* if we are not initializing,
  107527. ** build the sqlite_master entry
  107528. */
  107529. if( !db->init.busy ){
  107530. Vdbe *v;
  107531. char *z;
  107532. /* Make an entry in the sqlite_master table */
  107533. v = sqlite3GetVdbe(pParse);
  107534. if( v==0 ) goto triggerfinish_cleanup;
  107535. sqlite3BeginWriteOperation(pParse, 0, iDb);
  107536. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  107537. sqlite3NestedParse(pParse,
  107538. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  107539. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  107540. pTrig->table, z);
  107541. sqlite3DbFree(db, z);
  107542. sqlite3ChangeCookie(pParse, iDb);
  107543. sqlite3VdbeAddParseSchemaOp(v, iDb,
  107544. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  107545. }
  107546. if( db->init.busy ){
  107547. Trigger *pLink = pTrig;
  107548. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  107549. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107550. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  107551. if( pTrig ){
  107552. db->mallocFailed = 1;
  107553. }else if( pLink->pSchema==pLink->pTabSchema ){
  107554. Table *pTab;
  107555. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  107556. assert( pTab!=0 );
  107557. pLink->pNext = pTab->pTrigger;
  107558. pTab->pTrigger = pLink;
  107559. }
  107560. }
  107561. triggerfinish_cleanup:
  107562. sqlite3DeleteTrigger(db, pTrig);
  107563. assert( !pParse->pNewTrigger );
  107564. sqlite3DeleteTriggerStep(db, pStepList);
  107565. }
  107566. /*
  107567. ** Turn a SELECT statement (that the pSelect parameter points to) into
  107568. ** a trigger step. Return a pointer to a TriggerStep structure.
  107569. **
  107570. ** The parser calls this routine when it finds a SELECT statement in
  107571. ** body of a TRIGGER.
  107572. */
  107573. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  107574. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  107575. if( pTriggerStep==0 ) {
  107576. sqlite3SelectDelete(db, pSelect);
  107577. return 0;
  107578. }
  107579. pTriggerStep->op = TK_SELECT;
  107580. pTriggerStep->pSelect = pSelect;
  107581. pTriggerStep->orconf = OE_Default;
  107582. return pTriggerStep;
  107583. }
  107584. /*
  107585. ** Allocate space to hold a new trigger step. The allocated space
  107586. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  107587. **
  107588. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  107589. */
  107590. static TriggerStep *triggerStepAllocate(
  107591. sqlite3 *db, /* Database connection */
  107592. u8 op, /* Trigger opcode */
  107593. Token *pName /* The target name */
  107594. ){
  107595. TriggerStep *pTriggerStep;
  107596. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  107597. if( pTriggerStep ){
  107598. char *z = (char*)&pTriggerStep[1];
  107599. memcpy(z, pName->z, pName->n);
  107600. sqlite3Dequote(z);
  107601. pTriggerStep->zTarget = z;
  107602. pTriggerStep->op = op;
  107603. }
  107604. return pTriggerStep;
  107605. }
  107606. /*
  107607. ** Build a trigger step out of an INSERT statement. Return a pointer
  107608. ** to the new trigger step.
  107609. **
  107610. ** The parser calls this routine when it sees an INSERT inside the
  107611. ** body of a trigger.
  107612. */
  107613. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  107614. sqlite3 *db, /* The database connection */
  107615. Token *pTableName, /* Name of the table into which we insert */
  107616. IdList *pColumn, /* List of columns in pTableName to insert into */
  107617. Select *pSelect, /* A SELECT statement that supplies values */
  107618. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  107619. ){
  107620. TriggerStep *pTriggerStep;
  107621. assert(pSelect != 0 || db->mallocFailed);
  107622. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  107623. if( pTriggerStep ){
  107624. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  107625. pTriggerStep->pIdList = pColumn;
  107626. pTriggerStep->orconf = orconf;
  107627. }else{
  107628. sqlite3IdListDelete(db, pColumn);
  107629. }
  107630. sqlite3SelectDelete(db, pSelect);
  107631. return pTriggerStep;
  107632. }
  107633. /*
  107634. ** Construct a trigger step that implements an UPDATE statement and return
  107635. ** a pointer to that trigger step. The parser calls this routine when it
  107636. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  107637. */
  107638. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  107639. sqlite3 *db, /* The database connection */
  107640. Token *pTableName, /* Name of the table to be updated */
  107641. ExprList *pEList, /* The SET clause: list of column and new values */
  107642. Expr *pWhere, /* The WHERE clause */
  107643. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  107644. ){
  107645. TriggerStep *pTriggerStep;
  107646. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  107647. if( pTriggerStep ){
  107648. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  107649. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  107650. pTriggerStep->orconf = orconf;
  107651. }
  107652. sqlite3ExprListDelete(db, pEList);
  107653. sqlite3ExprDelete(db, pWhere);
  107654. return pTriggerStep;
  107655. }
  107656. /*
  107657. ** Construct a trigger step that implements a DELETE statement and return
  107658. ** a pointer to that trigger step. The parser calls this routine when it
  107659. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  107660. */
  107661. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  107662. sqlite3 *db, /* Database connection */
  107663. Token *pTableName, /* The table from which rows are deleted */
  107664. Expr *pWhere /* The WHERE clause */
  107665. ){
  107666. TriggerStep *pTriggerStep;
  107667. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  107668. if( pTriggerStep ){
  107669. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  107670. pTriggerStep->orconf = OE_Default;
  107671. }
  107672. sqlite3ExprDelete(db, pWhere);
  107673. return pTriggerStep;
  107674. }
  107675. /*
  107676. ** Recursively delete a Trigger structure
  107677. */
  107678. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  107679. if( pTrigger==0 ) return;
  107680. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  107681. sqlite3DbFree(db, pTrigger->zName);
  107682. sqlite3DbFree(db, pTrigger->table);
  107683. sqlite3ExprDelete(db, pTrigger->pWhen);
  107684. sqlite3IdListDelete(db, pTrigger->pColumns);
  107685. sqlite3DbFree(db, pTrigger);
  107686. }
  107687. /*
  107688. ** This function is called to drop a trigger from the database schema.
  107689. **
  107690. ** This may be called directly from the parser and therefore identifies
  107691. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  107692. ** same job as this routine except it takes a pointer to the trigger
  107693. ** instead of the trigger name.
  107694. **/
  107695. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  107696. Trigger *pTrigger = 0;
  107697. int i;
  107698. const char *zDb;
  107699. const char *zName;
  107700. sqlite3 *db = pParse->db;
  107701. if( db->mallocFailed ) goto drop_trigger_cleanup;
  107702. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  107703. goto drop_trigger_cleanup;
  107704. }
  107705. assert( pName->nSrc==1 );
  107706. zDb = pName->a[0].zDatabase;
  107707. zName = pName->a[0].zName;
  107708. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  107709. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  107710. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  107711. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  107712. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  107713. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  107714. if( pTrigger ) break;
  107715. }
  107716. if( !pTrigger ){
  107717. if( !noErr ){
  107718. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  107719. }else{
  107720. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  107721. }
  107722. pParse->checkSchema = 1;
  107723. goto drop_trigger_cleanup;
  107724. }
  107725. sqlite3DropTriggerPtr(pParse, pTrigger);
  107726. drop_trigger_cleanup:
  107727. sqlite3SrcListDelete(db, pName);
  107728. }
  107729. /*
  107730. ** Return a pointer to the Table structure for the table that a trigger
  107731. ** is set on.
  107732. */
  107733. static Table *tableOfTrigger(Trigger *pTrigger){
  107734. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  107735. }
  107736. /*
  107737. ** Drop a trigger given a pointer to that trigger.
  107738. */
  107739. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  107740. Table *pTable;
  107741. Vdbe *v;
  107742. sqlite3 *db = pParse->db;
  107743. int iDb;
  107744. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  107745. assert( iDb>=0 && iDb<db->nDb );
  107746. pTable = tableOfTrigger(pTrigger);
  107747. assert( pTable );
  107748. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  107749. #ifndef SQLITE_OMIT_AUTHORIZATION
  107750. {
  107751. int code = SQLITE_DROP_TRIGGER;
  107752. const char *zDb = db->aDb[iDb].zName;
  107753. const char *zTab = SCHEMA_TABLE(iDb);
  107754. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  107755. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  107756. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  107757. return;
  107758. }
  107759. }
  107760. #endif
  107761. /* Generate code to destroy the database record of the trigger.
  107762. */
  107763. assert( pTable!=0 );
  107764. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  107765. int base;
  107766. static const int iLn = VDBE_OFFSET_LINENO(2);
  107767. static const VdbeOpList dropTrigger[] = {
  107768. { OP_Rewind, 0, ADDR(9), 0},
  107769. { OP_String8, 0, 1, 0}, /* 1 */
  107770. { OP_Column, 0, 1, 2},
  107771. { OP_Ne, 2, ADDR(8), 1},
  107772. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  107773. { OP_Column, 0, 0, 2},
  107774. { OP_Ne, 2, ADDR(8), 1},
  107775. { OP_Delete, 0, 0, 0},
  107776. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  107777. };
  107778. sqlite3BeginWriteOperation(pParse, 0, iDb);
  107779. sqlite3OpenMasterTable(pParse, iDb);
  107780. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
  107781. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  107782. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  107783. sqlite3ChangeCookie(pParse, iDb);
  107784. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  107785. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  107786. if( pParse->nMem<3 ){
  107787. pParse->nMem = 3;
  107788. }
  107789. }
  107790. }
  107791. /*
  107792. ** Remove a trigger from the hash tables of the sqlite* pointer.
  107793. */
  107794. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  107795. Trigger *pTrigger;
  107796. Hash *pHash;
  107797. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107798. pHash = &(db->aDb[iDb].pSchema->trigHash);
  107799. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  107800. if( ALWAYS(pTrigger) ){
  107801. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  107802. Table *pTab = tableOfTrigger(pTrigger);
  107803. Trigger **pp;
  107804. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  107805. *pp = (*pp)->pNext;
  107806. }
  107807. sqlite3DeleteTrigger(db, pTrigger);
  107808. db->flags |= SQLITE_InternChanges;
  107809. }
  107810. }
  107811. /*
  107812. ** pEList is the SET clause of an UPDATE statement. Each entry
  107813. ** in pEList is of the format <id>=<expr>. If any of the entries
  107814. ** in pEList have an <id> which matches an identifier in pIdList,
  107815. ** then return TRUE. If pIdList==NULL, then it is considered a
  107816. ** wildcard that matches anything. Likewise if pEList==NULL then
  107817. ** it matches anything so always return true. Return false only
  107818. ** if there is no match.
  107819. */
  107820. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  107821. int e;
  107822. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  107823. for(e=0; e<pEList->nExpr; e++){
  107824. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  107825. }
  107826. return 0;
  107827. }
  107828. /*
  107829. ** Return a list of all triggers on table pTab if there exists at least
  107830. ** one trigger that must be fired when an operation of type 'op' is
  107831. ** performed on the table, and, if that operation is an UPDATE, if at
  107832. ** least one of the columns in pChanges is being modified.
  107833. */
  107834. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  107835. Parse *pParse, /* Parse context */
  107836. Table *pTab, /* The table the contains the triggers */
  107837. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  107838. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  107839. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  107840. ){
  107841. int mask = 0;
  107842. Trigger *pList = 0;
  107843. Trigger *p;
  107844. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  107845. pList = sqlite3TriggerList(pParse, pTab);
  107846. }
  107847. assert( pList==0 || IsVirtual(pTab)==0 );
  107848. for(p=pList; p; p=p->pNext){
  107849. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  107850. mask |= p->tr_tm;
  107851. }
  107852. }
  107853. if( pMask ){
  107854. *pMask = mask;
  107855. }
  107856. return (mask ? pList : 0);
  107857. }
  107858. /*
  107859. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  107860. ** to that SrcList.
  107861. **
  107862. ** This routine adds a specific database name, if needed, to the target when
  107863. ** forming the SrcList. This prevents a trigger in one database from
  107864. ** referring to a target in another database. An exception is when the
  107865. ** trigger is in TEMP in which case it can refer to any other database it
  107866. ** wants.
  107867. */
  107868. static SrcList *targetSrcList(
  107869. Parse *pParse, /* The parsing context */
  107870. TriggerStep *pStep /* The trigger containing the target token */
  107871. ){
  107872. sqlite3 *db = pParse->db;
  107873. int iDb; /* Index of the database to use */
  107874. SrcList *pSrc; /* SrcList to be returned */
  107875. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  107876. if( pSrc ){
  107877. assert( pSrc->nSrc>0 );
  107878. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  107879. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  107880. if( iDb==0 || iDb>=2 ){
  107881. assert( iDb<db->nDb );
  107882. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  107883. }
  107884. }
  107885. return pSrc;
  107886. }
  107887. /*
  107888. ** Generate VDBE code for the statements inside the body of a single
  107889. ** trigger.
  107890. */
  107891. static int codeTriggerProgram(
  107892. Parse *pParse, /* The parser context */
  107893. TriggerStep *pStepList, /* List of statements inside the trigger body */
  107894. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  107895. ){
  107896. TriggerStep *pStep;
  107897. Vdbe *v = pParse->pVdbe;
  107898. sqlite3 *db = pParse->db;
  107899. assert( pParse->pTriggerTab && pParse->pToplevel );
  107900. assert( pStepList );
  107901. assert( v!=0 );
  107902. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  107903. /* Figure out the ON CONFLICT policy that will be used for this step
  107904. ** of the trigger program. If the statement that caused this trigger
  107905. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  107906. ** the ON CONFLICT policy that was specified as part of the trigger
  107907. ** step statement. Example:
  107908. **
  107909. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  107910. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  107911. ** END;
  107912. **
  107913. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  107914. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  107915. */
  107916. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  107917. assert( pParse->okConstFactor==0 );
  107918. switch( pStep->op ){
  107919. case TK_UPDATE: {
  107920. sqlite3Update(pParse,
  107921. targetSrcList(pParse, pStep),
  107922. sqlite3ExprListDup(db, pStep->pExprList, 0),
  107923. sqlite3ExprDup(db, pStep->pWhere, 0),
  107924. pParse->eOrconf
  107925. );
  107926. break;
  107927. }
  107928. case TK_INSERT: {
  107929. sqlite3Insert(pParse,
  107930. targetSrcList(pParse, pStep),
  107931. sqlite3SelectDup(db, pStep->pSelect, 0),
  107932. sqlite3IdListDup(db, pStep->pIdList),
  107933. pParse->eOrconf
  107934. );
  107935. break;
  107936. }
  107937. case TK_DELETE: {
  107938. sqlite3DeleteFrom(pParse,
  107939. targetSrcList(pParse, pStep),
  107940. sqlite3ExprDup(db, pStep->pWhere, 0)
  107941. );
  107942. break;
  107943. }
  107944. default: assert( pStep->op==TK_SELECT ); {
  107945. SelectDest sDest;
  107946. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  107947. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  107948. sqlite3Select(pParse, pSelect, &sDest);
  107949. sqlite3SelectDelete(db, pSelect);
  107950. break;
  107951. }
  107952. }
  107953. if( pStep->op!=TK_SELECT ){
  107954. sqlite3VdbeAddOp0(v, OP_ResetCount);
  107955. }
  107956. }
  107957. return 0;
  107958. }
  107959. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  107960. /*
  107961. ** This function is used to add VdbeComment() annotations to a VDBE
  107962. ** program. It is not used in production code, only for debugging.
  107963. */
  107964. static const char *onErrorText(int onError){
  107965. switch( onError ){
  107966. case OE_Abort: return "abort";
  107967. case OE_Rollback: return "rollback";
  107968. case OE_Fail: return "fail";
  107969. case OE_Replace: return "replace";
  107970. case OE_Ignore: return "ignore";
  107971. case OE_Default: return "default";
  107972. }
  107973. return "n/a";
  107974. }
  107975. #endif
  107976. /*
  107977. ** Parse context structure pFrom has just been used to create a sub-vdbe
  107978. ** (trigger program). If an error has occurred, transfer error information
  107979. ** from pFrom to pTo.
  107980. */
  107981. static void transferParseError(Parse *pTo, Parse *pFrom){
  107982. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  107983. assert( pTo->zErrMsg==0 || pTo->nErr );
  107984. if( pTo->nErr==0 ){
  107985. pTo->zErrMsg = pFrom->zErrMsg;
  107986. pTo->nErr = pFrom->nErr;
  107987. pTo->rc = pFrom->rc;
  107988. }else{
  107989. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  107990. }
  107991. }
  107992. /*
  107993. ** Create and populate a new TriggerPrg object with a sub-program
  107994. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  107995. */
  107996. static TriggerPrg *codeRowTrigger(
  107997. Parse *pParse, /* Current parse context */
  107998. Trigger *pTrigger, /* Trigger to code */
  107999. Table *pTab, /* The table pTrigger is attached to */
  108000. int orconf /* ON CONFLICT policy to code trigger program with */
  108001. ){
  108002. Parse *pTop = sqlite3ParseToplevel(pParse);
  108003. sqlite3 *db = pParse->db; /* Database handle */
  108004. TriggerPrg *pPrg; /* Value to return */
  108005. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  108006. Vdbe *v; /* Temporary VM */
  108007. NameContext sNC; /* Name context for sub-vdbe */
  108008. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  108009. Parse *pSubParse; /* Parse context for sub-vdbe */
  108010. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  108011. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  108012. assert( pTop->pVdbe );
  108013. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  108014. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  108015. ** list of the top-level Parse object sooner rather than later. */
  108016. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  108017. if( !pPrg ) return 0;
  108018. pPrg->pNext = pTop->pTriggerPrg;
  108019. pTop->pTriggerPrg = pPrg;
  108020. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  108021. if( !pProgram ) return 0;
  108022. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  108023. pPrg->pTrigger = pTrigger;
  108024. pPrg->orconf = orconf;
  108025. pPrg->aColmask[0] = 0xffffffff;
  108026. pPrg->aColmask[1] = 0xffffffff;
  108027. /* Allocate and populate a new Parse context to use for coding the
  108028. ** trigger sub-program. */
  108029. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  108030. if( !pSubParse ) return 0;
  108031. memset(&sNC, 0, sizeof(sNC));
  108032. sNC.pParse = pSubParse;
  108033. pSubParse->db = db;
  108034. pSubParse->pTriggerTab = pTab;
  108035. pSubParse->pToplevel = pTop;
  108036. pSubParse->zAuthContext = pTrigger->zName;
  108037. pSubParse->eTriggerOp = pTrigger->op;
  108038. pSubParse->nQueryLoop = pParse->nQueryLoop;
  108039. v = sqlite3GetVdbe(pSubParse);
  108040. if( v ){
  108041. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  108042. pTrigger->zName, onErrorText(orconf),
  108043. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  108044. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  108045. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  108046. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  108047. pTab->zName
  108048. ));
  108049. #ifndef SQLITE_OMIT_TRACE
  108050. sqlite3VdbeChangeP4(v, -1,
  108051. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  108052. );
  108053. #endif
  108054. /* If one was specified, code the WHEN clause. If it evaluates to false
  108055. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  108056. ** OP_Halt inserted at the end of the program. */
  108057. if( pTrigger->pWhen ){
  108058. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  108059. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  108060. && db->mallocFailed==0
  108061. ){
  108062. iEndTrigger = sqlite3VdbeMakeLabel(v);
  108063. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  108064. }
  108065. sqlite3ExprDelete(db, pWhen);
  108066. }
  108067. /* Code the trigger program into the sub-vdbe. */
  108068. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  108069. /* Insert an OP_Halt at the end of the sub-program. */
  108070. if( iEndTrigger ){
  108071. sqlite3VdbeResolveLabel(v, iEndTrigger);
  108072. }
  108073. sqlite3VdbeAddOp0(v, OP_Halt);
  108074. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  108075. transferParseError(pParse, pSubParse);
  108076. if( db->mallocFailed==0 ){
  108077. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  108078. }
  108079. pProgram->nMem = pSubParse->nMem;
  108080. pProgram->nCsr = pSubParse->nTab;
  108081. pProgram->nOnce = pSubParse->nOnce;
  108082. pProgram->token = (void *)pTrigger;
  108083. pPrg->aColmask[0] = pSubParse->oldmask;
  108084. pPrg->aColmask[1] = pSubParse->newmask;
  108085. sqlite3VdbeDelete(v);
  108086. }
  108087. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  108088. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  108089. sqlite3ParserReset(pSubParse);
  108090. sqlite3StackFree(db, pSubParse);
  108091. return pPrg;
  108092. }
  108093. /*
  108094. ** Return a pointer to a TriggerPrg object containing the sub-program for
  108095. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  108096. ** TriggerPrg object exists, a new object is allocated and populated before
  108097. ** being returned.
  108098. */
  108099. static TriggerPrg *getRowTrigger(
  108100. Parse *pParse, /* Current parse context */
  108101. Trigger *pTrigger, /* Trigger to code */
  108102. Table *pTab, /* The table trigger pTrigger is attached to */
  108103. int orconf /* ON CONFLICT algorithm. */
  108104. ){
  108105. Parse *pRoot = sqlite3ParseToplevel(pParse);
  108106. TriggerPrg *pPrg;
  108107. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  108108. /* It may be that this trigger has already been coded (or is in the
  108109. ** process of being coded). If this is the case, then an entry with
  108110. ** a matching TriggerPrg.pTrigger field will be present somewhere
  108111. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  108112. for(pPrg=pRoot->pTriggerPrg;
  108113. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  108114. pPrg=pPrg->pNext
  108115. );
  108116. /* If an existing TriggerPrg could not be located, create a new one. */
  108117. if( !pPrg ){
  108118. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  108119. }
  108120. return pPrg;
  108121. }
  108122. /*
  108123. ** Generate code for the trigger program associated with trigger p on
  108124. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  108125. ** function are the same as those described in the header function for
  108126. ** sqlite3CodeRowTrigger()
  108127. */
  108128. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  108129. Parse *pParse, /* Parse context */
  108130. Trigger *p, /* Trigger to code */
  108131. Table *pTab, /* The table to code triggers from */
  108132. int reg, /* Reg array containing OLD.* and NEW.* values */
  108133. int orconf, /* ON CONFLICT policy */
  108134. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  108135. ){
  108136. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  108137. TriggerPrg *pPrg;
  108138. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  108139. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  108140. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  108141. ** is a pointer to the sub-vdbe containing the trigger program. */
  108142. if( pPrg ){
  108143. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  108144. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  108145. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  108146. VdbeComment(
  108147. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  108148. /* Set the P5 operand of the OP_Program instruction to non-zero if
  108149. ** recursive invocation of this trigger program is disallowed. Recursive
  108150. ** invocation is disallowed if (a) the sub-program is really a trigger,
  108151. ** not a foreign key action, and (b) the flag to enable recursive triggers
  108152. ** is clear. */
  108153. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  108154. }
  108155. }
  108156. /*
  108157. ** This is called to code the required FOR EACH ROW triggers for an operation
  108158. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  108159. ** is given by the op parameter. The tr_tm parameter determines whether the
  108160. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  108161. ** parameter pChanges is passed the list of columns being modified.
  108162. **
  108163. ** If there are no triggers that fire at the specified time for the specified
  108164. ** operation on pTab, this function is a no-op.
  108165. **
  108166. ** The reg argument is the address of the first in an array of registers
  108167. ** that contain the values substituted for the new.* and old.* references
  108168. ** in the trigger program. If N is the number of columns in table pTab
  108169. ** (a copy of pTab->nCol), then registers are populated as follows:
  108170. **
  108171. ** Register Contains
  108172. ** ------------------------------------------------------
  108173. ** reg+0 OLD.rowid
  108174. ** reg+1 OLD.* value of left-most column of pTab
  108175. ** ... ...
  108176. ** reg+N OLD.* value of right-most column of pTab
  108177. ** reg+N+1 NEW.rowid
  108178. ** reg+N+2 OLD.* value of left-most column of pTab
  108179. ** ... ...
  108180. ** reg+N+N+1 NEW.* value of right-most column of pTab
  108181. **
  108182. ** For ON DELETE triggers, the registers containing the NEW.* values will
  108183. ** never be accessed by the trigger program, so they are not allocated or
  108184. ** populated by the caller (there is no data to populate them with anyway).
  108185. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  108186. ** are never accessed, and so are not allocated by the caller. So, for an
  108187. ** ON INSERT trigger, the value passed to this function as parameter reg
  108188. ** is not a readable register, although registers (reg+N) through
  108189. ** (reg+N+N+1) are.
  108190. **
  108191. ** Parameter orconf is the default conflict resolution algorithm for the
  108192. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  108193. ** is the instruction that control should jump to if a trigger program
  108194. ** raises an IGNORE exception.
  108195. */
  108196. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  108197. Parse *pParse, /* Parse context */
  108198. Trigger *pTrigger, /* List of triggers on table pTab */
  108199. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  108200. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  108201. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  108202. Table *pTab, /* The table to code triggers from */
  108203. int reg, /* The first in an array of registers (see above) */
  108204. int orconf, /* ON CONFLICT policy */
  108205. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  108206. ){
  108207. Trigger *p; /* Used to iterate through pTrigger list */
  108208. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  108209. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  108210. assert( (op==TK_UPDATE)==(pChanges!=0) );
  108211. for(p=pTrigger; p; p=p->pNext){
  108212. /* Sanity checking: The schema for the trigger and for the table are
  108213. ** always defined. The trigger must be in the same schema as the table
  108214. ** or else it must be a TEMP trigger. */
  108215. assert( p->pSchema!=0 );
  108216. assert( p->pTabSchema!=0 );
  108217. assert( p->pSchema==p->pTabSchema
  108218. || p->pSchema==pParse->db->aDb[1].pSchema );
  108219. /* Determine whether we should code this trigger */
  108220. if( p->op==op
  108221. && p->tr_tm==tr_tm
  108222. && checkColumnOverlap(p->pColumns, pChanges)
  108223. ){
  108224. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  108225. }
  108226. }
  108227. }
  108228. /*
  108229. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  108230. ** This function returns a 32-bit bitmask indicating which columns of the
  108231. ** old.* or new.* tables actually are used by triggers. This information
  108232. ** may be used by the caller, for example, to avoid having to load the entire
  108233. ** old.* record into memory when executing an UPDATE or DELETE command.
  108234. **
  108235. ** Bit 0 of the returned mask is set if the left-most column of the
  108236. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  108237. ** the second leftmost column value is required, and so on. If there
  108238. ** are more than 32 columns in the table, and at least one of the columns
  108239. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  108240. **
  108241. ** It is not possible to determine if the old.rowid or new.rowid column is
  108242. ** accessed by triggers. The caller must always assume that it is.
  108243. **
  108244. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  108245. ** applies to the old.* table. If 1, the new.* table.
  108246. **
  108247. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  108248. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  108249. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  108250. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  108251. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  108252. */
  108253. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  108254. Parse *pParse, /* Parse context */
  108255. Trigger *pTrigger, /* List of triggers on table pTab */
  108256. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  108257. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  108258. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  108259. Table *pTab, /* The table to code triggers from */
  108260. int orconf /* Default ON CONFLICT policy for trigger steps */
  108261. ){
  108262. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  108263. u32 mask = 0;
  108264. Trigger *p;
  108265. assert( isNew==1 || isNew==0 );
  108266. for(p=pTrigger; p; p=p->pNext){
  108267. if( p->op==op && (tr_tm&p->tr_tm)
  108268. && checkColumnOverlap(p->pColumns,pChanges)
  108269. ){
  108270. TriggerPrg *pPrg;
  108271. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  108272. if( pPrg ){
  108273. mask |= pPrg->aColmask[isNew];
  108274. }
  108275. }
  108276. }
  108277. return mask;
  108278. }
  108279. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  108280. /************** End of trigger.c *********************************************/
  108281. /************** Begin file update.c ******************************************/
  108282. /*
  108283. ** 2001 September 15
  108284. **
  108285. ** The author disclaims copyright to this source code. In place of
  108286. ** a legal notice, here is a blessing:
  108287. **
  108288. ** May you do good and not evil.
  108289. ** May you find forgiveness for yourself and forgive others.
  108290. ** May you share freely, never taking more than you give.
  108291. **
  108292. *************************************************************************
  108293. ** This file contains C code routines that are called by the parser
  108294. ** to handle UPDATE statements.
  108295. */
  108296. /* #include "sqliteInt.h" */
  108297. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108298. /* Forward declaration */
  108299. static void updateVirtualTable(
  108300. Parse *pParse, /* The parsing context */
  108301. SrcList *pSrc, /* The virtual table to be modified */
  108302. Table *pTab, /* The virtual table */
  108303. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  108304. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  108305. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  108306. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  108307. int onError /* ON CONFLICT strategy */
  108308. );
  108309. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108310. /*
  108311. ** The most recently coded instruction was an OP_Column to retrieve the
  108312. ** i-th column of table pTab. This routine sets the P4 parameter of the
  108313. ** OP_Column to the default value, if any.
  108314. **
  108315. ** The default value of a column is specified by a DEFAULT clause in the
  108316. ** column definition. This was either supplied by the user when the table
  108317. ** was created, or added later to the table definition by an ALTER TABLE
  108318. ** command. If the latter, then the row-records in the table btree on disk
  108319. ** may not contain a value for the column and the default value, taken
  108320. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  108321. ** If the former, then all row-records are guaranteed to include a value
  108322. ** for the column and the P4 value is not required.
  108323. **
  108324. ** Column definitions created by an ALTER TABLE command may only have
  108325. ** literal default values specified: a number, null or a string. (If a more
  108326. ** complicated default expression value was provided, it is evaluated
  108327. ** when the ALTER TABLE is executed and one of the literal values written
  108328. ** into the sqlite_master table.)
  108329. **
  108330. ** Therefore, the P4 parameter is only required if the default value for
  108331. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  108332. ** function is capable of transforming these types of expressions into
  108333. ** sqlite3_value objects.
  108334. **
  108335. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  108336. ** on register iReg. This is used when an equivalent integer value is
  108337. ** stored in place of an 8-byte floating point value in order to save
  108338. ** space.
  108339. */
  108340. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  108341. assert( pTab!=0 );
  108342. if( !pTab->pSelect ){
  108343. sqlite3_value *pValue = 0;
  108344. u8 enc = ENC(sqlite3VdbeDb(v));
  108345. Column *pCol = &pTab->aCol[i];
  108346. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  108347. assert( i<pTab->nCol );
  108348. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  108349. pCol->affinity, &pValue);
  108350. if( pValue ){
  108351. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  108352. }
  108353. #ifndef SQLITE_OMIT_FLOATING_POINT
  108354. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  108355. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  108356. }
  108357. #endif
  108358. }
  108359. }
  108360. /*
  108361. ** Process an UPDATE statement.
  108362. **
  108363. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  108364. ** \_______/ \________/ \______/ \________________/
  108365. * onError pTabList pChanges pWhere
  108366. */
  108367. SQLITE_PRIVATE void sqlite3Update(
  108368. Parse *pParse, /* The parser context */
  108369. SrcList *pTabList, /* The table in which we should change things */
  108370. ExprList *pChanges, /* Things to be changed */
  108371. Expr *pWhere, /* The WHERE clause. May be null */
  108372. int onError /* How to handle constraint errors */
  108373. ){
  108374. int i, j; /* Loop counters */
  108375. Table *pTab; /* The table to be updated */
  108376. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  108377. WhereInfo *pWInfo; /* Information about the WHERE clause */
  108378. Vdbe *v; /* The virtual database engine */
  108379. Index *pIdx; /* For looping over indices */
  108380. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  108381. int nIdx; /* Number of indices that need updating */
  108382. int iBaseCur; /* Base cursor number */
  108383. int iDataCur; /* Cursor for the canonical data btree */
  108384. int iIdxCur; /* Cursor for the first index */
  108385. sqlite3 *db; /* The database structure */
  108386. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  108387. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  108388. ** an expression for the i-th column of the table.
  108389. ** aXRef[i]==-1 if the i-th column is not changed. */
  108390. u8 *aToOpen; /* 1 for tables and indices to be opened */
  108391. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  108392. u8 chngRowid; /* Rowid changed in a normal table */
  108393. u8 chngKey; /* Either chngPk or chngRowid */
  108394. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  108395. AuthContext sContext; /* The authorization context */
  108396. NameContext sNC; /* The name-context to resolve expressions in */
  108397. int iDb; /* Database containing the table being updated */
  108398. int okOnePass; /* True for one-pass algorithm without the FIFO */
  108399. int hasFK; /* True if foreign key processing is required */
  108400. int labelBreak; /* Jump here to break out of UPDATE loop */
  108401. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  108402. #ifndef SQLITE_OMIT_TRIGGER
  108403. int isView; /* True when updating a view (INSTEAD OF trigger) */
  108404. Trigger *pTrigger; /* List of triggers on pTab, if required */
  108405. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  108406. #endif
  108407. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  108408. int iEph = 0; /* Ephemeral table holding all primary key values */
  108409. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  108410. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  108411. /* Register Allocations */
  108412. int regRowCount = 0; /* A count of rows changed */
  108413. int regOldRowid = 0; /* The old rowid */
  108414. int regNewRowid = 0; /* The new rowid */
  108415. int regNew = 0; /* Content of the NEW.* table in triggers */
  108416. int regOld = 0; /* Content of OLD.* table in triggers */
  108417. int regRowSet = 0; /* Rowset of rows to be updated */
  108418. int regKey = 0; /* composite PRIMARY KEY value */
  108419. memset(&sContext, 0, sizeof(sContext));
  108420. db = pParse->db;
  108421. if( pParse->nErr || db->mallocFailed ){
  108422. goto update_cleanup;
  108423. }
  108424. assert( pTabList->nSrc==1 );
  108425. /* Locate the table which we want to update.
  108426. */
  108427. pTab = sqlite3SrcListLookup(pParse, pTabList);
  108428. if( pTab==0 ) goto update_cleanup;
  108429. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  108430. /* Figure out if we have any triggers and if the table being
  108431. ** updated is a view.
  108432. */
  108433. #ifndef SQLITE_OMIT_TRIGGER
  108434. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  108435. isView = pTab->pSelect!=0;
  108436. assert( pTrigger || tmask==0 );
  108437. #else
  108438. # define pTrigger 0
  108439. # define isView 0
  108440. # define tmask 0
  108441. #endif
  108442. #ifdef SQLITE_OMIT_VIEW
  108443. # undef isView
  108444. # define isView 0
  108445. #endif
  108446. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  108447. goto update_cleanup;
  108448. }
  108449. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  108450. goto update_cleanup;
  108451. }
  108452. /* Allocate a cursors for the main database table and for all indices.
  108453. ** The index cursors might not be used, but if they are used they
  108454. ** need to occur right after the database cursor. So go ahead and
  108455. ** allocate enough space, just in case.
  108456. */
  108457. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  108458. iIdxCur = iDataCur+1;
  108459. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  108460. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  108461. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  108462. iDataCur = pParse->nTab;
  108463. pTabList->a[0].iCursor = iDataCur;
  108464. }
  108465. pParse->nTab++;
  108466. }
  108467. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  108468. ** Initialize aXRef[] and aToOpen[] to their default values.
  108469. */
  108470. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  108471. if( aXRef==0 ) goto update_cleanup;
  108472. aRegIdx = aXRef+pTab->nCol;
  108473. aToOpen = (u8*)(aRegIdx+nIdx);
  108474. memset(aToOpen, 1, nIdx+1);
  108475. aToOpen[nIdx+1] = 0;
  108476. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  108477. /* Initialize the name-context */
  108478. memset(&sNC, 0, sizeof(sNC));
  108479. sNC.pParse = pParse;
  108480. sNC.pSrcList = pTabList;
  108481. /* Resolve the column names in all the expressions of the
  108482. ** of the UPDATE statement. Also find the column index
  108483. ** for each column to be updated in the pChanges array. For each
  108484. ** column to be updated, make sure we have authorization to change
  108485. ** that column.
  108486. */
  108487. chngRowid = chngPk = 0;
  108488. for(i=0; i<pChanges->nExpr; i++){
  108489. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  108490. goto update_cleanup;
  108491. }
  108492. for(j=0; j<pTab->nCol; j++){
  108493. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  108494. if( j==pTab->iPKey ){
  108495. chngRowid = 1;
  108496. pRowidExpr = pChanges->a[i].pExpr;
  108497. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  108498. chngPk = 1;
  108499. }
  108500. aXRef[j] = i;
  108501. break;
  108502. }
  108503. }
  108504. if( j>=pTab->nCol ){
  108505. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  108506. j = -1;
  108507. chngRowid = 1;
  108508. pRowidExpr = pChanges->a[i].pExpr;
  108509. }else{
  108510. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  108511. pParse->checkSchema = 1;
  108512. goto update_cleanup;
  108513. }
  108514. }
  108515. #ifndef SQLITE_OMIT_AUTHORIZATION
  108516. {
  108517. int rc;
  108518. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  108519. j<0 ? "ROWID" : pTab->aCol[j].zName,
  108520. db->aDb[iDb].zName);
  108521. if( rc==SQLITE_DENY ){
  108522. goto update_cleanup;
  108523. }else if( rc==SQLITE_IGNORE ){
  108524. aXRef[j] = -1;
  108525. }
  108526. }
  108527. #endif
  108528. }
  108529. assert( (chngRowid & chngPk)==0 );
  108530. assert( chngRowid==0 || chngRowid==1 );
  108531. assert( chngPk==0 || chngPk==1 );
  108532. chngKey = chngRowid + chngPk;
  108533. /* The SET expressions are not actually used inside the WHERE loop.
  108534. ** So reset the colUsed mask
  108535. */
  108536. pTabList->a[0].colUsed = 0;
  108537. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  108538. /* There is one entry in the aRegIdx[] array for each index on the table
  108539. ** being updated. Fill in aRegIdx[] with a register number that will hold
  108540. ** the key for accessing each index.
  108541. **
  108542. ** FIXME: Be smarter about omitting indexes that use expressions.
  108543. */
  108544. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  108545. int reg;
  108546. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  108547. reg = ++pParse->nMem;
  108548. }else{
  108549. reg = 0;
  108550. for(i=0; i<pIdx->nKeyCol; i++){
  108551. i16 iIdxCol = pIdx->aiColumn[i];
  108552. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  108553. reg = ++pParse->nMem;
  108554. break;
  108555. }
  108556. }
  108557. }
  108558. if( reg==0 ) aToOpen[j+1] = 0;
  108559. aRegIdx[j] = reg;
  108560. }
  108561. /* Begin generating code. */
  108562. v = sqlite3GetVdbe(pParse);
  108563. if( v==0 ) goto update_cleanup;
  108564. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  108565. sqlite3BeginWriteOperation(pParse, 1, iDb);
  108566. /* Allocate required registers. */
  108567. if( !IsVirtual(pTab) ){
  108568. regRowSet = ++pParse->nMem;
  108569. regOldRowid = regNewRowid = ++pParse->nMem;
  108570. if( chngPk || pTrigger || hasFK ){
  108571. regOld = pParse->nMem + 1;
  108572. pParse->nMem += pTab->nCol;
  108573. }
  108574. if( chngKey || pTrigger || hasFK ){
  108575. regNewRowid = ++pParse->nMem;
  108576. }
  108577. regNew = pParse->nMem + 1;
  108578. pParse->nMem += pTab->nCol;
  108579. }
  108580. /* Start the view context. */
  108581. if( isView ){
  108582. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  108583. }
  108584. /* If we are trying to update a view, realize that view into
  108585. ** an ephemeral table.
  108586. */
  108587. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  108588. if( isView ){
  108589. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  108590. }
  108591. #endif
  108592. /* Resolve the column names in all the expressions in the
  108593. ** WHERE clause.
  108594. */
  108595. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  108596. goto update_cleanup;
  108597. }
  108598. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108599. /* Virtual tables must be handled separately */
  108600. if( IsVirtual(pTab) ){
  108601. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  108602. pWhere, onError);
  108603. goto update_cleanup;
  108604. }
  108605. #endif
  108606. /* Begin the database scan
  108607. */
  108608. if( HasRowid(pTab) ){
  108609. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  108610. pWInfo = sqlite3WhereBegin(
  108611. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  108612. );
  108613. if( pWInfo==0 ) goto update_cleanup;
  108614. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  108615. /* Remember the rowid of every item to be updated.
  108616. */
  108617. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  108618. if( !okOnePass ){
  108619. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  108620. }
  108621. /* End the database scan loop.
  108622. */
  108623. sqlite3WhereEnd(pWInfo);
  108624. }else{
  108625. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  108626. i16 nPk; /* Number of components of the PRIMARY KEY */
  108627. int addrOpen; /* Address of the OpenEphemeral instruction */
  108628. assert( pPk!=0 );
  108629. nPk = pPk->nKeyCol;
  108630. iPk = pParse->nMem+1;
  108631. pParse->nMem += nPk;
  108632. regKey = ++pParse->nMem;
  108633. iEph = pParse->nTab++;
  108634. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  108635. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  108636. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  108637. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  108638. WHERE_ONEPASS_DESIRED, iIdxCur);
  108639. if( pWInfo==0 ) goto update_cleanup;
  108640. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  108641. for(i=0; i<nPk; i++){
  108642. assert( pPk->aiColumn[i]>=0 );
  108643. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  108644. iPk+i);
  108645. }
  108646. if( okOnePass ){
  108647. sqlite3VdbeChangeToNoop(v, addrOpen);
  108648. nKey = nPk;
  108649. regKey = iPk;
  108650. }else{
  108651. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  108652. sqlite3IndexAffinityStr(db, pPk), nPk);
  108653. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  108654. }
  108655. sqlite3WhereEnd(pWInfo);
  108656. }
  108657. /* Initialize the count of updated rows
  108658. */
  108659. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  108660. regRowCount = ++pParse->nMem;
  108661. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  108662. }
  108663. labelBreak = sqlite3VdbeMakeLabel(v);
  108664. if( !isView ){
  108665. /*
  108666. ** Open every index that needs updating. Note that if any
  108667. ** index could potentially invoke a REPLACE conflict resolution
  108668. ** action, then we need to open all indices because we might need
  108669. ** to be deleting some records.
  108670. */
  108671. if( onError==OE_Replace ){
  108672. memset(aToOpen, 1, nIdx+1);
  108673. }else{
  108674. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108675. if( pIdx->onError==OE_Replace ){
  108676. memset(aToOpen, 1, nIdx+1);
  108677. break;
  108678. }
  108679. }
  108680. }
  108681. if( okOnePass ){
  108682. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  108683. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  108684. }
  108685. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
  108686. 0, 0);
  108687. }
  108688. /* Top of the update loop */
  108689. if( okOnePass ){
  108690. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  108691. assert( pPk );
  108692. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  108693. VdbeCoverageNeverTaken(v);
  108694. }
  108695. labelContinue = labelBreak;
  108696. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  108697. VdbeCoverageIf(v, pPk==0);
  108698. VdbeCoverageIf(v, pPk!=0);
  108699. }else if( pPk ){
  108700. labelContinue = sqlite3VdbeMakeLabel(v);
  108701. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  108702. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  108703. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  108704. VdbeCoverage(v);
  108705. }else{
  108706. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  108707. regOldRowid);
  108708. VdbeCoverage(v);
  108709. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  108710. VdbeCoverage(v);
  108711. }
  108712. /* If the record number will change, set register regNewRowid to
  108713. ** contain the new value. If the record number is not being modified,
  108714. ** then regNewRowid is the same register as regOldRowid, which is
  108715. ** already populated. */
  108716. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  108717. if( chngRowid ){
  108718. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  108719. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  108720. }
  108721. /* Compute the old pre-UPDATE content of the row being changed, if that
  108722. ** information is needed */
  108723. if( chngPk || hasFK || pTrigger ){
  108724. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  108725. oldmask |= sqlite3TriggerColmask(pParse,
  108726. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  108727. );
  108728. for(i=0; i<pTab->nCol; i++){
  108729. if( oldmask==0xffffffff
  108730. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  108731. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  108732. ){
  108733. testcase( oldmask!=0xffffffff && i==31 );
  108734. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  108735. }else{
  108736. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  108737. }
  108738. }
  108739. if( chngRowid==0 && pPk==0 ){
  108740. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  108741. }
  108742. }
  108743. /* Populate the array of registers beginning at regNew with the new
  108744. ** row data. This array is used to check constants, create the new
  108745. ** table and index records, and as the values for any new.* references
  108746. ** made by triggers.
  108747. **
  108748. ** If there are one or more BEFORE triggers, then do not populate the
  108749. ** registers associated with columns that are (a) not modified by
  108750. ** this UPDATE statement and (b) not accessed by new.* references. The
  108751. ** values for registers not modified by the UPDATE must be reloaded from
  108752. ** the database after the BEFORE triggers are fired anyway (as the trigger
  108753. ** may have modified them). So not loading those that are not going to
  108754. ** be used eliminates some redundant opcodes.
  108755. */
  108756. newmask = sqlite3TriggerColmask(
  108757. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  108758. );
  108759. for(i=0; i<pTab->nCol; i++){
  108760. if( i==pTab->iPKey ){
  108761. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  108762. }else{
  108763. j = aXRef[i];
  108764. if( j>=0 ){
  108765. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  108766. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  108767. /* This branch loads the value of a column that will not be changed
  108768. ** into a register. This is done if there are no BEFORE triggers, or
  108769. ** if there are one or more BEFORE triggers that use this value via
  108770. ** a new.* reference in a trigger program.
  108771. */
  108772. testcase( i==31 );
  108773. testcase( i==32 );
  108774. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  108775. }else{
  108776. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  108777. }
  108778. }
  108779. }
  108780. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  108781. ** verified. One could argue that this is wrong.
  108782. */
  108783. if( tmask&TRIGGER_BEFORE ){
  108784. sqlite3TableAffinity(v, pTab, regNew);
  108785. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  108786. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  108787. /* The row-trigger may have deleted the row being updated. In this
  108788. ** case, jump to the next row. No updates or AFTER triggers are
  108789. ** required. This behavior - what happens when the row being updated
  108790. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  108791. ** documentation.
  108792. */
  108793. if( pPk ){
  108794. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  108795. VdbeCoverage(v);
  108796. }else{
  108797. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  108798. VdbeCoverage(v);
  108799. }
  108800. /* If it did not delete it, the row-trigger may still have modified
  108801. ** some of the columns of the row being updated. Load the values for
  108802. ** all columns not modified by the update statement into their
  108803. ** registers in case this has happened.
  108804. */
  108805. for(i=0; i<pTab->nCol; i++){
  108806. if( aXRef[i]<0 && i!=pTab->iPKey ){
  108807. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  108808. }
  108809. }
  108810. }
  108811. if( !isView ){
  108812. int addr1 = 0; /* Address of jump instruction */
  108813. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  108814. /* Do constraint checks. */
  108815. assert( regOldRowid>0 );
  108816. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  108817. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  108818. /* Do FK constraint checks. */
  108819. if( hasFK ){
  108820. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  108821. }
  108822. /* Delete the index entries associated with the current record. */
  108823. if( bReplace || chngKey ){
  108824. if( pPk ){
  108825. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  108826. }else{
  108827. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  108828. }
  108829. VdbeCoverageNeverTaken(v);
  108830. }
  108831. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  108832. /* If changing the record number, delete the old record. */
  108833. if( hasFK || chngKey || pPk!=0 ){
  108834. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  108835. }
  108836. if( bReplace || chngKey ){
  108837. sqlite3VdbeJumpHere(v, addr1);
  108838. }
  108839. if( hasFK ){
  108840. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  108841. }
  108842. /* Insert the new index entries and the new record. */
  108843. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  108844. regNewRowid, aRegIdx, 1, 0, 0);
  108845. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  108846. ** handle rows (possibly in other tables) that refer via a foreign key
  108847. ** to the row just updated. */
  108848. if( hasFK ){
  108849. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  108850. }
  108851. }
  108852. /* Increment the row counter
  108853. */
  108854. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  108855. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  108856. }
  108857. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  108858. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  108859. /* Repeat the above with the next record to be updated, until
  108860. ** all record selected by the WHERE clause have been updated.
  108861. */
  108862. if( okOnePass ){
  108863. /* Nothing to do at end-of-loop for a single-pass */
  108864. }else if( pPk ){
  108865. sqlite3VdbeResolveLabel(v, labelContinue);
  108866. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  108867. }else{
  108868. sqlite3VdbeGoto(v, labelContinue);
  108869. }
  108870. sqlite3VdbeResolveLabel(v, labelBreak);
  108871. /* Close all tables */
  108872. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  108873. assert( aRegIdx );
  108874. if( aToOpen[i+1] ){
  108875. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  108876. }
  108877. }
  108878. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  108879. /* Update the sqlite_sequence table by storing the content of the
  108880. ** maximum rowid counter values recorded while inserting into
  108881. ** autoincrement tables.
  108882. */
  108883. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  108884. sqlite3AutoincrementEnd(pParse);
  108885. }
  108886. /*
  108887. ** Return the number of rows that were changed. If this routine is
  108888. ** generating code because of a call to sqlite3NestedParse(), do not
  108889. ** invoke the callback function.
  108890. */
  108891. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  108892. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  108893. sqlite3VdbeSetNumCols(v, 1);
  108894. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  108895. }
  108896. update_cleanup:
  108897. sqlite3AuthContextPop(&sContext);
  108898. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  108899. sqlite3SrcListDelete(db, pTabList);
  108900. sqlite3ExprListDelete(db, pChanges);
  108901. sqlite3ExprDelete(db, pWhere);
  108902. return;
  108903. }
  108904. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  108905. ** they may interfere with compilation of other functions in this file
  108906. ** (or in another file, if this file becomes part of the amalgamation). */
  108907. #ifdef isView
  108908. #undef isView
  108909. #endif
  108910. #ifdef pTrigger
  108911. #undef pTrigger
  108912. #endif
  108913. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108914. /*
  108915. ** Generate code for an UPDATE of a virtual table.
  108916. **
  108917. ** There are two possible strategies - the default and the special
  108918. ** "onepass" strategy. Onepass is only used if the virtual table
  108919. ** implementation indicates that pWhere may match at most one row.
  108920. **
  108921. ** The default strategy is to create an ephemeral table that contains
  108922. ** for each row to be changed:
  108923. **
  108924. ** (A) The original rowid of that row.
  108925. ** (B) The revised rowid for the row.
  108926. ** (C) The content of every column in the row.
  108927. **
  108928. ** Then loop through the contents of this ephemeral table executing a
  108929. ** VUpdate for each row. When finished, drop the ephemeral table.
  108930. **
  108931. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  108932. ** stores the same values (A, B and C above) in a register array and
  108933. ** makes a single invocation of VUpdate.
  108934. */
  108935. static void updateVirtualTable(
  108936. Parse *pParse, /* The parsing context */
  108937. SrcList *pSrc, /* The virtual table to be modified */
  108938. Table *pTab, /* The virtual table */
  108939. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  108940. Expr *pRowid, /* Expression used to recompute the rowid */
  108941. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  108942. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  108943. int onError /* ON CONFLICT strategy */
  108944. ){
  108945. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  108946. int ephemTab; /* Table holding the result of the SELECT */
  108947. int i; /* Loop counter */
  108948. sqlite3 *db = pParse->db; /* Database connection */
  108949. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  108950. WhereInfo *pWInfo;
  108951. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  108952. int regArg; /* First register in VUpdate arg array */
  108953. int regRec; /* Register in which to assemble record */
  108954. int regRowid; /* Register for ephem table rowid */
  108955. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  108956. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  108957. int bOnePass; /* True to use onepass strategy */
  108958. int addr; /* Address of OP_OpenEphemeral */
  108959. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  108960. ** create and open the ephemeral table in which the records created from
  108961. ** these arguments will be temporarily stored. */
  108962. assert( v );
  108963. ephemTab = pParse->nTab++;
  108964. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  108965. regArg = pParse->nMem + 1;
  108966. pParse->nMem += nArg;
  108967. regRec = ++pParse->nMem;
  108968. regRowid = ++pParse->nMem;
  108969. /* Start scanning the virtual table */
  108970. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  108971. if( pWInfo==0 ) return;
  108972. /* Populate the argument registers. */
  108973. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  108974. if( pRowid ){
  108975. sqlite3ExprCode(pParse, pRowid, regArg+1);
  108976. }else{
  108977. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  108978. }
  108979. for(i=0; i<pTab->nCol; i++){
  108980. if( aXRef[i]>=0 ){
  108981. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  108982. }else{
  108983. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  108984. }
  108985. }
  108986. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  108987. if( bOnePass ){
  108988. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  108989. ** above. Also, if this is a top-level parse (not a trigger), clear the
  108990. ** multi-write flag so that the VM does not open a statement journal */
  108991. sqlite3VdbeChangeToNoop(v, addr);
  108992. if( sqlite3IsToplevel(pParse) ){
  108993. pParse->isMultiWrite = 0;
  108994. }
  108995. }else{
  108996. /* Create a record from the argument register contents and insert it into
  108997. ** the ephemeral table. */
  108998. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  108999. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  109000. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  109001. }
  109002. if( bOnePass==0 ){
  109003. /* End the virtual table scan */
  109004. sqlite3WhereEnd(pWInfo);
  109005. /* Begin scannning through the ephemeral table. */
  109006. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  109007. /* Extract arguments from the current row of the ephemeral table and
  109008. ** invoke the VUpdate method. */
  109009. for(i=0; i<nArg; i++){
  109010. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  109011. }
  109012. }
  109013. sqlite3VtabMakeWritable(pParse, pTab);
  109014. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  109015. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  109016. sqlite3MayAbort(pParse);
  109017. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  109018. ** jump to here if the scan visited zero rows. */
  109019. if( bOnePass==0 ){
  109020. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  109021. sqlite3VdbeJumpHere(v, addr);
  109022. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  109023. }else{
  109024. sqlite3WhereEnd(pWInfo);
  109025. }
  109026. }
  109027. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109028. /************** End of update.c **********************************************/
  109029. /************** Begin file vacuum.c ******************************************/
  109030. /*
  109031. ** 2003 April 6
  109032. **
  109033. ** The author disclaims copyright to this source code. In place of
  109034. ** a legal notice, here is a blessing:
  109035. **
  109036. ** May you do good and not evil.
  109037. ** May you find forgiveness for yourself and forgive others.
  109038. ** May you share freely, never taking more than you give.
  109039. **
  109040. *************************************************************************
  109041. ** This file contains code used to implement the VACUUM command.
  109042. **
  109043. ** Most of the code in this file may be omitted by defining the
  109044. ** SQLITE_OMIT_VACUUM macro.
  109045. */
  109046. /* #include "sqliteInt.h" */
  109047. /* #include "vdbeInt.h" */
  109048. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  109049. /*
  109050. ** Finalize a prepared statement. If there was an error, store the
  109051. ** text of the error message in *pzErrMsg. Return the result code.
  109052. */
  109053. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  109054. int rc;
  109055. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  109056. if( rc ){
  109057. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  109058. }
  109059. return rc;
  109060. }
  109061. /*
  109062. ** Execute zSql on database db. Return an error code.
  109063. */
  109064. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  109065. sqlite3_stmt *pStmt;
  109066. VVA_ONLY( int rc; )
  109067. if( !zSql ){
  109068. return SQLITE_NOMEM;
  109069. }
  109070. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  109071. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  109072. return sqlite3_errcode(db);
  109073. }
  109074. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  109075. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  109076. return vacuumFinalize(db, pStmt, pzErrMsg);
  109077. }
  109078. /*
  109079. ** Execute zSql on database db. The statement returns exactly
  109080. ** one column. Execute this as SQL on the same database.
  109081. */
  109082. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  109083. sqlite3_stmt *pStmt;
  109084. int rc;
  109085. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  109086. if( rc!=SQLITE_OK ) return rc;
  109087. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  109088. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  109089. if( rc!=SQLITE_OK ){
  109090. vacuumFinalize(db, pStmt, pzErrMsg);
  109091. return rc;
  109092. }
  109093. }
  109094. return vacuumFinalize(db, pStmt, pzErrMsg);
  109095. }
  109096. /*
  109097. ** The VACUUM command is used to clean up the database,
  109098. ** collapse free space, etc. It is modelled after the VACUUM command
  109099. ** in PostgreSQL. The VACUUM command works as follows:
  109100. **
  109101. ** (1) Create a new transient database file
  109102. ** (2) Copy all content from the database being vacuumed into
  109103. ** the new transient database file
  109104. ** (3) Copy content from the transient database back into the
  109105. ** original database.
  109106. **
  109107. ** The transient database requires temporary disk space approximately
  109108. ** equal to the size of the original database. The copy operation of
  109109. ** step (3) requires additional temporary disk space approximately equal
  109110. ** to the size of the original database for the rollback journal.
  109111. ** Hence, temporary disk space that is approximately 2x the size of the
  109112. ** original database is required. Every page of the database is written
  109113. ** approximately 3 times: Once for step (2) and twice for step (3).
  109114. ** Two writes per page are required in step (3) because the original
  109115. ** database content must be written into the rollback journal prior to
  109116. ** overwriting the database with the vacuumed content.
  109117. **
  109118. ** Only 1x temporary space and only 1x writes would be required if
  109119. ** the copy of step (3) were replaced by deleting the original database
  109120. ** and renaming the transient database as the original. But that will
  109121. ** not work if other processes are attached to the original database.
  109122. ** And a power loss in between deleting the original and renaming the
  109123. ** transient would cause the database file to appear to be deleted
  109124. ** following reboot.
  109125. */
  109126. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  109127. Vdbe *v = sqlite3GetVdbe(pParse);
  109128. if( v ){
  109129. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  109130. sqlite3VdbeUsesBtree(v, 0);
  109131. }
  109132. return;
  109133. }
  109134. /*
  109135. ** This routine implements the OP_Vacuum opcode of the VDBE.
  109136. */
  109137. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  109138. int rc = SQLITE_OK; /* Return code from service routines */
  109139. Btree *pMain; /* The database being vacuumed */
  109140. Btree *pTemp; /* The temporary database we vacuum into */
  109141. char *zSql = 0; /* SQL statements */
  109142. int saved_flags; /* Saved value of the db->flags */
  109143. int saved_nChange; /* Saved value of db->nChange */
  109144. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  109145. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  109146. Db *pDb = 0; /* Database to detach at end of vacuum */
  109147. int isMemDb; /* True if vacuuming a :memory: database */
  109148. int nRes; /* Bytes of reserved space at the end of each page */
  109149. int nDb; /* Number of attached databases */
  109150. if( !db->autoCommit ){
  109151. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  109152. return SQLITE_ERROR;
  109153. }
  109154. if( db->nVdbeActive>1 ){
  109155. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  109156. return SQLITE_ERROR;
  109157. }
  109158. /* Save the current value of the database flags so that it can be
  109159. ** restored before returning. Then set the writable-schema flag, and
  109160. ** disable CHECK and foreign key constraints. */
  109161. saved_flags = db->flags;
  109162. saved_nChange = db->nChange;
  109163. saved_nTotalChange = db->nTotalChange;
  109164. saved_xTrace = db->xTrace;
  109165. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  109166. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  109167. db->xTrace = 0;
  109168. pMain = db->aDb[0].pBt;
  109169. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  109170. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  109171. ** can be set to 'off' for this file, as it is not recovered if a crash
  109172. ** occurs anyway. The integrity of the database is maintained by a
  109173. ** (possibly synchronous) transaction opened on the main database before
  109174. ** sqlite3BtreeCopyFile() is called.
  109175. **
  109176. ** An optimisation would be to use a non-journaled pager.
  109177. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  109178. ** that actually made the VACUUM run slower. Very little journalling
  109179. ** actually occurs when doing a vacuum since the vacuum_db is initially
  109180. ** empty. Only the journal header is written. Apparently it takes more
  109181. ** time to parse and run the PRAGMA to turn journalling off than it does
  109182. ** to write the journal header file.
  109183. */
  109184. nDb = db->nDb;
  109185. if( sqlite3TempInMemory(db) ){
  109186. zSql = "ATTACH ':memory:' AS vacuum_db;";
  109187. }else{
  109188. zSql = "ATTACH '' AS vacuum_db;";
  109189. }
  109190. rc = execSql(db, pzErrMsg, zSql);
  109191. if( db->nDb>nDb ){
  109192. pDb = &db->aDb[db->nDb-1];
  109193. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  109194. }
  109195. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109196. pTemp = db->aDb[db->nDb-1].pBt;
  109197. /* The call to execSql() to attach the temp database has left the file
  109198. ** locked (as there was more than one active statement when the transaction
  109199. ** to read the schema was concluded. Unlock it here so that this doesn't
  109200. ** cause problems for the call to BtreeSetPageSize() below. */
  109201. sqlite3BtreeCommit(pTemp);
  109202. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  109203. /* A VACUUM cannot change the pagesize of an encrypted database. */
  109204. #ifdef SQLITE_HAS_CODEC
  109205. if( db->nextPagesize ){
  109206. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  109207. int nKey;
  109208. char *zKey;
  109209. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  109210. if( nKey ) db->nextPagesize = 0;
  109211. }
  109212. #endif
  109213. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  109214. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109215. /* Begin a transaction and take an exclusive lock on the main database
  109216. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  109217. ** to ensure that we do not try to change the page-size on a WAL database.
  109218. */
  109219. rc = execSql(db, pzErrMsg, "BEGIN;");
  109220. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109221. rc = sqlite3BtreeBeginTrans(pMain, 2);
  109222. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109223. /* Do not attempt to change the page size for a WAL database */
  109224. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  109225. ==PAGER_JOURNALMODE_WAL ){
  109226. db->nextPagesize = 0;
  109227. }
  109228. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  109229. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  109230. || NEVER(db->mallocFailed)
  109231. ){
  109232. rc = SQLITE_NOMEM;
  109233. goto end_of_vacuum;
  109234. }
  109235. #ifndef SQLITE_OMIT_AUTOVACUUM
  109236. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  109237. sqlite3BtreeGetAutoVacuum(pMain));
  109238. #endif
  109239. /* Query the schema of the main database. Create a mirror schema
  109240. ** in the temporary database.
  109241. */
  109242. rc = execExecSql(db, pzErrMsg,
  109243. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  109244. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  109245. " AND coalesce(rootpage,1)>0"
  109246. );
  109247. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109248. rc = execExecSql(db, pzErrMsg,
  109249. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  109250. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  109251. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109252. rc = execExecSql(db, pzErrMsg,
  109253. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  109254. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  109255. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109256. /* Loop through the tables in the main database. For each, do
  109257. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  109258. ** the contents to the temporary database.
  109259. */
  109260. assert( (db->flags & SQLITE_Vacuum)==0 );
  109261. db->flags |= SQLITE_Vacuum;
  109262. rc = execExecSql(db, pzErrMsg,
  109263. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  109264. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  109265. "FROM main.sqlite_master "
  109266. "WHERE type = 'table' AND name!='sqlite_sequence' "
  109267. " AND coalesce(rootpage,1)>0"
  109268. );
  109269. assert( (db->flags & SQLITE_Vacuum)!=0 );
  109270. db->flags &= ~SQLITE_Vacuum;
  109271. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109272. /* Copy over the sequence table
  109273. */
  109274. rc = execExecSql(db, pzErrMsg,
  109275. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  109276. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  109277. );
  109278. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109279. rc = execExecSql(db, pzErrMsg,
  109280. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  109281. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  109282. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  109283. );
  109284. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109285. /* Copy the triggers, views, and virtual tables from the main database
  109286. ** over to the temporary database. None of these objects has any
  109287. ** associated storage, so all we have to do is copy their entries
  109288. ** from the SQLITE_MASTER table.
  109289. */
  109290. rc = execSql(db, pzErrMsg,
  109291. "INSERT INTO vacuum_db.sqlite_master "
  109292. " SELECT type, name, tbl_name, rootpage, sql"
  109293. " FROM main.sqlite_master"
  109294. " WHERE type='view' OR type='trigger'"
  109295. " OR (type='table' AND rootpage=0)"
  109296. );
  109297. if( rc ) goto end_of_vacuum;
  109298. /* At this point, there is a write transaction open on both the
  109299. ** vacuum database and the main database. Assuming no error occurs,
  109300. ** both transactions are closed by this block - the main database
  109301. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  109302. ** call to sqlite3BtreeCommit().
  109303. */
  109304. {
  109305. u32 meta;
  109306. int i;
  109307. /* This array determines which meta meta values are preserved in the
  109308. ** vacuum. Even entries are the meta value number and odd entries
  109309. ** are an increment to apply to the meta value after the vacuum.
  109310. ** The increment is used to increase the schema cookie so that other
  109311. ** connections to the same database will know to reread the schema.
  109312. */
  109313. static const unsigned char aCopy[] = {
  109314. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  109315. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  109316. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  109317. BTREE_USER_VERSION, 0, /* Preserve the user version */
  109318. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  109319. };
  109320. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  109321. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  109322. /* Copy Btree meta values */
  109323. for(i=0; i<ArraySize(aCopy); i+=2){
  109324. /* GetMeta() and UpdateMeta() cannot fail in this context because
  109325. ** we already have page 1 loaded into cache and marked dirty. */
  109326. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  109327. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  109328. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  109329. }
  109330. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  109331. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109332. rc = sqlite3BtreeCommit(pTemp);
  109333. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  109334. #ifndef SQLITE_OMIT_AUTOVACUUM
  109335. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  109336. #endif
  109337. }
  109338. assert( rc==SQLITE_OK );
  109339. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  109340. end_of_vacuum:
  109341. /* Restore the original value of db->flags */
  109342. db->flags = saved_flags;
  109343. db->nChange = saved_nChange;
  109344. db->nTotalChange = saved_nTotalChange;
  109345. db->xTrace = saved_xTrace;
  109346. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  109347. /* Currently there is an SQL level transaction open on the vacuum
  109348. ** database. No locks are held on any other files (since the main file
  109349. ** was committed at the btree level). So it safe to end the transaction
  109350. ** by manually setting the autoCommit flag to true and detaching the
  109351. ** vacuum database. The vacuum_db journal file is deleted when the pager
  109352. ** is closed by the DETACH.
  109353. */
  109354. db->autoCommit = 1;
  109355. if( pDb ){
  109356. sqlite3BtreeClose(pDb->pBt);
  109357. pDb->pBt = 0;
  109358. pDb->pSchema = 0;
  109359. }
  109360. /* This both clears the schemas and reduces the size of the db->aDb[]
  109361. ** array. */
  109362. sqlite3ResetAllSchemasOfConnection(db);
  109363. return rc;
  109364. }
  109365. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  109366. /************** End of vacuum.c **********************************************/
  109367. /************** Begin file vtab.c ********************************************/
  109368. /*
  109369. ** 2006 June 10
  109370. **
  109371. ** The author disclaims copyright to this source code. In place of
  109372. ** a legal notice, here is a blessing:
  109373. **
  109374. ** May you do good and not evil.
  109375. ** May you find forgiveness for yourself and forgive others.
  109376. ** May you share freely, never taking more than you give.
  109377. **
  109378. *************************************************************************
  109379. ** This file contains code used to help implement virtual tables.
  109380. */
  109381. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109382. /* #include "sqliteInt.h" */
  109383. /*
  109384. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  109385. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  109386. ** this struct allocated on the stack. It is used by the implementation of
  109387. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  109388. ** are invoked only from within xCreate and xConnect methods.
  109389. */
  109390. struct VtabCtx {
  109391. VTable *pVTable; /* The virtual table being constructed */
  109392. Table *pTab; /* The Table object to which the virtual table belongs */
  109393. VtabCtx *pPrior; /* Parent context (if any) */
  109394. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  109395. };
  109396. /*
  109397. ** The actual function that does the work of creating a new module.
  109398. ** This function implements the sqlite3_create_module() and
  109399. ** sqlite3_create_module_v2() interfaces.
  109400. */
  109401. static int createModule(
  109402. sqlite3 *db, /* Database in which module is registered */
  109403. const char *zName, /* Name assigned to this module */
  109404. const sqlite3_module *pModule, /* The definition of the module */
  109405. void *pAux, /* Context pointer for xCreate/xConnect */
  109406. void (*xDestroy)(void *) /* Module destructor function */
  109407. ){
  109408. int rc = SQLITE_OK;
  109409. int nName;
  109410. sqlite3_mutex_enter(db->mutex);
  109411. nName = sqlite3Strlen30(zName);
  109412. if( sqlite3HashFind(&db->aModule, zName) ){
  109413. rc = SQLITE_MISUSE_BKPT;
  109414. }else{
  109415. Module *pMod;
  109416. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  109417. if( pMod ){
  109418. Module *pDel;
  109419. char *zCopy = (char *)(&pMod[1]);
  109420. memcpy(zCopy, zName, nName+1);
  109421. pMod->zName = zCopy;
  109422. pMod->pModule = pModule;
  109423. pMod->pAux = pAux;
  109424. pMod->xDestroy = xDestroy;
  109425. pMod->pEpoTab = 0;
  109426. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  109427. assert( pDel==0 || pDel==pMod );
  109428. if( pDel ){
  109429. db->mallocFailed = 1;
  109430. sqlite3DbFree(db, pDel);
  109431. }
  109432. }
  109433. }
  109434. rc = sqlite3ApiExit(db, rc);
  109435. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  109436. sqlite3_mutex_leave(db->mutex);
  109437. return rc;
  109438. }
  109439. /*
  109440. ** External API function used to create a new virtual-table module.
  109441. */
  109442. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  109443. sqlite3 *db, /* Database in which module is registered */
  109444. const char *zName, /* Name assigned to this module */
  109445. const sqlite3_module *pModule, /* The definition of the module */
  109446. void *pAux /* Context pointer for xCreate/xConnect */
  109447. ){
  109448. #ifdef SQLITE_ENABLE_API_ARMOR
  109449. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  109450. #endif
  109451. return createModule(db, zName, pModule, pAux, 0);
  109452. }
  109453. /*
  109454. ** External API function used to create a new virtual-table module.
  109455. */
  109456. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  109457. sqlite3 *db, /* Database in which module is registered */
  109458. const char *zName, /* Name assigned to this module */
  109459. const sqlite3_module *pModule, /* The definition of the module */
  109460. void *pAux, /* Context pointer for xCreate/xConnect */
  109461. void (*xDestroy)(void *) /* Module destructor function */
  109462. ){
  109463. #ifdef SQLITE_ENABLE_API_ARMOR
  109464. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  109465. #endif
  109466. return createModule(db, zName, pModule, pAux, xDestroy);
  109467. }
  109468. /*
  109469. ** Lock the virtual table so that it cannot be disconnected.
  109470. ** Locks nest. Every lock should have a corresponding unlock.
  109471. ** If an unlock is omitted, resources leaks will occur.
  109472. **
  109473. ** If a disconnect is attempted while a virtual table is locked,
  109474. ** the disconnect is deferred until all locks have been removed.
  109475. */
  109476. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  109477. pVTab->nRef++;
  109478. }
  109479. /*
  109480. ** pTab is a pointer to a Table structure representing a virtual-table.
  109481. ** Return a pointer to the VTable object used by connection db to access
  109482. ** this virtual-table, if one has been created, or NULL otherwise.
  109483. */
  109484. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  109485. VTable *pVtab;
  109486. assert( IsVirtual(pTab) );
  109487. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  109488. return pVtab;
  109489. }
  109490. /*
  109491. ** Decrement the ref-count on a virtual table object. When the ref-count
  109492. ** reaches zero, call the xDisconnect() method to delete the object.
  109493. */
  109494. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  109495. sqlite3 *db = pVTab->db;
  109496. assert( db );
  109497. assert( pVTab->nRef>0 );
  109498. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  109499. pVTab->nRef--;
  109500. if( pVTab->nRef==0 ){
  109501. sqlite3_vtab *p = pVTab->pVtab;
  109502. if( p ){
  109503. p->pModule->xDisconnect(p);
  109504. }
  109505. sqlite3DbFree(db, pVTab);
  109506. }
  109507. }
  109508. /*
  109509. ** Table p is a virtual table. This function moves all elements in the
  109510. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  109511. ** database connections to be disconnected at the next opportunity.
  109512. ** Except, if argument db is not NULL, then the entry associated with
  109513. ** connection db is left in the p->pVTable list.
  109514. */
  109515. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  109516. VTable *pRet = 0;
  109517. VTable *pVTable = p->pVTable;
  109518. p->pVTable = 0;
  109519. /* Assert that the mutex (if any) associated with the BtShared database
  109520. ** that contains table p is held by the caller. See header comments
  109521. ** above function sqlite3VtabUnlockList() for an explanation of why
  109522. ** this makes it safe to access the sqlite3.pDisconnect list of any
  109523. ** database connection that may have an entry in the p->pVTable list.
  109524. */
  109525. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  109526. while( pVTable ){
  109527. sqlite3 *db2 = pVTable->db;
  109528. VTable *pNext = pVTable->pNext;
  109529. assert( db2 );
  109530. if( db2==db ){
  109531. pRet = pVTable;
  109532. p->pVTable = pRet;
  109533. pRet->pNext = 0;
  109534. }else{
  109535. pVTable->pNext = db2->pDisconnect;
  109536. db2->pDisconnect = pVTable;
  109537. }
  109538. pVTable = pNext;
  109539. }
  109540. assert( !db || pRet );
  109541. return pRet;
  109542. }
  109543. /*
  109544. ** Table *p is a virtual table. This function removes the VTable object
  109545. ** for table *p associated with database connection db from the linked
  109546. ** list in p->pVTab. It also decrements the VTable ref count. This is
  109547. ** used when closing database connection db to free all of its VTable
  109548. ** objects without disturbing the rest of the Schema object (which may
  109549. ** be being used by other shared-cache connections).
  109550. */
  109551. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  109552. VTable **ppVTab;
  109553. assert( IsVirtual(p) );
  109554. assert( sqlite3BtreeHoldsAllMutexes(db) );
  109555. assert( sqlite3_mutex_held(db->mutex) );
  109556. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  109557. if( (*ppVTab)->db==db ){
  109558. VTable *pVTab = *ppVTab;
  109559. *ppVTab = pVTab->pNext;
  109560. sqlite3VtabUnlock(pVTab);
  109561. break;
  109562. }
  109563. }
  109564. }
  109565. /*
  109566. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  109567. **
  109568. ** This function may only be called when the mutexes associated with all
  109569. ** shared b-tree databases opened using connection db are held by the
  109570. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  109571. ** sqlite3.pDisconnect list is accessed only as follows:
  109572. **
  109573. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  109574. ** associated with the database handle itself must be held.
  109575. **
  109576. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  109577. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  109578. ** associated with the database the virtual table is stored in is held
  109579. ** or, if the virtual table is stored in a non-sharable database, then
  109580. ** the database handle mutex is held.
  109581. **
  109582. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  109583. ** by multiple threads. It is thread-safe.
  109584. */
  109585. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  109586. VTable *p = db->pDisconnect;
  109587. db->pDisconnect = 0;
  109588. assert( sqlite3BtreeHoldsAllMutexes(db) );
  109589. assert( sqlite3_mutex_held(db->mutex) );
  109590. if( p ){
  109591. sqlite3ExpirePreparedStatements(db);
  109592. do {
  109593. VTable *pNext = p->pNext;
  109594. sqlite3VtabUnlock(p);
  109595. p = pNext;
  109596. }while( p );
  109597. }
  109598. }
  109599. /*
  109600. ** Clear any and all virtual-table information from the Table record.
  109601. ** This routine is called, for example, just before deleting the Table
  109602. ** record.
  109603. **
  109604. ** Since it is a virtual-table, the Table structure contains a pointer
  109605. ** to the head of a linked list of VTable structures. Each VTable
  109606. ** structure is associated with a single sqlite3* user of the schema.
  109607. ** The reference count of the VTable structure associated with database
  109608. ** connection db is decremented immediately (which may lead to the
  109609. ** structure being xDisconnected and free). Any other VTable structures
  109610. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  109611. ** database connection.
  109612. */
  109613. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  109614. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  109615. if( p->azModuleArg ){
  109616. int i;
  109617. for(i=0; i<p->nModuleArg; i++){
  109618. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  109619. }
  109620. sqlite3DbFree(db, p->azModuleArg);
  109621. }
  109622. }
  109623. /*
  109624. ** Add a new module argument to pTable->azModuleArg[].
  109625. ** The string is not copied - the pointer is stored. The
  109626. ** string will be freed automatically when the table is
  109627. ** deleted.
  109628. */
  109629. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  109630. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  109631. char **azModuleArg;
  109632. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  109633. if( azModuleArg==0 ){
  109634. sqlite3DbFree(db, zArg);
  109635. }else{
  109636. int i = pTable->nModuleArg++;
  109637. azModuleArg[i] = zArg;
  109638. azModuleArg[i+1] = 0;
  109639. pTable->azModuleArg = azModuleArg;
  109640. }
  109641. }
  109642. /*
  109643. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  109644. ** statement. The module name has been parsed, but the optional list
  109645. ** of parameters that follow the module name are still pending.
  109646. */
  109647. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  109648. Parse *pParse, /* Parsing context */
  109649. Token *pName1, /* Name of new table, or database name */
  109650. Token *pName2, /* Name of new table or NULL */
  109651. Token *pModuleName, /* Name of the module for the virtual table */
  109652. int ifNotExists /* No error if the table already exists */
  109653. ){
  109654. int iDb; /* The database the table is being created in */
  109655. Table *pTable; /* The new virtual table */
  109656. sqlite3 *db; /* Database connection */
  109657. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  109658. pTable = pParse->pNewTable;
  109659. if( pTable==0 ) return;
  109660. assert( 0==pTable->pIndex );
  109661. db = pParse->db;
  109662. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  109663. assert( iDb>=0 );
  109664. pTable->tabFlags |= TF_Virtual;
  109665. pTable->nModuleArg = 0;
  109666. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  109667. addModuleArgument(db, pTable, 0);
  109668. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  109669. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  109670. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  109671. );
  109672. pParse->sNameToken.n = (int)(
  109673. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  109674. );
  109675. #ifndef SQLITE_OMIT_AUTHORIZATION
  109676. /* Creating a virtual table invokes the authorization callback twice.
  109677. ** The first invocation, to obtain permission to INSERT a row into the
  109678. ** sqlite_master table, has already been made by sqlite3StartTable().
  109679. ** The second call, to obtain permission to create the table, is made now.
  109680. */
  109681. if( pTable->azModuleArg ){
  109682. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  109683. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  109684. }
  109685. #endif
  109686. }
  109687. /*
  109688. ** This routine takes the module argument that has been accumulating
  109689. ** in pParse->zArg[] and appends it to the list of arguments on the
  109690. ** virtual table currently under construction in pParse->pTable.
  109691. */
  109692. static void addArgumentToVtab(Parse *pParse){
  109693. if( pParse->sArg.z && pParse->pNewTable ){
  109694. const char *z = (const char*)pParse->sArg.z;
  109695. int n = pParse->sArg.n;
  109696. sqlite3 *db = pParse->db;
  109697. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  109698. }
  109699. }
  109700. /*
  109701. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  109702. ** has been completely parsed.
  109703. */
  109704. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  109705. Table *pTab = pParse->pNewTable; /* The table being constructed */
  109706. sqlite3 *db = pParse->db; /* The database connection */
  109707. if( pTab==0 ) return;
  109708. addArgumentToVtab(pParse);
  109709. pParse->sArg.z = 0;
  109710. if( pTab->nModuleArg<1 ) return;
  109711. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  109712. ** first time (in other words if the virtual table is actually being
  109713. ** created now instead of just being read out of sqlite_master) then
  109714. ** do additional initialization work and store the statement text
  109715. ** in the sqlite_master table.
  109716. */
  109717. if( !db->init.busy ){
  109718. char *zStmt;
  109719. char *zWhere;
  109720. int iDb;
  109721. int iReg;
  109722. Vdbe *v;
  109723. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  109724. if( pEnd ){
  109725. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  109726. }
  109727. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  109728. /* A slot for the record has already been allocated in the
  109729. ** SQLITE_MASTER table. We just need to update that slot with all
  109730. ** the information we've collected.
  109731. **
  109732. ** The VM register number pParse->regRowid holds the rowid of an
  109733. ** entry in the sqlite_master table tht was created for this vtab
  109734. ** by sqlite3StartTable().
  109735. */
  109736. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  109737. sqlite3NestedParse(pParse,
  109738. "UPDATE %Q.%s "
  109739. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  109740. "WHERE rowid=#%d",
  109741. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  109742. pTab->zName,
  109743. pTab->zName,
  109744. zStmt,
  109745. pParse->regRowid
  109746. );
  109747. sqlite3DbFree(db, zStmt);
  109748. v = sqlite3GetVdbe(pParse);
  109749. sqlite3ChangeCookie(pParse, iDb);
  109750. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  109751. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  109752. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  109753. iReg = ++pParse->nMem;
  109754. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  109755. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  109756. }
  109757. /* If we are rereading the sqlite_master table create the in-memory
  109758. ** record of the table. The xConnect() method is not called until
  109759. ** the first time the virtual table is used in an SQL statement. This
  109760. ** allows a schema that contains virtual tables to be loaded before
  109761. ** the required virtual table implementations are registered. */
  109762. else {
  109763. Table *pOld;
  109764. Schema *pSchema = pTab->pSchema;
  109765. const char *zName = pTab->zName;
  109766. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  109767. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  109768. if( pOld ){
  109769. db->mallocFailed = 1;
  109770. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  109771. return;
  109772. }
  109773. pParse->pNewTable = 0;
  109774. }
  109775. }
  109776. /*
  109777. ** The parser calls this routine when it sees the first token
  109778. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  109779. */
  109780. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  109781. addArgumentToVtab(pParse);
  109782. pParse->sArg.z = 0;
  109783. pParse->sArg.n = 0;
  109784. }
  109785. /*
  109786. ** The parser calls this routine for each token after the first token
  109787. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  109788. */
  109789. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  109790. Token *pArg = &pParse->sArg;
  109791. if( pArg->z==0 ){
  109792. pArg->z = p->z;
  109793. pArg->n = p->n;
  109794. }else{
  109795. assert(pArg->z <= p->z);
  109796. pArg->n = (int)(&p->z[p->n] - pArg->z);
  109797. }
  109798. }
  109799. /*
  109800. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  109801. ** pointer to the function to invoke is passed as the fourth parameter
  109802. ** to this procedure.
  109803. */
  109804. static int vtabCallConstructor(
  109805. sqlite3 *db,
  109806. Table *pTab,
  109807. Module *pMod,
  109808. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  109809. char **pzErr
  109810. ){
  109811. VtabCtx sCtx;
  109812. VTable *pVTable;
  109813. int rc;
  109814. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  109815. int nArg = pTab->nModuleArg;
  109816. char *zErr = 0;
  109817. char *zModuleName;
  109818. int iDb;
  109819. VtabCtx *pCtx;
  109820. /* Check that the virtual-table is not already being initialized */
  109821. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  109822. if( pCtx->pTab==pTab ){
  109823. *pzErr = sqlite3MPrintf(db,
  109824. "vtable constructor called recursively: %s", pTab->zName
  109825. );
  109826. return SQLITE_LOCKED;
  109827. }
  109828. }
  109829. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  109830. if( !zModuleName ){
  109831. return SQLITE_NOMEM;
  109832. }
  109833. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  109834. if( !pVTable ){
  109835. sqlite3DbFree(db, zModuleName);
  109836. return SQLITE_NOMEM;
  109837. }
  109838. pVTable->db = db;
  109839. pVTable->pMod = pMod;
  109840. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  109841. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  109842. /* Invoke the virtual table constructor */
  109843. assert( &db->pVtabCtx );
  109844. assert( xConstruct );
  109845. sCtx.pTab = pTab;
  109846. sCtx.pVTable = pVTable;
  109847. sCtx.pPrior = db->pVtabCtx;
  109848. sCtx.bDeclared = 0;
  109849. db->pVtabCtx = &sCtx;
  109850. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  109851. db->pVtabCtx = sCtx.pPrior;
  109852. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  109853. assert( sCtx.pTab==pTab );
  109854. if( SQLITE_OK!=rc ){
  109855. if( zErr==0 ){
  109856. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  109857. }else {
  109858. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  109859. sqlite3_free(zErr);
  109860. }
  109861. sqlite3DbFree(db, pVTable);
  109862. }else if( ALWAYS(pVTable->pVtab) ){
  109863. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  109864. ** the sqlite3_vtab object if successful. */
  109865. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  109866. pVTable->pVtab->pModule = pMod->pModule;
  109867. pVTable->nRef = 1;
  109868. if( sCtx.bDeclared==0 ){
  109869. const char *zFormat = "vtable constructor did not declare schema: %s";
  109870. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  109871. sqlite3VtabUnlock(pVTable);
  109872. rc = SQLITE_ERROR;
  109873. }else{
  109874. int iCol;
  109875. u8 oooHidden = 0;
  109876. /* If everything went according to plan, link the new VTable structure
  109877. ** into the linked list headed by pTab->pVTable. Then loop through the
  109878. ** columns of the table to see if any of them contain the token "hidden".
  109879. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  109880. ** the type string. */
  109881. pVTable->pNext = pTab->pVTable;
  109882. pTab->pVTable = pVTable;
  109883. for(iCol=0; iCol<pTab->nCol; iCol++){
  109884. char *zType = pTab->aCol[iCol].zType;
  109885. int nType;
  109886. int i = 0;
  109887. if( !zType ){
  109888. pTab->tabFlags |= oooHidden;
  109889. continue;
  109890. }
  109891. nType = sqlite3Strlen30(zType);
  109892. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  109893. for(i=0; i<nType; i++){
  109894. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  109895. && (zType[i+7]=='\0' || zType[i+7]==' ')
  109896. ){
  109897. i++;
  109898. break;
  109899. }
  109900. }
  109901. }
  109902. if( i<nType ){
  109903. int j;
  109904. int nDel = 6 + (zType[i+6] ? 1 : 0);
  109905. for(j=i; (j+nDel)<=nType; j++){
  109906. zType[j] = zType[j+nDel];
  109907. }
  109908. if( zType[i]=='\0' && i>0 ){
  109909. assert(zType[i-1]==' ');
  109910. zType[i-1] = '\0';
  109911. }
  109912. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  109913. oooHidden = TF_OOOHidden;
  109914. }else{
  109915. pTab->tabFlags |= oooHidden;
  109916. }
  109917. }
  109918. }
  109919. }
  109920. sqlite3DbFree(db, zModuleName);
  109921. return rc;
  109922. }
  109923. /*
  109924. ** This function is invoked by the parser to call the xConnect() method
  109925. ** of the virtual table pTab. If an error occurs, an error code is returned
  109926. ** and an error left in pParse.
  109927. **
  109928. ** This call is a no-op if table pTab is not a virtual table.
  109929. */
  109930. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  109931. sqlite3 *db = pParse->db;
  109932. const char *zMod;
  109933. Module *pMod;
  109934. int rc;
  109935. assert( pTab );
  109936. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  109937. return SQLITE_OK;
  109938. }
  109939. /* Locate the required virtual table module */
  109940. zMod = pTab->azModuleArg[0];
  109941. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  109942. if( !pMod ){
  109943. const char *zModule = pTab->azModuleArg[0];
  109944. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  109945. rc = SQLITE_ERROR;
  109946. }else{
  109947. char *zErr = 0;
  109948. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  109949. if( rc!=SQLITE_OK ){
  109950. sqlite3ErrorMsg(pParse, "%s", zErr);
  109951. }
  109952. sqlite3DbFree(db, zErr);
  109953. }
  109954. return rc;
  109955. }
  109956. /*
  109957. ** Grow the db->aVTrans[] array so that there is room for at least one
  109958. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  109959. */
  109960. static int growVTrans(sqlite3 *db){
  109961. const int ARRAY_INCR = 5;
  109962. /* Grow the sqlite3.aVTrans array if required */
  109963. if( (db->nVTrans%ARRAY_INCR)==0 ){
  109964. VTable **aVTrans;
  109965. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  109966. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  109967. if( !aVTrans ){
  109968. return SQLITE_NOMEM;
  109969. }
  109970. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  109971. db->aVTrans = aVTrans;
  109972. }
  109973. return SQLITE_OK;
  109974. }
  109975. /*
  109976. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  109977. ** have already been reserved using growVTrans().
  109978. */
  109979. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  109980. /* Add pVtab to the end of sqlite3.aVTrans */
  109981. db->aVTrans[db->nVTrans++] = pVTab;
  109982. sqlite3VtabLock(pVTab);
  109983. }
  109984. /*
  109985. ** This function is invoked by the vdbe to call the xCreate method
  109986. ** of the virtual table named zTab in database iDb.
  109987. **
  109988. ** If an error occurs, *pzErr is set to point an an English language
  109989. ** description of the error and an SQLITE_XXX error code is returned.
  109990. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  109991. */
  109992. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  109993. int rc = SQLITE_OK;
  109994. Table *pTab;
  109995. Module *pMod;
  109996. const char *zMod;
  109997. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  109998. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  109999. /* Locate the required virtual table module */
  110000. zMod = pTab->azModuleArg[0];
  110001. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  110002. /* If the module has been registered and includes a Create method,
  110003. ** invoke it now. If the module has not been registered, return an
  110004. ** error. Otherwise, do nothing.
  110005. */
  110006. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  110007. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  110008. rc = SQLITE_ERROR;
  110009. }else{
  110010. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  110011. }
  110012. /* Justification of ALWAYS(): The xConstructor method is required to
  110013. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  110014. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  110015. rc = growVTrans(db);
  110016. if( rc==SQLITE_OK ){
  110017. addToVTrans(db, sqlite3GetVTable(db, pTab));
  110018. }
  110019. }
  110020. return rc;
  110021. }
  110022. /*
  110023. ** This function is used to set the schema of a virtual table. It is only
  110024. ** valid to call this function from within the xCreate() or xConnect() of a
  110025. ** virtual table module.
  110026. */
  110027. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  110028. VtabCtx *pCtx;
  110029. Parse *pParse;
  110030. int rc = SQLITE_OK;
  110031. Table *pTab;
  110032. char *zErr = 0;
  110033. #ifdef SQLITE_ENABLE_API_ARMOR
  110034. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  110035. return SQLITE_MISUSE_BKPT;
  110036. }
  110037. #endif
  110038. sqlite3_mutex_enter(db->mutex);
  110039. pCtx = db->pVtabCtx;
  110040. if( !pCtx || pCtx->bDeclared ){
  110041. sqlite3Error(db, SQLITE_MISUSE);
  110042. sqlite3_mutex_leave(db->mutex);
  110043. return SQLITE_MISUSE_BKPT;
  110044. }
  110045. pTab = pCtx->pTab;
  110046. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  110047. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  110048. if( pParse==0 ){
  110049. rc = SQLITE_NOMEM;
  110050. }else{
  110051. pParse->declareVtab = 1;
  110052. pParse->db = db;
  110053. pParse->nQueryLoop = 1;
  110054. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  110055. && pParse->pNewTable
  110056. && !db->mallocFailed
  110057. && !pParse->pNewTable->pSelect
  110058. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  110059. ){
  110060. if( !pTab->aCol ){
  110061. pTab->aCol = pParse->pNewTable->aCol;
  110062. pTab->nCol = pParse->pNewTable->nCol;
  110063. pParse->pNewTable->nCol = 0;
  110064. pParse->pNewTable->aCol = 0;
  110065. }
  110066. pCtx->bDeclared = 1;
  110067. }else{
  110068. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  110069. sqlite3DbFree(db, zErr);
  110070. rc = SQLITE_ERROR;
  110071. }
  110072. pParse->declareVtab = 0;
  110073. if( pParse->pVdbe ){
  110074. sqlite3VdbeFinalize(pParse->pVdbe);
  110075. }
  110076. sqlite3DeleteTable(db, pParse->pNewTable);
  110077. sqlite3ParserReset(pParse);
  110078. sqlite3StackFree(db, pParse);
  110079. }
  110080. assert( (rc&0xff)==rc );
  110081. rc = sqlite3ApiExit(db, rc);
  110082. sqlite3_mutex_leave(db->mutex);
  110083. return rc;
  110084. }
  110085. /*
  110086. ** This function is invoked by the vdbe to call the xDestroy method
  110087. ** of the virtual table named zTab in database iDb. This occurs
  110088. ** when a DROP TABLE is mentioned.
  110089. **
  110090. ** This call is a no-op if zTab is not a virtual table.
  110091. */
  110092. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  110093. int rc = SQLITE_OK;
  110094. Table *pTab;
  110095. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  110096. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  110097. VTable *p;
  110098. int (*xDestroy)(sqlite3_vtab *);
  110099. for(p=pTab->pVTable; p; p=p->pNext){
  110100. assert( p->pVtab );
  110101. if( p->pVtab->nRef>0 ){
  110102. return SQLITE_LOCKED;
  110103. }
  110104. }
  110105. p = vtabDisconnectAll(db, pTab);
  110106. xDestroy = p->pMod->pModule->xDestroy;
  110107. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  110108. rc = xDestroy(p->pVtab);
  110109. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  110110. if( rc==SQLITE_OK ){
  110111. assert( pTab->pVTable==p && p->pNext==0 );
  110112. p->pVtab = 0;
  110113. pTab->pVTable = 0;
  110114. sqlite3VtabUnlock(p);
  110115. }
  110116. }
  110117. return rc;
  110118. }
  110119. /*
  110120. ** This function invokes either the xRollback or xCommit method
  110121. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  110122. ** called is identified by the second argument, "offset", which is
  110123. ** the offset of the method to call in the sqlite3_module structure.
  110124. **
  110125. ** The array is cleared after invoking the callbacks.
  110126. */
  110127. static void callFinaliser(sqlite3 *db, int offset){
  110128. int i;
  110129. if( db->aVTrans ){
  110130. VTable **aVTrans = db->aVTrans;
  110131. db->aVTrans = 0;
  110132. for(i=0; i<db->nVTrans; i++){
  110133. VTable *pVTab = aVTrans[i];
  110134. sqlite3_vtab *p = pVTab->pVtab;
  110135. if( p ){
  110136. int (*x)(sqlite3_vtab *);
  110137. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  110138. if( x ) x(p);
  110139. }
  110140. pVTab->iSavepoint = 0;
  110141. sqlite3VtabUnlock(pVTab);
  110142. }
  110143. sqlite3DbFree(db, aVTrans);
  110144. db->nVTrans = 0;
  110145. }
  110146. }
  110147. /*
  110148. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  110149. ** array. Return the error code for the first error that occurs, or
  110150. ** SQLITE_OK if all xSync operations are successful.
  110151. **
  110152. ** If an error message is available, leave it in p->zErrMsg.
  110153. */
  110154. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  110155. int i;
  110156. int rc = SQLITE_OK;
  110157. VTable **aVTrans = db->aVTrans;
  110158. db->aVTrans = 0;
  110159. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  110160. int (*x)(sqlite3_vtab *);
  110161. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  110162. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  110163. rc = x(pVtab);
  110164. sqlite3VtabImportErrmsg(p, pVtab);
  110165. }
  110166. }
  110167. db->aVTrans = aVTrans;
  110168. return rc;
  110169. }
  110170. /*
  110171. ** Invoke the xRollback method of all virtual tables in the
  110172. ** sqlite3.aVTrans array. Then clear the array itself.
  110173. */
  110174. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  110175. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  110176. return SQLITE_OK;
  110177. }
  110178. /*
  110179. ** Invoke the xCommit method of all virtual tables in the
  110180. ** sqlite3.aVTrans array. Then clear the array itself.
  110181. */
  110182. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  110183. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  110184. return SQLITE_OK;
  110185. }
  110186. /*
  110187. ** If the virtual table pVtab supports the transaction interface
  110188. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  110189. ** not currently open, invoke the xBegin method now.
  110190. **
  110191. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  110192. ** in the sqlite3.aVTrans array.
  110193. */
  110194. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  110195. int rc = SQLITE_OK;
  110196. const sqlite3_module *pModule;
  110197. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  110198. ** than zero, then this function is being called from within a
  110199. ** virtual module xSync() callback. It is illegal to write to
  110200. ** virtual module tables in this case, so return SQLITE_LOCKED.
  110201. */
  110202. if( sqlite3VtabInSync(db) ){
  110203. return SQLITE_LOCKED;
  110204. }
  110205. if( !pVTab ){
  110206. return SQLITE_OK;
  110207. }
  110208. pModule = pVTab->pVtab->pModule;
  110209. if( pModule->xBegin ){
  110210. int i;
  110211. /* If pVtab is already in the aVTrans array, return early */
  110212. for(i=0; i<db->nVTrans; i++){
  110213. if( db->aVTrans[i]==pVTab ){
  110214. return SQLITE_OK;
  110215. }
  110216. }
  110217. /* Invoke the xBegin method. If successful, add the vtab to the
  110218. ** sqlite3.aVTrans[] array. */
  110219. rc = growVTrans(db);
  110220. if( rc==SQLITE_OK ){
  110221. rc = pModule->xBegin(pVTab->pVtab);
  110222. if( rc==SQLITE_OK ){
  110223. int iSvpt = db->nStatement + db->nSavepoint;
  110224. addToVTrans(db, pVTab);
  110225. if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
  110226. }
  110227. }
  110228. }
  110229. return rc;
  110230. }
  110231. /*
  110232. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  110233. ** virtual tables that currently have an open transaction. Pass iSavepoint
  110234. ** as the second argument to the virtual table method invoked.
  110235. **
  110236. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  110237. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  110238. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  110239. ** an open transaction is invoked.
  110240. **
  110241. ** If any virtual table method returns an error code other than SQLITE_OK,
  110242. ** processing is abandoned and the error returned to the caller of this
  110243. ** function immediately. If all calls to virtual table methods are successful,
  110244. ** SQLITE_OK is returned.
  110245. */
  110246. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  110247. int rc = SQLITE_OK;
  110248. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  110249. assert( iSavepoint>=-1 );
  110250. if( db->aVTrans ){
  110251. int i;
  110252. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  110253. VTable *pVTab = db->aVTrans[i];
  110254. const sqlite3_module *pMod = pVTab->pMod->pModule;
  110255. if( pVTab->pVtab && pMod->iVersion>=2 ){
  110256. int (*xMethod)(sqlite3_vtab *, int);
  110257. switch( op ){
  110258. case SAVEPOINT_BEGIN:
  110259. xMethod = pMod->xSavepoint;
  110260. pVTab->iSavepoint = iSavepoint+1;
  110261. break;
  110262. case SAVEPOINT_ROLLBACK:
  110263. xMethod = pMod->xRollbackTo;
  110264. break;
  110265. default:
  110266. xMethod = pMod->xRelease;
  110267. break;
  110268. }
  110269. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  110270. rc = xMethod(pVTab->pVtab, iSavepoint);
  110271. }
  110272. }
  110273. }
  110274. }
  110275. return rc;
  110276. }
  110277. /*
  110278. ** The first parameter (pDef) is a function implementation. The
  110279. ** second parameter (pExpr) is the first argument to this function.
  110280. ** If pExpr is a column in a virtual table, then let the virtual
  110281. ** table implementation have an opportunity to overload the function.
  110282. **
  110283. ** This routine is used to allow virtual table implementations to
  110284. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  110285. **
  110286. ** Return either the pDef argument (indicating no change) or a
  110287. ** new FuncDef structure that is marked as ephemeral using the
  110288. ** SQLITE_FUNC_EPHEM flag.
  110289. */
  110290. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  110291. sqlite3 *db, /* Database connection for reporting malloc problems */
  110292. FuncDef *pDef, /* Function to possibly overload */
  110293. int nArg, /* Number of arguments to the function */
  110294. Expr *pExpr /* First argument to the function */
  110295. ){
  110296. Table *pTab;
  110297. sqlite3_vtab *pVtab;
  110298. sqlite3_module *pMod;
  110299. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  110300. void *pArg = 0;
  110301. FuncDef *pNew;
  110302. int rc = 0;
  110303. char *zLowerName;
  110304. unsigned char *z;
  110305. /* Check to see the left operand is a column in a virtual table */
  110306. if( NEVER(pExpr==0) ) return pDef;
  110307. if( pExpr->op!=TK_COLUMN ) return pDef;
  110308. pTab = pExpr->pTab;
  110309. if( NEVER(pTab==0) ) return pDef;
  110310. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  110311. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  110312. assert( pVtab!=0 );
  110313. assert( pVtab->pModule!=0 );
  110314. pMod = (sqlite3_module *)pVtab->pModule;
  110315. if( pMod->xFindFunction==0 ) return pDef;
  110316. /* Call the xFindFunction method on the virtual table implementation
  110317. ** to see if the implementation wants to overload this function
  110318. */
  110319. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  110320. if( zLowerName ){
  110321. for(z=(unsigned char*)zLowerName; *z; z++){
  110322. *z = sqlite3UpperToLower[*z];
  110323. }
  110324. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  110325. sqlite3DbFree(db, zLowerName);
  110326. }
  110327. if( rc==0 ){
  110328. return pDef;
  110329. }
  110330. /* Create a new ephemeral function definition for the overloaded
  110331. ** function */
  110332. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  110333. + sqlite3Strlen30(pDef->zName) + 1);
  110334. if( pNew==0 ){
  110335. return pDef;
  110336. }
  110337. *pNew = *pDef;
  110338. pNew->zName = (char *)&pNew[1];
  110339. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  110340. pNew->xFunc = xFunc;
  110341. pNew->pUserData = pArg;
  110342. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  110343. return pNew;
  110344. }
  110345. /*
  110346. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  110347. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  110348. ** array if it is missing. If pTab is already in the array, this routine
  110349. ** is a no-op.
  110350. */
  110351. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  110352. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  110353. int i, n;
  110354. Table **apVtabLock;
  110355. assert( IsVirtual(pTab) );
  110356. for(i=0; i<pToplevel->nVtabLock; i++){
  110357. if( pTab==pToplevel->apVtabLock[i] ) return;
  110358. }
  110359. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  110360. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  110361. if( apVtabLock ){
  110362. pToplevel->apVtabLock = apVtabLock;
  110363. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  110364. }else{
  110365. pToplevel->db->mallocFailed = 1;
  110366. }
  110367. }
  110368. /*
  110369. ** Check to see if virtual tale module pMod can be have an eponymous
  110370. ** virtual table instance. If it can, create one if one does not already
  110371. ** exist. Return non-zero if the eponymous virtual table instance exists
  110372. ** when this routine returns, and return zero if it does not exist.
  110373. **
  110374. ** An eponymous virtual table instance is one that is named after its
  110375. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  110376. ** statement in order to come into existance. Eponymous virtual table
  110377. ** instances always exist. They cannot be DROP-ed.
  110378. **
  110379. ** Any virtual table module for which xConnect and xCreate are the same
  110380. ** method can have an eponymous virtual table instance.
  110381. */
  110382. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  110383. const sqlite3_module *pModule = pMod->pModule;
  110384. Table *pTab;
  110385. char *zErr = 0;
  110386. int nName;
  110387. int rc;
  110388. sqlite3 *db = pParse->db;
  110389. if( pMod->pEpoTab ) return 1;
  110390. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  110391. nName = sqlite3Strlen30(pMod->zName) + 1;
  110392. pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
  110393. if( pTab==0 ) return 0;
  110394. pMod->pEpoTab = pTab;
  110395. pTab->zName = (char*)&pTab[1];
  110396. memcpy(pTab->zName, pMod->zName, nName);
  110397. pTab->nRef = 1;
  110398. pTab->pSchema = db->aDb[0].pSchema;
  110399. pTab->tabFlags |= TF_Virtual;
  110400. pTab->nModuleArg = 0;
  110401. pTab->iPKey = -1;
  110402. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  110403. addModuleArgument(db, pTab, 0);
  110404. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  110405. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  110406. if( rc ){
  110407. sqlite3ErrorMsg(pParse, "%s", zErr);
  110408. sqlite3DbFree(db, zErr);
  110409. sqlite3VtabEponymousTableClear(db, pMod);
  110410. return 0;
  110411. }
  110412. return 1;
  110413. }
  110414. /*
  110415. ** Erase the eponymous virtual table instance associated with
  110416. ** virtual table module pMod, if it exists.
  110417. */
  110418. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  110419. Table *pTab = pMod->pEpoTab;
  110420. if( pTab!=0 ){
  110421. sqlite3DeleteColumnNames(db, pTab);
  110422. sqlite3VtabClear(db, pTab);
  110423. sqlite3DbFree(db, pTab);
  110424. pMod->pEpoTab = 0;
  110425. }
  110426. }
  110427. /*
  110428. ** Return the ON CONFLICT resolution mode in effect for the virtual
  110429. ** table update operation currently in progress.
  110430. **
  110431. ** The results of this routine are undefined unless it is called from
  110432. ** within an xUpdate method.
  110433. */
  110434. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
  110435. static const unsigned char aMap[] = {
  110436. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  110437. };
  110438. #ifdef SQLITE_ENABLE_API_ARMOR
  110439. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  110440. #endif
  110441. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  110442. assert( OE_Ignore==4 && OE_Replace==5 );
  110443. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  110444. return (int)aMap[db->vtabOnConflict-1];
  110445. }
  110446. /*
  110447. ** Call from within the xCreate() or xConnect() methods to provide
  110448. ** the SQLite core with additional information about the behavior
  110449. ** of the virtual table being implemented.
  110450. */
  110451. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
  110452. va_list ap;
  110453. int rc = SQLITE_OK;
  110454. #ifdef SQLITE_ENABLE_API_ARMOR
  110455. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  110456. #endif
  110457. sqlite3_mutex_enter(db->mutex);
  110458. va_start(ap, op);
  110459. switch( op ){
  110460. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  110461. VtabCtx *p = db->pVtabCtx;
  110462. if( !p ){
  110463. rc = SQLITE_MISUSE_BKPT;
  110464. }else{
  110465. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  110466. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  110467. }
  110468. break;
  110469. }
  110470. default:
  110471. rc = SQLITE_MISUSE_BKPT;
  110472. break;
  110473. }
  110474. va_end(ap);
  110475. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  110476. sqlite3_mutex_leave(db->mutex);
  110477. return rc;
  110478. }
  110479. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110480. /************** End of vtab.c ************************************************/
  110481. /************** Begin file wherecode.c ***************************************/
  110482. /*
  110483. ** 2015-06-06
  110484. **
  110485. ** The author disclaims copyright to this source code. In place of
  110486. ** a legal notice, here is a blessing:
  110487. **
  110488. ** May you do good and not evil.
  110489. ** May you find forgiveness for yourself and forgive others.
  110490. ** May you share freely, never taking more than you give.
  110491. **
  110492. *************************************************************************
  110493. ** This module contains C code that generates VDBE code used to process
  110494. ** the WHERE clause of SQL statements.
  110495. **
  110496. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  110497. ** size of where.c and make it easier to edit. This file contains the routines
  110498. ** that actually generate the bulk of the WHERE loop code. The original where.c
  110499. ** file retains the code that does query planning and analysis.
  110500. */
  110501. /* #include "sqliteInt.h" */
  110502. /************** Include whereInt.h in the middle of wherecode.c **************/
  110503. /************** Begin file whereInt.h ****************************************/
  110504. /*
  110505. ** 2013-11-12
  110506. **
  110507. ** The author disclaims copyright to this source code. In place of
  110508. ** a legal notice, here is a blessing:
  110509. **
  110510. ** May you do good and not evil.
  110511. ** May you find forgiveness for yourself and forgive others.
  110512. ** May you share freely, never taking more than you give.
  110513. **
  110514. *************************************************************************
  110515. **
  110516. ** This file contains structure and macro definitions for the query
  110517. ** planner logic in "where.c". These definitions are broken out into
  110518. ** a separate source file for easier editing.
  110519. */
  110520. /*
  110521. ** Trace output macros
  110522. */
  110523. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  110524. /***/ int sqlite3WhereTrace;
  110525. #endif
  110526. #if defined(SQLITE_DEBUG) \
  110527. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  110528. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  110529. # define WHERETRACE_ENABLED 1
  110530. #else
  110531. # define WHERETRACE(K,X)
  110532. #endif
  110533. /* Forward references
  110534. */
  110535. typedef struct WhereClause WhereClause;
  110536. typedef struct WhereMaskSet WhereMaskSet;
  110537. typedef struct WhereOrInfo WhereOrInfo;
  110538. typedef struct WhereAndInfo WhereAndInfo;
  110539. typedef struct WhereLevel WhereLevel;
  110540. typedef struct WhereLoop WhereLoop;
  110541. typedef struct WherePath WherePath;
  110542. typedef struct WhereTerm WhereTerm;
  110543. typedef struct WhereLoopBuilder WhereLoopBuilder;
  110544. typedef struct WhereScan WhereScan;
  110545. typedef struct WhereOrCost WhereOrCost;
  110546. typedef struct WhereOrSet WhereOrSet;
  110547. /*
  110548. ** This object contains information needed to implement a single nested
  110549. ** loop in WHERE clause.
  110550. **
  110551. ** Contrast this object with WhereLoop. This object describes the
  110552. ** implementation of the loop. WhereLoop describes the algorithm.
  110553. ** This object contains a pointer to the WhereLoop algorithm as one of
  110554. ** its elements.
  110555. **
  110556. ** The WhereInfo object contains a single instance of this object for
  110557. ** each term in the FROM clause (which is to say, for each of the
  110558. ** nested loops as implemented). The order of WhereLevel objects determines
  110559. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  110560. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  110561. */
  110562. struct WhereLevel {
  110563. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  110564. int iTabCur; /* The VDBE cursor used to access the table */
  110565. int iIdxCur; /* The VDBE cursor used to access pIdx */
  110566. int addrBrk; /* Jump here to break out of the loop */
  110567. int addrNxt; /* Jump here to start the next IN combination */
  110568. int addrSkip; /* Jump here for next iteration of skip-scan */
  110569. int addrCont; /* Jump here to continue with the next loop cycle */
  110570. int addrFirst; /* First instruction of interior of the loop */
  110571. int addrBody; /* Beginning of the body of this loop */
  110572. int iLikeRepCntr; /* LIKE range processing counter register */
  110573. int addrLikeRep; /* LIKE range processing address */
  110574. u8 iFrom; /* Which entry in the FROM clause */
  110575. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  110576. int p1, p2; /* Operands of the opcode used to ends the loop */
  110577. union { /* Information that depends on pWLoop->wsFlags */
  110578. struct {
  110579. int nIn; /* Number of entries in aInLoop[] */
  110580. struct InLoop {
  110581. int iCur; /* The VDBE cursor used by this IN operator */
  110582. int addrInTop; /* Top of the IN loop */
  110583. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  110584. } *aInLoop; /* Information about each nested IN operator */
  110585. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  110586. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  110587. } u;
  110588. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  110589. Bitmask notReady; /* FROM entries not usable at this level */
  110590. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  110591. int addrVisit; /* Address at which row is visited */
  110592. #endif
  110593. };
  110594. /*
  110595. ** Each instance of this object represents an algorithm for evaluating one
  110596. ** term of a join. Every term of the FROM clause will have at least
  110597. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  110598. ** prevent a query solution - which is an error) and many terms of the
  110599. ** FROM clause will have multiple WhereLoop objects, each describing a
  110600. ** potential way of implementing that FROM-clause term, together with
  110601. ** dependencies and cost estimates for using the chosen algorithm.
  110602. **
  110603. ** Query planning consists of building up a collection of these WhereLoop
  110604. ** objects, then computing a particular sequence of WhereLoop objects, with
  110605. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  110606. ** and that minimize the overall cost.
  110607. */
  110608. struct WhereLoop {
  110609. Bitmask prereq; /* Bitmask of other loops that must run first */
  110610. Bitmask maskSelf; /* Bitmask identifying table iTab */
  110611. #ifdef SQLITE_DEBUG
  110612. char cId; /* Symbolic ID of this loop for debugging use */
  110613. #endif
  110614. u8 iTab; /* Position in FROM clause of table for this loop */
  110615. u8 iSortIdx; /* Sorting index number. 0==None */
  110616. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  110617. LogEst rRun; /* Cost of running each loop */
  110618. LogEst nOut; /* Estimated number of output rows */
  110619. union {
  110620. struct { /* Information for internal btree tables */
  110621. u16 nEq; /* Number of equality constraints */
  110622. Index *pIndex; /* Index used, or NULL */
  110623. } btree;
  110624. struct { /* Information for virtual tables */
  110625. int idxNum; /* Index number */
  110626. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  110627. i8 isOrdered; /* True if satisfies ORDER BY */
  110628. u16 omitMask; /* Terms that may be omitted */
  110629. char *idxStr; /* Index identifier string */
  110630. } vtab;
  110631. } u;
  110632. u32 wsFlags; /* WHERE_* flags describing the plan */
  110633. u16 nLTerm; /* Number of entries in aLTerm[] */
  110634. u16 nSkip; /* Number of NULL aLTerm[] entries */
  110635. /**** whereLoopXfer() copies fields above ***********************/
  110636. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  110637. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  110638. WhereTerm **aLTerm; /* WhereTerms used */
  110639. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  110640. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  110641. };
  110642. /* This object holds the prerequisites and the cost of running a
  110643. ** subquery on one operand of an OR operator in the WHERE clause.
  110644. ** See WhereOrSet for additional information
  110645. */
  110646. struct WhereOrCost {
  110647. Bitmask prereq; /* Prerequisites */
  110648. LogEst rRun; /* Cost of running this subquery */
  110649. LogEst nOut; /* Number of outputs for this subquery */
  110650. };
  110651. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  110652. ** correspond to the subquery(s) of OR-clause processing. Only the
  110653. ** best N_OR_COST elements are retained.
  110654. */
  110655. #define N_OR_COST 3
  110656. struct WhereOrSet {
  110657. u16 n; /* Number of valid a[] entries */
  110658. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  110659. };
  110660. /*
  110661. ** Each instance of this object holds a sequence of WhereLoop objects
  110662. ** that implement some or all of a query plan.
  110663. **
  110664. ** Think of each WhereLoop object as a node in a graph with arcs
  110665. ** showing dependencies and costs for travelling between nodes. (That is
  110666. ** not a completely accurate description because WhereLoop costs are a
  110667. ** vector, not a scalar, and because dependencies are many-to-one, not
  110668. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  110669. ** Then a WherePath object is a path through the graph that visits some
  110670. ** or all of the WhereLoop objects once.
  110671. **
  110672. ** The "solver" works by creating the N best WherePath objects of length
  110673. ** 1. Then using those as a basis to compute the N best WherePath objects
  110674. ** of length 2. And so forth until the length of WherePaths equals the
  110675. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  110676. ** at the end is the chosen query plan.
  110677. */
  110678. struct WherePath {
  110679. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  110680. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  110681. LogEst nRow; /* Estimated number of rows generated by this path */
  110682. LogEst rCost; /* Total cost of this path */
  110683. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  110684. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  110685. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  110686. };
  110687. /*
  110688. ** The query generator uses an array of instances of this structure to
  110689. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  110690. ** clause subexpression is separated from the others by AND operators,
  110691. ** usually, or sometimes subexpressions separated by OR.
  110692. **
  110693. ** All WhereTerms are collected into a single WhereClause structure.
  110694. ** The following identity holds:
  110695. **
  110696. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  110697. **
  110698. ** When a term is of the form:
  110699. **
  110700. ** X <op> <expr>
  110701. **
  110702. ** where X is a column name and <op> is one of certain operators,
  110703. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  110704. ** cursor number and column number for X. WhereTerm.eOperator records
  110705. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  110706. ** use of a bitmask encoding for the operator allows us to search
  110707. ** quickly for terms that match any of several different operators.
  110708. **
  110709. ** A WhereTerm might also be two or more subterms connected by OR:
  110710. **
  110711. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  110712. **
  110713. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  110714. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  110715. ** is collected about the OR clause.
  110716. **
  110717. ** If a term in the WHERE clause does not match either of the two previous
  110718. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  110719. ** to the original subexpression content and wtFlags is set up appropriately
  110720. ** but no other fields in the WhereTerm object are meaningful.
  110721. **
  110722. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  110723. ** but they do so indirectly. A single WhereMaskSet structure translates
  110724. ** cursor number into bits and the translated bit is stored in the prereq
  110725. ** fields. The translation is used in order to maximize the number of
  110726. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  110727. ** spread out over the non-negative integers. For example, the cursor
  110728. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  110729. ** translates these sparse cursor numbers into consecutive integers
  110730. ** beginning with 0 in order to make the best possible use of the available
  110731. ** bits in the Bitmask. So, in the example above, the cursor numbers
  110732. ** would be mapped into integers 0 through 7.
  110733. **
  110734. ** The number of terms in a join is limited by the number of bits
  110735. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  110736. ** is only able to process joins with 64 or fewer tables.
  110737. */
  110738. struct WhereTerm {
  110739. Expr *pExpr; /* Pointer to the subexpression that is this term */
  110740. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  110741. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  110742. union {
  110743. int leftColumn; /* Column number of X in "X <op> <expr>" */
  110744. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  110745. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  110746. } u;
  110747. LogEst truthProb; /* Probability of truth for this expression */
  110748. u16 eOperator; /* A WO_xx value describing <op> */
  110749. u16 wtFlags; /* TERM_xxx bit flags. See below */
  110750. u8 nChild; /* Number of children that must disable us */
  110751. WhereClause *pWC; /* The clause this term is part of */
  110752. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  110753. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  110754. };
  110755. /*
  110756. ** Allowed values of WhereTerm.wtFlags
  110757. */
  110758. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  110759. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  110760. #define TERM_CODED 0x04 /* This term is already coded */
  110761. #define TERM_COPIED 0x08 /* Has a child */
  110762. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  110763. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  110764. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  110765. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110766. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  110767. #else
  110768. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  110769. #endif
  110770. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  110771. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  110772. #define TERM_LIKE 0x400 /* The original LIKE operator */
  110773. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  110774. /*
  110775. ** An instance of the WhereScan object is used as an iterator for locating
  110776. ** terms in the WHERE clause that are useful to the query planner.
  110777. */
  110778. struct WhereScan {
  110779. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  110780. WhereClause *pWC; /* WhereClause currently being scanned */
  110781. char *zCollName; /* Required collating sequence, if not NULL */
  110782. Expr *pIdxExpr; /* Search for this index expression */
  110783. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  110784. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  110785. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  110786. u32 opMask; /* Acceptable operators */
  110787. int k; /* Resume scanning at this->pWC->a[this->k] */
  110788. int aiCur[11]; /* Cursors in the equivalence class */
  110789. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  110790. };
  110791. /*
  110792. ** An instance of the following structure holds all information about a
  110793. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  110794. **
  110795. ** Explanation of pOuter: For a WHERE clause of the form
  110796. **
  110797. ** a AND ((b AND c) OR (d AND e)) AND f
  110798. **
  110799. ** There are separate WhereClause objects for the whole clause and for
  110800. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  110801. ** subclauses points to the WhereClause object for the whole clause.
  110802. */
  110803. struct WhereClause {
  110804. WhereInfo *pWInfo; /* WHERE clause processing context */
  110805. WhereClause *pOuter; /* Outer conjunction */
  110806. u8 op; /* Split operator. TK_AND or TK_OR */
  110807. int nTerm; /* Number of terms */
  110808. int nSlot; /* Number of entries in a[] */
  110809. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  110810. #if defined(SQLITE_SMALL_STACK)
  110811. WhereTerm aStatic[1]; /* Initial static space for a[] */
  110812. #else
  110813. WhereTerm aStatic[8]; /* Initial static space for a[] */
  110814. #endif
  110815. };
  110816. /*
  110817. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  110818. ** a dynamically allocated instance of the following structure.
  110819. */
  110820. struct WhereOrInfo {
  110821. WhereClause wc; /* Decomposition into subterms */
  110822. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  110823. };
  110824. /*
  110825. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  110826. ** a dynamically allocated instance of the following structure.
  110827. */
  110828. struct WhereAndInfo {
  110829. WhereClause wc; /* The subexpression broken out */
  110830. };
  110831. /*
  110832. ** An instance of the following structure keeps track of a mapping
  110833. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  110834. **
  110835. ** The VDBE cursor numbers are small integers contained in
  110836. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  110837. ** clause, the cursor numbers might not begin with 0 and they might
  110838. ** contain gaps in the numbering sequence. But we want to make maximum
  110839. ** use of the bits in our bitmasks. This structure provides a mapping
  110840. ** from the sparse cursor numbers into consecutive integers beginning
  110841. ** with 0.
  110842. **
  110843. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  110844. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  110845. **
  110846. ** For example, if the WHERE clause expression used these VDBE
  110847. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  110848. ** would map those cursor numbers into bits 0 through 5.
  110849. **
  110850. ** Note that the mapping is not necessarily ordered. In the example
  110851. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  110852. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  110853. ** does not really matter. What is important is that sparse cursor
  110854. ** numbers all get mapped into bit numbers that begin with 0 and contain
  110855. ** no gaps.
  110856. */
  110857. struct WhereMaskSet {
  110858. int n; /* Number of assigned cursor values */
  110859. int ix[BMS]; /* Cursor assigned to each bit */
  110860. };
  110861. /*
  110862. ** Initialize a WhereMaskSet object
  110863. */
  110864. #define initMaskSet(P) (P)->n=0
  110865. /*
  110866. ** This object is a convenience wrapper holding all information needed
  110867. ** to construct WhereLoop objects for a particular query.
  110868. */
  110869. struct WhereLoopBuilder {
  110870. WhereInfo *pWInfo; /* Information about this WHERE */
  110871. WhereClause *pWC; /* WHERE clause terms */
  110872. ExprList *pOrderBy; /* ORDER BY clause */
  110873. WhereLoop *pNew; /* Template WhereLoop */
  110874. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  110875. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110876. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  110877. int nRecValid; /* Number of valid fields currently in pRec */
  110878. #endif
  110879. };
  110880. /*
  110881. ** The WHERE clause processing routine has two halves. The
  110882. ** first part does the start of the WHERE loop and the second
  110883. ** half does the tail of the WHERE loop. An instance of
  110884. ** this structure is returned by the first half and passed
  110885. ** into the second half to give some continuity.
  110886. **
  110887. ** An instance of this object holds the complete state of the query
  110888. ** planner.
  110889. */
  110890. struct WhereInfo {
  110891. Parse *pParse; /* Parsing and code generating context */
  110892. SrcList *pTabList; /* List of tables in the join */
  110893. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  110894. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  110895. WhereLoop *pLoops; /* List of all WhereLoop objects */
  110896. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  110897. LogEst nRowOut; /* Estimated number of output rows */
  110898. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  110899. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  110900. u8 sorted; /* True if really sorted (not just grouped) */
  110901. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  110902. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  110903. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  110904. u8 nLevel; /* Number of nested loop */
  110905. int iTop; /* The very beginning of the WHERE loop */
  110906. int iContinue; /* Jump here to continue with next record */
  110907. int iBreak; /* Jump here to break out of the loop */
  110908. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  110909. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  110910. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  110911. WhereClause sWC; /* Decomposition of the WHERE clause */
  110912. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  110913. };
  110914. /*
  110915. ** Private interfaces - callable only by other where.c routines.
  110916. **
  110917. ** where.c:
  110918. */
  110919. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  110920. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  110921. WhereClause *pWC, /* The WHERE clause to be searched */
  110922. int iCur, /* Cursor number of LHS */
  110923. int iColumn, /* Column number of LHS */
  110924. Bitmask notReady, /* RHS must not overlap with this mask */
  110925. u32 op, /* Mask of WO_xx values describing operator */
  110926. Index *pIdx /* Must be compatible with this index, if not NULL */
  110927. );
  110928. /* wherecode.c: */
  110929. #ifndef SQLITE_OMIT_EXPLAIN
  110930. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  110931. Parse *pParse, /* Parse context */
  110932. SrcList *pTabList, /* Table list this loop refers to */
  110933. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  110934. int iLevel, /* Value for "level" column of output */
  110935. int iFrom, /* Value for "from" column of output */
  110936. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  110937. );
  110938. #else
  110939. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  110940. #endif /* SQLITE_OMIT_EXPLAIN */
  110941. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  110942. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  110943. Vdbe *v, /* Vdbe to add scanstatus entry to */
  110944. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  110945. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  110946. int addrExplain /* Address of OP_Explain (or 0) */
  110947. );
  110948. #else
  110949. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  110950. #endif
  110951. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  110952. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  110953. int iLevel, /* Which level of pWInfo->a[] should be coded */
  110954. Bitmask notReady /* Which tables are currently available */
  110955. );
  110956. /* whereexpr.c: */
  110957. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  110958. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  110959. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  110960. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  110961. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  110962. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  110963. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  110964. /*
  110965. ** Bitmasks for the operators on WhereTerm objects. These are all
  110966. ** operators that are of interest to the query planner. An
  110967. ** OR-ed combination of these values can be used when searching for
  110968. ** particular WhereTerms within a WhereClause.
  110969. */
  110970. #define WO_IN 0x0001
  110971. #define WO_EQ 0x0002
  110972. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  110973. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  110974. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  110975. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  110976. #define WO_MATCH 0x0040
  110977. #define WO_IS 0x0080
  110978. #define WO_ISNULL 0x0100
  110979. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  110980. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  110981. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  110982. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  110983. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  110984. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  110985. /*
  110986. ** These are definitions of bits in the WhereLoop.wsFlags field.
  110987. ** The particular combination of bits in each WhereLoop help to
  110988. ** determine the algorithm that WhereLoop represents.
  110989. */
  110990. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  110991. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  110992. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  110993. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  110994. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  110995. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  110996. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  110997. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  110998. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  110999. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  111000. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  111001. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  111002. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  111003. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  111004. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  111005. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  111006. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  111007. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  111008. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  111009. /************** End of whereInt.h ********************************************/
  111010. /************** Continuing where we left off in wherecode.c ******************/
  111011. #ifndef SQLITE_OMIT_EXPLAIN
  111012. /*
  111013. ** This routine is a helper for explainIndexRange() below
  111014. **
  111015. ** pStr holds the text of an expression that we are building up one term
  111016. ** at a time. This routine adds a new term to the end of the expression.
  111017. ** Terms are separated by AND so add the "AND" text for second and subsequent
  111018. ** terms only.
  111019. */
  111020. static void explainAppendTerm(
  111021. StrAccum *pStr, /* The text expression being built */
  111022. int iTerm, /* Index of this term. First is zero */
  111023. const char *zColumn, /* Name of the column */
  111024. const char *zOp /* Name of the operator */
  111025. ){
  111026. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  111027. sqlite3StrAccumAppendAll(pStr, zColumn);
  111028. sqlite3StrAccumAppend(pStr, zOp, 1);
  111029. sqlite3StrAccumAppend(pStr, "?", 1);
  111030. }
  111031. /*
  111032. ** Return the name of the i-th column of the pIdx index.
  111033. */
  111034. static const char *explainIndexColumnName(Index *pIdx, int i){
  111035. i = pIdx->aiColumn[i];
  111036. if( i==XN_EXPR ) return "<expr>";
  111037. if( i==XN_ROWID ) return "rowid";
  111038. return pIdx->pTable->aCol[i].zName;
  111039. }
  111040. /*
  111041. ** Argument pLevel describes a strategy for scanning table pTab. This
  111042. ** function appends text to pStr that describes the subset of table
  111043. ** rows scanned by the strategy in the form of an SQL expression.
  111044. **
  111045. ** For example, if the query:
  111046. **
  111047. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  111048. **
  111049. ** is run and there is an index on (a, b), then this function returns a
  111050. ** string similar to:
  111051. **
  111052. ** "a=? AND b>?"
  111053. */
  111054. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  111055. Index *pIndex = pLoop->u.btree.pIndex;
  111056. u16 nEq = pLoop->u.btree.nEq;
  111057. u16 nSkip = pLoop->nSkip;
  111058. int i, j;
  111059. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  111060. sqlite3StrAccumAppend(pStr, " (", 2);
  111061. for(i=0; i<nEq; i++){
  111062. const char *z = explainIndexColumnName(pIndex, i);
  111063. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  111064. sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  111065. }
  111066. j = i;
  111067. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  111068. const char *z = explainIndexColumnName(pIndex, i);
  111069. explainAppendTerm(pStr, i++, z, ">");
  111070. }
  111071. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  111072. const char *z = explainIndexColumnName(pIndex, j);
  111073. explainAppendTerm(pStr, i, z, "<");
  111074. }
  111075. sqlite3StrAccumAppend(pStr, ")", 1);
  111076. }
  111077. /*
  111078. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  111079. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  111080. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  111081. ** is added to the output to describe the table scan strategy in pLevel.
  111082. **
  111083. ** If an OP_Explain opcode is added to the VM, its address is returned.
  111084. ** Otherwise, if no OP_Explain is coded, zero is returned.
  111085. */
  111086. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  111087. Parse *pParse, /* Parse context */
  111088. SrcList *pTabList, /* Table list this loop refers to */
  111089. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  111090. int iLevel, /* Value for "level" column of output */
  111091. int iFrom, /* Value for "from" column of output */
  111092. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  111093. ){
  111094. int ret = 0;
  111095. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  111096. if( pParse->explain==2 )
  111097. #endif
  111098. {
  111099. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  111100. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  111101. sqlite3 *db = pParse->db; /* Database handle */
  111102. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  111103. int isSearch; /* True for a SEARCH. False for SCAN. */
  111104. WhereLoop *pLoop; /* The controlling WhereLoop object */
  111105. u32 flags; /* Flags that describe this loop */
  111106. char *zMsg; /* Text to add to EQP output */
  111107. StrAccum str; /* EQP output string */
  111108. char zBuf[100]; /* Initial space for EQP output string */
  111109. pLoop = pLevel->pWLoop;
  111110. flags = pLoop->wsFlags;
  111111. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
  111112. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  111113. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  111114. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  111115. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  111116. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  111117. if( pItem->pSelect ){
  111118. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  111119. }else{
  111120. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  111121. }
  111122. if( pItem->zAlias ){
  111123. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  111124. }
  111125. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  111126. const char *zFmt = 0;
  111127. Index *pIdx;
  111128. assert( pLoop->u.btree.pIndex!=0 );
  111129. pIdx = pLoop->u.btree.pIndex;
  111130. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  111131. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  111132. if( isSearch ){
  111133. zFmt = "PRIMARY KEY";
  111134. }
  111135. }else if( flags & WHERE_PARTIALIDX ){
  111136. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  111137. }else if( flags & WHERE_AUTO_INDEX ){
  111138. zFmt = "AUTOMATIC COVERING INDEX";
  111139. }else if( flags & WHERE_IDX_ONLY ){
  111140. zFmt = "COVERING INDEX %s";
  111141. }else{
  111142. zFmt = "INDEX %s";
  111143. }
  111144. if( zFmt ){
  111145. sqlite3StrAccumAppend(&str, " USING ", 7);
  111146. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  111147. explainIndexRange(&str, pLoop);
  111148. }
  111149. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  111150. const char *zRangeOp;
  111151. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  111152. zRangeOp = "=";
  111153. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  111154. zRangeOp = ">? AND rowid<";
  111155. }else if( flags&WHERE_BTM_LIMIT ){
  111156. zRangeOp = ">";
  111157. }else{
  111158. assert( flags&WHERE_TOP_LIMIT);
  111159. zRangeOp = "<";
  111160. }
  111161. sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  111162. }
  111163. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111164. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  111165. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  111166. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  111167. }
  111168. #endif
  111169. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  111170. if( pLoop->nOut>=10 ){
  111171. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  111172. }else{
  111173. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  111174. }
  111175. #endif
  111176. zMsg = sqlite3StrAccumFinish(&str);
  111177. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  111178. }
  111179. return ret;
  111180. }
  111181. #endif /* SQLITE_OMIT_EXPLAIN */
  111182. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  111183. /*
  111184. ** Configure the VM passed as the first argument with an
  111185. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  111186. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  111187. ** clause that the scan reads data from.
  111188. **
  111189. ** If argument addrExplain is not 0, it must be the address of an
  111190. ** OP_Explain instruction that describes the same loop.
  111191. */
  111192. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  111193. Vdbe *v, /* Vdbe to add scanstatus entry to */
  111194. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  111195. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  111196. int addrExplain /* Address of OP_Explain (or 0) */
  111197. ){
  111198. const char *zObj = 0;
  111199. WhereLoop *pLoop = pLvl->pWLoop;
  111200. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  111201. zObj = pLoop->u.btree.pIndex->zName;
  111202. }else{
  111203. zObj = pSrclist->a[pLvl->iFrom].zName;
  111204. }
  111205. sqlite3VdbeScanStatus(
  111206. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  111207. );
  111208. }
  111209. #endif
  111210. /*
  111211. ** Disable a term in the WHERE clause. Except, do not disable the term
  111212. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  111213. ** or USING clause of that join.
  111214. **
  111215. ** Consider the term t2.z='ok' in the following queries:
  111216. **
  111217. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  111218. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  111219. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  111220. **
  111221. ** The t2.z='ok' is disabled in the in (2) because it originates
  111222. ** in the ON clause. The term is disabled in (3) because it is not part
  111223. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  111224. **
  111225. ** Disabling a term causes that term to not be tested in the inner loop
  111226. ** of the join. Disabling is an optimization. When terms are satisfied
  111227. ** by indices, we disable them to prevent redundant tests in the inner
  111228. ** loop. We would get the correct results if nothing were ever disabled,
  111229. ** but joins might run a little slower. The trick is to disable as much
  111230. ** as we can without disabling too much. If we disabled in (1), we'd get
  111231. ** the wrong answer. See ticket #813.
  111232. **
  111233. ** If all the children of a term are disabled, then that term is also
  111234. ** automatically disabled. In this way, terms get disabled if derived
  111235. ** virtual terms are tested first. For example:
  111236. **
  111237. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  111238. ** \___________/ \______/ \_____/
  111239. ** parent child1 child2
  111240. **
  111241. ** Only the parent term was in the original WHERE clause. The child1
  111242. ** and child2 terms were added by the LIKE optimization. If both of
  111243. ** the virtual child terms are valid, then testing of the parent can be
  111244. ** skipped.
  111245. **
  111246. ** Usually the parent term is marked as TERM_CODED. But if the parent
  111247. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  111248. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  111249. ** a conditional such that is only evaluated on the second pass of a
  111250. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  111251. */
  111252. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  111253. int nLoop = 0;
  111254. while( pTerm
  111255. && (pTerm->wtFlags & TERM_CODED)==0
  111256. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  111257. && (pLevel->notReady & pTerm->prereqAll)==0
  111258. ){
  111259. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  111260. pTerm->wtFlags |= TERM_LIKECOND;
  111261. }else{
  111262. pTerm->wtFlags |= TERM_CODED;
  111263. }
  111264. if( pTerm->iParent<0 ) break;
  111265. pTerm = &pTerm->pWC->a[pTerm->iParent];
  111266. pTerm->nChild--;
  111267. if( pTerm->nChild!=0 ) break;
  111268. nLoop++;
  111269. }
  111270. }
  111271. /*
  111272. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  111273. ** to the n registers starting at base.
  111274. **
  111275. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  111276. ** beginning and end of zAff are ignored. If all entries in zAff are
  111277. ** SQLITE_AFF_BLOB, then no code gets generated.
  111278. **
  111279. ** This routine makes its own copy of zAff so that the caller is free
  111280. ** to modify zAff after this routine returns.
  111281. */
  111282. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  111283. Vdbe *v = pParse->pVdbe;
  111284. if( zAff==0 ){
  111285. assert( pParse->db->mallocFailed );
  111286. return;
  111287. }
  111288. assert( v!=0 );
  111289. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  111290. ** and end of the affinity string.
  111291. */
  111292. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  111293. n--;
  111294. base++;
  111295. zAff++;
  111296. }
  111297. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  111298. n--;
  111299. }
  111300. /* Code the OP_Affinity opcode if there is anything left to do. */
  111301. if( n>0 ){
  111302. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  111303. sqlite3VdbeChangeP4(v, -1, zAff, n);
  111304. sqlite3ExprCacheAffinityChange(pParse, base, n);
  111305. }
  111306. }
  111307. /*
  111308. ** Generate code for a single equality term of the WHERE clause. An equality
  111309. ** term can be either X=expr or X IN (...). pTerm is the term to be
  111310. ** coded.
  111311. **
  111312. ** The current value for the constraint is left in register iReg.
  111313. **
  111314. ** For a constraint of the form X=expr, the expression is evaluated and its
  111315. ** result is left on the stack. For constraints of the form X IN (...)
  111316. ** this routine sets up a loop that will iterate over all values of X.
  111317. */
  111318. static int codeEqualityTerm(
  111319. Parse *pParse, /* The parsing context */
  111320. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  111321. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  111322. int iEq, /* Index of the equality term within this level */
  111323. int bRev, /* True for reverse-order IN operations */
  111324. int iTarget /* Attempt to leave results in this register */
  111325. ){
  111326. Expr *pX = pTerm->pExpr;
  111327. Vdbe *v = pParse->pVdbe;
  111328. int iReg; /* Register holding results */
  111329. assert( iTarget>0 );
  111330. if( pX->op==TK_EQ || pX->op==TK_IS ){
  111331. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  111332. }else if( pX->op==TK_ISNULL ){
  111333. iReg = iTarget;
  111334. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  111335. #ifndef SQLITE_OMIT_SUBQUERY
  111336. }else{
  111337. int eType;
  111338. int iTab;
  111339. struct InLoop *pIn;
  111340. WhereLoop *pLoop = pLevel->pWLoop;
  111341. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  111342. && pLoop->u.btree.pIndex!=0
  111343. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  111344. ){
  111345. testcase( iEq==0 );
  111346. testcase( bRev );
  111347. bRev = !bRev;
  111348. }
  111349. assert( pX->op==TK_IN );
  111350. iReg = iTarget;
  111351. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  111352. if( eType==IN_INDEX_INDEX_DESC ){
  111353. testcase( bRev );
  111354. bRev = !bRev;
  111355. }
  111356. iTab = pX->iTable;
  111357. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  111358. VdbeCoverageIf(v, bRev);
  111359. VdbeCoverageIf(v, !bRev);
  111360. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  111361. pLoop->wsFlags |= WHERE_IN_ABLE;
  111362. if( pLevel->u.in.nIn==0 ){
  111363. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  111364. }
  111365. pLevel->u.in.nIn++;
  111366. pLevel->u.in.aInLoop =
  111367. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  111368. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  111369. pIn = pLevel->u.in.aInLoop;
  111370. if( pIn ){
  111371. pIn += pLevel->u.in.nIn - 1;
  111372. pIn->iCur = iTab;
  111373. if( eType==IN_INDEX_ROWID ){
  111374. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  111375. }else{
  111376. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  111377. }
  111378. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  111379. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  111380. }else{
  111381. pLevel->u.in.nIn = 0;
  111382. }
  111383. #endif
  111384. }
  111385. disableTerm(pLevel, pTerm);
  111386. return iReg;
  111387. }
  111388. /*
  111389. ** Generate code that will evaluate all == and IN constraints for an
  111390. ** index scan.
  111391. **
  111392. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  111393. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  111394. ** The index has as many as three equality constraints, but in this
  111395. ** example, the third "c" value is an inequality. So only two
  111396. ** constraints are coded. This routine will generate code to evaluate
  111397. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  111398. ** in consecutive registers and the index of the first register is returned.
  111399. **
  111400. ** In the example above nEq==2. But this subroutine works for any value
  111401. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  111402. ** The only thing it does is allocate the pLevel->iMem memory cell and
  111403. ** compute the affinity string.
  111404. **
  111405. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  111406. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  111407. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  111408. ** occurs after the nEq quality constraints.
  111409. **
  111410. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  111411. ** the index of the first memory cell in that range. The code that
  111412. ** calls this routine will use that memory range to store keys for
  111413. ** start and termination conditions of the loop.
  111414. ** key value of the loop. If one or more IN operators appear, then
  111415. ** this routine allocates an additional nEq memory cells for internal
  111416. ** use.
  111417. **
  111418. ** Before returning, *pzAff is set to point to a buffer containing a
  111419. ** copy of the column affinity string of the index allocated using
  111420. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  111421. ** with equality constraints that use BLOB or NONE affinity are set to
  111422. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  111423. **
  111424. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  111425. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  111426. **
  111427. ** In the example above, the index on t1(a) has TEXT affinity. But since
  111428. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  111429. ** no conversion should be attempted before using a t2.b value as part of
  111430. ** a key to search the index. Hence the first byte in the returned affinity
  111431. ** string in this example would be set to SQLITE_AFF_BLOB.
  111432. */
  111433. static int codeAllEqualityTerms(
  111434. Parse *pParse, /* Parsing context */
  111435. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  111436. int bRev, /* Reverse the order of IN operators */
  111437. int nExtraReg, /* Number of extra registers to allocate */
  111438. char **pzAff /* OUT: Set to point to affinity string */
  111439. ){
  111440. u16 nEq; /* The number of == or IN constraints to code */
  111441. u16 nSkip; /* Number of left-most columns to skip */
  111442. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  111443. Index *pIdx; /* The index being used for this loop */
  111444. WhereTerm *pTerm; /* A single constraint term */
  111445. WhereLoop *pLoop; /* The WhereLoop object */
  111446. int j; /* Loop counter */
  111447. int regBase; /* Base register */
  111448. int nReg; /* Number of registers to allocate */
  111449. char *zAff; /* Affinity string to return */
  111450. /* This module is only called on query plans that use an index. */
  111451. pLoop = pLevel->pWLoop;
  111452. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  111453. nEq = pLoop->u.btree.nEq;
  111454. nSkip = pLoop->nSkip;
  111455. pIdx = pLoop->u.btree.pIndex;
  111456. assert( pIdx!=0 );
  111457. /* Figure out how many memory cells we will need then allocate them.
  111458. */
  111459. regBase = pParse->nMem + 1;
  111460. nReg = pLoop->u.btree.nEq + nExtraReg;
  111461. pParse->nMem += nReg;
  111462. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  111463. if( !zAff ){
  111464. pParse->db->mallocFailed = 1;
  111465. }
  111466. if( nSkip ){
  111467. int iIdxCur = pLevel->iIdxCur;
  111468. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  111469. VdbeCoverageIf(v, bRev==0);
  111470. VdbeCoverageIf(v, bRev!=0);
  111471. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  111472. j = sqlite3VdbeAddOp0(v, OP_Goto);
  111473. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  111474. iIdxCur, 0, regBase, nSkip);
  111475. VdbeCoverageIf(v, bRev==0);
  111476. VdbeCoverageIf(v, bRev!=0);
  111477. sqlite3VdbeJumpHere(v, j);
  111478. for(j=0; j<nSkip; j++){
  111479. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  111480. testcase( pIdx->aiColumn[j]==XN_EXPR );
  111481. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  111482. }
  111483. }
  111484. /* Evaluate the equality constraints
  111485. */
  111486. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  111487. for(j=nSkip; j<nEq; j++){
  111488. int r1;
  111489. pTerm = pLoop->aLTerm[j];
  111490. assert( pTerm!=0 );
  111491. /* The following testcase is true for indices with redundant columns.
  111492. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  111493. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  111494. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111495. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  111496. if( r1!=regBase+j ){
  111497. if( nReg==1 ){
  111498. sqlite3ReleaseTempReg(pParse, regBase);
  111499. regBase = r1;
  111500. }else{
  111501. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  111502. }
  111503. }
  111504. testcase( pTerm->eOperator & WO_ISNULL );
  111505. testcase( pTerm->eOperator & WO_IN );
  111506. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  111507. Expr *pRight = pTerm->pExpr->pRight;
  111508. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  111509. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  111510. VdbeCoverage(v);
  111511. }
  111512. if( zAff ){
  111513. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  111514. zAff[j] = SQLITE_AFF_BLOB;
  111515. }
  111516. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  111517. zAff[j] = SQLITE_AFF_BLOB;
  111518. }
  111519. }
  111520. }
  111521. }
  111522. *pzAff = zAff;
  111523. return regBase;
  111524. }
  111525. /*
  111526. ** If the most recently coded instruction is a constant range contraint
  111527. ** that originated from the LIKE optimization, then change the P3 to be
  111528. ** pLoop->iLikeRepCntr and set P5.
  111529. **
  111530. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  111531. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  111532. ** scan loop run twice, once for strings and a second time for BLOBs.
  111533. ** The OP_String opcodes on the second pass convert the upper and lower
  111534. ** bound string contants to blobs. This routine makes the necessary changes
  111535. ** to the OP_String opcodes for that to happen.
  111536. */
  111537. static void whereLikeOptimizationStringFixup(
  111538. Vdbe *v, /* prepared statement under construction */
  111539. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  111540. WhereTerm *pTerm /* The upper or lower bound just coded */
  111541. ){
  111542. if( pTerm->wtFlags & TERM_LIKEOPT ){
  111543. VdbeOp *pOp;
  111544. assert( pLevel->iLikeRepCntr>0 );
  111545. pOp = sqlite3VdbeGetOp(v, -1);
  111546. assert( pOp!=0 );
  111547. assert( pOp->opcode==OP_String8
  111548. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  111549. pOp->p3 = pLevel->iLikeRepCntr;
  111550. pOp->p5 = 1;
  111551. }
  111552. }
  111553. /*
  111554. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  111555. ** implementation described by pWInfo.
  111556. */
  111557. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  111558. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  111559. int iLevel, /* Which level of pWInfo->a[] should be coded */
  111560. Bitmask notReady /* Which tables are currently available */
  111561. ){
  111562. int j, k; /* Loop counters */
  111563. int iCur; /* The VDBE cursor for the table */
  111564. int addrNxt; /* Where to jump to continue with the next IN case */
  111565. int omitTable; /* True if we use the index only */
  111566. int bRev; /* True if we need to scan in reverse order */
  111567. WhereLevel *pLevel; /* The where level to be coded */
  111568. WhereLoop *pLoop; /* The WhereLoop object being coded */
  111569. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  111570. WhereTerm *pTerm; /* A WHERE clause term */
  111571. Parse *pParse; /* Parsing context */
  111572. sqlite3 *db; /* Database connection */
  111573. Vdbe *v; /* The prepared stmt under constructions */
  111574. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  111575. int addrBrk; /* Jump here to break out of the loop */
  111576. int addrCont; /* Jump here to continue with next cycle */
  111577. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  111578. int iReleaseReg = 0; /* Temp register to free before returning */
  111579. pParse = pWInfo->pParse;
  111580. v = pParse->pVdbe;
  111581. pWC = &pWInfo->sWC;
  111582. db = pParse->db;
  111583. pLevel = &pWInfo->a[iLevel];
  111584. pLoop = pLevel->pWLoop;
  111585. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  111586. iCur = pTabItem->iCursor;
  111587. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  111588. bRev = (pWInfo->revMask>>iLevel)&1;
  111589. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  111590. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  111591. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  111592. /* Create labels for the "break" and "continue" instructions
  111593. ** for the current loop. Jump to addrBrk to break out of a loop.
  111594. ** Jump to cont to go immediately to the next iteration of the
  111595. ** loop.
  111596. **
  111597. ** When there is an IN operator, we also have a "addrNxt" label that
  111598. ** means to continue with the next IN value combination. When
  111599. ** there are no IN operators in the constraints, the "addrNxt" label
  111600. ** is the same as "addrBrk".
  111601. */
  111602. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  111603. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  111604. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  111605. ** initialize a memory cell that records if this table matches any
  111606. ** row of the left table of the join.
  111607. */
  111608. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  111609. pLevel->iLeftJoin = ++pParse->nMem;
  111610. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  111611. VdbeComment((v, "init LEFT JOIN no-match flag"));
  111612. }
  111613. /* Special case of a FROM clause subquery implemented as a co-routine */
  111614. if( pTabItem->fg.viaCoroutine ){
  111615. int regYield = pTabItem->regReturn;
  111616. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  111617. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  111618. VdbeCoverage(v);
  111619. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  111620. pLevel->op = OP_Goto;
  111621. }else
  111622. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111623. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  111624. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  111625. ** to access the data.
  111626. */
  111627. int iReg; /* P3 Value for OP_VFilter */
  111628. int addrNotFound;
  111629. int nConstraint = pLoop->nLTerm;
  111630. sqlite3ExprCachePush(pParse);
  111631. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  111632. addrNotFound = pLevel->addrBrk;
  111633. for(j=0; j<nConstraint; j++){
  111634. int iTarget = iReg+j+2;
  111635. pTerm = pLoop->aLTerm[j];
  111636. if( pTerm==0 ) continue;
  111637. if( pTerm->eOperator & WO_IN ){
  111638. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  111639. addrNotFound = pLevel->addrNxt;
  111640. }else{
  111641. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  111642. }
  111643. }
  111644. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  111645. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  111646. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  111647. pLoop->u.vtab.idxStr,
  111648. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  111649. VdbeCoverage(v);
  111650. pLoop->u.vtab.needFree = 0;
  111651. for(j=0; j<nConstraint && j<16; j++){
  111652. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  111653. disableTerm(pLevel, pLoop->aLTerm[j]);
  111654. }
  111655. }
  111656. pLevel->p1 = iCur;
  111657. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  111658. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  111659. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  111660. sqlite3ExprCachePop(pParse);
  111661. }else
  111662. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111663. if( (pLoop->wsFlags & WHERE_IPK)!=0
  111664. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  111665. ){
  111666. /* Case 2: We can directly reference a single row using an
  111667. ** equality comparison against the ROWID field. Or
  111668. ** we reference multiple rows using a "rowid IN (...)"
  111669. ** construct.
  111670. */
  111671. assert( pLoop->u.btree.nEq==1 );
  111672. pTerm = pLoop->aLTerm[0];
  111673. assert( pTerm!=0 );
  111674. assert( pTerm->pExpr!=0 );
  111675. assert( omitTable==0 );
  111676. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111677. iReleaseReg = ++pParse->nMem;
  111678. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  111679. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  111680. addrNxt = pLevel->addrNxt;
  111681. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  111682. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  111683. VdbeCoverage(v);
  111684. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  111685. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  111686. VdbeComment((v, "pk"));
  111687. pLevel->op = OP_Noop;
  111688. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  111689. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  111690. ){
  111691. /* Case 3: We have an inequality comparison against the ROWID field.
  111692. */
  111693. int testOp = OP_Noop;
  111694. int start;
  111695. int memEndValue = 0;
  111696. WhereTerm *pStart, *pEnd;
  111697. assert( omitTable==0 );
  111698. j = 0;
  111699. pStart = pEnd = 0;
  111700. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  111701. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  111702. assert( pStart!=0 || pEnd!=0 );
  111703. if( bRev ){
  111704. pTerm = pStart;
  111705. pStart = pEnd;
  111706. pEnd = pTerm;
  111707. }
  111708. if( pStart ){
  111709. Expr *pX; /* The expression that defines the start bound */
  111710. int r1, rTemp; /* Registers for holding the start boundary */
  111711. /* The following constant maps TK_xx codes into corresponding
  111712. ** seek opcodes. It depends on a particular ordering of TK_xx
  111713. */
  111714. const u8 aMoveOp[] = {
  111715. /* TK_GT */ OP_SeekGT,
  111716. /* TK_LE */ OP_SeekLE,
  111717. /* TK_LT */ OP_SeekLT,
  111718. /* TK_GE */ OP_SeekGE
  111719. };
  111720. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  111721. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  111722. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  111723. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  111724. testcase( pStart->wtFlags & TERM_VIRTUAL );
  111725. pX = pStart->pExpr;
  111726. assert( pX!=0 );
  111727. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  111728. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  111729. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  111730. VdbeComment((v, "pk"));
  111731. VdbeCoverageIf(v, pX->op==TK_GT);
  111732. VdbeCoverageIf(v, pX->op==TK_LE);
  111733. VdbeCoverageIf(v, pX->op==TK_LT);
  111734. VdbeCoverageIf(v, pX->op==TK_GE);
  111735. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  111736. sqlite3ReleaseTempReg(pParse, rTemp);
  111737. disableTerm(pLevel, pStart);
  111738. }else{
  111739. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  111740. VdbeCoverageIf(v, bRev==0);
  111741. VdbeCoverageIf(v, bRev!=0);
  111742. }
  111743. if( pEnd ){
  111744. Expr *pX;
  111745. pX = pEnd->pExpr;
  111746. assert( pX!=0 );
  111747. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  111748. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  111749. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  111750. memEndValue = ++pParse->nMem;
  111751. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  111752. if( pX->op==TK_LT || pX->op==TK_GT ){
  111753. testOp = bRev ? OP_Le : OP_Ge;
  111754. }else{
  111755. testOp = bRev ? OP_Lt : OP_Gt;
  111756. }
  111757. disableTerm(pLevel, pEnd);
  111758. }
  111759. start = sqlite3VdbeCurrentAddr(v);
  111760. pLevel->op = bRev ? OP_Prev : OP_Next;
  111761. pLevel->p1 = iCur;
  111762. pLevel->p2 = start;
  111763. assert( pLevel->p5==0 );
  111764. if( testOp!=OP_Noop ){
  111765. iRowidReg = ++pParse->nMem;
  111766. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  111767. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  111768. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  111769. VdbeCoverageIf(v, testOp==OP_Le);
  111770. VdbeCoverageIf(v, testOp==OP_Lt);
  111771. VdbeCoverageIf(v, testOp==OP_Ge);
  111772. VdbeCoverageIf(v, testOp==OP_Gt);
  111773. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  111774. }
  111775. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  111776. /* Case 4: A scan using an index.
  111777. **
  111778. ** The WHERE clause may contain zero or more equality
  111779. ** terms ("==" or "IN" operators) that refer to the N
  111780. ** left-most columns of the index. It may also contain
  111781. ** inequality constraints (>, <, >= or <=) on the indexed
  111782. ** column that immediately follows the N equalities. Only
  111783. ** the right-most column can be an inequality - the rest must
  111784. ** use the "==" and "IN" operators. For example, if the
  111785. ** index is on (x,y,z), then the following clauses are all
  111786. ** optimized:
  111787. **
  111788. ** x=5
  111789. ** x=5 AND y=10
  111790. ** x=5 AND y<10
  111791. ** x=5 AND y>5 AND y<10
  111792. ** x=5 AND y=5 AND z<=10
  111793. **
  111794. ** The z<10 term of the following cannot be used, only
  111795. ** the x=5 term:
  111796. **
  111797. ** x=5 AND z<10
  111798. **
  111799. ** N may be zero if there are inequality constraints.
  111800. ** If there are no inequality constraints, then N is at
  111801. ** least one.
  111802. **
  111803. ** This case is also used when there are no WHERE clause
  111804. ** constraints but an index is selected anyway, in order
  111805. ** to force the output order to conform to an ORDER BY.
  111806. */
  111807. static const u8 aStartOp[] = {
  111808. 0,
  111809. 0,
  111810. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  111811. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  111812. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  111813. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  111814. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  111815. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  111816. };
  111817. static const u8 aEndOp[] = {
  111818. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  111819. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  111820. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  111821. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  111822. };
  111823. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  111824. int regBase; /* Base register holding constraint values */
  111825. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  111826. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  111827. int startEq; /* True if range start uses ==, >= or <= */
  111828. int endEq; /* True if range end uses ==, >= or <= */
  111829. int start_constraints; /* Start of range is constrained */
  111830. int nConstraint; /* Number of constraint terms */
  111831. Index *pIdx; /* The index we will be using */
  111832. int iIdxCur; /* The VDBE cursor for the index */
  111833. int nExtraReg = 0; /* Number of extra registers needed */
  111834. int op; /* Instruction opcode */
  111835. char *zStartAff; /* Affinity for start of range constraint */
  111836. char cEndAff = 0; /* Affinity for end of range constraint */
  111837. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  111838. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  111839. pIdx = pLoop->u.btree.pIndex;
  111840. iIdxCur = pLevel->iIdxCur;
  111841. assert( nEq>=pLoop->nSkip );
  111842. /* If this loop satisfies a sort order (pOrderBy) request that
  111843. ** was passed to this function to implement a "SELECT min(x) ..."
  111844. ** query, then the caller will only allow the loop to run for
  111845. ** a single iteration. This means that the first row returned
  111846. ** should not have a NULL value stored in 'x'. If column 'x' is
  111847. ** the first one after the nEq equality constraints in the index,
  111848. ** this requires some special handling.
  111849. */
  111850. assert( pWInfo->pOrderBy==0
  111851. || pWInfo->pOrderBy->nExpr==1
  111852. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  111853. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  111854. && pWInfo->nOBSat>0
  111855. && (pIdx->nKeyCol>nEq)
  111856. ){
  111857. assert( pLoop->nSkip==0 );
  111858. bSeekPastNull = 1;
  111859. nExtraReg = 1;
  111860. }
  111861. /* Find any inequality constraint terms for the start and end
  111862. ** of the range.
  111863. */
  111864. j = nEq;
  111865. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  111866. pRangeStart = pLoop->aLTerm[j++];
  111867. nExtraReg = 1;
  111868. /* Like optimization range constraints always occur in pairs */
  111869. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  111870. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  111871. }
  111872. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  111873. pRangeEnd = pLoop->aLTerm[j++];
  111874. nExtraReg = 1;
  111875. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  111876. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  111877. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  111878. pLevel->iLikeRepCntr = ++pParse->nMem;
  111879. testcase( bRev );
  111880. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  111881. sqlite3VdbeAddOp2(v, OP_Integer,
  111882. bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
  111883. pLevel->iLikeRepCntr);
  111884. VdbeComment((v, "LIKE loop counter"));
  111885. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  111886. }
  111887. if( pRangeStart==0
  111888. && (j = pIdx->aiColumn[nEq])>=0
  111889. && pIdx->pTable->aCol[j].notNull==0
  111890. ){
  111891. bSeekPastNull = 1;
  111892. }
  111893. }
  111894. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  111895. /* Generate code to evaluate all constraint terms using == or IN
  111896. ** and store the values of those terms in an array of registers
  111897. ** starting at regBase.
  111898. */
  111899. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  111900. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  111901. if( zStartAff ) cEndAff = zStartAff[nEq];
  111902. addrNxt = pLevel->addrNxt;
  111903. /* If we are doing a reverse order scan on an ascending index, or
  111904. ** a forward order scan on a descending index, interchange the
  111905. ** start and end terms (pRangeStart and pRangeEnd).
  111906. */
  111907. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  111908. || (bRev && pIdx->nKeyCol==nEq)
  111909. ){
  111910. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  111911. SWAP(u8, bSeekPastNull, bStopAtNull);
  111912. }
  111913. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  111914. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  111915. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  111916. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  111917. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  111918. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  111919. start_constraints = pRangeStart || nEq>0;
  111920. /* Seek the index cursor to the start of the range. */
  111921. nConstraint = nEq;
  111922. if( pRangeStart ){
  111923. Expr *pRight = pRangeStart->pExpr->pRight;
  111924. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  111925. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  111926. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  111927. && sqlite3ExprCanBeNull(pRight)
  111928. ){
  111929. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  111930. VdbeCoverage(v);
  111931. }
  111932. if( zStartAff ){
  111933. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
  111934. /* Since the comparison is to be performed with no conversions
  111935. ** applied to the operands, set the affinity to apply to pRight to
  111936. ** SQLITE_AFF_BLOB. */
  111937. zStartAff[nEq] = SQLITE_AFF_BLOB;
  111938. }
  111939. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  111940. zStartAff[nEq] = SQLITE_AFF_BLOB;
  111941. }
  111942. }
  111943. nConstraint++;
  111944. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  111945. }else if( bSeekPastNull ){
  111946. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  111947. nConstraint++;
  111948. startEq = 0;
  111949. start_constraints = 1;
  111950. }
  111951. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  111952. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  111953. assert( op!=0 );
  111954. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  111955. VdbeCoverage(v);
  111956. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  111957. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  111958. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  111959. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  111960. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  111961. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  111962. /* Load the value for the inequality constraint at the end of the
  111963. ** range (if any).
  111964. */
  111965. nConstraint = nEq;
  111966. if( pRangeEnd ){
  111967. Expr *pRight = pRangeEnd->pExpr->pRight;
  111968. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  111969. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  111970. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  111971. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  111972. && sqlite3ExprCanBeNull(pRight)
  111973. ){
  111974. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  111975. VdbeCoverage(v);
  111976. }
  111977. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
  111978. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  111979. ){
  111980. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  111981. }
  111982. nConstraint++;
  111983. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  111984. }else if( bStopAtNull ){
  111985. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  111986. endEq = 0;
  111987. nConstraint++;
  111988. }
  111989. sqlite3DbFree(db, zStartAff);
  111990. /* Top of the loop body */
  111991. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  111992. /* Check if the index cursor is past the end of the range. */
  111993. if( nConstraint ){
  111994. op = aEndOp[bRev*2 + endEq];
  111995. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  111996. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  111997. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  111998. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  111999. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  112000. }
  112001. /* Seek the table cursor, if required */
  112002. disableTerm(pLevel, pRangeStart);
  112003. disableTerm(pLevel, pRangeEnd);
  112004. if( omitTable ){
  112005. /* pIdx is a covering index. No need to access the main table. */
  112006. }else if( HasRowid(pIdx->pTable) ){
  112007. iRowidReg = ++pParse->nMem;
  112008. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  112009. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  112010. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  112011. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  112012. VdbeCoverage(v);
  112013. }else{
  112014. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  112015. }
  112016. }else if( iCur!=iIdxCur ){
  112017. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  112018. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  112019. for(j=0; j<pPk->nKeyCol; j++){
  112020. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  112021. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  112022. }
  112023. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  112024. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  112025. }
  112026. /* Record the instruction used to terminate the loop. Disable
  112027. ** WHERE clause terms made redundant by the index range scan.
  112028. */
  112029. if( pLoop->wsFlags & WHERE_ONEROW ){
  112030. pLevel->op = OP_Noop;
  112031. }else if( bRev ){
  112032. pLevel->op = OP_Prev;
  112033. }else{
  112034. pLevel->op = OP_Next;
  112035. }
  112036. pLevel->p1 = iIdxCur;
  112037. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  112038. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  112039. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  112040. }else{
  112041. assert( pLevel->p5==0 );
  112042. }
  112043. }else
  112044. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  112045. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  112046. /* Case 5: Two or more separately indexed terms connected by OR
  112047. **
  112048. ** Example:
  112049. **
  112050. ** CREATE TABLE t1(a,b,c,d);
  112051. ** CREATE INDEX i1 ON t1(a);
  112052. ** CREATE INDEX i2 ON t1(b);
  112053. ** CREATE INDEX i3 ON t1(c);
  112054. **
  112055. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  112056. **
  112057. ** In the example, there are three indexed terms connected by OR.
  112058. ** The top of the loop looks like this:
  112059. **
  112060. ** Null 1 # Zero the rowset in reg 1
  112061. **
  112062. ** Then, for each indexed term, the following. The arguments to
  112063. ** RowSetTest are such that the rowid of the current row is inserted
  112064. ** into the RowSet. If it is already present, control skips the
  112065. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  112066. **
  112067. ** sqlite3WhereBegin(<term>)
  112068. ** RowSetTest # Insert rowid into rowset
  112069. ** Gosub 2 A
  112070. ** sqlite3WhereEnd()
  112071. **
  112072. ** Following the above, code to terminate the loop. Label A, the target
  112073. ** of the Gosub above, jumps to the instruction right after the Goto.
  112074. **
  112075. ** Null 1 # Zero the rowset in reg 1
  112076. ** Goto B # The loop is finished.
  112077. **
  112078. ** A: <loop body> # Return data, whatever.
  112079. **
  112080. ** Return 2 # Jump back to the Gosub
  112081. **
  112082. ** B: <after the loop>
  112083. **
  112084. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  112085. ** use an ephemeral index instead of a RowSet to record the primary
  112086. ** keys of the rows we have already seen.
  112087. **
  112088. */
  112089. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  112090. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  112091. Index *pCov = 0; /* Potential covering index (or NULL) */
  112092. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  112093. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  112094. int regRowset = 0; /* Register for RowSet object */
  112095. int regRowid = 0; /* Register holding rowid */
  112096. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  112097. int iRetInit; /* Address of regReturn init */
  112098. int untestedTerms = 0; /* Some terms not completely tested */
  112099. int ii; /* Loop counter */
  112100. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  112101. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  112102. Table *pTab = pTabItem->pTab;
  112103. pTerm = pLoop->aLTerm[0];
  112104. assert( pTerm!=0 );
  112105. assert( pTerm->eOperator & WO_OR );
  112106. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  112107. pOrWc = &pTerm->u.pOrInfo->wc;
  112108. pLevel->op = OP_Return;
  112109. pLevel->p1 = regReturn;
  112110. /* Set up a new SrcList in pOrTab containing the table being scanned
  112111. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  112112. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  112113. */
  112114. if( pWInfo->nLevel>1 ){
  112115. int nNotReady; /* The number of notReady tables */
  112116. struct SrcList_item *origSrc; /* Original list of tables */
  112117. nNotReady = pWInfo->nLevel - iLevel - 1;
  112118. pOrTab = sqlite3StackAllocRaw(db,
  112119. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  112120. if( pOrTab==0 ) return notReady;
  112121. pOrTab->nAlloc = (u8)(nNotReady + 1);
  112122. pOrTab->nSrc = pOrTab->nAlloc;
  112123. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  112124. origSrc = pWInfo->pTabList->a;
  112125. for(k=1; k<=nNotReady; k++){
  112126. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  112127. }
  112128. }else{
  112129. pOrTab = pWInfo->pTabList;
  112130. }
  112131. /* Initialize the rowset register to contain NULL. An SQL NULL is
  112132. ** equivalent to an empty rowset. Or, create an ephemeral index
  112133. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  112134. **
  112135. ** Also initialize regReturn to contain the address of the instruction
  112136. ** immediately following the OP_Return at the bottom of the loop. This
  112137. ** is required in a few obscure LEFT JOIN cases where control jumps
  112138. ** over the top of the loop into the body of it. In this case the
  112139. ** correct response for the end-of-loop code (the OP_Return) is to
  112140. ** fall through to the next instruction, just as an OP_Next does if
  112141. ** called on an uninitialized cursor.
  112142. */
  112143. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  112144. if( HasRowid(pTab) ){
  112145. regRowset = ++pParse->nMem;
  112146. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  112147. }else{
  112148. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112149. regRowset = pParse->nTab++;
  112150. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  112151. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  112152. }
  112153. regRowid = ++pParse->nMem;
  112154. }
  112155. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  112156. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  112157. ** Then for every term xN, evaluate as the subexpression: xN AND z
  112158. ** That way, terms in y that are factored into the disjunction will
  112159. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  112160. **
  112161. ** Actually, each subexpression is converted to "xN AND w" where w is
  112162. ** the "interesting" terms of z - terms that did not originate in the
  112163. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  112164. ** indices.
  112165. **
  112166. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  112167. ** is not contained in the ON clause of a LEFT JOIN.
  112168. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  112169. */
  112170. if( pWC->nTerm>1 ){
  112171. int iTerm;
  112172. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  112173. Expr *pExpr = pWC->a[iTerm].pExpr;
  112174. if( &pWC->a[iTerm] == pTerm ) continue;
  112175. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  112176. if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
  112177. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  112178. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  112179. pExpr = sqlite3ExprDup(db, pExpr, 0);
  112180. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  112181. }
  112182. if( pAndExpr ){
  112183. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  112184. }
  112185. }
  112186. /* Run a separate WHERE clause for each term of the OR clause. After
  112187. ** eliminating duplicates from other WHERE clauses, the action for each
  112188. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  112189. */
  112190. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  112191. | WHERE_FORCE_TABLE
  112192. | WHERE_ONETABLE_ONLY
  112193. | WHERE_NO_AUTOINDEX;
  112194. for(ii=0; ii<pOrWc->nTerm; ii++){
  112195. WhereTerm *pOrTerm = &pOrWc->a[ii];
  112196. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  112197. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  112198. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  112199. int jmp1 = 0; /* Address of jump operation */
  112200. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  112201. pAndExpr->pLeft = pOrExpr;
  112202. pOrExpr = pAndExpr;
  112203. }
  112204. /* Loop through table entries that match term pOrTerm. */
  112205. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  112206. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  112207. wctrlFlags, iCovCur);
  112208. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  112209. if( pSubWInfo ){
  112210. WhereLoop *pSubLoop;
  112211. int addrExplain = sqlite3WhereExplainOneScan(
  112212. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  112213. );
  112214. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  112215. /* This is the sub-WHERE clause body. First skip over
  112216. ** duplicate rows from prior sub-WHERE clauses, and record the
  112217. ** rowid (or PRIMARY KEY) for the current row so that the same
  112218. ** row will be skipped in subsequent sub-WHERE clauses.
  112219. */
  112220. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  112221. int r;
  112222. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  112223. if( HasRowid(pTab) ){
  112224. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  112225. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  112226. r,iSet);
  112227. VdbeCoverage(v);
  112228. }else{
  112229. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112230. int nPk = pPk->nKeyCol;
  112231. int iPk;
  112232. /* Read the PK into an array of temp registers. */
  112233. r = sqlite3GetTempRange(pParse, nPk);
  112234. for(iPk=0; iPk<nPk; iPk++){
  112235. int iCol = pPk->aiColumn[iPk];
  112236. int rx;
  112237. rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
  112238. if( rx!=r+iPk ){
  112239. sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
  112240. }
  112241. }
  112242. /* Check if the temp table already contains this key. If so,
  112243. ** the row has already been included in the result set and
  112244. ** can be ignored (by jumping past the Gosub below). Otherwise,
  112245. ** insert the key into the temp table and proceed with processing
  112246. ** the row.
  112247. **
  112248. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  112249. ** is zero, assume that the key cannot already be present in
  112250. ** the temp table. And if iSet is -1, assume that there is no
  112251. ** need to insert the key into the temp table, as it will never
  112252. ** be tested for. */
  112253. if( iSet ){
  112254. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  112255. VdbeCoverage(v);
  112256. }
  112257. if( iSet>=0 ){
  112258. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  112259. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  112260. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  112261. }
  112262. /* Release the array of temp registers */
  112263. sqlite3ReleaseTempRange(pParse, r, nPk);
  112264. }
  112265. }
  112266. /* Invoke the main loop body as a subroutine */
  112267. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  112268. /* Jump here (skipping the main loop body subroutine) if the
  112269. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  112270. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  112271. /* The pSubWInfo->untestedTerms flag means that this OR term
  112272. ** contained one or more AND term from a notReady table. The
  112273. ** terms from the notReady table could not be tested and will
  112274. ** need to be tested later.
  112275. */
  112276. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  112277. /* If all of the OR-connected terms are optimized using the same
  112278. ** index, and the index is opened using the same cursor number
  112279. ** by each call to sqlite3WhereBegin() made by this loop, it may
  112280. ** be possible to use that index as a covering index.
  112281. **
  112282. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  112283. ** uses an index, and this is either the first OR-connected term
  112284. ** processed or the index is the same as that used by all previous
  112285. ** terms, set pCov to the candidate covering index. Otherwise, set
  112286. ** pCov to NULL to indicate that no candidate covering index will
  112287. ** be available.
  112288. */
  112289. pSubLoop = pSubWInfo->a[0].pWLoop;
  112290. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  112291. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  112292. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  112293. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  112294. ){
  112295. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  112296. pCov = pSubLoop->u.btree.pIndex;
  112297. wctrlFlags |= WHERE_REOPEN_IDX;
  112298. }else{
  112299. pCov = 0;
  112300. }
  112301. /* Finish the loop through table entries that match term pOrTerm. */
  112302. sqlite3WhereEnd(pSubWInfo);
  112303. }
  112304. }
  112305. }
  112306. pLevel->u.pCovidx = pCov;
  112307. if( pCov ) pLevel->iIdxCur = iCovCur;
  112308. if( pAndExpr ){
  112309. pAndExpr->pLeft = 0;
  112310. sqlite3ExprDelete(db, pAndExpr);
  112311. }
  112312. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  112313. sqlite3VdbeGoto(v, pLevel->addrBrk);
  112314. sqlite3VdbeResolveLabel(v, iLoopBody);
  112315. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  112316. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  112317. }else
  112318. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  112319. {
  112320. /* Case 6: There is no usable index. We must do a complete
  112321. ** scan of the entire table.
  112322. */
  112323. static const u8 aStep[] = { OP_Next, OP_Prev };
  112324. static const u8 aStart[] = { OP_Rewind, OP_Last };
  112325. assert( bRev==0 || bRev==1 );
  112326. if( pTabItem->fg.isRecursive ){
  112327. /* Tables marked isRecursive have only a single row that is stored in
  112328. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  112329. pLevel->op = OP_Noop;
  112330. }else{
  112331. pLevel->op = aStep[bRev];
  112332. pLevel->p1 = iCur;
  112333. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  112334. VdbeCoverageIf(v, bRev==0);
  112335. VdbeCoverageIf(v, bRev!=0);
  112336. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  112337. }
  112338. }
  112339. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112340. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  112341. #endif
  112342. /* Insert code to test every subexpression that can be completely
  112343. ** computed using the current set of tables.
  112344. */
  112345. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  112346. Expr *pE;
  112347. int skipLikeAddr = 0;
  112348. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112349. testcase( pTerm->wtFlags & TERM_CODED );
  112350. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112351. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  112352. testcase( pWInfo->untestedTerms==0
  112353. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  112354. pWInfo->untestedTerms = 1;
  112355. continue;
  112356. }
  112357. pE = pTerm->pExpr;
  112358. assert( pE!=0 );
  112359. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  112360. continue;
  112361. }
  112362. if( pTerm->wtFlags & TERM_LIKECOND ){
  112363. assert( pLevel->iLikeRepCntr>0 );
  112364. skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
  112365. VdbeCoverage(v);
  112366. }
  112367. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  112368. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  112369. pTerm->wtFlags |= TERM_CODED;
  112370. }
  112371. /* Insert code to test for implied constraints based on transitivity
  112372. ** of the "==" operator.
  112373. **
  112374. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  112375. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  112376. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  112377. ** the implied "t1.a=123" constraint.
  112378. */
  112379. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  112380. Expr *pE, *pEAlt;
  112381. WhereTerm *pAlt;
  112382. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112383. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  112384. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  112385. if( pTerm->leftCursor!=iCur ) continue;
  112386. if( pLevel->iLeftJoin ) continue;
  112387. pE = pTerm->pExpr;
  112388. assert( !ExprHasProperty(pE, EP_FromJoin) );
  112389. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  112390. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  112391. WO_EQ|WO_IN|WO_IS, 0);
  112392. if( pAlt==0 ) continue;
  112393. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  112394. testcase( pAlt->eOperator & WO_EQ );
  112395. testcase( pAlt->eOperator & WO_IS );
  112396. testcase( pAlt->eOperator & WO_IN );
  112397. VdbeModuleComment((v, "begin transitive constraint"));
  112398. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  112399. if( pEAlt ){
  112400. *pEAlt = *pAlt->pExpr;
  112401. pEAlt->pLeft = pE->pLeft;
  112402. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  112403. sqlite3StackFree(db, pEAlt);
  112404. }
  112405. }
  112406. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  112407. ** at least one row of the right table has matched the left table.
  112408. */
  112409. if( pLevel->iLeftJoin ){
  112410. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  112411. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  112412. VdbeComment((v, "record LEFT JOIN hit"));
  112413. sqlite3ExprCacheClear(pParse);
  112414. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  112415. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112416. testcase( pTerm->wtFlags & TERM_CODED );
  112417. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112418. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  112419. assert( pWInfo->untestedTerms );
  112420. continue;
  112421. }
  112422. assert( pTerm->pExpr );
  112423. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  112424. pTerm->wtFlags |= TERM_CODED;
  112425. }
  112426. }
  112427. return pLevel->notReady;
  112428. }
  112429. /************** End of wherecode.c *******************************************/
  112430. /************** Begin file whereexpr.c ***************************************/
  112431. /*
  112432. ** 2015-06-08
  112433. **
  112434. ** The author disclaims copyright to this source code. In place of
  112435. ** a legal notice, here is a blessing:
  112436. **
  112437. ** May you do good and not evil.
  112438. ** May you find forgiveness for yourself and forgive others.
  112439. ** May you share freely, never taking more than you give.
  112440. **
  112441. *************************************************************************
  112442. ** This module contains C code that generates VDBE code used to process
  112443. ** the WHERE clause of SQL statements.
  112444. **
  112445. ** This file was originally part of where.c but was split out to improve
  112446. ** readability and editabiliity. This file contains utility routines for
  112447. ** analyzing Expr objects in the WHERE clause.
  112448. */
  112449. /* #include "sqliteInt.h" */
  112450. /* #include "whereInt.h" */
  112451. /* Forward declarations */
  112452. static void exprAnalyze(SrcList*, WhereClause*, int);
  112453. /*
  112454. ** Deallocate all memory associated with a WhereOrInfo object.
  112455. */
  112456. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  112457. sqlite3WhereClauseClear(&p->wc);
  112458. sqlite3DbFree(db, p);
  112459. }
  112460. /*
  112461. ** Deallocate all memory associated with a WhereAndInfo object.
  112462. */
  112463. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  112464. sqlite3WhereClauseClear(&p->wc);
  112465. sqlite3DbFree(db, p);
  112466. }
  112467. /*
  112468. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  112469. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  112470. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  112471. ** 0 is returned if the new WhereTerm could not be added due to a memory
  112472. ** allocation error. The memory allocation failure will be recorded in
  112473. ** the db->mallocFailed flag so that higher-level functions can detect it.
  112474. **
  112475. ** This routine will increase the size of the pWC->a[] array as necessary.
  112476. **
  112477. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  112478. ** for freeing the expression p is assumed by the WhereClause object pWC.
  112479. ** This is true even if this routine fails to allocate a new WhereTerm.
  112480. **
  112481. ** WARNING: This routine might reallocate the space used to store
  112482. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  112483. ** calling this routine. Such pointers may be reinitialized by referencing
  112484. ** the pWC->a[] array.
  112485. */
  112486. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  112487. WhereTerm *pTerm;
  112488. int idx;
  112489. testcase( wtFlags & TERM_VIRTUAL );
  112490. if( pWC->nTerm>=pWC->nSlot ){
  112491. WhereTerm *pOld = pWC->a;
  112492. sqlite3 *db = pWC->pWInfo->pParse->db;
  112493. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  112494. if( pWC->a==0 ){
  112495. if( wtFlags & TERM_DYNAMIC ){
  112496. sqlite3ExprDelete(db, p);
  112497. }
  112498. pWC->a = pOld;
  112499. return 0;
  112500. }
  112501. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  112502. if( pOld!=pWC->aStatic ){
  112503. sqlite3DbFree(db, pOld);
  112504. }
  112505. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  112506. memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
  112507. }
  112508. pTerm = &pWC->a[idx = pWC->nTerm++];
  112509. if( p && ExprHasProperty(p, EP_Unlikely) ){
  112510. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  112511. }else{
  112512. pTerm->truthProb = 1;
  112513. }
  112514. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  112515. pTerm->wtFlags = wtFlags;
  112516. pTerm->pWC = pWC;
  112517. pTerm->iParent = -1;
  112518. return idx;
  112519. }
  112520. /*
  112521. ** Return TRUE if the given operator is one of the operators that is
  112522. ** allowed for an indexable WHERE clause term. The allowed operators are
  112523. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  112524. */
  112525. static int allowedOp(int op){
  112526. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  112527. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  112528. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  112529. assert( TK_GE==TK_EQ+4 );
  112530. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  112531. }
  112532. /*
  112533. ** Commute a comparison operator. Expressions of the form "X op Y"
  112534. ** are converted into "Y op X".
  112535. **
  112536. ** If left/right precedence rules come into play when determining the
  112537. ** collating sequence, then COLLATE operators are adjusted to ensure
  112538. ** that the collating sequence does not change. For example:
  112539. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  112540. ** the left hand side of a comparison overrides any collation sequence
  112541. ** attached to the right. For the same reason the EP_Collate flag
  112542. ** is not commuted.
  112543. */
  112544. static void exprCommute(Parse *pParse, Expr *pExpr){
  112545. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  112546. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  112547. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  112548. if( expRight==expLeft ){
  112549. /* Either X and Y both have COLLATE operator or neither do */
  112550. if( expRight ){
  112551. /* Both X and Y have COLLATE operators. Make sure X is always
  112552. ** used by clearing the EP_Collate flag from Y. */
  112553. pExpr->pRight->flags &= ~EP_Collate;
  112554. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  112555. /* Neither X nor Y have COLLATE operators, but X has a non-default
  112556. ** collating sequence. So add the EP_Collate marker on X to cause
  112557. ** it to be searched first. */
  112558. pExpr->pLeft->flags |= EP_Collate;
  112559. }
  112560. }
  112561. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  112562. if( pExpr->op>=TK_GT ){
  112563. assert( TK_LT==TK_GT+2 );
  112564. assert( TK_GE==TK_LE+2 );
  112565. assert( TK_GT>TK_EQ );
  112566. assert( TK_GT<TK_LE );
  112567. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  112568. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  112569. }
  112570. }
  112571. /*
  112572. ** Translate from TK_xx operator to WO_xx bitmask.
  112573. */
  112574. static u16 operatorMask(int op){
  112575. u16 c;
  112576. assert( allowedOp(op) );
  112577. if( op==TK_IN ){
  112578. c = WO_IN;
  112579. }else if( op==TK_ISNULL ){
  112580. c = WO_ISNULL;
  112581. }else if( op==TK_IS ){
  112582. c = WO_IS;
  112583. }else{
  112584. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  112585. c = (u16)(WO_EQ<<(op-TK_EQ));
  112586. }
  112587. assert( op!=TK_ISNULL || c==WO_ISNULL );
  112588. assert( op!=TK_IN || c==WO_IN );
  112589. assert( op!=TK_EQ || c==WO_EQ );
  112590. assert( op!=TK_LT || c==WO_LT );
  112591. assert( op!=TK_LE || c==WO_LE );
  112592. assert( op!=TK_GT || c==WO_GT );
  112593. assert( op!=TK_GE || c==WO_GE );
  112594. assert( op!=TK_IS || c==WO_IS );
  112595. return c;
  112596. }
  112597. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  112598. /*
  112599. ** Check to see if the given expression is a LIKE or GLOB operator that
  112600. ** can be optimized using inequality constraints. Return TRUE if it is
  112601. ** so and false if not.
  112602. **
  112603. ** In order for the operator to be optimizible, the RHS must be a string
  112604. ** literal that does not begin with a wildcard. The LHS must be a column
  112605. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  112606. ** that virtual tables cannot participate in the LIKE optimization.) The
  112607. ** collating sequence for the column on the LHS must be appropriate for
  112608. ** the operator.
  112609. */
  112610. static int isLikeOrGlob(
  112611. Parse *pParse, /* Parsing and code generating context */
  112612. Expr *pExpr, /* Test this expression */
  112613. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  112614. int *pisComplete, /* True if the only wildcard is % in the last character */
  112615. int *pnoCase /* True if uppercase is equivalent to lowercase */
  112616. ){
  112617. const char *z = 0; /* String on RHS of LIKE operator */
  112618. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  112619. ExprList *pList; /* List of operands to the LIKE operator */
  112620. int c; /* One character in z[] */
  112621. int cnt; /* Number of non-wildcard prefix characters */
  112622. char wc[3]; /* Wildcard characters */
  112623. sqlite3 *db = pParse->db; /* Database connection */
  112624. sqlite3_value *pVal = 0;
  112625. int op; /* Opcode of pRight */
  112626. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  112627. return 0;
  112628. }
  112629. #ifdef SQLITE_EBCDIC
  112630. if( *pnoCase ) return 0;
  112631. #endif
  112632. pList = pExpr->x.pList;
  112633. pLeft = pList->a[1].pExpr;
  112634. if( pLeft->op!=TK_COLUMN
  112635. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  112636. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  112637. ){
  112638. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  112639. ** be the name of an indexed column with TEXT affinity. */
  112640. return 0;
  112641. }
  112642. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  112643. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  112644. op = pRight->op;
  112645. if( op==TK_VARIABLE ){
  112646. Vdbe *pReprepare = pParse->pReprepare;
  112647. int iCol = pRight->iColumn;
  112648. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  112649. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  112650. z = (char *)sqlite3_value_text(pVal);
  112651. }
  112652. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  112653. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  112654. }else if( op==TK_STRING ){
  112655. z = pRight->u.zToken;
  112656. }
  112657. if( z ){
  112658. cnt = 0;
  112659. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  112660. cnt++;
  112661. }
  112662. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  112663. Expr *pPrefix;
  112664. *pisComplete = c==wc[0] && z[cnt+1]==0;
  112665. pPrefix = sqlite3Expr(db, TK_STRING, z);
  112666. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  112667. *ppPrefix = pPrefix;
  112668. if( op==TK_VARIABLE ){
  112669. Vdbe *v = pParse->pVdbe;
  112670. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  112671. if( *pisComplete && pRight->u.zToken[1] ){
  112672. /* If the rhs of the LIKE expression is a variable, and the current
  112673. ** value of the variable means there is no need to invoke the LIKE
  112674. ** function, then no OP_Variable will be added to the program.
  112675. ** This causes problems for the sqlite3_bind_parameter_name()
  112676. ** API. To work around them, add a dummy OP_Variable here.
  112677. */
  112678. int r1 = sqlite3GetTempReg(pParse);
  112679. sqlite3ExprCodeTarget(pParse, pRight, r1);
  112680. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  112681. sqlite3ReleaseTempReg(pParse, r1);
  112682. }
  112683. }
  112684. }else{
  112685. z = 0;
  112686. }
  112687. }
  112688. sqlite3ValueFree(pVal);
  112689. return (z!=0);
  112690. }
  112691. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  112692. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112693. /*
  112694. ** Check to see if the given expression is of the form
  112695. **
  112696. ** column MATCH expr
  112697. **
  112698. ** If it is then return TRUE. If not, return FALSE.
  112699. */
  112700. static int isMatchOfColumn(
  112701. Expr *pExpr /* Test this expression */
  112702. ){
  112703. ExprList *pList;
  112704. if( pExpr->op!=TK_FUNCTION ){
  112705. return 0;
  112706. }
  112707. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  112708. return 0;
  112709. }
  112710. pList = pExpr->x.pList;
  112711. if( pList->nExpr!=2 ){
  112712. return 0;
  112713. }
  112714. if( pList->a[1].pExpr->op != TK_COLUMN ){
  112715. return 0;
  112716. }
  112717. return 1;
  112718. }
  112719. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  112720. /*
  112721. ** If the pBase expression originated in the ON or USING clause of
  112722. ** a join, then transfer the appropriate markings over to derived.
  112723. */
  112724. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  112725. if( pDerived ){
  112726. pDerived->flags |= pBase->flags & EP_FromJoin;
  112727. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  112728. }
  112729. }
  112730. /*
  112731. ** Mark term iChild as being a child of term iParent
  112732. */
  112733. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  112734. pWC->a[iChild].iParent = iParent;
  112735. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  112736. pWC->a[iParent].nChild++;
  112737. }
  112738. /*
  112739. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  112740. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  112741. ** the number of available subterms, return NULL.
  112742. */
  112743. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  112744. if( pTerm->eOperator!=WO_AND ){
  112745. return N==0 ? pTerm : 0;
  112746. }
  112747. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  112748. return &pTerm->u.pAndInfo->wc.a[N];
  112749. }
  112750. return 0;
  112751. }
  112752. /*
  112753. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  112754. ** two subterms are in disjunction - they are OR-ed together.
  112755. **
  112756. ** If these two terms are both of the form: "A op B" with the same
  112757. ** A and B values but different operators and if the operators are
  112758. ** compatible (if one is = and the other is <, for example) then
  112759. ** add a new virtual AND term to pWC that is the combination of the
  112760. ** two.
  112761. **
  112762. ** Some examples:
  112763. **
  112764. ** x<y OR x=y --> x<=y
  112765. ** x=y OR x=y --> x=y
  112766. ** x<=y OR x<y --> x<=y
  112767. **
  112768. ** The following is NOT generated:
  112769. **
  112770. ** x<y OR x>y --> x!=y
  112771. */
  112772. static void whereCombineDisjuncts(
  112773. SrcList *pSrc, /* the FROM clause */
  112774. WhereClause *pWC, /* The complete WHERE clause */
  112775. WhereTerm *pOne, /* First disjunct */
  112776. WhereTerm *pTwo /* Second disjunct */
  112777. ){
  112778. u16 eOp = pOne->eOperator | pTwo->eOperator;
  112779. sqlite3 *db; /* Database connection (for malloc) */
  112780. Expr *pNew; /* New virtual expression */
  112781. int op; /* Operator for the combined expression */
  112782. int idxNew; /* Index in pWC of the next virtual term */
  112783. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  112784. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  112785. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  112786. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  112787. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  112788. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  112789. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  112790. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  112791. /* If we reach this point, it means the two subterms can be combined */
  112792. if( (eOp & (eOp-1))!=0 ){
  112793. if( eOp & (WO_LT|WO_LE) ){
  112794. eOp = WO_LE;
  112795. }else{
  112796. assert( eOp & (WO_GT|WO_GE) );
  112797. eOp = WO_GE;
  112798. }
  112799. }
  112800. db = pWC->pWInfo->pParse->db;
  112801. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  112802. if( pNew==0 ) return;
  112803. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  112804. pNew->op = op;
  112805. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  112806. exprAnalyze(pSrc, pWC, idxNew);
  112807. }
  112808. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  112809. /*
  112810. ** Analyze a term that consists of two or more OR-connected
  112811. ** subterms. So in:
  112812. **
  112813. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  112814. ** ^^^^^^^^^^^^^^^^^^^^
  112815. **
  112816. ** This routine analyzes terms such as the middle term in the above example.
  112817. ** A WhereOrTerm object is computed and attached to the term under
  112818. ** analysis, regardless of the outcome of the analysis. Hence:
  112819. **
  112820. ** WhereTerm.wtFlags |= TERM_ORINFO
  112821. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  112822. **
  112823. ** The term being analyzed must have two or more of OR-connected subterms.
  112824. ** A single subterm might be a set of AND-connected sub-subterms.
  112825. ** Examples of terms under analysis:
  112826. **
  112827. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  112828. ** (B) x=expr1 OR expr2=x OR x=expr3
  112829. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  112830. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  112831. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  112832. ** (F) x>A OR (x=A AND y>=B)
  112833. **
  112834. ** CASE 1:
  112835. **
  112836. ** If all subterms are of the form T.C=expr for some single column of C and
  112837. ** a single table T (as shown in example B above) then create a new virtual
  112838. ** term that is an equivalent IN expression. In other words, if the term
  112839. ** being analyzed is:
  112840. **
  112841. ** x = expr1 OR expr2 = x OR x = expr3
  112842. **
  112843. ** then create a new virtual term like this:
  112844. **
  112845. ** x IN (expr1,expr2,expr3)
  112846. **
  112847. ** CASE 2:
  112848. **
  112849. ** If there are exactly two disjuncts and one side has x>A and the other side
  112850. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  112851. ** WHERE clause of the form "x>=A". Example:
  112852. **
  112853. ** x>A OR (x=A AND y>B) adds: x>=A
  112854. **
  112855. ** The added conjunct can sometimes be helpful in query planning.
  112856. **
  112857. ** CASE 3:
  112858. **
  112859. ** If all subterms are indexable by a single table T, then set
  112860. **
  112861. ** WhereTerm.eOperator = WO_OR
  112862. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  112863. **
  112864. ** A subterm is "indexable" if it is of the form
  112865. ** "T.C <op> <expr>" where C is any column of table T and
  112866. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  112867. ** A subterm is also indexable if it is an AND of two or more
  112868. ** subsubterms at least one of which is indexable. Indexable AND
  112869. ** subterms have their eOperator set to WO_AND and they have
  112870. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  112871. **
  112872. ** From another point of view, "indexable" means that the subterm could
  112873. ** potentially be used with an index if an appropriate index exists.
  112874. ** This analysis does not consider whether or not the index exists; that
  112875. ** is decided elsewhere. This analysis only looks at whether subterms
  112876. ** appropriate for indexing exist.
  112877. **
  112878. ** All examples A through E above satisfy case 3. But if a term
  112879. ** also satisfies case 1 (such as B) we know that the optimizer will
  112880. ** always prefer case 1, so in that case we pretend that case 3 is not
  112881. ** satisfied.
  112882. **
  112883. ** It might be the case that multiple tables are indexable. For example,
  112884. ** (E) above is indexable on tables P, Q, and R.
  112885. **
  112886. ** Terms that satisfy case 3 are candidates for lookup by using
  112887. ** separate indices to find rowids for each subterm and composing
  112888. ** the union of all rowids using a RowSet object. This is similar
  112889. ** to "bitmap indices" in other database engines.
  112890. **
  112891. ** OTHERWISE:
  112892. **
  112893. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  112894. ** zero. This term is not useful for search.
  112895. */
  112896. static void exprAnalyzeOrTerm(
  112897. SrcList *pSrc, /* the FROM clause */
  112898. WhereClause *pWC, /* the complete WHERE clause */
  112899. int idxTerm /* Index of the OR-term to be analyzed */
  112900. ){
  112901. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  112902. Parse *pParse = pWInfo->pParse; /* Parser context */
  112903. sqlite3 *db = pParse->db; /* Database connection */
  112904. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  112905. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  112906. int i; /* Loop counters */
  112907. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  112908. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  112909. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  112910. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  112911. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  112912. /*
  112913. ** Break the OR clause into its separate subterms. The subterms are
  112914. ** stored in a WhereClause structure containing within the WhereOrInfo
  112915. ** object that is attached to the original OR clause term.
  112916. */
  112917. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  112918. assert( pExpr->op==TK_OR );
  112919. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  112920. if( pOrInfo==0 ) return;
  112921. pTerm->wtFlags |= TERM_ORINFO;
  112922. pOrWc = &pOrInfo->wc;
  112923. sqlite3WhereClauseInit(pOrWc, pWInfo);
  112924. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  112925. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  112926. if( db->mallocFailed ) return;
  112927. assert( pOrWc->nTerm>=2 );
  112928. /*
  112929. ** Compute the set of tables that might satisfy cases 1 or 3.
  112930. */
  112931. indexable = ~(Bitmask)0;
  112932. chngToIN = ~(Bitmask)0;
  112933. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  112934. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  112935. WhereAndInfo *pAndInfo;
  112936. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  112937. chngToIN = 0;
  112938. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  112939. if( pAndInfo ){
  112940. WhereClause *pAndWC;
  112941. WhereTerm *pAndTerm;
  112942. int j;
  112943. Bitmask b = 0;
  112944. pOrTerm->u.pAndInfo = pAndInfo;
  112945. pOrTerm->wtFlags |= TERM_ANDINFO;
  112946. pOrTerm->eOperator = WO_AND;
  112947. pAndWC = &pAndInfo->wc;
  112948. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  112949. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  112950. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  112951. pAndWC->pOuter = pWC;
  112952. testcase( db->mallocFailed );
  112953. if( !db->mallocFailed ){
  112954. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  112955. assert( pAndTerm->pExpr );
  112956. if( allowedOp(pAndTerm->pExpr->op) ){
  112957. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  112958. }
  112959. }
  112960. }
  112961. indexable &= b;
  112962. }
  112963. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  112964. /* Skip this term for now. We revisit it when we process the
  112965. ** corresponding TERM_VIRTUAL term */
  112966. }else{
  112967. Bitmask b;
  112968. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  112969. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  112970. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  112971. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  112972. }
  112973. indexable &= b;
  112974. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  112975. chngToIN = 0;
  112976. }else{
  112977. chngToIN &= b;
  112978. }
  112979. }
  112980. }
  112981. /*
  112982. ** Record the set of tables that satisfy case 3. The set might be
  112983. ** empty.
  112984. */
  112985. pOrInfo->indexable = indexable;
  112986. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  112987. /* For a two-way OR, attempt to implementation case 2.
  112988. */
  112989. if( indexable && pOrWc->nTerm==2 ){
  112990. int iOne = 0;
  112991. WhereTerm *pOne;
  112992. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  112993. int iTwo = 0;
  112994. WhereTerm *pTwo;
  112995. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  112996. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  112997. }
  112998. }
  112999. }
  113000. /*
  113001. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  113002. ** we have to do some additional checking to see if case 1 really
  113003. ** is satisfied.
  113004. **
  113005. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  113006. ** that there is no possibility of transforming the OR clause into an
  113007. ** IN operator because one or more terms in the OR clause contain
  113008. ** something other than == on a column in the single table. The 1-bit
  113009. ** case means that every term of the OR clause is of the form
  113010. ** "table.column=expr" for some single table. The one bit that is set
  113011. ** will correspond to the common table. We still need to check to make
  113012. ** sure the same column is used on all terms. The 2-bit case is when
  113013. ** the all terms are of the form "table1.column=table2.column". It
  113014. ** might be possible to form an IN operator with either table1.column
  113015. ** or table2.column as the LHS if either is common to every term of
  113016. ** the OR clause.
  113017. **
  113018. ** Note that terms of the form "table.column1=table.column2" (the
  113019. ** same table on both sizes of the ==) cannot be optimized.
  113020. */
  113021. if( chngToIN ){
  113022. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  113023. int iColumn = -1; /* Column index on lhs of IN operator */
  113024. int iCursor = -1; /* Table cursor common to all terms */
  113025. int j = 0; /* Loop counter */
  113026. /* Search for a table and column that appears on one side or the
  113027. ** other of the == operator in every subterm. That table and column
  113028. ** will be recorded in iCursor and iColumn. There might not be any
  113029. ** such table and column. Set okToChngToIN if an appropriate table
  113030. ** and column is found but leave okToChngToIN false if not found.
  113031. */
  113032. for(j=0; j<2 && !okToChngToIN; j++){
  113033. pOrTerm = pOrWc->a;
  113034. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  113035. assert( pOrTerm->eOperator & WO_EQ );
  113036. pOrTerm->wtFlags &= ~TERM_OR_OK;
  113037. if( pOrTerm->leftCursor==iCursor ){
  113038. /* This is the 2-bit case and we are on the second iteration and
  113039. ** current term is from the first iteration. So skip this term. */
  113040. assert( j==1 );
  113041. continue;
  113042. }
  113043. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  113044. pOrTerm->leftCursor))==0 ){
  113045. /* This term must be of the form t1.a==t2.b where t2 is in the
  113046. ** chngToIN set but t1 is not. This term will be either preceded
  113047. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  113048. ** and use its inversion. */
  113049. testcase( pOrTerm->wtFlags & TERM_COPIED );
  113050. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  113051. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  113052. continue;
  113053. }
  113054. iColumn = pOrTerm->u.leftColumn;
  113055. iCursor = pOrTerm->leftCursor;
  113056. break;
  113057. }
  113058. if( i<0 ){
  113059. /* No candidate table+column was found. This can only occur
  113060. ** on the second iteration */
  113061. assert( j==1 );
  113062. assert( IsPowerOfTwo(chngToIN) );
  113063. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  113064. break;
  113065. }
  113066. testcase( j==1 );
  113067. /* We have found a candidate table and column. Check to see if that
  113068. ** table and column is common to every term in the OR clause */
  113069. okToChngToIN = 1;
  113070. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  113071. assert( pOrTerm->eOperator & WO_EQ );
  113072. if( pOrTerm->leftCursor!=iCursor ){
  113073. pOrTerm->wtFlags &= ~TERM_OR_OK;
  113074. }else if( pOrTerm->u.leftColumn!=iColumn ){
  113075. okToChngToIN = 0;
  113076. }else{
  113077. int affLeft, affRight;
  113078. /* If the right-hand side is also a column, then the affinities
  113079. ** of both right and left sides must be such that no type
  113080. ** conversions are required on the right. (Ticket #2249)
  113081. */
  113082. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  113083. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  113084. if( affRight!=0 && affRight!=affLeft ){
  113085. okToChngToIN = 0;
  113086. }else{
  113087. pOrTerm->wtFlags |= TERM_OR_OK;
  113088. }
  113089. }
  113090. }
  113091. }
  113092. /* At this point, okToChngToIN is true if original pTerm satisfies
  113093. ** case 1. In that case, construct a new virtual term that is
  113094. ** pTerm converted into an IN operator.
  113095. */
  113096. if( okToChngToIN ){
  113097. Expr *pDup; /* A transient duplicate expression */
  113098. ExprList *pList = 0; /* The RHS of the IN operator */
  113099. Expr *pLeft = 0; /* The LHS of the IN operator */
  113100. Expr *pNew; /* The complete IN operator */
  113101. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  113102. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  113103. assert( pOrTerm->eOperator & WO_EQ );
  113104. assert( pOrTerm->leftCursor==iCursor );
  113105. assert( pOrTerm->u.leftColumn==iColumn );
  113106. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  113107. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  113108. pLeft = pOrTerm->pExpr->pLeft;
  113109. }
  113110. assert( pLeft!=0 );
  113111. pDup = sqlite3ExprDup(db, pLeft, 0);
  113112. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  113113. if( pNew ){
  113114. int idxNew;
  113115. transferJoinMarkings(pNew, pExpr);
  113116. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  113117. pNew->x.pList = pList;
  113118. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  113119. testcase( idxNew==0 );
  113120. exprAnalyze(pSrc, pWC, idxNew);
  113121. pTerm = &pWC->a[idxTerm];
  113122. markTermAsChild(pWC, idxNew, idxTerm);
  113123. }else{
  113124. sqlite3ExprListDelete(db, pList);
  113125. }
  113126. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  113127. }
  113128. }
  113129. }
  113130. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  113131. /*
  113132. ** We already know that pExpr is a binary operator where both operands are
  113133. ** column references. This routine checks to see if pExpr is an equivalence
  113134. ** relation:
  113135. ** 1. The SQLITE_Transitive optimization must be enabled
  113136. ** 2. Must be either an == or an IS operator
  113137. ** 3. Not originating in the ON clause of an OUTER JOIN
  113138. ** 4. The affinities of A and B must be compatible
  113139. ** 5a. Both operands use the same collating sequence OR
  113140. ** 5b. The overall collating sequence is BINARY
  113141. ** If this routine returns TRUE, that means that the RHS can be substituted
  113142. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  113143. ** This is an optimization. No harm comes from returning 0. But if 1 is
  113144. ** returned when it should not be, then incorrect answers might result.
  113145. */
  113146. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  113147. char aff1, aff2;
  113148. CollSeq *pColl;
  113149. const char *zColl1, *zColl2;
  113150. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  113151. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  113152. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  113153. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  113154. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  113155. if( aff1!=aff2
  113156. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  113157. ){
  113158. return 0;
  113159. }
  113160. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  113161. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  113162. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  113163. /* Since pLeft and pRight are both a column references, their collating
  113164. ** sequence should always be defined. */
  113165. zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
  113166. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  113167. zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
  113168. return sqlite3StrICmp(zColl1, zColl2)==0;
  113169. }
  113170. /*
  113171. ** Recursively walk the expressions of a SELECT statement and generate
  113172. ** a bitmask indicating which tables are used in that expression
  113173. ** tree.
  113174. */
  113175. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  113176. Bitmask mask = 0;
  113177. while( pS ){
  113178. SrcList *pSrc = pS->pSrc;
  113179. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  113180. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  113181. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  113182. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  113183. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  113184. if( ALWAYS(pSrc!=0) ){
  113185. int i;
  113186. for(i=0; i<pSrc->nSrc; i++){
  113187. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  113188. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  113189. }
  113190. }
  113191. pS = pS->pPrior;
  113192. }
  113193. return mask;
  113194. }
  113195. /*
  113196. ** Expression pExpr is one operand of a comparison operator that might
  113197. ** be useful for indexing. This routine checks to see if pExpr appears
  113198. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  113199. ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
  113200. ** number of the table that is indexed and *piColumn to the column number
  113201. ** of the column that is indexed, or -2 if an expression is being indexed.
  113202. **
  113203. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  113204. ** true even if that particular column is not indexed, because the column
  113205. ** might be added to an automatic index later.
  113206. */
  113207. static int exprMightBeIndexed(
  113208. SrcList *pFrom, /* The FROM clause */
  113209. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  113210. Expr *pExpr, /* An operand of a comparison operator */
  113211. int *piCur, /* Write the referenced table cursor number here */
  113212. int *piColumn /* Write the referenced table column number here */
  113213. ){
  113214. Index *pIdx;
  113215. int i;
  113216. int iCur;
  113217. if( pExpr->op==TK_COLUMN ){
  113218. *piCur = pExpr->iTable;
  113219. *piColumn = pExpr->iColumn;
  113220. return 1;
  113221. }
  113222. if( mPrereq==0 ) return 0; /* No table references */
  113223. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  113224. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  113225. iCur = pFrom->a[i].iCursor;
  113226. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  113227. if( pIdx->aColExpr==0 ) continue;
  113228. for(i=0; i<pIdx->nKeyCol; i++){
  113229. if( pIdx->aiColumn[i]!=(-2) ) continue;
  113230. if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  113231. *piCur = iCur;
  113232. *piColumn = -2;
  113233. return 1;
  113234. }
  113235. }
  113236. }
  113237. return 0;
  113238. }
  113239. /*
  113240. ** The input to this routine is an WhereTerm structure with only the
  113241. ** "pExpr" field filled in. The job of this routine is to analyze the
  113242. ** subexpression and populate all the other fields of the WhereTerm
  113243. ** structure.
  113244. **
  113245. ** If the expression is of the form "<expr> <op> X" it gets commuted
  113246. ** to the standard form of "X <op> <expr>".
  113247. **
  113248. ** If the expression is of the form "X <op> Y" where both X and Y are
  113249. ** columns, then the original expression is unchanged and a new virtual
  113250. ** term of the form "Y <op> X" is added to the WHERE clause and
  113251. ** analyzed separately. The original term is marked with TERM_COPIED
  113252. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  113253. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  113254. ** is a commuted copy of a prior term.) The original term has nChild=1
  113255. ** and the copy has idxParent set to the index of the original term.
  113256. */
  113257. static void exprAnalyze(
  113258. SrcList *pSrc, /* the FROM clause */
  113259. WhereClause *pWC, /* the WHERE clause */
  113260. int idxTerm /* Index of the term to be analyzed */
  113261. ){
  113262. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  113263. WhereTerm *pTerm; /* The term to be analyzed */
  113264. WhereMaskSet *pMaskSet; /* Set of table index masks */
  113265. Expr *pExpr; /* The expression to be analyzed */
  113266. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  113267. Bitmask prereqAll; /* Prerequesites of pExpr */
  113268. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  113269. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  113270. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  113271. int noCase = 0; /* uppercase equivalent to lowercase */
  113272. int op; /* Top-level operator. pExpr->op */
  113273. Parse *pParse = pWInfo->pParse; /* Parsing context */
  113274. sqlite3 *db = pParse->db; /* Database connection */
  113275. if( db->mallocFailed ){
  113276. return;
  113277. }
  113278. pTerm = &pWC->a[idxTerm];
  113279. pMaskSet = &pWInfo->sMaskSet;
  113280. pExpr = pTerm->pExpr;
  113281. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  113282. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  113283. op = pExpr->op;
  113284. if( op==TK_IN ){
  113285. assert( pExpr->pRight==0 );
  113286. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  113287. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  113288. }else{
  113289. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  113290. }
  113291. }else if( op==TK_ISNULL ){
  113292. pTerm->prereqRight = 0;
  113293. }else{
  113294. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  113295. }
  113296. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  113297. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  113298. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  113299. prereqAll |= x;
  113300. extraRight = x-1; /* ON clause terms may not be used with an index
  113301. ** on left table of a LEFT JOIN. Ticket #3015 */
  113302. }
  113303. pTerm->prereqAll = prereqAll;
  113304. pTerm->leftCursor = -1;
  113305. pTerm->iParent = -1;
  113306. pTerm->eOperator = 0;
  113307. if( allowedOp(op) ){
  113308. int iCur, iColumn;
  113309. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  113310. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  113311. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  113312. if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
  113313. pTerm->leftCursor = iCur;
  113314. pTerm->u.leftColumn = iColumn;
  113315. pTerm->eOperator = operatorMask(op) & opMask;
  113316. }
  113317. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  113318. if( pRight
  113319. && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
  113320. ){
  113321. WhereTerm *pNew;
  113322. Expr *pDup;
  113323. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  113324. if( pTerm->leftCursor>=0 ){
  113325. int idxNew;
  113326. pDup = sqlite3ExprDup(db, pExpr, 0);
  113327. if( db->mallocFailed ){
  113328. sqlite3ExprDelete(db, pDup);
  113329. return;
  113330. }
  113331. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  113332. if( idxNew==0 ) return;
  113333. pNew = &pWC->a[idxNew];
  113334. markTermAsChild(pWC, idxNew, idxTerm);
  113335. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  113336. pTerm = &pWC->a[idxTerm];
  113337. pTerm->wtFlags |= TERM_COPIED;
  113338. if( termIsEquivalence(pParse, pDup) ){
  113339. pTerm->eOperator |= WO_EQUIV;
  113340. eExtraOp = WO_EQUIV;
  113341. }
  113342. }else{
  113343. pDup = pExpr;
  113344. pNew = pTerm;
  113345. }
  113346. exprCommute(pParse, pDup);
  113347. pNew->leftCursor = iCur;
  113348. pNew->u.leftColumn = iColumn;
  113349. testcase( (prereqLeft | extraRight) != prereqLeft );
  113350. pNew->prereqRight = prereqLeft | extraRight;
  113351. pNew->prereqAll = prereqAll;
  113352. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  113353. }
  113354. }
  113355. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  113356. /* If a term is the BETWEEN operator, create two new virtual terms
  113357. ** that define the range that the BETWEEN implements. For example:
  113358. **
  113359. ** a BETWEEN b AND c
  113360. **
  113361. ** is converted into:
  113362. **
  113363. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  113364. **
  113365. ** The two new terms are added onto the end of the WhereClause object.
  113366. ** The new terms are "dynamic" and are children of the original BETWEEN
  113367. ** term. That means that if the BETWEEN term is coded, the children are
  113368. ** skipped. Or, if the children are satisfied by an index, the original
  113369. ** BETWEEN term is skipped.
  113370. */
  113371. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  113372. ExprList *pList = pExpr->x.pList;
  113373. int i;
  113374. static const u8 ops[] = {TK_GE, TK_LE};
  113375. assert( pList!=0 );
  113376. assert( pList->nExpr==2 );
  113377. for(i=0; i<2; i++){
  113378. Expr *pNewExpr;
  113379. int idxNew;
  113380. pNewExpr = sqlite3PExpr(pParse, ops[i],
  113381. sqlite3ExprDup(db, pExpr->pLeft, 0),
  113382. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  113383. transferJoinMarkings(pNewExpr, pExpr);
  113384. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  113385. testcase( idxNew==0 );
  113386. exprAnalyze(pSrc, pWC, idxNew);
  113387. pTerm = &pWC->a[idxTerm];
  113388. markTermAsChild(pWC, idxNew, idxTerm);
  113389. }
  113390. }
  113391. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  113392. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  113393. /* Analyze a term that is composed of two or more subterms connected by
  113394. ** an OR operator.
  113395. */
  113396. else if( pExpr->op==TK_OR ){
  113397. assert( pWC->op==TK_AND );
  113398. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  113399. pTerm = &pWC->a[idxTerm];
  113400. }
  113401. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  113402. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  113403. /* Add constraints to reduce the search space on a LIKE or GLOB
  113404. ** operator.
  113405. **
  113406. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  113407. **
  113408. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  113409. **
  113410. ** The last character of the prefix "abc" is incremented to form the
  113411. ** termination condition "abd". If case is not significant (the default
  113412. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  113413. ** bound is made all lowercase so that the bounds also work when comparing
  113414. ** BLOBs.
  113415. */
  113416. if( pWC->op==TK_AND
  113417. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  113418. ){
  113419. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  113420. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  113421. Expr *pNewExpr1;
  113422. Expr *pNewExpr2;
  113423. int idxNew1;
  113424. int idxNew2;
  113425. const char *zCollSeqName; /* Name of collating sequence */
  113426. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  113427. pLeft = pExpr->x.pList->a[1].pExpr;
  113428. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  113429. /* Convert the lower bound to upper-case and the upper bound to
  113430. ** lower-case (upper-case is less than lower-case in ASCII) so that
  113431. ** the range constraints also work for BLOBs
  113432. */
  113433. if( noCase && !pParse->db->mallocFailed ){
  113434. int i;
  113435. char c;
  113436. pTerm->wtFlags |= TERM_LIKE;
  113437. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  113438. pStr1->u.zToken[i] = sqlite3Toupper(c);
  113439. pStr2->u.zToken[i] = sqlite3Tolower(c);
  113440. }
  113441. }
  113442. if( !db->mallocFailed ){
  113443. u8 c, *pC; /* Last character before the first wildcard */
  113444. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  113445. c = *pC;
  113446. if( noCase ){
  113447. /* The point is to increment the last character before the first
  113448. ** wildcard. But if we increment '@', that will push it into the
  113449. ** alphabetic range where case conversions will mess up the
  113450. ** inequality. To avoid this, make sure to also run the full
  113451. ** LIKE on all candidate expressions by clearing the isComplete flag
  113452. */
  113453. if( c=='A'-1 ) isComplete = 0;
  113454. c = sqlite3UpperToLower[c];
  113455. }
  113456. *pC = c + 1;
  113457. }
  113458. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  113459. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  113460. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  113461. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  113462. pStr1, 0);
  113463. transferJoinMarkings(pNewExpr1, pExpr);
  113464. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  113465. testcase( idxNew1==0 );
  113466. exprAnalyze(pSrc, pWC, idxNew1);
  113467. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  113468. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  113469. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  113470. pStr2, 0);
  113471. transferJoinMarkings(pNewExpr2, pExpr);
  113472. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  113473. testcase( idxNew2==0 );
  113474. exprAnalyze(pSrc, pWC, idxNew2);
  113475. pTerm = &pWC->a[idxTerm];
  113476. if( isComplete ){
  113477. markTermAsChild(pWC, idxNew1, idxTerm);
  113478. markTermAsChild(pWC, idxNew2, idxTerm);
  113479. }
  113480. }
  113481. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  113482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113483. /* Add a WO_MATCH auxiliary term to the constraint set if the
  113484. ** current expression is of the form: column MATCH expr.
  113485. ** This information is used by the xBestIndex methods of
  113486. ** virtual tables. The native query optimizer does not attempt
  113487. ** to do anything with MATCH functions.
  113488. */
  113489. if( isMatchOfColumn(pExpr) ){
  113490. int idxNew;
  113491. Expr *pRight, *pLeft;
  113492. WhereTerm *pNewTerm;
  113493. Bitmask prereqColumn, prereqExpr;
  113494. pRight = pExpr->x.pList->a[0].pExpr;
  113495. pLeft = pExpr->x.pList->a[1].pExpr;
  113496. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  113497. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  113498. if( (prereqExpr & prereqColumn)==0 ){
  113499. Expr *pNewExpr;
  113500. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  113501. 0, sqlite3ExprDup(db, pRight, 0), 0);
  113502. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  113503. testcase( idxNew==0 );
  113504. pNewTerm = &pWC->a[idxNew];
  113505. pNewTerm->prereqRight = prereqExpr;
  113506. pNewTerm->leftCursor = pLeft->iTable;
  113507. pNewTerm->u.leftColumn = pLeft->iColumn;
  113508. pNewTerm->eOperator = WO_MATCH;
  113509. markTermAsChild(pWC, idxNew, idxTerm);
  113510. pTerm = &pWC->a[idxTerm];
  113511. pTerm->wtFlags |= TERM_COPIED;
  113512. pNewTerm->prereqAll = pTerm->prereqAll;
  113513. }
  113514. }
  113515. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  113516. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113517. /* When sqlite_stat3 histogram data is available an operator of the
  113518. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  113519. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  113520. ** virtual term of that form.
  113521. **
  113522. ** Note that the virtual term must be tagged with TERM_VNULL.
  113523. */
  113524. if( pExpr->op==TK_NOTNULL
  113525. && pExpr->pLeft->op==TK_COLUMN
  113526. && pExpr->pLeft->iColumn>=0
  113527. && OptimizationEnabled(db, SQLITE_Stat34)
  113528. ){
  113529. Expr *pNewExpr;
  113530. Expr *pLeft = pExpr->pLeft;
  113531. int idxNew;
  113532. WhereTerm *pNewTerm;
  113533. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  113534. sqlite3ExprDup(db, pLeft, 0),
  113535. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  113536. idxNew = whereClauseInsert(pWC, pNewExpr,
  113537. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  113538. if( idxNew ){
  113539. pNewTerm = &pWC->a[idxNew];
  113540. pNewTerm->prereqRight = 0;
  113541. pNewTerm->leftCursor = pLeft->iTable;
  113542. pNewTerm->u.leftColumn = pLeft->iColumn;
  113543. pNewTerm->eOperator = WO_GT;
  113544. markTermAsChild(pWC, idxNew, idxTerm);
  113545. pTerm = &pWC->a[idxTerm];
  113546. pTerm->wtFlags |= TERM_COPIED;
  113547. pNewTerm->prereqAll = pTerm->prereqAll;
  113548. }
  113549. }
  113550. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  113551. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  113552. ** an index for tables to the left of the join.
  113553. */
  113554. pTerm->prereqRight |= extraRight;
  113555. }
  113556. /***************************************************************************
  113557. ** Routines with file scope above. Interface to the rest of the where.c
  113558. ** subsystem follows.
  113559. ***************************************************************************/
  113560. /*
  113561. ** This routine identifies subexpressions in the WHERE clause where
  113562. ** each subexpression is separated by the AND operator or some other
  113563. ** operator specified in the op parameter. The WhereClause structure
  113564. ** is filled with pointers to subexpressions. For example:
  113565. **
  113566. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  113567. ** \________/ \_______________/ \________________/
  113568. ** slot[0] slot[1] slot[2]
  113569. **
  113570. ** The original WHERE clause in pExpr is unaltered. All this routine
  113571. ** does is make slot[] entries point to substructure within pExpr.
  113572. **
  113573. ** In the previous sentence and in the diagram, "slot[]" refers to
  113574. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  113575. ** all terms of the WHERE clause.
  113576. */
  113577. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  113578. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  113579. pWC->op = op;
  113580. if( pE2==0 ) return;
  113581. if( pE2->op!=op ){
  113582. whereClauseInsert(pWC, pExpr, 0);
  113583. }else{
  113584. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  113585. sqlite3WhereSplit(pWC, pE2->pRight, op);
  113586. }
  113587. }
  113588. /*
  113589. ** Initialize a preallocated WhereClause structure.
  113590. */
  113591. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  113592. WhereClause *pWC, /* The WhereClause to be initialized */
  113593. WhereInfo *pWInfo /* The WHERE processing context */
  113594. ){
  113595. pWC->pWInfo = pWInfo;
  113596. pWC->pOuter = 0;
  113597. pWC->nTerm = 0;
  113598. pWC->nSlot = ArraySize(pWC->aStatic);
  113599. pWC->a = pWC->aStatic;
  113600. }
  113601. /*
  113602. ** Deallocate a WhereClause structure. The WhereClause structure
  113603. ** itself is not freed. This routine is the inverse of sqlite3WhereClauseInit().
  113604. */
  113605. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  113606. int i;
  113607. WhereTerm *a;
  113608. sqlite3 *db = pWC->pWInfo->pParse->db;
  113609. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  113610. if( a->wtFlags & TERM_DYNAMIC ){
  113611. sqlite3ExprDelete(db, a->pExpr);
  113612. }
  113613. if( a->wtFlags & TERM_ORINFO ){
  113614. whereOrInfoDelete(db, a->u.pOrInfo);
  113615. }else if( a->wtFlags & TERM_ANDINFO ){
  113616. whereAndInfoDelete(db, a->u.pAndInfo);
  113617. }
  113618. }
  113619. if( pWC->a!=pWC->aStatic ){
  113620. sqlite3DbFree(db, pWC->a);
  113621. }
  113622. }
  113623. /*
  113624. ** These routines walk (recursively) an expression tree and generate
  113625. ** a bitmask indicating which tables are used in that expression
  113626. ** tree.
  113627. */
  113628. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  113629. Bitmask mask = 0;
  113630. if( p==0 ) return 0;
  113631. if( p->op==TK_COLUMN ){
  113632. mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
  113633. return mask;
  113634. }
  113635. mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
  113636. mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  113637. if( ExprHasProperty(p, EP_xIsSelect) ){
  113638. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  113639. }else{
  113640. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  113641. }
  113642. return mask;
  113643. }
  113644. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  113645. int i;
  113646. Bitmask mask = 0;
  113647. if( pList ){
  113648. for(i=0; i<pList->nExpr; i++){
  113649. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  113650. }
  113651. }
  113652. return mask;
  113653. }
  113654. /*
  113655. ** Call exprAnalyze on all terms in a WHERE clause.
  113656. **
  113657. ** Note that exprAnalyze() might add new virtual terms onto the
  113658. ** end of the WHERE clause. We do not want to analyze these new
  113659. ** virtual terms, so start analyzing at the end and work forward
  113660. ** so that the added virtual terms are never processed.
  113661. */
  113662. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  113663. SrcList *pTabList, /* the FROM clause */
  113664. WhereClause *pWC /* the WHERE clause to be analyzed */
  113665. ){
  113666. int i;
  113667. for(i=pWC->nTerm-1; i>=0; i--){
  113668. exprAnalyze(pTabList, pWC, i);
  113669. }
  113670. }
  113671. /*
  113672. ** For table-valued-functions, transform the function arguments into
  113673. ** new WHERE clause terms.
  113674. **
  113675. ** Each function argument translates into an equality constraint against
  113676. ** a HIDDEN column in the table.
  113677. */
  113678. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  113679. Parse *pParse, /* Parsing context */
  113680. struct SrcList_item *pItem, /* The FROM clause term to process */
  113681. WhereClause *pWC /* Xfer function arguments to here */
  113682. ){
  113683. Table *pTab;
  113684. int j, k;
  113685. ExprList *pArgs;
  113686. Expr *pColRef;
  113687. Expr *pTerm;
  113688. if( pItem->fg.isTabFunc==0 ) return;
  113689. pTab = pItem->pTab;
  113690. assert( pTab!=0 );
  113691. pArgs = pItem->u1.pFuncArg;
  113692. assert( pArgs!=0 );
  113693. for(j=k=0; j<pArgs->nExpr; j++){
  113694. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){ k++; }
  113695. if( k>=pTab->nCol ){
  113696. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  113697. pTab->zName, j);
  113698. return;
  113699. }
  113700. pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  113701. if( pColRef==0 ) return;
  113702. pColRef->iTable = pItem->iCursor;
  113703. pColRef->iColumn = k++;
  113704. pColRef->pTab = pTab;
  113705. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  113706. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  113707. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  113708. }
  113709. }
  113710. /************** End of whereexpr.c *******************************************/
  113711. /************** Begin file where.c *******************************************/
  113712. /*
  113713. ** 2001 September 15
  113714. **
  113715. ** The author disclaims copyright to this source code. In place of
  113716. ** a legal notice, here is a blessing:
  113717. **
  113718. ** May you do good and not evil.
  113719. ** May you find forgiveness for yourself and forgive others.
  113720. ** May you share freely, never taking more than you give.
  113721. **
  113722. *************************************************************************
  113723. ** This module contains C code that generates VDBE code used to process
  113724. ** the WHERE clause of SQL statements. This module is responsible for
  113725. ** generating the code that loops through a table looking for applicable
  113726. ** rows. Indices are selected and used to speed the search when doing
  113727. ** so is applicable. Because this module is responsible for selecting
  113728. ** indices, you might also think of this module as the "query optimizer".
  113729. */
  113730. /* #include "sqliteInt.h" */
  113731. /* #include "whereInt.h" */
  113732. /* Forward declaration of methods */
  113733. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  113734. /* Test variable that can be set to enable WHERE tracing */
  113735. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  113736. /***/ int sqlite3WhereTrace = 0;
  113737. #endif
  113738. /*
  113739. ** Return the estimated number of output rows from a WHERE clause
  113740. */
  113741. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  113742. return sqlite3LogEstToInt(pWInfo->nRowOut);
  113743. }
  113744. /*
  113745. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  113746. ** WHERE clause returns outputs for DISTINCT processing.
  113747. */
  113748. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  113749. return pWInfo->eDistinct;
  113750. }
  113751. /*
  113752. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  113753. ** Return FALSE if the output needs to be sorted.
  113754. */
  113755. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  113756. return pWInfo->nOBSat;
  113757. }
  113758. /*
  113759. ** Return the VDBE address or label to jump to in order to continue
  113760. ** immediately with the next row of a WHERE clause.
  113761. */
  113762. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  113763. assert( pWInfo->iContinue!=0 );
  113764. return pWInfo->iContinue;
  113765. }
  113766. /*
  113767. ** Return the VDBE address or label to jump to in order to break
  113768. ** out of a WHERE loop.
  113769. */
  113770. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  113771. return pWInfo->iBreak;
  113772. }
  113773. /*
  113774. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  113775. ** operate directly on the rowis returned by a WHERE clause. Return
  113776. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  113777. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  113778. ** optimization can be used on multiple
  113779. **
  113780. ** If the ONEPASS optimization is used (if this routine returns true)
  113781. ** then also write the indices of open cursors used by ONEPASS
  113782. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  113783. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  113784. ** Either value may be -1, indicating that cursor is not used.
  113785. ** Any cursors returned will have been opened for writing.
  113786. **
  113787. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  113788. ** unable to use the ONEPASS optimization.
  113789. */
  113790. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  113791. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  113792. #ifdef WHERETRACE_ENABLED
  113793. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  113794. sqlite3DebugPrintf("%s cursors: %d %d\n",
  113795. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  113796. aiCur[0], aiCur[1]);
  113797. }
  113798. #endif
  113799. return pWInfo->eOnePass;
  113800. }
  113801. /*
  113802. ** Move the content of pSrc into pDest
  113803. */
  113804. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  113805. pDest->n = pSrc->n;
  113806. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  113807. }
  113808. /*
  113809. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  113810. **
  113811. ** The new entry might overwrite an existing entry, or it might be
  113812. ** appended, or it might be discarded. Do whatever is the right thing
  113813. ** so that pSet keeps the N_OR_COST best entries seen so far.
  113814. */
  113815. static int whereOrInsert(
  113816. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  113817. Bitmask prereq, /* Prerequisites of the new entry */
  113818. LogEst rRun, /* Run-cost of the new entry */
  113819. LogEst nOut /* Number of outputs for the new entry */
  113820. ){
  113821. u16 i;
  113822. WhereOrCost *p;
  113823. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  113824. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  113825. goto whereOrInsert_done;
  113826. }
  113827. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  113828. return 0;
  113829. }
  113830. }
  113831. if( pSet->n<N_OR_COST ){
  113832. p = &pSet->a[pSet->n++];
  113833. p->nOut = nOut;
  113834. }else{
  113835. p = pSet->a;
  113836. for(i=1; i<pSet->n; i++){
  113837. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  113838. }
  113839. if( p->rRun<=rRun ) return 0;
  113840. }
  113841. whereOrInsert_done:
  113842. p->prereq = prereq;
  113843. p->rRun = rRun;
  113844. if( p->nOut>nOut ) p->nOut = nOut;
  113845. return 1;
  113846. }
  113847. /*
  113848. ** Return the bitmask for the given cursor number. Return 0 if
  113849. ** iCursor is not in the set.
  113850. */
  113851. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  113852. int i;
  113853. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  113854. for(i=0; i<pMaskSet->n; i++){
  113855. if( pMaskSet->ix[i]==iCursor ){
  113856. return MASKBIT(i);
  113857. }
  113858. }
  113859. return 0;
  113860. }
  113861. /*
  113862. ** Create a new mask for cursor iCursor.
  113863. **
  113864. ** There is one cursor per table in the FROM clause. The number of
  113865. ** tables in the FROM clause is limited by a test early in the
  113866. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  113867. ** array will never overflow.
  113868. */
  113869. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  113870. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  113871. pMaskSet->ix[pMaskSet->n++] = iCursor;
  113872. }
  113873. /*
  113874. ** Advance to the next WhereTerm that matches according to the criteria
  113875. ** established when the pScan object was initialized by whereScanInit().
  113876. ** Return NULL if there are no more matching WhereTerms.
  113877. */
  113878. static WhereTerm *whereScanNext(WhereScan *pScan){
  113879. int iCur; /* The cursor on the LHS of the term */
  113880. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  113881. Expr *pX; /* An expression being tested */
  113882. WhereClause *pWC; /* Shorthand for pScan->pWC */
  113883. WhereTerm *pTerm; /* The term being tested */
  113884. int k = pScan->k; /* Where to start scanning */
  113885. while( pScan->iEquiv<=pScan->nEquiv ){
  113886. iCur = pScan->aiCur[pScan->iEquiv-1];
  113887. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  113888. if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
  113889. while( (pWC = pScan->pWC)!=0 ){
  113890. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  113891. if( pTerm->leftCursor==iCur
  113892. && pTerm->u.leftColumn==iColumn
  113893. && (iColumn!=XN_EXPR
  113894. || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
  113895. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  113896. ){
  113897. if( (pTerm->eOperator & WO_EQUIV)!=0
  113898. && pScan->nEquiv<ArraySize(pScan->aiCur)
  113899. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  113900. ){
  113901. int j;
  113902. for(j=0; j<pScan->nEquiv; j++){
  113903. if( pScan->aiCur[j]==pX->iTable
  113904. && pScan->aiColumn[j]==pX->iColumn ){
  113905. break;
  113906. }
  113907. }
  113908. if( j==pScan->nEquiv ){
  113909. pScan->aiCur[j] = pX->iTable;
  113910. pScan->aiColumn[j] = pX->iColumn;
  113911. pScan->nEquiv++;
  113912. }
  113913. }
  113914. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  113915. /* Verify the affinity and collating sequence match */
  113916. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  113917. CollSeq *pColl;
  113918. Parse *pParse = pWC->pWInfo->pParse;
  113919. pX = pTerm->pExpr;
  113920. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  113921. continue;
  113922. }
  113923. assert(pX->pLeft);
  113924. pColl = sqlite3BinaryCompareCollSeq(pParse,
  113925. pX->pLeft, pX->pRight);
  113926. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  113927. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  113928. continue;
  113929. }
  113930. }
  113931. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  113932. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  113933. && pX->iTable==pScan->aiCur[0]
  113934. && pX->iColumn==pScan->aiColumn[0]
  113935. ){
  113936. testcase( pTerm->eOperator & WO_IS );
  113937. continue;
  113938. }
  113939. pScan->k = k+1;
  113940. return pTerm;
  113941. }
  113942. }
  113943. }
  113944. pScan->pWC = pScan->pWC->pOuter;
  113945. k = 0;
  113946. }
  113947. pScan->pWC = pScan->pOrigWC;
  113948. k = 0;
  113949. pScan->iEquiv++;
  113950. }
  113951. return 0;
  113952. }
  113953. /*
  113954. ** Initialize a WHERE clause scanner object. Return a pointer to the
  113955. ** first match. Return NULL if there are no matches.
  113956. **
  113957. ** The scanner will be searching the WHERE clause pWC. It will look
  113958. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  113959. ** iCur. The <op> must be one of the operators described by opMask.
  113960. **
  113961. ** If the search is for X and the WHERE clause contains terms of the
  113962. ** form X=Y then this routine might also return terms of the form
  113963. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  113964. ** but is enough to handle most commonly occurring SQL statements.
  113965. **
  113966. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  113967. ** index pIdx.
  113968. */
  113969. static WhereTerm *whereScanInit(
  113970. WhereScan *pScan, /* The WhereScan object being initialized */
  113971. WhereClause *pWC, /* The WHERE clause to be scanned */
  113972. int iCur, /* Cursor to scan for */
  113973. int iColumn, /* Column to scan for */
  113974. u32 opMask, /* Operator(s) to scan for */
  113975. Index *pIdx /* Must be compatible with this index */
  113976. ){
  113977. int j = 0;
  113978. /* memset(pScan, 0, sizeof(*pScan)); */
  113979. pScan->pOrigWC = pWC;
  113980. pScan->pWC = pWC;
  113981. pScan->pIdxExpr = 0;
  113982. if( pIdx ){
  113983. j = iColumn;
  113984. iColumn = pIdx->aiColumn[j];
  113985. if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  113986. }
  113987. if( pIdx && iColumn>=0 ){
  113988. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  113989. pScan->zCollName = pIdx->azColl[j];
  113990. }else{
  113991. pScan->idxaff = 0;
  113992. pScan->zCollName = 0;
  113993. }
  113994. pScan->opMask = opMask;
  113995. pScan->k = 0;
  113996. pScan->aiCur[0] = iCur;
  113997. pScan->aiColumn[0] = iColumn;
  113998. pScan->nEquiv = 1;
  113999. pScan->iEquiv = 1;
  114000. return whereScanNext(pScan);
  114001. }
  114002. /*
  114003. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  114004. ** where X is a reference to the iColumn of table iCur and <op> is one of
  114005. ** the WO_xx operator codes specified by the op parameter.
  114006. ** Return a pointer to the term. Return 0 if not found.
  114007. **
  114008. ** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
  114009. ** rather than the iColumn-th column of table iCur.
  114010. **
  114011. ** The term returned might by Y=<expr> if there is another constraint in
  114012. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  114013. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  114014. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  114015. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  114016. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  114017. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  114018. **
  114019. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  114020. ** then try for the one with no dependencies on <expr> - in other words where
  114021. ** <expr> is a constant expression of some kind. Only return entries of
  114022. ** the form "X <op> Y" where Y is a column in another table if no terms of
  114023. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  114024. ** exist, try to return a term that does not use WO_EQUIV.
  114025. */
  114026. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  114027. WhereClause *pWC, /* The WHERE clause to be searched */
  114028. int iCur, /* Cursor number of LHS */
  114029. int iColumn, /* Column number of LHS */
  114030. Bitmask notReady, /* RHS must not overlap with this mask */
  114031. u32 op, /* Mask of WO_xx values describing operator */
  114032. Index *pIdx /* Must be compatible with this index, if not NULL */
  114033. ){
  114034. WhereTerm *pResult = 0;
  114035. WhereTerm *p;
  114036. WhereScan scan;
  114037. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  114038. op &= WO_EQ|WO_IS;
  114039. while( p ){
  114040. if( (p->prereqRight & notReady)==0 ){
  114041. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  114042. testcase( p->eOperator & WO_IS );
  114043. return p;
  114044. }
  114045. if( pResult==0 ) pResult = p;
  114046. }
  114047. p = whereScanNext(&scan);
  114048. }
  114049. return pResult;
  114050. }
  114051. /*
  114052. ** This function searches pList for an entry that matches the iCol-th column
  114053. ** of index pIdx.
  114054. **
  114055. ** If such an expression is found, its index in pList->a[] is returned. If
  114056. ** no expression is found, -1 is returned.
  114057. */
  114058. static int findIndexCol(
  114059. Parse *pParse, /* Parse context */
  114060. ExprList *pList, /* Expression list to search */
  114061. int iBase, /* Cursor for table associated with pIdx */
  114062. Index *pIdx, /* Index to match column of */
  114063. int iCol /* Column of index to match */
  114064. ){
  114065. int i;
  114066. const char *zColl = pIdx->azColl[iCol];
  114067. for(i=0; i<pList->nExpr; i++){
  114068. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  114069. if( p->op==TK_COLUMN
  114070. && p->iColumn==pIdx->aiColumn[iCol]
  114071. && p->iTable==iBase
  114072. ){
  114073. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  114074. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  114075. return i;
  114076. }
  114077. }
  114078. }
  114079. return -1;
  114080. }
  114081. /*
  114082. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  114083. */
  114084. static int indexColumnNotNull(Index *pIdx, int iCol){
  114085. int j;
  114086. assert( pIdx!=0 );
  114087. assert( iCol>=0 && iCol<pIdx->nColumn );
  114088. j = pIdx->aiColumn[iCol];
  114089. if( j>=0 ){
  114090. return pIdx->pTable->aCol[j].notNull;
  114091. }else if( j==(-1) ){
  114092. return 1;
  114093. }else{
  114094. assert( j==(-2) );
  114095. return 0; /* Assume an indexed expression can always yield a NULL */
  114096. }
  114097. }
  114098. /*
  114099. ** Return true if the DISTINCT expression-list passed as the third argument
  114100. ** is redundant.
  114101. **
  114102. ** A DISTINCT list is redundant if any subset of the columns in the
  114103. ** DISTINCT list are collectively unique and individually non-null.
  114104. */
  114105. static int isDistinctRedundant(
  114106. Parse *pParse, /* Parsing context */
  114107. SrcList *pTabList, /* The FROM clause */
  114108. WhereClause *pWC, /* The WHERE clause */
  114109. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  114110. ){
  114111. Table *pTab;
  114112. Index *pIdx;
  114113. int i;
  114114. int iBase;
  114115. /* If there is more than one table or sub-select in the FROM clause of
  114116. ** this query, then it will not be possible to show that the DISTINCT
  114117. ** clause is redundant. */
  114118. if( pTabList->nSrc!=1 ) return 0;
  114119. iBase = pTabList->a[0].iCursor;
  114120. pTab = pTabList->a[0].pTab;
  114121. /* If any of the expressions is an IPK column on table iBase, then return
  114122. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  114123. ** current SELECT is a correlated sub-query.
  114124. */
  114125. for(i=0; i<pDistinct->nExpr; i++){
  114126. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  114127. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  114128. }
  114129. /* Loop through all indices on the table, checking each to see if it makes
  114130. ** the DISTINCT qualifier redundant. It does so if:
  114131. **
  114132. ** 1. The index is itself UNIQUE, and
  114133. **
  114134. ** 2. All of the columns in the index are either part of the pDistinct
  114135. ** list, or else the WHERE clause contains a term of the form "col=X",
  114136. ** where X is a constant value. The collation sequences of the
  114137. ** comparison and select-list expressions must match those of the index.
  114138. **
  114139. ** 3. All of those index columns for which the WHERE clause does not
  114140. ** contain a "col=X" term are subject to a NOT NULL constraint.
  114141. */
  114142. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114143. if( !IsUniqueIndex(pIdx) ) continue;
  114144. for(i=0; i<pIdx->nKeyCol; i++){
  114145. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  114146. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  114147. if( indexColumnNotNull(pIdx, i)==0 ) break;
  114148. }
  114149. }
  114150. if( i==pIdx->nKeyCol ){
  114151. /* This index implies that the DISTINCT qualifier is redundant. */
  114152. return 1;
  114153. }
  114154. }
  114155. return 0;
  114156. }
  114157. /*
  114158. ** Estimate the logarithm of the input value to base 2.
  114159. */
  114160. static LogEst estLog(LogEst N){
  114161. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  114162. }
  114163. /*
  114164. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  114165. **
  114166. ** This routine runs over generated VDBE code and translates OP_Column
  114167. ** opcodes into OP_Copy, and OP_Rowid into OP_Null, when the table is being
  114168. ** accessed via co-routine instead of via table lookup.
  114169. */
  114170. static void translateColumnToCopy(
  114171. Vdbe *v, /* The VDBE containing code to translate */
  114172. int iStart, /* Translate from this opcode to the end */
  114173. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  114174. int iRegister /* The first column is in this register */
  114175. ){
  114176. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  114177. int iEnd = sqlite3VdbeCurrentAddr(v);
  114178. for(; iStart<iEnd; iStart++, pOp++){
  114179. if( pOp->p1!=iTabCur ) continue;
  114180. if( pOp->opcode==OP_Column ){
  114181. pOp->opcode = OP_Copy;
  114182. pOp->p1 = pOp->p2 + iRegister;
  114183. pOp->p2 = pOp->p3;
  114184. pOp->p3 = 0;
  114185. }else if( pOp->opcode==OP_Rowid ){
  114186. pOp->opcode = OP_Null;
  114187. pOp->p1 = 0;
  114188. pOp->p3 = 0;
  114189. }
  114190. }
  114191. }
  114192. /*
  114193. ** Two routines for printing the content of an sqlite3_index_info
  114194. ** structure. Used for testing and debugging only. If neither
  114195. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  114196. ** are no-ops.
  114197. */
  114198. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  114199. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  114200. int i;
  114201. if( !sqlite3WhereTrace ) return;
  114202. for(i=0; i<p->nConstraint; i++){
  114203. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  114204. i,
  114205. p->aConstraint[i].iColumn,
  114206. p->aConstraint[i].iTermOffset,
  114207. p->aConstraint[i].op,
  114208. p->aConstraint[i].usable);
  114209. }
  114210. for(i=0; i<p->nOrderBy; i++){
  114211. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  114212. i,
  114213. p->aOrderBy[i].iColumn,
  114214. p->aOrderBy[i].desc);
  114215. }
  114216. }
  114217. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  114218. int i;
  114219. if( !sqlite3WhereTrace ) return;
  114220. for(i=0; i<p->nConstraint; i++){
  114221. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  114222. i,
  114223. p->aConstraintUsage[i].argvIndex,
  114224. p->aConstraintUsage[i].omit);
  114225. }
  114226. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  114227. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  114228. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  114229. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  114230. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  114231. }
  114232. #else
  114233. #define TRACE_IDX_INPUTS(A)
  114234. #define TRACE_IDX_OUTPUTS(A)
  114235. #endif
  114236. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  114237. /*
  114238. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  114239. ** could be used with an index to access pSrc, assuming an appropriate
  114240. ** index existed.
  114241. */
  114242. static int termCanDriveIndex(
  114243. WhereTerm *pTerm, /* WHERE clause term to check */
  114244. struct SrcList_item *pSrc, /* Table we are trying to access */
  114245. Bitmask notReady /* Tables in outer loops of the join */
  114246. ){
  114247. char aff;
  114248. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  114249. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  114250. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  114251. if( pTerm->u.leftColumn<0 ) return 0;
  114252. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  114253. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  114254. testcase( pTerm->pExpr->op==TK_IS );
  114255. return 1;
  114256. }
  114257. #endif
  114258. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  114259. /*
  114260. ** Generate code to construct the Index object for an automatic index
  114261. ** and to set up the WhereLevel object pLevel so that the code generator
  114262. ** makes use of the automatic index.
  114263. */
  114264. static void constructAutomaticIndex(
  114265. Parse *pParse, /* The parsing context */
  114266. WhereClause *pWC, /* The WHERE clause */
  114267. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  114268. Bitmask notReady, /* Mask of cursors that are not available */
  114269. WhereLevel *pLevel /* Write new index here */
  114270. ){
  114271. int nKeyCol; /* Number of columns in the constructed index */
  114272. WhereTerm *pTerm; /* A single term of the WHERE clause */
  114273. WhereTerm *pWCEnd; /* End of pWC->a[] */
  114274. Index *pIdx; /* Object describing the transient index */
  114275. Vdbe *v; /* Prepared statement under construction */
  114276. int addrInit; /* Address of the initialization bypass jump */
  114277. Table *pTable; /* The table being indexed */
  114278. int addrTop; /* Top of the index fill loop */
  114279. int regRecord; /* Register holding an index record */
  114280. int n; /* Column counter */
  114281. int i; /* Loop counter */
  114282. int mxBitCol; /* Maximum column in pSrc->colUsed */
  114283. CollSeq *pColl; /* Collating sequence to on a column */
  114284. WhereLoop *pLoop; /* The Loop object */
  114285. char *zNotUsed; /* Extra space on the end of pIdx */
  114286. Bitmask idxCols; /* Bitmap of columns used for indexing */
  114287. Bitmask extraCols; /* Bitmap of additional columns */
  114288. u8 sentWarning = 0; /* True if a warnning has been issued */
  114289. Expr *pPartial = 0; /* Partial Index Expression */
  114290. int iContinue = 0; /* Jump here to skip excluded rows */
  114291. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  114292. /* Generate code to skip over the creation and initialization of the
  114293. ** transient index on 2nd and subsequent iterations of the loop. */
  114294. v = pParse->pVdbe;
  114295. assert( v!=0 );
  114296. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  114297. /* Count the number of columns that will be added to the index
  114298. ** and used to match WHERE clause constraints */
  114299. nKeyCol = 0;
  114300. pTable = pSrc->pTab;
  114301. pWCEnd = &pWC->a[pWC->nTerm];
  114302. pLoop = pLevel->pWLoop;
  114303. idxCols = 0;
  114304. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  114305. Expr *pExpr = pTerm->pExpr;
  114306. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  114307. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  114308. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  114309. if( pLoop->prereq==0
  114310. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  114311. && !ExprHasProperty(pExpr, EP_FromJoin)
  114312. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  114313. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  114314. sqlite3ExprDup(pParse->db, pExpr, 0));
  114315. }
  114316. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  114317. int iCol = pTerm->u.leftColumn;
  114318. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  114319. testcase( iCol==BMS );
  114320. testcase( iCol==BMS-1 );
  114321. if( !sentWarning ){
  114322. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  114323. "automatic index on %s(%s)", pTable->zName,
  114324. pTable->aCol[iCol].zName);
  114325. sentWarning = 1;
  114326. }
  114327. if( (idxCols & cMask)==0 ){
  114328. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  114329. goto end_auto_index_create;
  114330. }
  114331. pLoop->aLTerm[nKeyCol++] = pTerm;
  114332. idxCols |= cMask;
  114333. }
  114334. }
  114335. }
  114336. assert( nKeyCol>0 );
  114337. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  114338. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  114339. | WHERE_AUTO_INDEX;
  114340. /* Count the number of additional columns needed to create a
  114341. ** covering index. A "covering index" is an index that contains all
  114342. ** columns that are needed by the query. With a covering index, the
  114343. ** original table never needs to be accessed. Automatic indices must
  114344. ** be a covering index because the index will not be updated if the
  114345. ** original table changes and the index and table cannot both be used
  114346. ** if they go out of sync.
  114347. */
  114348. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  114349. mxBitCol = MIN(BMS-1,pTable->nCol);
  114350. testcase( pTable->nCol==BMS-1 );
  114351. testcase( pTable->nCol==BMS-2 );
  114352. for(i=0; i<mxBitCol; i++){
  114353. if( extraCols & MASKBIT(i) ) nKeyCol++;
  114354. }
  114355. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  114356. nKeyCol += pTable->nCol - BMS + 1;
  114357. }
  114358. /* Construct the Index object to describe this index */
  114359. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  114360. if( pIdx==0 ) goto end_auto_index_create;
  114361. pLoop->u.btree.pIndex = pIdx;
  114362. pIdx->zName = "auto-index";
  114363. pIdx->pTable = pTable;
  114364. n = 0;
  114365. idxCols = 0;
  114366. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  114367. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  114368. int iCol = pTerm->u.leftColumn;
  114369. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  114370. testcase( iCol==BMS-1 );
  114371. testcase( iCol==BMS );
  114372. if( (idxCols & cMask)==0 ){
  114373. Expr *pX = pTerm->pExpr;
  114374. idxCols |= cMask;
  114375. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  114376. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  114377. pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
  114378. n++;
  114379. }
  114380. }
  114381. }
  114382. assert( (u32)n==pLoop->u.btree.nEq );
  114383. /* Add additional columns needed to make the automatic index into
  114384. ** a covering index */
  114385. for(i=0; i<mxBitCol; i++){
  114386. if( extraCols & MASKBIT(i) ){
  114387. pIdx->aiColumn[n] = i;
  114388. pIdx->azColl[n] = "BINARY";
  114389. n++;
  114390. }
  114391. }
  114392. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  114393. for(i=BMS-1; i<pTable->nCol; i++){
  114394. pIdx->aiColumn[n] = i;
  114395. pIdx->azColl[n] = "BINARY";
  114396. n++;
  114397. }
  114398. }
  114399. assert( n==nKeyCol );
  114400. pIdx->aiColumn[n] = XN_ROWID;
  114401. pIdx->azColl[n] = "BINARY";
  114402. /* Create the automatic index */
  114403. assert( pLevel->iIdxCur>=0 );
  114404. pLevel->iIdxCur = pParse->nTab++;
  114405. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  114406. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  114407. VdbeComment((v, "for %s", pTable->zName));
  114408. /* Fill the automatic index with content */
  114409. sqlite3ExprCachePush(pParse);
  114410. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  114411. if( pTabItem->fg.viaCoroutine ){
  114412. int regYield = pTabItem->regReturn;
  114413. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  114414. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  114415. VdbeCoverage(v);
  114416. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  114417. }else{
  114418. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  114419. }
  114420. if( pPartial ){
  114421. iContinue = sqlite3VdbeMakeLabel(v);
  114422. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  114423. pLoop->wsFlags |= WHERE_PARTIALIDX;
  114424. }
  114425. regRecord = sqlite3GetTempReg(pParse);
  114426. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  114427. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  114428. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  114429. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  114430. if( pTabItem->fg.viaCoroutine ){
  114431. translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult);
  114432. sqlite3VdbeGoto(v, addrTop);
  114433. pTabItem->fg.viaCoroutine = 0;
  114434. }else{
  114435. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  114436. }
  114437. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  114438. sqlite3VdbeJumpHere(v, addrTop);
  114439. sqlite3ReleaseTempReg(pParse, regRecord);
  114440. sqlite3ExprCachePop(pParse);
  114441. /* Jump here when skipping the initialization */
  114442. sqlite3VdbeJumpHere(v, addrInit);
  114443. end_auto_index_create:
  114444. sqlite3ExprDelete(pParse->db, pPartial);
  114445. }
  114446. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  114447. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114448. /*
  114449. ** Allocate and populate an sqlite3_index_info structure. It is the
  114450. ** responsibility of the caller to eventually release the structure
  114451. ** by passing the pointer returned by this function to sqlite3_free().
  114452. */
  114453. static sqlite3_index_info *allocateIndexInfo(
  114454. Parse *pParse,
  114455. WhereClause *pWC,
  114456. Bitmask mUnusable, /* Ignore terms with these prereqs */
  114457. struct SrcList_item *pSrc,
  114458. ExprList *pOrderBy
  114459. ){
  114460. int i, j;
  114461. int nTerm;
  114462. struct sqlite3_index_constraint *pIdxCons;
  114463. struct sqlite3_index_orderby *pIdxOrderBy;
  114464. struct sqlite3_index_constraint_usage *pUsage;
  114465. WhereTerm *pTerm;
  114466. int nOrderBy;
  114467. sqlite3_index_info *pIdxInfo;
  114468. /* Count the number of possible WHERE clause constraints referring
  114469. ** to this virtual table */
  114470. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  114471. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  114472. if( pTerm->prereqRight & mUnusable ) continue;
  114473. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  114474. testcase( pTerm->eOperator & WO_IN );
  114475. testcase( pTerm->eOperator & WO_ISNULL );
  114476. testcase( pTerm->eOperator & WO_IS );
  114477. testcase( pTerm->eOperator & WO_ALL );
  114478. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  114479. if( pTerm->wtFlags & TERM_VNULL ) continue;
  114480. assert( pTerm->u.leftColumn>=(-1) );
  114481. nTerm++;
  114482. }
  114483. /* If the ORDER BY clause contains only columns in the current
  114484. ** virtual table then allocate space for the aOrderBy part of
  114485. ** the sqlite3_index_info structure.
  114486. */
  114487. nOrderBy = 0;
  114488. if( pOrderBy ){
  114489. int n = pOrderBy->nExpr;
  114490. for(i=0; i<n; i++){
  114491. Expr *pExpr = pOrderBy->a[i].pExpr;
  114492. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  114493. }
  114494. if( i==n){
  114495. nOrderBy = n;
  114496. }
  114497. }
  114498. /* Allocate the sqlite3_index_info structure
  114499. */
  114500. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  114501. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  114502. + sizeof(*pIdxOrderBy)*nOrderBy );
  114503. if( pIdxInfo==0 ){
  114504. sqlite3ErrorMsg(pParse, "out of memory");
  114505. return 0;
  114506. }
  114507. /* Initialize the structure. The sqlite3_index_info structure contains
  114508. ** many fields that are declared "const" to prevent xBestIndex from
  114509. ** changing them. We have to do some funky casting in order to
  114510. ** initialize those fields.
  114511. */
  114512. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  114513. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  114514. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  114515. *(int*)&pIdxInfo->nConstraint = nTerm;
  114516. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  114517. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  114518. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  114519. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  114520. pUsage;
  114521. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  114522. u8 op;
  114523. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  114524. if( pTerm->prereqRight & mUnusable ) continue;
  114525. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  114526. testcase( pTerm->eOperator & WO_IN );
  114527. testcase( pTerm->eOperator & WO_IS );
  114528. testcase( pTerm->eOperator & WO_ISNULL );
  114529. testcase( pTerm->eOperator & WO_ALL );
  114530. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  114531. if( pTerm->wtFlags & TERM_VNULL ) continue;
  114532. assert( pTerm->u.leftColumn>=(-1) );
  114533. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  114534. pIdxCons[j].iTermOffset = i;
  114535. op = (u8)pTerm->eOperator & WO_ALL;
  114536. if( op==WO_IN ) op = WO_EQ;
  114537. pIdxCons[j].op = op;
  114538. /* The direct assignment in the previous line is possible only because
  114539. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  114540. ** following asserts verify this fact. */
  114541. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  114542. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  114543. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  114544. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  114545. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  114546. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  114547. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  114548. j++;
  114549. }
  114550. for(i=0; i<nOrderBy; i++){
  114551. Expr *pExpr = pOrderBy->a[i].pExpr;
  114552. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  114553. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  114554. }
  114555. return pIdxInfo;
  114556. }
  114557. /*
  114558. ** The table object reference passed as the second argument to this function
  114559. ** must represent a virtual table. This function invokes the xBestIndex()
  114560. ** method of the virtual table with the sqlite3_index_info object that
  114561. ** comes in as the 3rd argument to this function.
  114562. **
  114563. ** If an error occurs, pParse is populated with an error message and a
  114564. ** non-zero value is returned. Otherwise, 0 is returned and the output
  114565. ** part of the sqlite3_index_info structure is left populated.
  114566. **
  114567. ** Whether or not an error is returned, it is the responsibility of the
  114568. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  114569. ** that this is required.
  114570. */
  114571. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  114572. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  114573. int i;
  114574. int rc;
  114575. TRACE_IDX_INPUTS(p);
  114576. rc = pVtab->pModule->xBestIndex(pVtab, p);
  114577. TRACE_IDX_OUTPUTS(p);
  114578. if( rc!=SQLITE_OK ){
  114579. if( rc==SQLITE_NOMEM ){
  114580. pParse->db->mallocFailed = 1;
  114581. }else if( !pVtab->zErrMsg ){
  114582. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  114583. }else{
  114584. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  114585. }
  114586. }
  114587. sqlite3_free(pVtab->zErrMsg);
  114588. pVtab->zErrMsg = 0;
  114589. for(i=0; i<p->nConstraint; i++){
  114590. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  114591. sqlite3ErrorMsg(pParse,
  114592. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  114593. }
  114594. }
  114595. return pParse->nErr;
  114596. }
  114597. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  114598. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114599. /*
  114600. ** Estimate the location of a particular key among all keys in an
  114601. ** index. Store the results in aStat as follows:
  114602. **
  114603. ** aStat[0] Est. number of rows less than pRec
  114604. ** aStat[1] Est. number of rows equal to pRec
  114605. **
  114606. ** Return the index of the sample that is the smallest sample that
  114607. ** is greater than or equal to pRec. Note that this index is not an index
  114608. ** into the aSample[] array - it is an index into a virtual set of samples
  114609. ** based on the contents of aSample[] and the number of fields in record
  114610. ** pRec.
  114611. */
  114612. static int whereKeyStats(
  114613. Parse *pParse, /* Database connection */
  114614. Index *pIdx, /* Index to consider domain of */
  114615. UnpackedRecord *pRec, /* Vector of values to consider */
  114616. int roundUp, /* Round up if true. Round down if false */
  114617. tRowcnt *aStat /* OUT: stats written here */
  114618. ){
  114619. IndexSample *aSample = pIdx->aSample;
  114620. int iCol; /* Index of required stats in anEq[] etc. */
  114621. int i; /* Index of first sample >= pRec */
  114622. int iSample; /* Smallest sample larger than or equal to pRec */
  114623. int iMin = 0; /* Smallest sample not yet tested */
  114624. int iTest; /* Next sample to test */
  114625. int res; /* Result of comparison operation */
  114626. int nField; /* Number of fields in pRec */
  114627. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  114628. #ifndef SQLITE_DEBUG
  114629. UNUSED_PARAMETER( pParse );
  114630. #endif
  114631. assert( pRec!=0 );
  114632. assert( pIdx->nSample>0 );
  114633. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  114634. /* Do a binary search to find the first sample greater than or equal
  114635. ** to pRec. If pRec contains a single field, the set of samples to search
  114636. ** is simply the aSample[] array. If the samples in aSample[] contain more
  114637. ** than one fields, all fields following the first are ignored.
  114638. **
  114639. ** If pRec contains N fields, where N is more than one, then as well as the
  114640. ** samples in aSample[] (truncated to N fields), the search also has to
  114641. ** consider prefixes of those samples. For example, if the set of samples
  114642. ** in aSample is:
  114643. **
  114644. ** aSample[0] = (a, 5)
  114645. ** aSample[1] = (a, 10)
  114646. ** aSample[2] = (b, 5)
  114647. ** aSample[3] = (c, 100)
  114648. ** aSample[4] = (c, 105)
  114649. **
  114650. ** Then the search space should ideally be the samples above and the
  114651. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  114652. ** the code actually searches this set:
  114653. **
  114654. ** 0: (a)
  114655. ** 1: (a, 5)
  114656. ** 2: (a, 10)
  114657. ** 3: (a, 10)
  114658. ** 4: (b)
  114659. ** 5: (b, 5)
  114660. ** 6: (c)
  114661. ** 7: (c, 100)
  114662. ** 8: (c, 105)
  114663. ** 9: (c, 105)
  114664. **
  114665. ** For each sample in the aSample[] array, N samples are present in the
  114666. ** effective sample array. In the above, samples 0 and 1 are based on
  114667. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  114668. **
  114669. ** Often, sample i of each block of N effective samples has (i+1) fields.
  114670. ** Except, each sample may be extended to ensure that it is greater than or
  114671. ** equal to the previous sample in the array. For example, in the above,
  114672. ** sample 2 is the first sample of a block of N samples, so at first it
  114673. ** appears that it should be 1 field in size. However, that would make it
  114674. ** smaller than sample 1, so the binary search would not work. As a result,
  114675. ** it is extended to two fields. The duplicates that this creates do not
  114676. ** cause any problems.
  114677. */
  114678. nField = pRec->nField;
  114679. iCol = 0;
  114680. iSample = pIdx->nSample * nField;
  114681. do{
  114682. int iSamp; /* Index in aSample[] of test sample */
  114683. int n; /* Number of fields in test sample */
  114684. iTest = (iMin+iSample)/2;
  114685. iSamp = iTest / nField;
  114686. if( iSamp>0 ){
  114687. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  114688. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  114689. ** fields that is greater than the previous effective sample. */
  114690. for(n=(iTest % nField) + 1; n<nField; n++){
  114691. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  114692. }
  114693. }else{
  114694. n = iTest + 1;
  114695. }
  114696. pRec->nField = n;
  114697. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  114698. if( res<0 ){
  114699. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  114700. iMin = iTest+1;
  114701. }else if( res==0 && n<nField ){
  114702. iLower = aSample[iSamp].anLt[n-1];
  114703. iMin = iTest+1;
  114704. res = -1;
  114705. }else{
  114706. iSample = iTest;
  114707. iCol = n-1;
  114708. }
  114709. }while( res && iMin<iSample );
  114710. i = iSample / nField;
  114711. #ifdef SQLITE_DEBUG
  114712. /* The following assert statements check that the binary search code
  114713. ** above found the right answer. This block serves no purpose other
  114714. ** than to invoke the asserts. */
  114715. if( pParse->db->mallocFailed==0 ){
  114716. if( res==0 ){
  114717. /* If (res==0) is true, then pRec must be equal to sample i. */
  114718. assert( i<pIdx->nSample );
  114719. assert( iCol==nField-1 );
  114720. pRec->nField = nField;
  114721. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  114722. || pParse->db->mallocFailed
  114723. );
  114724. }else{
  114725. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  114726. ** all samples in the aSample[] array, pRec must be smaller than the
  114727. ** (iCol+1) field prefix of sample i. */
  114728. assert( i<=pIdx->nSample && i>=0 );
  114729. pRec->nField = iCol+1;
  114730. assert( i==pIdx->nSample
  114731. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  114732. || pParse->db->mallocFailed );
  114733. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  114734. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  114735. ** be greater than or equal to the (iCol) field prefix of sample i.
  114736. ** If (i>0), then pRec must also be greater than sample (i-1). */
  114737. if( iCol>0 ){
  114738. pRec->nField = iCol;
  114739. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  114740. || pParse->db->mallocFailed );
  114741. }
  114742. if( i>0 ){
  114743. pRec->nField = nField;
  114744. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  114745. || pParse->db->mallocFailed );
  114746. }
  114747. }
  114748. }
  114749. #endif /* ifdef SQLITE_DEBUG */
  114750. if( res==0 ){
  114751. /* Record pRec is equal to sample i */
  114752. assert( iCol==nField-1 );
  114753. aStat[0] = aSample[i].anLt[iCol];
  114754. aStat[1] = aSample[i].anEq[iCol];
  114755. }else{
  114756. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  114757. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  114758. ** is larger than all samples in the array. */
  114759. tRowcnt iUpper, iGap;
  114760. if( i>=pIdx->nSample ){
  114761. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  114762. }else{
  114763. iUpper = aSample[i].anLt[iCol];
  114764. }
  114765. if( iLower>=iUpper ){
  114766. iGap = 0;
  114767. }else{
  114768. iGap = iUpper - iLower;
  114769. }
  114770. if( roundUp ){
  114771. iGap = (iGap*2)/3;
  114772. }else{
  114773. iGap = iGap/3;
  114774. }
  114775. aStat[0] = iLower + iGap;
  114776. aStat[1] = pIdx->aAvgEq[iCol];
  114777. }
  114778. /* Restore the pRec->nField value before returning. */
  114779. pRec->nField = nField;
  114780. return i;
  114781. }
  114782. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  114783. /*
  114784. ** If it is not NULL, pTerm is a term that provides an upper or lower
  114785. ** bound on a range scan. Without considering pTerm, it is estimated
  114786. ** that the scan will visit nNew rows. This function returns the number
  114787. ** estimated to be visited after taking pTerm into account.
  114788. **
  114789. ** If the user explicitly specified a likelihood() value for this term,
  114790. ** then the return value is the likelihood multiplied by the number of
  114791. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  114792. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  114793. */
  114794. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  114795. LogEst nRet = nNew;
  114796. if( pTerm ){
  114797. if( pTerm->truthProb<=0 ){
  114798. nRet += pTerm->truthProb;
  114799. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  114800. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  114801. }
  114802. }
  114803. return nRet;
  114804. }
  114805. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114806. /*
  114807. ** Return the affinity for a single column of an index.
  114808. */
  114809. static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  114810. assert( iCol>=0 && iCol<pIdx->nColumn );
  114811. if( !pIdx->zColAff ){
  114812. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  114813. }
  114814. return pIdx->zColAff[iCol];
  114815. }
  114816. #endif
  114817. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114818. /*
  114819. ** This function is called to estimate the number of rows visited by a
  114820. ** range-scan on a skip-scan index. For example:
  114821. **
  114822. ** CREATE INDEX i1 ON t1(a, b, c);
  114823. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  114824. **
  114825. ** Value pLoop->nOut is currently set to the estimated number of rows
  114826. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  114827. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  114828. ** on the stat4 data for the index. this scan will be peformed multiple
  114829. ** times (once for each (a,b) combination that matches a=?) is dealt with
  114830. ** by the caller.
  114831. **
  114832. ** It does this by scanning through all stat4 samples, comparing values
  114833. ** extracted from pLower and pUpper with the corresponding column in each
  114834. ** sample. If L and U are the number of samples found to be less than or
  114835. ** equal to the values extracted from pLower and pUpper respectively, and
  114836. ** N is the total number of samples, the pLoop->nOut value is adjusted
  114837. ** as follows:
  114838. **
  114839. ** nOut = nOut * ( min(U - L, 1) / N )
  114840. **
  114841. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  114842. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  114843. ** U is set to N.
  114844. **
  114845. ** Normally, this function sets *pbDone to 1 before returning. However,
  114846. ** if no value can be extracted from either pLower or pUpper (and so the
  114847. ** estimate of the number of rows delivered remains unchanged), *pbDone
  114848. ** is left as is.
  114849. **
  114850. ** If an error occurs, an SQLite error code is returned. Otherwise,
  114851. ** SQLITE_OK.
  114852. */
  114853. static int whereRangeSkipScanEst(
  114854. Parse *pParse, /* Parsing & code generating context */
  114855. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  114856. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  114857. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  114858. int *pbDone /* Set to true if at least one expr. value extracted */
  114859. ){
  114860. Index *p = pLoop->u.btree.pIndex;
  114861. int nEq = pLoop->u.btree.nEq;
  114862. sqlite3 *db = pParse->db;
  114863. int nLower = -1;
  114864. int nUpper = p->nSample+1;
  114865. int rc = SQLITE_OK;
  114866. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  114867. CollSeq *pColl;
  114868. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  114869. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  114870. sqlite3_value *pVal = 0; /* Value extracted from record */
  114871. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  114872. if( pLower ){
  114873. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  114874. nLower = 0;
  114875. }
  114876. if( pUpper && rc==SQLITE_OK ){
  114877. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  114878. nUpper = p2 ? 0 : p->nSample;
  114879. }
  114880. if( p1 || p2 ){
  114881. int i;
  114882. int nDiff;
  114883. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  114884. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  114885. if( rc==SQLITE_OK && p1 ){
  114886. int res = sqlite3MemCompare(p1, pVal, pColl);
  114887. if( res>=0 ) nLower++;
  114888. }
  114889. if( rc==SQLITE_OK && p2 ){
  114890. int res = sqlite3MemCompare(p2, pVal, pColl);
  114891. if( res>=0 ) nUpper++;
  114892. }
  114893. }
  114894. nDiff = (nUpper - nLower);
  114895. if( nDiff<=0 ) nDiff = 1;
  114896. /* If there is both an upper and lower bound specified, and the
  114897. ** comparisons indicate that they are close together, use the fallback
  114898. ** method (assume that the scan visits 1/64 of the rows) for estimating
  114899. ** the number of rows visited. Otherwise, estimate the number of rows
  114900. ** using the method described in the header comment for this function. */
  114901. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  114902. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  114903. pLoop->nOut -= nAdjust;
  114904. *pbDone = 1;
  114905. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  114906. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  114907. }
  114908. }else{
  114909. assert( *pbDone==0 );
  114910. }
  114911. sqlite3ValueFree(p1);
  114912. sqlite3ValueFree(p2);
  114913. sqlite3ValueFree(pVal);
  114914. return rc;
  114915. }
  114916. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  114917. /*
  114918. ** This function is used to estimate the number of rows that will be visited
  114919. ** by scanning an index for a range of values. The range may have an upper
  114920. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  114921. ** and lower bounds are represented by pLower and pUpper respectively. For
  114922. ** example, assuming that index p is on t1(a):
  114923. **
  114924. ** ... FROM t1 WHERE a > ? AND a < ? ...
  114925. ** |_____| |_____|
  114926. ** | |
  114927. ** pLower pUpper
  114928. **
  114929. ** If either of the upper or lower bound is not present, then NULL is passed in
  114930. ** place of the corresponding WhereTerm.
  114931. **
  114932. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  114933. ** column subject to the range constraint. Or, equivalently, the number of
  114934. ** equality constraints optimized by the proposed index scan. For example,
  114935. ** assuming index p is on t1(a, b), and the SQL query is:
  114936. **
  114937. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  114938. **
  114939. ** then nEq is set to 1 (as the range restricted column, b, is the second
  114940. ** left-most column of the index). Or, if the query is:
  114941. **
  114942. ** ... FROM t1 WHERE a > ? AND a < ? ...
  114943. **
  114944. ** then nEq is set to 0.
  114945. **
  114946. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  114947. ** number of rows that the index scan is expected to visit without
  114948. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  114949. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  114950. ** to account for the range constraints pLower and pUpper.
  114951. **
  114952. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  114953. ** used, a single range inequality reduces the search space by a factor of 4.
  114954. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  114955. ** rows visited by a factor of 64.
  114956. */
  114957. static int whereRangeScanEst(
  114958. Parse *pParse, /* Parsing & code generating context */
  114959. WhereLoopBuilder *pBuilder,
  114960. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  114961. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  114962. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  114963. ){
  114964. int rc = SQLITE_OK;
  114965. int nOut = pLoop->nOut;
  114966. LogEst nNew;
  114967. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114968. Index *p = pLoop->u.btree.pIndex;
  114969. int nEq = pLoop->u.btree.nEq;
  114970. if( p->nSample>0 && nEq<p->nSampleCol ){
  114971. if( nEq==pBuilder->nRecValid ){
  114972. UnpackedRecord *pRec = pBuilder->pRec;
  114973. tRowcnt a[2];
  114974. u8 aff;
  114975. /* Variable iLower will be set to the estimate of the number of rows in
  114976. ** the index that are less than the lower bound of the range query. The
  114977. ** lower bound being the concatenation of $P and $L, where $P is the
  114978. ** key-prefix formed by the nEq values matched against the nEq left-most
  114979. ** columns of the index, and $L is the value in pLower.
  114980. **
  114981. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  114982. ** is not a simple variable or literal value), the lower bound of the
  114983. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  114984. ** if $L is available, whereKeyStats() is called for both ($P) and
  114985. ** ($P:$L) and the larger of the two returned values is used.
  114986. **
  114987. ** Similarly, iUpper is to be set to the estimate of the number of rows
  114988. ** less than the upper bound of the range query. Where the upper bound
  114989. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  114990. ** of iUpper are requested of whereKeyStats() and the smaller used.
  114991. **
  114992. ** The number of rows between the two bounds is then just iUpper-iLower.
  114993. */
  114994. tRowcnt iLower; /* Rows less than the lower bound */
  114995. tRowcnt iUpper; /* Rows less than the upper bound */
  114996. int iLwrIdx = -2; /* aSample[] for the lower bound */
  114997. int iUprIdx = -1; /* aSample[] for the upper bound */
  114998. if( pRec ){
  114999. testcase( pRec->nField!=pBuilder->nRecValid );
  115000. pRec->nField = pBuilder->nRecValid;
  115001. }
  115002. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
  115003. assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
  115004. /* Determine iLower and iUpper using ($P) only. */
  115005. if( nEq==0 ){
  115006. iLower = 0;
  115007. iUpper = p->nRowEst0;
  115008. }else{
  115009. /* Note: this call could be optimized away - since the same values must
  115010. ** have been requested when testing key $P in whereEqualScanEst(). */
  115011. whereKeyStats(pParse, p, pRec, 0, a);
  115012. iLower = a[0];
  115013. iUpper = a[0] + a[1];
  115014. }
  115015. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  115016. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  115017. assert( p->aSortOrder!=0 );
  115018. if( p->aSortOrder[nEq] ){
  115019. /* The roles of pLower and pUpper are swapped for a DESC index */
  115020. SWAP(WhereTerm*, pLower, pUpper);
  115021. }
  115022. /* If possible, improve on the iLower estimate using ($P:$L). */
  115023. if( pLower ){
  115024. int bOk; /* True if value is extracted from pExpr */
  115025. Expr *pExpr = pLower->pExpr->pRight;
  115026. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  115027. if( rc==SQLITE_OK && bOk ){
  115028. tRowcnt iNew;
  115029. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  115030. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  115031. if( iNew>iLower ) iLower = iNew;
  115032. nOut--;
  115033. pLower = 0;
  115034. }
  115035. }
  115036. /* If possible, improve on the iUpper estimate using ($P:$U). */
  115037. if( pUpper ){
  115038. int bOk; /* True if value is extracted from pExpr */
  115039. Expr *pExpr = pUpper->pExpr->pRight;
  115040. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  115041. if( rc==SQLITE_OK && bOk ){
  115042. tRowcnt iNew;
  115043. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  115044. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  115045. if( iNew<iUpper ) iUpper = iNew;
  115046. nOut--;
  115047. pUpper = 0;
  115048. }
  115049. }
  115050. pBuilder->pRec = pRec;
  115051. if( rc==SQLITE_OK ){
  115052. if( iUpper>iLower ){
  115053. nNew = sqlite3LogEst(iUpper - iLower);
  115054. /* TUNING: If both iUpper and iLower are derived from the same
  115055. ** sample, then assume they are 4x more selective. This brings
  115056. ** the estimated selectivity more in line with what it would be
  115057. ** if estimated without the use of STAT3/4 tables. */
  115058. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  115059. }else{
  115060. nNew = 10; assert( 10==sqlite3LogEst(2) );
  115061. }
  115062. if( nNew<nOut ){
  115063. nOut = nNew;
  115064. }
  115065. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  115066. (u32)iLower, (u32)iUpper, nOut));
  115067. }
  115068. }else{
  115069. int bDone = 0;
  115070. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  115071. if( bDone ) return rc;
  115072. }
  115073. }
  115074. #else
  115075. UNUSED_PARAMETER(pParse);
  115076. UNUSED_PARAMETER(pBuilder);
  115077. assert( pLower || pUpper );
  115078. #endif
  115079. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  115080. nNew = whereRangeAdjust(pLower, nOut);
  115081. nNew = whereRangeAdjust(pUpper, nNew);
  115082. /* TUNING: If there is both an upper and lower limit and neither limit
  115083. ** has an application-defined likelihood(), assume the range is
  115084. ** reduced by an additional 75%. This means that, by default, an open-ended
  115085. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  115086. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  115087. ** match 1/64 of the index. */
  115088. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  115089. nNew -= 20;
  115090. }
  115091. nOut -= (pLower!=0) + (pUpper!=0);
  115092. if( nNew<10 ) nNew = 10;
  115093. if( nNew<nOut ) nOut = nNew;
  115094. #if defined(WHERETRACE_ENABLED)
  115095. if( pLoop->nOut>nOut ){
  115096. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  115097. pLoop->nOut, nOut));
  115098. }
  115099. #endif
  115100. pLoop->nOut = (LogEst)nOut;
  115101. return rc;
  115102. }
  115103. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115104. /*
  115105. ** Estimate the number of rows that will be returned based on
  115106. ** an equality constraint x=VALUE and where that VALUE occurs in
  115107. ** the histogram data. This only works when x is the left-most
  115108. ** column of an index and sqlite_stat3 histogram data is available
  115109. ** for that index. When pExpr==NULL that means the constraint is
  115110. ** "x IS NULL" instead of "x=VALUE".
  115111. **
  115112. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  115113. ** If unable to make an estimate, leave *pnRow unchanged and return
  115114. ** non-zero.
  115115. **
  115116. ** This routine can fail if it is unable to load a collating sequence
  115117. ** required for string comparison, or if unable to allocate memory
  115118. ** for a UTF conversion required for comparison. The error is stored
  115119. ** in the pParse structure.
  115120. */
  115121. static int whereEqualScanEst(
  115122. Parse *pParse, /* Parsing & code generating context */
  115123. WhereLoopBuilder *pBuilder,
  115124. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  115125. tRowcnt *pnRow /* Write the revised row estimate here */
  115126. ){
  115127. Index *p = pBuilder->pNew->u.btree.pIndex;
  115128. int nEq = pBuilder->pNew->u.btree.nEq;
  115129. UnpackedRecord *pRec = pBuilder->pRec;
  115130. u8 aff; /* Column affinity */
  115131. int rc; /* Subfunction return code */
  115132. tRowcnt a[2]; /* Statistics */
  115133. int bOk;
  115134. assert( nEq>=1 );
  115135. assert( nEq<=p->nColumn );
  115136. assert( p->aSample!=0 );
  115137. assert( p->nSample>0 );
  115138. assert( pBuilder->nRecValid<nEq );
  115139. /* If values are not available for all fields of the index to the left
  115140. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  115141. if( pBuilder->nRecValid<(nEq-1) ){
  115142. return SQLITE_NOTFOUND;
  115143. }
  115144. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  115145. ** below would return the same value. */
  115146. if( nEq>=p->nColumn ){
  115147. *pnRow = 1;
  115148. return SQLITE_OK;
  115149. }
  115150. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
  115151. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  115152. pBuilder->pRec = pRec;
  115153. if( rc!=SQLITE_OK ) return rc;
  115154. if( bOk==0 ) return SQLITE_NOTFOUND;
  115155. pBuilder->nRecValid = nEq;
  115156. whereKeyStats(pParse, p, pRec, 0, a);
  115157. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  115158. *pnRow = a[1];
  115159. return rc;
  115160. }
  115161. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  115162. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115163. /*
  115164. ** Estimate the number of rows that will be returned based on
  115165. ** an IN constraint where the right-hand side of the IN operator
  115166. ** is a list of values. Example:
  115167. **
  115168. ** WHERE x IN (1,2,3,4)
  115169. **
  115170. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  115171. ** If unable to make an estimate, leave *pnRow unchanged and return
  115172. ** non-zero.
  115173. **
  115174. ** This routine can fail if it is unable to load a collating sequence
  115175. ** required for string comparison, or if unable to allocate memory
  115176. ** for a UTF conversion required for comparison. The error is stored
  115177. ** in the pParse structure.
  115178. */
  115179. static int whereInScanEst(
  115180. Parse *pParse, /* Parsing & code generating context */
  115181. WhereLoopBuilder *pBuilder,
  115182. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  115183. tRowcnt *pnRow /* Write the revised row estimate here */
  115184. ){
  115185. Index *p = pBuilder->pNew->u.btree.pIndex;
  115186. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  115187. int nRecValid = pBuilder->nRecValid;
  115188. int rc = SQLITE_OK; /* Subfunction return code */
  115189. tRowcnt nEst; /* Number of rows for a single term */
  115190. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  115191. int i; /* Loop counter */
  115192. assert( p->aSample!=0 );
  115193. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  115194. nEst = nRow0;
  115195. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  115196. nRowEst += nEst;
  115197. pBuilder->nRecValid = nRecValid;
  115198. }
  115199. if( rc==SQLITE_OK ){
  115200. if( nRowEst > nRow0 ) nRowEst = nRow0;
  115201. *pnRow = nRowEst;
  115202. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  115203. }
  115204. assert( pBuilder->nRecValid==nRecValid );
  115205. return rc;
  115206. }
  115207. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  115208. #ifdef WHERETRACE_ENABLED
  115209. /*
  115210. ** Print the content of a WhereTerm object
  115211. */
  115212. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  115213. if( pTerm==0 ){
  115214. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  115215. }else{
  115216. char zType[4];
  115217. memcpy(zType, "...", 4);
  115218. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  115219. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  115220. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  115221. sqlite3DebugPrintf(
  115222. "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
  115223. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  115224. pTerm->eOperator, pTerm->wtFlags);
  115225. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  115226. }
  115227. }
  115228. #endif
  115229. #ifdef WHERETRACE_ENABLED
  115230. /*
  115231. ** Print a WhereLoop object for debugging purposes
  115232. */
  115233. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  115234. WhereInfo *pWInfo = pWC->pWInfo;
  115235. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  115236. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  115237. Table *pTab = pItem->pTab;
  115238. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  115239. p->iTab, nb, p->maskSelf, nb, p->prereq);
  115240. sqlite3DebugPrintf(" %12s",
  115241. pItem->zAlias ? pItem->zAlias : pTab->zName);
  115242. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  115243. const char *zName;
  115244. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  115245. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  115246. int i = sqlite3Strlen30(zName) - 1;
  115247. while( zName[i]!='_' ) i--;
  115248. zName += i;
  115249. }
  115250. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  115251. }else{
  115252. sqlite3DebugPrintf("%20s","");
  115253. }
  115254. }else{
  115255. char *z;
  115256. if( p->u.vtab.idxStr ){
  115257. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  115258. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  115259. }else{
  115260. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  115261. }
  115262. sqlite3DebugPrintf(" %-19s", z);
  115263. sqlite3_free(z);
  115264. }
  115265. if( p->wsFlags & WHERE_SKIPSCAN ){
  115266. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  115267. }else{
  115268. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  115269. }
  115270. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  115271. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  115272. int i;
  115273. for(i=0; i<p->nLTerm; i++){
  115274. whereTermPrint(p->aLTerm[i], i);
  115275. }
  115276. }
  115277. }
  115278. #endif
  115279. /*
  115280. ** Convert bulk memory into a valid WhereLoop that can be passed
  115281. ** to whereLoopClear harmlessly.
  115282. */
  115283. static void whereLoopInit(WhereLoop *p){
  115284. p->aLTerm = p->aLTermSpace;
  115285. p->nLTerm = 0;
  115286. p->nLSlot = ArraySize(p->aLTermSpace);
  115287. p->wsFlags = 0;
  115288. }
  115289. /*
  115290. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  115291. */
  115292. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  115293. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  115294. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  115295. sqlite3_free(p->u.vtab.idxStr);
  115296. p->u.vtab.needFree = 0;
  115297. p->u.vtab.idxStr = 0;
  115298. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  115299. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  115300. sqlite3DbFree(db, p->u.btree.pIndex);
  115301. p->u.btree.pIndex = 0;
  115302. }
  115303. }
  115304. }
  115305. /*
  115306. ** Deallocate internal memory used by a WhereLoop object
  115307. */
  115308. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  115309. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  115310. whereLoopClearUnion(db, p);
  115311. whereLoopInit(p);
  115312. }
  115313. /*
  115314. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  115315. */
  115316. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  115317. WhereTerm **paNew;
  115318. if( p->nLSlot>=n ) return SQLITE_OK;
  115319. n = (n+7)&~7;
  115320. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  115321. if( paNew==0 ) return SQLITE_NOMEM;
  115322. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  115323. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  115324. p->aLTerm = paNew;
  115325. p->nLSlot = n;
  115326. return SQLITE_OK;
  115327. }
  115328. /*
  115329. ** Transfer content from the second pLoop into the first.
  115330. */
  115331. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  115332. whereLoopClearUnion(db, pTo);
  115333. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  115334. memset(&pTo->u, 0, sizeof(pTo->u));
  115335. return SQLITE_NOMEM;
  115336. }
  115337. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  115338. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  115339. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  115340. pFrom->u.vtab.needFree = 0;
  115341. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  115342. pFrom->u.btree.pIndex = 0;
  115343. }
  115344. return SQLITE_OK;
  115345. }
  115346. /*
  115347. ** Delete a WhereLoop object
  115348. */
  115349. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  115350. whereLoopClear(db, p);
  115351. sqlite3DbFree(db, p);
  115352. }
  115353. /*
  115354. ** Free a WhereInfo structure
  115355. */
  115356. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  115357. if( ALWAYS(pWInfo) ){
  115358. int i;
  115359. for(i=0; i<pWInfo->nLevel; i++){
  115360. WhereLevel *pLevel = &pWInfo->a[i];
  115361. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  115362. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  115363. }
  115364. }
  115365. sqlite3WhereClauseClear(&pWInfo->sWC);
  115366. while( pWInfo->pLoops ){
  115367. WhereLoop *p = pWInfo->pLoops;
  115368. pWInfo->pLoops = p->pNextLoop;
  115369. whereLoopDelete(db, p);
  115370. }
  115371. sqlite3DbFree(db, pWInfo);
  115372. }
  115373. }
  115374. /*
  115375. ** Return TRUE if all of the following are true:
  115376. **
  115377. ** (1) X has the same or lower cost that Y
  115378. ** (2) X is a proper subset of Y
  115379. ** (3) X skips at least as many columns as Y
  115380. **
  115381. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  115382. ** than Y and that every WHERE clause term used by X is also used
  115383. ** by Y.
  115384. **
  115385. ** If X is a proper subset of Y then Y is a better choice and ought
  115386. ** to have a lower cost. This routine returns TRUE when that cost
  115387. ** relationship is inverted and needs to be adjusted. The third rule
  115388. ** was added because if X uses skip-scan less than Y it still might
  115389. ** deserve a lower cost even if it is a proper subset of Y.
  115390. */
  115391. static int whereLoopCheaperProperSubset(
  115392. const WhereLoop *pX, /* First WhereLoop to compare */
  115393. const WhereLoop *pY /* Compare against this WhereLoop */
  115394. ){
  115395. int i, j;
  115396. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  115397. return 0; /* X is not a subset of Y */
  115398. }
  115399. if( pY->nSkip > pX->nSkip ) return 0;
  115400. if( pX->rRun >= pY->rRun ){
  115401. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  115402. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  115403. }
  115404. for(i=pX->nLTerm-1; i>=0; i--){
  115405. if( pX->aLTerm[i]==0 ) continue;
  115406. for(j=pY->nLTerm-1; j>=0; j--){
  115407. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  115408. }
  115409. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  115410. }
  115411. return 1; /* All conditions meet */
  115412. }
  115413. /*
  115414. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  115415. ** that:
  115416. **
  115417. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  115418. ** subset of pTemplate
  115419. **
  115420. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  115421. ** is a proper subset.
  115422. **
  115423. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  115424. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  115425. ** also used by Y.
  115426. */
  115427. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  115428. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  115429. for(; p; p=p->pNextLoop){
  115430. if( p->iTab!=pTemplate->iTab ) continue;
  115431. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  115432. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  115433. /* Adjust pTemplate cost downward so that it is cheaper than its
  115434. ** subset p. */
  115435. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  115436. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  115437. pTemplate->rRun = p->rRun;
  115438. pTemplate->nOut = p->nOut - 1;
  115439. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  115440. /* Adjust pTemplate cost upward so that it is costlier than p since
  115441. ** pTemplate is a proper subset of p */
  115442. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  115443. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  115444. pTemplate->rRun = p->rRun;
  115445. pTemplate->nOut = p->nOut + 1;
  115446. }
  115447. }
  115448. }
  115449. /*
  115450. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  115451. ** supplanted by pTemplate.
  115452. **
  115453. ** Return NULL if the WhereLoop list contains an entry that can supplant
  115454. ** pTemplate, in other words if pTemplate does not belong on the list.
  115455. **
  115456. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  115457. ** link that points to pX.
  115458. **
  115459. ** If pTemplate cannot supplant any existing element of the list but needs
  115460. ** to be added to the list, then return a pointer to the tail of the list.
  115461. */
  115462. static WhereLoop **whereLoopFindLesser(
  115463. WhereLoop **ppPrev,
  115464. const WhereLoop *pTemplate
  115465. ){
  115466. WhereLoop *p;
  115467. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  115468. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  115469. /* If either the iTab or iSortIdx values for two WhereLoop are different
  115470. ** then those WhereLoops need to be considered separately. Neither is
  115471. ** a candidate to replace the other. */
  115472. continue;
  115473. }
  115474. /* In the current implementation, the rSetup value is either zero
  115475. ** or the cost of building an automatic index (NlogN) and the NlogN
  115476. ** is the same for compatible WhereLoops. */
  115477. assert( p->rSetup==0 || pTemplate->rSetup==0
  115478. || p->rSetup==pTemplate->rSetup );
  115479. /* whereLoopAddBtree() always generates and inserts the automatic index
  115480. ** case first. Hence compatible candidate WhereLoops never have a larger
  115481. ** rSetup. Call this SETUP-INVARIANT */
  115482. assert( p->rSetup>=pTemplate->rSetup );
  115483. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  115484. ** UNIQUE constraint) with one or more == constraints is better
  115485. ** than an automatic index. Unless it is a skip-scan. */
  115486. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  115487. && (pTemplate->nSkip)==0
  115488. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  115489. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  115490. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  115491. ){
  115492. break;
  115493. }
  115494. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  115495. ** discarded. WhereLoop p is better if:
  115496. ** (1) p has no more dependencies than pTemplate, and
  115497. ** (2) p has an equal or lower cost than pTemplate
  115498. */
  115499. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  115500. && p->rSetup<=pTemplate->rSetup /* (2a) */
  115501. && p->rRun<=pTemplate->rRun /* (2b) */
  115502. && p->nOut<=pTemplate->nOut /* (2c) */
  115503. ){
  115504. return 0; /* Discard pTemplate */
  115505. }
  115506. /* If pTemplate is always better than p, then cause p to be overwritten
  115507. ** with pTemplate. pTemplate is better than p if:
  115508. ** (1) pTemplate has no more dependences than p, and
  115509. ** (2) pTemplate has an equal or lower cost than p.
  115510. */
  115511. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  115512. && p->rRun>=pTemplate->rRun /* (2a) */
  115513. && p->nOut>=pTemplate->nOut /* (2b) */
  115514. ){
  115515. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  115516. break; /* Cause p to be overwritten by pTemplate */
  115517. }
  115518. }
  115519. return ppPrev;
  115520. }
  115521. /*
  115522. ** Insert or replace a WhereLoop entry using the template supplied.
  115523. **
  115524. ** An existing WhereLoop entry might be overwritten if the new template
  115525. ** is better and has fewer dependencies. Or the template will be ignored
  115526. ** and no insert will occur if an existing WhereLoop is faster and has
  115527. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  115528. ** added based on the template.
  115529. **
  115530. ** If pBuilder->pOrSet is not NULL then we care about only the
  115531. ** prerequisites and rRun and nOut costs of the N best loops. That
  115532. ** information is gathered in the pBuilder->pOrSet object. This special
  115533. ** processing mode is used only for OR clause processing.
  115534. **
  115535. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  115536. ** still might overwrite similar loops with the new template if the
  115537. ** new template is better. Loops may be overwritten if the following
  115538. ** conditions are met:
  115539. **
  115540. ** (1) They have the same iTab.
  115541. ** (2) They have the same iSortIdx.
  115542. ** (3) The template has same or fewer dependencies than the current loop
  115543. ** (4) The template has the same or lower cost than the current loop
  115544. */
  115545. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  115546. WhereLoop **ppPrev, *p;
  115547. WhereInfo *pWInfo = pBuilder->pWInfo;
  115548. sqlite3 *db = pWInfo->pParse->db;
  115549. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  115550. ** and prereqs.
  115551. */
  115552. if( pBuilder->pOrSet!=0 ){
  115553. if( pTemplate->nLTerm ){
  115554. #if WHERETRACE_ENABLED
  115555. u16 n = pBuilder->pOrSet->n;
  115556. int x =
  115557. #endif
  115558. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  115559. pTemplate->nOut);
  115560. #if WHERETRACE_ENABLED /* 0x8 */
  115561. if( sqlite3WhereTrace & 0x8 ){
  115562. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  115563. whereLoopPrint(pTemplate, pBuilder->pWC);
  115564. }
  115565. #endif
  115566. }
  115567. return SQLITE_OK;
  115568. }
  115569. /* Look for an existing WhereLoop to replace with pTemplate
  115570. */
  115571. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  115572. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  115573. if( ppPrev==0 ){
  115574. /* There already exists a WhereLoop on the list that is better
  115575. ** than pTemplate, so just ignore pTemplate */
  115576. #if WHERETRACE_ENABLED /* 0x8 */
  115577. if( sqlite3WhereTrace & 0x8 ){
  115578. sqlite3DebugPrintf(" skip: ");
  115579. whereLoopPrint(pTemplate, pBuilder->pWC);
  115580. }
  115581. #endif
  115582. return SQLITE_OK;
  115583. }else{
  115584. p = *ppPrev;
  115585. }
  115586. /* If we reach this point it means that either p[] should be overwritten
  115587. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  115588. ** WhereLoop and insert it.
  115589. */
  115590. #if WHERETRACE_ENABLED /* 0x8 */
  115591. if( sqlite3WhereTrace & 0x8 ){
  115592. if( p!=0 ){
  115593. sqlite3DebugPrintf("replace: ");
  115594. whereLoopPrint(p, pBuilder->pWC);
  115595. }
  115596. sqlite3DebugPrintf(" add: ");
  115597. whereLoopPrint(pTemplate, pBuilder->pWC);
  115598. }
  115599. #endif
  115600. if( p==0 ){
  115601. /* Allocate a new WhereLoop to add to the end of the list */
  115602. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  115603. if( p==0 ) return SQLITE_NOMEM;
  115604. whereLoopInit(p);
  115605. p->pNextLoop = 0;
  115606. }else{
  115607. /* We will be overwriting WhereLoop p[]. But before we do, first
  115608. ** go through the rest of the list and delete any other entries besides
  115609. ** p[] that are also supplated by pTemplate */
  115610. WhereLoop **ppTail = &p->pNextLoop;
  115611. WhereLoop *pToDel;
  115612. while( *ppTail ){
  115613. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  115614. if( ppTail==0 ) break;
  115615. pToDel = *ppTail;
  115616. if( pToDel==0 ) break;
  115617. *ppTail = pToDel->pNextLoop;
  115618. #if WHERETRACE_ENABLED /* 0x8 */
  115619. if( sqlite3WhereTrace & 0x8 ){
  115620. sqlite3DebugPrintf(" delete: ");
  115621. whereLoopPrint(pToDel, pBuilder->pWC);
  115622. }
  115623. #endif
  115624. whereLoopDelete(db, pToDel);
  115625. }
  115626. }
  115627. whereLoopXfer(db, p, pTemplate);
  115628. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  115629. Index *pIndex = p->u.btree.pIndex;
  115630. if( pIndex && pIndex->tnum==0 ){
  115631. p->u.btree.pIndex = 0;
  115632. }
  115633. }
  115634. return SQLITE_OK;
  115635. }
  115636. /*
  115637. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  115638. ** WHERE clause that reference the loop but which are not used by an
  115639. ** index.
  115640. *
  115641. ** For every WHERE clause term that is not used by the index
  115642. ** and which has a truth probability assigned by one of the likelihood(),
  115643. ** likely(), or unlikely() SQL functions, reduce the estimated number
  115644. ** of output rows by the probability specified.
  115645. **
  115646. ** TUNING: For every WHERE clause term that is not used by the index
  115647. ** and which does not have an assigned truth probability, heuristics
  115648. ** described below are used to try to estimate the truth probability.
  115649. ** TODO --> Perhaps this is something that could be improved by better
  115650. ** table statistics.
  115651. **
  115652. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  115653. ** value corresponds to -1 in LogEst notation, so this means decrement
  115654. ** the WhereLoop.nOut field for every such WHERE clause term.
  115655. **
  115656. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  115657. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  115658. ** final output row estimate is no greater than 1/4 of the total number
  115659. ** of rows in the table. In other words, assume that x==EXPR will filter
  115660. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  115661. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  115662. ** on the "x" column and so in that case only cap the output row estimate
  115663. ** at 1/2 instead of 1/4.
  115664. */
  115665. static void whereLoopOutputAdjust(
  115666. WhereClause *pWC, /* The WHERE clause */
  115667. WhereLoop *pLoop, /* The loop to adjust downward */
  115668. LogEst nRow /* Number of rows in the entire table */
  115669. ){
  115670. WhereTerm *pTerm, *pX;
  115671. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  115672. int i, j, k;
  115673. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  115674. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  115675. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  115676. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  115677. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  115678. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  115679. for(j=pLoop->nLTerm-1; j>=0; j--){
  115680. pX = pLoop->aLTerm[j];
  115681. if( pX==0 ) continue;
  115682. if( pX==pTerm ) break;
  115683. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  115684. }
  115685. if( j<0 ){
  115686. if( pTerm->truthProb<=0 ){
  115687. /* If a truth probability is specified using the likelihood() hints,
  115688. ** then use the probability provided by the application. */
  115689. pLoop->nOut += pTerm->truthProb;
  115690. }else{
  115691. /* In the absence of explicit truth probabilities, use heuristics to
  115692. ** guess a reasonable truth probability. */
  115693. pLoop->nOut--;
  115694. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  115695. Expr *pRight = pTerm->pExpr->pRight;
  115696. testcase( pTerm->pExpr->op==TK_IS );
  115697. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  115698. k = 10;
  115699. }else{
  115700. k = 20;
  115701. }
  115702. if( iReduce<k ) iReduce = k;
  115703. }
  115704. }
  115705. }
  115706. }
  115707. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  115708. }
  115709. /*
  115710. ** Adjust the cost C by the costMult facter T. This only occurs if
  115711. ** compiled with -DSQLITE_ENABLE_COSTMULT
  115712. */
  115713. #ifdef SQLITE_ENABLE_COSTMULT
  115714. # define ApplyCostMultiplier(C,T) C += T
  115715. #else
  115716. # define ApplyCostMultiplier(C,T)
  115717. #endif
  115718. /*
  115719. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  115720. ** index pIndex. Try to match one more.
  115721. **
  115722. ** When this function is called, pBuilder->pNew->nOut contains the
  115723. ** number of rows expected to be visited by filtering using the nEq
  115724. ** terms only. If it is modified, this value is restored before this
  115725. ** function returns.
  115726. **
  115727. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  115728. ** INTEGER PRIMARY KEY.
  115729. */
  115730. static int whereLoopAddBtreeIndex(
  115731. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  115732. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  115733. Index *pProbe, /* An index on pSrc */
  115734. LogEst nInMul /* log(Number of iterations due to IN) */
  115735. ){
  115736. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  115737. Parse *pParse = pWInfo->pParse; /* Parsing context */
  115738. sqlite3 *db = pParse->db; /* Database connection malloc context */
  115739. WhereLoop *pNew; /* Template WhereLoop under construction */
  115740. WhereTerm *pTerm; /* A WhereTerm under consideration */
  115741. int opMask; /* Valid operators for constraints */
  115742. WhereScan scan; /* Iterator for WHERE terms */
  115743. Bitmask saved_prereq; /* Original value of pNew->prereq */
  115744. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  115745. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  115746. u16 saved_nSkip; /* Original value of pNew->nSkip */
  115747. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  115748. LogEst saved_nOut; /* Original value of pNew->nOut */
  115749. int rc = SQLITE_OK; /* Return code */
  115750. LogEst rSize; /* Number of rows in the table */
  115751. LogEst rLogSize; /* Logarithm of table size */
  115752. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  115753. pNew = pBuilder->pNew;
  115754. if( db->mallocFailed ) return SQLITE_NOMEM;
  115755. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  115756. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  115757. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  115758. opMask = WO_LT|WO_LE;
  115759. }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
  115760. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  115761. }else{
  115762. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  115763. }
  115764. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  115765. assert( pNew->u.btree.nEq<pProbe->nColumn );
  115766. saved_nEq = pNew->u.btree.nEq;
  115767. saved_nSkip = pNew->nSkip;
  115768. saved_nLTerm = pNew->nLTerm;
  115769. saved_wsFlags = pNew->wsFlags;
  115770. saved_prereq = pNew->prereq;
  115771. saved_nOut = pNew->nOut;
  115772. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  115773. opMask, pProbe);
  115774. pNew->rSetup = 0;
  115775. rSize = pProbe->aiRowLogEst[0];
  115776. rLogSize = estLog(rSize);
  115777. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  115778. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  115779. LogEst rCostIdx;
  115780. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  115781. int nIn = 0;
  115782. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115783. int nRecValid = pBuilder->nRecValid;
  115784. #endif
  115785. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  115786. && indexColumnNotNull(pProbe, saved_nEq)
  115787. ){
  115788. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  115789. }
  115790. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  115791. /* Do not allow the upper bound of a LIKE optimization range constraint
  115792. ** to mix with a lower range bound from some other source */
  115793. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  115794. pNew->wsFlags = saved_wsFlags;
  115795. pNew->u.btree.nEq = saved_nEq;
  115796. pNew->nLTerm = saved_nLTerm;
  115797. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  115798. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  115799. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  115800. assert( nInMul==0
  115801. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  115802. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  115803. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  115804. );
  115805. if( eOp & WO_IN ){
  115806. Expr *pExpr = pTerm->pExpr;
  115807. pNew->wsFlags |= WHERE_COLUMN_IN;
  115808. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  115809. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  115810. nIn = 46; assert( 46==sqlite3LogEst(25) );
  115811. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  115812. /* "x IN (value, value, ...)" */
  115813. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  115814. }
  115815. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  115816. ** changes "x IN (?)" into "x=?". */
  115817. }else if( eOp & (WO_EQ|WO_IS) ){
  115818. int iCol = pProbe->aiColumn[saved_nEq];
  115819. pNew->wsFlags |= WHERE_COLUMN_EQ;
  115820. assert( saved_nEq==pNew->u.btree.nEq );
  115821. if( iCol==XN_ROWID
  115822. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  115823. ){
  115824. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  115825. pNew->wsFlags |= WHERE_UNQ_WANTED;
  115826. }else{
  115827. pNew->wsFlags |= WHERE_ONEROW;
  115828. }
  115829. }
  115830. }else if( eOp & WO_ISNULL ){
  115831. pNew->wsFlags |= WHERE_COLUMN_NULL;
  115832. }else if( eOp & (WO_GT|WO_GE) ){
  115833. testcase( eOp & WO_GT );
  115834. testcase( eOp & WO_GE );
  115835. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  115836. pBtm = pTerm;
  115837. pTop = 0;
  115838. if( pTerm->wtFlags & TERM_LIKEOPT ){
  115839. /* Range contraints that come from the LIKE optimization are
  115840. ** always used in pairs. */
  115841. pTop = &pTerm[1];
  115842. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  115843. assert( pTop->wtFlags & TERM_LIKEOPT );
  115844. assert( pTop->eOperator==WO_LT );
  115845. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  115846. pNew->aLTerm[pNew->nLTerm++] = pTop;
  115847. pNew->wsFlags |= WHERE_TOP_LIMIT;
  115848. }
  115849. }else{
  115850. assert( eOp & (WO_LT|WO_LE) );
  115851. testcase( eOp & WO_LT );
  115852. testcase( eOp & WO_LE );
  115853. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  115854. pTop = pTerm;
  115855. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  115856. pNew->aLTerm[pNew->nLTerm-2] : 0;
  115857. }
  115858. /* At this point pNew->nOut is set to the number of rows expected to
  115859. ** be visited by the index scan before considering term pTerm, or the
  115860. ** values of nIn and nInMul. In other words, assuming that all
  115861. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  115862. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  115863. assert( pNew->nOut==saved_nOut );
  115864. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  115865. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  115866. ** data, using some other estimate. */
  115867. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  115868. }else{
  115869. int nEq = ++pNew->u.btree.nEq;
  115870. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  115871. assert( pNew->nOut==saved_nOut );
  115872. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  115873. assert( (eOp & WO_IN) || nIn==0 );
  115874. testcase( eOp & WO_IN );
  115875. pNew->nOut += pTerm->truthProb;
  115876. pNew->nOut -= nIn;
  115877. }else{
  115878. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115879. tRowcnt nOut = 0;
  115880. if( nInMul==0
  115881. && pProbe->nSample
  115882. && pNew->u.btree.nEq<=pProbe->nSampleCol
  115883. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  115884. ){
  115885. Expr *pExpr = pTerm->pExpr;
  115886. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  115887. testcase( eOp & WO_EQ );
  115888. testcase( eOp & WO_IS );
  115889. testcase( eOp & WO_ISNULL );
  115890. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  115891. }else{
  115892. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  115893. }
  115894. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  115895. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  115896. if( nOut ){
  115897. pNew->nOut = sqlite3LogEst(nOut);
  115898. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  115899. pNew->nOut -= nIn;
  115900. }
  115901. }
  115902. if( nOut==0 )
  115903. #endif
  115904. {
  115905. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  115906. if( eOp & WO_ISNULL ){
  115907. /* TUNING: If there is no likelihood() value, assume that a
  115908. ** "col IS NULL" expression matches twice as many rows
  115909. ** as (col=?). */
  115910. pNew->nOut += 10;
  115911. }
  115912. }
  115913. }
  115914. }
  115915. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  115916. ** it to pNew->rRun, which is currently set to the cost of the index
  115917. ** seek only. Then, if this is a non-covering index, add the cost of
  115918. ** visiting the rows in the main table. */
  115919. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  115920. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  115921. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  115922. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  115923. }
  115924. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  115925. nOutUnadjusted = pNew->nOut;
  115926. pNew->rRun += nInMul + nIn;
  115927. pNew->nOut += nInMul + nIn;
  115928. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  115929. rc = whereLoopInsert(pBuilder, pNew);
  115930. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  115931. pNew->nOut = saved_nOut;
  115932. }else{
  115933. pNew->nOut = nOutUnadjusted;
  115934. }
  115935. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  115936. && pNew->u.btree.nEq<pProbe->nColumn
  115937. ){
  115938. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  115939. }
  115940. pNew->nOut = saved_nOut;
  115941. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115942. pBuilder->nRecValid = nRecValid;
  115943. #endif
  115944. }
  115945. pNew->prereq = saved_prereq;
  115946. pNew->u.btree.nEq = saved_nEq;
  115947. pNew->nSkip = saved_nSkip;
  115948. pNew->wsFlags = saved_wsFlags;
  115949. pNew->nOut = saved_nOut;
  115950. pNew->nLTerm = saved_nLTerm;
  115951. /* Consider using a skip-scan if there are no WHERE clause constraints
  115952. ** available for the left-most terms of the index, and if the average
  115953. ** number of repeats in the left-most terms is at least 18.
  115954. **
  115955. ** The magic number 18 is selected on the basis that scanning 17 rows
  115956. ** is almost always quicker than an index seek (even though if the index
  115957. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  115958. ** the code). And, even if it is not, it should not be too much slower.
  115959. ** On the other hand, the extra seeks could end up being significantly
  115960. ** more expensive. */
  115961. assert( 42==sqlite3LogEst(18) );
  115962. if( saved_nEq==saved_nSkip
  115963. && saved_nEq+1<pProbe->nKeyCol
  115964. && pProbe->noSkipScan==0
  115965. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  115966. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  115967. ){
  115968. LogEst nIter;
  115969. pNew->u.btree.nEq++;
  115970. pNew->nSkip++;
  115971. pNew->aLTerm[pNew->nLTerm++] = 0;
  115972. pNew->wsFlags |= WHERE_SKIPSCAN;
  115973. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  115974. pNew->nOut -= nIter;
  115975. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  115976. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  115977. nIter += 5;
  115978. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  115979. pNew->nOut = saved_nOut;
  115980. pNew->u.btree.nEq = saved_nEq;
  115981. pNew->nSkip = saved_nSkip;
  115982. pNew->wsFlags = saved_wsFlags;
  115983. }
  115984. return rc;
  115985. }
  115986. /*
  115987. ** Return True if it is possible that pIndex might be useful in
  115988. ** implementing the ORDER BY clause in pBuilder.
  115989. **
  115990. ** Return False if pBuilder does not contain an ORDER BY clause or
  115991. ** if there is no way for pIndex to be useful in implementing that
  115992. ** ORDER BY clause.
  115993. */
  115994. static int indexMightHelpWithOrderBy(
  115995. WhereLoopBuilder *pBuilder,
  115996. Index *pIndex,
  115997. int iCursor
  115998. ){
  115999. ExprList *pOB;
  116000. ExprList *aColExpr;
  116001. int ii, jj;
  116002. if( pIndex->bUnordered ) return 0;
  116003. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  116004. for(ii=0; ii<pOB->nExpr; ii++){
  116005. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  116006. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  116007. if( pExpr->iColumn<0 ) return 1;
  116008. for(jj=0; jj<pIndex->nKeyCol; jj++){
  116009. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  116010. }
  116011. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  116012. for(jj=0; jj<pIndex->nKeyCol; jj++){
  116013. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  116014. if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  116015. return 1;
  116016. }
  116017. }
  116018. }
  116019. }
  116020. return 0;
  116021. }
  116022. /*
  116023. ** Return a bitmask where 1s indicate that the corresponding column of
  116024. ** the table is used by an index. Only the first 63 columns are considered.
  116025. */
  116026. static Bitmask columnsInIndex(Index *pIdx){
  116027. Bitmask m = 0;
  116028. int j;
  116029. for(j=pIdx->nColumn-1; j>=0; j--){
  116030. int x = pIdx->aiColumn[j];
  116031. if( x>=0 ){
  116032. testcase( x==BMS-1 );
  116033. testcase( x==BMS-2 );
  116034. if( x<BMS-1 ) m |= MASKBIT(x);
  116035. }
  116036. }
  116037. return m;
  116038. }
  116039. /* Check to see if a partial index with pPartIndexWhere can be used
  116040. ** in the current query. Return true if it can be and false if not.
  116041. */
  116042. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  116043. int i;
  116044. WhereTerm *pTerm;
  116045. while( pWhere->op==TK_AND ){
  116046. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  116047. pWhere = pWhere->pRight;
  116048. }
  116049. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  116050. Expr *pExpr = pTerm->pExpr;
  116051. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  116052. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  116053. ){
  116054. return 1;
  116055. }
  116056. }
  116057. return 0;
  116058. }
  116059. /*
  116060. ** Add all WhereLoop objects for a single table of the join where the table
  116061. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  116062. ** a b-tree table, not a virtual table.
  116063. **
  116064. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  116065. ** are calculated as follows:
  116066. **
  116067. ** For a full scan, assuming the table (or index) contains nRow rows:
  116068. **
  116069. ** cost = nRow * 3.0 // full-table scan
  116070. ** cost = nRow * K // scan of covering index
  116071. ** cost = nRow * (K+3.0) // scan of non-covering index
  116072. **
  116073. ** where K is a value between 1.1 and 3.0 set based on the relative
  116074. ** estimated average size of the index and table records.
  116075. **
  116076. ** For an index scan, where nVisit is the number of index rows visited
  116077. ** by the scan, and nSeek is the number of seek operations required on
  116078. ** the index b-tree:
  116079. **
  116080. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  116081. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  116082. **
  116083. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  116084. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  116085. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  116086. **
  116087. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  116088. ** of uncertainty. For this reason, scoring is designed to pick plans that
  116089. ** "do the least harm" if the estimates are inaccurate. For example, a
  116090. ** log(nRow) factor is omitted from a non-covering index scan in order to
  116091. ** bias the scoring in favor of using an index, since the worst-case
  116092. ** performance of using an index is far better than the worst-case performance
  116093. ** of a full table scan.
  116094. */
  116095. static int whereLoopAddBtree(
  116096. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  116097. Bitmask mExtra /* Extra prerequesites for using this table */
  116098. ){
  116099. WhereInfo *pWInfo; /* WHERE analysis context */
  116100. Index *pProbe; /* An index we are evaluating */
  116101. Index sPk; /* A fake index object for the primary key */
  116102. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  116103. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  116104. SrcList *pTabList; /* The FROM clause */
  116105. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  116106. WhereLoop *pNew; /* Template WhereLoop object */
  116107. int rc = SQLITE_OK; /* Return code */
  116108. int iSortIdx = 1; /* Index number */
  116109. int b; /* A boolean value */
  116110. LogEst rSize; /* number of rows in the table */
  116111. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  116112. WhereClause *pWC; /* The parsed WHERE clause */
  116113. Table *pTab; /* Table being queried */
  116114. pNew = pBuilder->pNew;
  116115. pWInfo = pBuilder->pWInfo;
  116116. pTabList = pWInfo->pTabList;
  116117. pSrc = pTabList->a + pNew->iTab;
  116118. pTab = pSrc->pTab;
  116119. pWC = pBuilder->pWC;
  116120. assert( !IsVirtual(pSrc->pTab) );
  116121. if( pSrc->pIBIndex ){
  116122. /* An INDEXED BY clause specifies a particular index to use */
  116123. pProbe = pSrc->pIBIndex;
  116124. }else if( !HasRowid(pTab) ){
  116125. pProbe = pTab->pIndex;
  116126. }else{
  116127. /* There is no INDEXED BY clause. Create a fake Index object in local
  116128. ** variable sPk to represent the rowid primary key index. Make this
  116129. ** fake index the first in a chain of Index objects with all of the real
  116130. ** indices to follow */
  116131. Index *pFirst; /* First of real indices on the table */
  116132. memset(&sPk, 0, sizeof(Index));
  116133. sPk.nKeyCol = 1;
  116134. sPk.nColumn = 1;
  116135. sPk.aiColumn = &aiColumnPk;
  116136. sPk.aiRowLogEst = aiRowEstPk;
  116137. sPk.onError = OE_Replace;
  116138. sPk.pTable = pTab;
  116139. sPk.szIdxRow = pTab->szTabRow;
  116140. aiRowEstPk[0] = pTab->nRowLogEst;
  116141. aiRowEstPk[1] = 0;
  116142. pFirst = pSrc->pTab->pIndex;
  116143. if( pSrc->fg.notIndexed==0 ){
  116144. /* The real indices of the table are only considered if the
  116145. ** NOT INDEXED qualifier is omitted from the FROM clause */
  116146. sPk.pNext = pFirst;
  116147. }
  116148. pProbe = &sPk;
  116149. }
  116150. rSize = pTab->nRowLogEst;
  116151. rLogSize = estLog(rSize);
  116152. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  116153. /* Automatic indexes */
  116154. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  116155. && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
  116156. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  116157. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  116158. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  116159. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  116160. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  116161. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  116162. ){
  116163. /* Generate auto-index WhereLoops */
  116164. WhereTerm *pTerm;
  116165. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  116166. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  116167. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  116168. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  116169. pNew->u.btree.nEq = 1;
  116170. pNew->nSkip = 0;
  116171. pNew->u.btree.pIndex = 0;
  116172. pNew->nLTerm = 1;
  116173. pNew->aLTerm[0] = pTerm;
  116174. /* TUNING: One-time cost for computing the automatic index is
  116175. ** estimated to be X*N*log2(N) where N is the number of rows in
  116176. ** the table being indexed and where X is 7 (LogEst=28) for normal
  116177. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  116178. ** of X is smaller for views and subqueries so that the query planner
  116179. ** will be more aggressive about generating automatic indexes for
  116180. ** those objects, since there is no opportunity to add schema
  116181. ** indexes on subqueries and views. */
  116182. pNew->rSetup = rLogSize + rSize + 4;
  116183. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  116184. pNew->rSetup += 24;
  116185. }
  116186. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  116187. /* TUNING: Each index lookup yields 20 rows in the table. This
  116188. ** is more than the usual guess of 10 rows, since we have no way
  116189. ** of knowing how selective the index will ultimately be. It would
  116190. ** not be unreasonable to make this value much larger. */
  116191. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  116192. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  116193. pNew->wsFlags = WHERE_AUTO_INDEX;
  116194. pNew->prereq = mExtra | pTerm->prereqRight;
  116195. rc = whereLoopInsert(pBuilder, pNew);
  116196. }
  116197. }
  116198. }
  116199. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  116200. /* Loop over all indices
  116201. */
  116202. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  116203. if( pProbe->pPartIdxWhere!=0
  116204. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  116205. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  116206. continue; /* Partial index inappropriate for this query */
  116207. }
  116208. rSize = pProbe->aiRowLogEst[0];
  116209. pNew->u.btree.nEq = 0;
  116210. pNew->nSkip = 0;
  116211. pNew->nLTerm = 0;
  116212. pNew->iSortIdx = 0;
  116213. pNew->rSetup = 0;
  116214. pNew->prereq = mExtra;
  116215. pNew->nOut = rSize;
  116216. pNew->u.btree.pIndex = pProbe;
  116217. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  116218. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  116219. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  116220. if( pProbe->tnum<=0 ){
  116221. /* Integer primary key index */
  116222. pNew->wsFlags = WHERE_IPK;
  116223. /* Full table scan */
  116224. pNew->iSortIdx = b ? iSortIdx : 0;
  116225. /* TUNING: Cost of full table scan is (N*3.0). */
  116226. pNew->rRun = rSize + 16;
  116227. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  116228. whereLoopOutputAdjust(pWC, pNew, rSize);
  116229. rc = whereLoopInsert(pBuilder, pNew);
  116230. pNew->nOut = rSize;
  116231. if( rc ) break;
  116232. }else{
  116233. Bitmask m;
  116234. if( pProbe->isCovering ){
  116235. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  116236. m = 0;
  116237. }else{
  116238. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  116239. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  116240. }
  116241. /* Full scan via index */
  116242. if( b
  116243. || !HasRowid(pTab)
  116244. || ( m==0
  116245. && pProbe->bUnordered==0
  116246. && (pProbe->szIdxRow<pTab->szTabRow)
  116247. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  116248. && sqlite3GlobalConfig.bUseCis
  116249. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  116250. )
  116251. ){
  116252. pNew->iSortIdx = b ? iSortIdx : 0;
  116253. /* The cost of visiting the index rows is N*K, where K is
  116254. ** between 1.1 and 3.0, depending on the relative sizes of the
  116255. ** index and table rows. If this is a non-covering index scan,
  116256. ** also add the cost of visiting table rows (N*3.0). */
  116257. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  116258. if( m!=0 ){
  116259. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  116260. }
  116261. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  116262. whereLoopOutputAdjust(pWC, pNew, rSize);
  116263. rc = whereLoopInsert(pBuilder, pNew);
  116264. pNew->nOut = rSize;
  116265. if( rc ) break;
  116266. }
  116267. }
  116268. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  116269. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116270. sqlite3Stat4ProbeFree(pBuilder->pRec);
  116271. pBuilder->nRecValid = 0;
  116272. pBuilder->pRec = 0;
  116273. #endif
  116274. /* If there was an INDEXED BY clause, then only that one index is
  116275. ** considered. */
  116276. if( pSrc->pIBIndex ) break;
  116277. }
  116278. return rc;
  116279. }
  116280. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116281. /*
  116282. ** Add all WhereLoop objects for a table of the join identified by
  116283. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  116284. **
  116285. ** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
  116286. ** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
  116287. ** entries that occur before the virtual table in the FROM clause and are
  116288. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  116289. ** mUnusable mask contains all FROM clause entries that occur after the
  116290. ** virtual table and are separated from it by at least one LEFT or
  116291. ** CROSS JOIN.
  116292. **
  116293. ** For example, if the query were:
  116294. **
  116295. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  116296. **
  116297. ** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
  116298. **
  116299. ** All the tables in mExtra must be scanned before the current virtual
  116300. ** table. So any terms for which all prerequisites are satisfied by
  116301. ** mExtra may be specified as "usable" in all calls to xBestIndex.
  116302. ** Conversely, all tables in mUnusable must be scanned after the current
  116303. ** virtual table, so any terms for which the prerequisites overlap with
  116304. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  116305. */
  116306. static int whereLoopAddVirtual(
  116307. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  116308. Bitmask mExtra, /* Tables that must be scanned before this one */
  116309. Bitmask mUnusable /* Tables that must be scanned after this one */
  116310. ){
  116311. WhereInfo *pWInfo; /* WHERE analysis context */
  116312. Parse *pParse; /* The parsing context */
  116313. WhereClause *pWC; /* The WHERE clause */
  116314. struct SrcList_item *pSrc; /* The FROM clause term to search */
  116315. Table *pTab;
  116316. sqlite3 *db;
  116317. sqlite3_index_info *pIdxInfo;
  116318. struct sqlite3_index_constraint *pIdxCons;
  116319. struct sqlite3_index_constraint_usage *pUsage;
  116320. WhereTerm *pTerm;
  116321. int i, j;
  116322. int iTerm, mxTerm;
  116323. int nConstraint;
  116324. int seenIn = 0; /* True if an IN operator is seen */
  116325. int seenVar = 0; /* True if a non-constant constraint is seen */
  116326. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  116327. WhereLoop *pNew;
  116328. int rc = SQLITE_OK;
  116329. assert( (mExtra & mUnusable)==0 );
  116330. pWInfo = pBuilder->pWInfo;
  116331. pParse = pWInfo->pParse;
  116332. db = pParse->db;
  116333. pWC = pBuilder->pWC;
  116334. pNew = pBuilder->pNew;
  116335. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  116336. pTab = pSrc->pTab;
  116337. assert( IsVirtual(pTab) );
  116338. pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
  116339. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  116340. pNew->prereq = 0;
  116341. pNew->rSetup = 0;
  116342. pNew->wsFlags = WHERE_VIRTUALTABLE;
  116343. pNew->nLTerm = 0;
  116344. pNew->u.vtab.needFree = 0;
  116345. pUsage = pIdxInfo->aConstraintUsage;
  116346. nConstraint = pIdxInfo->nConstraint;
  116347. if( whereLoopResize(db, pNew, nConstraint) ){
  116348. sqlite3DbFree(db, pIdxInfo);
  116349. return SQLITE_NOMEM;
  116350. }
  116351. for(iPhase=0; iPhase<=3; iPhase++){
  116352. if( !seenIn && (iPhase&1)!=0 ){
  116353. iPhase++;
  116354. if( iPhase>3 ) break;
  116355. }
  116356. if( !seenVar && iPhase>1 ) break;
  116357. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  116358. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  116359. j = pIdxCons->iTermOffset;
  116360. pTerm = &pWC->a[j];
  116361. switch( iPhase ){
  116362. case 0: /* Constants without IN operator */
  116363. pIdxCons->usable = 0;
  116364. if( (pTerm->eOperator & WO_IN)!=0 ){
  116365. seenIn = 1;
  116366. }
  116367. if( (pTerm->prereqRight & ~mExtra)!=0 ){
  116368. seenVar = 1;
  116369. }else if( (pTerm->eOperator & WO_IN)==0 ){
  116370. pIdxCons->usable = 1;
  116371. }
  116372. break;
  116373. case 1: /* Constants with IN operators */
  116374. assert( seenIn );
  116375. pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
  116376. break;
  116377. case 2: /* Variables without IN */
  116378. assert( seenVar );
  116379. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  116380. break;
  116381. default: /* Variables with IN */
  116382. assert( seenVar && seenIn );
  116383. pIdxCons->usable = 1;
  116384. break;
  116385. }
  116386. }
  116387. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  116388. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  116389. pIdxInfo->idxStr = 0;
  116390. pIdxInfo->idxNum = 0;
  116391. pIdxInfo->needToFreeIdxStr = 0;
  116392. pIdxInfo->orderByConsumed = 0;
  116393. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  116394. pIdxInfo->estimatedRows = 25;
  116395. pIdxInfo->idxFlags = 0;
  116396. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  116397. if( rc ) goto whereLoopAddVtab_exit;
  116398. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  116399. pNew->prereq = mExtra;
  116400. mxTerm = -1;
  116401. assert( pNew->nLSlot>=nConstraint );
  116402. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  116403. pNew->u.vtab.omitMask = 0;
  116404. for(i=0; i<nConstraint; i++, pIdxCons++){
  116405. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  116406. j = pIdxCons->iTermOffset;
  116407. if( iTerm>=nConstraint
  116408. || j<0
  116409. || j>=pWC->nTerm
  116410. || pNew->aLTerm[iTerm]!=0
  116411. ){
  116412. rc = SQLITE_ERROR;
  116413. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  116414. goto whereLoopAddVtab_exit;
  116415. }
  116416. testcase( iTerm==nConstraint-1 );
  116417. testcase( j==0 );
  116418. testcase( j==pWC->nTerm-1 );
  116419. pTerm = &pWC->a[j];
  116420. pNew->prereq |= pTerm->prereqRight;
  116421. assert( iTerm<pNew->nLSlot );
  116422. pNew->aLTerm[iTerm] = pTerm;
  116423. if( iTerm>mxTerm ) mxTerm = iTerm;
  116424. testcase( iTerm==15 );
  116425. testcase( iTerm==16 );
  116426. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  116427. if( (pTerm->eOperator & WO_IN)!=0 ){
  116428. if( pUsage[i].omit==0 ){
  116429. /* Do not attempt to use an IN constraint if the virtual table
  116430. ** says that the equivalent EQ constraint cannot be safely omitted.
  116431. ** If we do attempt to use such a constraint, some rows might be
  116432. ** repeated in the output. */
  116433. break;
  116434. }
  116435. /* A virtual table that is constrained by an IN clause may not
  116436. ** consume the ORDER BY clause because (1) the order of IN terms
  116437. ** is not necessarily related to the order of output terms and
  116438. ** (2) Multiple outputs from a single IN value will not merge
  116439. ** together. */
  116440. pIdxInfo->orderByConsumed = 0;
  116441. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  116442. }
  116443. }
  116444. }
  116445. if( i>=nConstraint ){
  116446. pNew->nLTerm = mxTerm+1;
  116447. assert( pNew->nLTerm<=pNew->nLSlot );
  116448. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  116449. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  116450. pIdxInfo->needToFreeIdxStr = 0;
  116451. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  116452. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  116453. pIdxInfo->nOrderBy : 0);
  116454. pNew->rSetup = 0;
  116455. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  116456. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  116457. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  116458. ** that the scan will visit at most one row. Clear it otherwise. */
  116459. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  116460. pNew->wsFlags |= WHERE_ONEROW;
  116461. }else{
  116462. pNew->wsFlags &= ~WHERE_ONEROW;
  116463. }
  116464. whereLoopInsert(pBuilder, pNew);
  116465. if( pNew->u.vtab.needFree ){
  116466. sqlite3_free(pNew->u.vtab.idxStr);
  116467. pNew->u.vtab.needFree = 0;
  116468. }
  116469. }
  116470. }
  116471. whereLoopAddVtab_exit:
  116472. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  116473. sqlite3DbFree(db, pIdxInfo);
  116474. return rc;
  116475. }
  116476. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116477. /*
  116478. ** Add WhereLoop entries to handle OR terms. This works for either
  116479. ** btrees or virtual tables.
  116480. */
  116481. static int whereLoopAddOr(
  116482. WhereLoopBuilder *pBuilder,
  116483. Bitmask mExtra,
  116484. Bitmask mUnusable
  116485. ){
  116486. WhereInfo *pWInfo = pBuilder->pWInfo;
  116487. WhereClause *pWC;
  116488. WhereLoop *pNew;
  116489. WhereTerm *pTerm, *pWCEnd;
  116490. int rc = SQLITE_OK;
  116491. int iCur;
  116492. WhereClause tempWC;
  116493. WhereLoopBuilder sSubBuild;
  116494. WhereOrSet sSum, sCur;
  116495. struct SrcList_item *pItem;
  116496. pWC = pBuilder->pWC;
  116497. pWCEnd = pWC->a + pWC->nTerm;
  116498. pNew = pBuilder->pNew;
  116499. memset(&sSum, 0, sizeof(sSum));
  116500. pItem = pWInfo->pTabList->a + pNew->iTab;
  116501. iCur = pItem->iCursor;
  116502. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  116503. if( (pTerm->eOperator & WO_OR)!=0
  116504. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  116505. ){
  116506. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  116507. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  116508. WhereTerm *pOrTerm;
  116509. int once = 1;
  116510. int i, j;
  116511. sSubBuild = *pBuilder;
  116512. sSubBuild.pOrderBy = 0;
  116513. sSubBuild.pOrSet = &sCur;
  116514. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  116515. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  116516. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  116517. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  116518. }else if( pOrTerm->leftCursor==iCur ){
  116519. tempWC.pWInfo = pWC->pWInfo;
  116520. tempWC.pOuter = pWC;
  116521. tempWC.op = TK_AND;
  116522. tempWC.nTerm = 1;
  116523. tempWC.a = pOrTerm;
  116524. sSubBuild.pWC = &tempWC;
  116525. }else{
  116526. continue;
  116527. }
  116528. sCur.n = 0;
  116529. #ifdef WHERETRACE_ENABLED
  116530. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  116531. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  116532. if( sqlite3WhereTrace & 0x400 ){
  116533. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  116534. whereTermPrint(&sSubBuild.pWC->a[i], i);
  116535. }
  116536. }
  116537. #endif
  116538. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116539. if( IsVirtual(pItem->pTab) ){
  116540. rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
  116541. }else
  116542. #endif
  116543. {
  116544. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  116545. }
  116546. if( rc==SQLITE_OK ){
  116547. rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
  116548. }
  116549. assert( rc==SQLITE_OK || sCur.n==0 );
  116550. if( sCur.n==0 ){
  116551. sSum.n = 0;
  116552. break;
  116553. }else if( once ){
  116554. whereOrMove(&sSum, &sCur);
  116555. once = 0;
  116556. }else{
  116557. WhereOrSet sPrev;
  116558. whereOrMove(&sPrev, &sSum);
  116559. sSum.n = 0;
  116560. for(i=0; i<sPrev.n; i++){
  116561. for(j=0; j<sCur.n; j++){
  116562. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  116563. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  116564. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  116565. }
  116566. }
  116567. }
  116568. }
  116569. pNew->nLTerm = 1;
  116570. pNew->aLTerm[0] = pTerm;
  116571. pNew->wsFlags = WHERE_MULTI_OR;
  116572. pNew->rSetup = 0;
  116573. pNew->iSortIdx = 0;
  116574. memset(&pNew->u, 0, sizeof(pNew->u));
  116575. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  116576. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  116577. ** of all sub-scans required by the OR-scan. However, due to rounding
  116578. ** errors, it may be that the cost of the OR-scan is equal to its
  116579. ** most expensive sub-scan. Add the smallest possible penalty
  116580. ** (equivalent to multiplying the cost by 1.07) to ensure that
  116581. ** this does not happen. Otherwise, for WHERE clauses such as the
  116582. ** following where there is an index on "y":
  116583. **
  116584. ** WHERE likelihood(x=?, 0.99) OR y=?
  116585. **
  116586. ** the planner may elect to "OR" together a full-table scan and an
  116587. ** index lookup. And other similarly odd results. */
  116588. pNew->rRun = sSum.a[i].rRun + 1;
  116589. pNew->nOut = sSum.a[i].nOut;
  116590. pNew->prereq = sSum.a[i].prereq;
  116591. rc = whereLoopInsert(pBuilder, pNew);
  116592. }
  116593. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  116594. }
  116595. }
  116596. return rc;
  116597. }
  116598. /*
  116599. ** Add all WhereLoop objects for all tables
  116600. */
  116601. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  116602. WhereInfo *pWInfo = pBuilder->pWInfo;
  116603. Bitmask mExtra = 0;
  116604. Bitmask mPrior = 0;
  116605. int iTab;
  116606. SrcList *pTabList = pWInfo->pTabList;
  116607. struct SrcList_item *pItem;
  116608. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  116609. sqlite3 *db = pWInfo->pParse->db;
  116610. int rc = SQLITE_OK;
  116611. WhereLoop *pNew;
  116612. u8 priorJointype = 0;
  116613. /* Loop over the tables in the join, from left to right */
  116614. pNew = pBuilder->pNew;
  116615. whereLoopInit(pNew);
  116616. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  116617. Bitmask mUnusable = 0;
  116618. pNew->iTab = iTab;
  116619. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  116620. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  116621. /* This condition is true when pItem is the FROM clause term on the
  116622. ** right-hand-side of a LEFT or CROSS JOIN. */
  116623. mExtra = mPrior;
  116624. }
  116625. priorJointype = pItem->fg.jointype;
  116626. if( IsVirtual(pItem->pTab) ){
  116627. struct SrcList_item *p;
  116628. for(p=&pItem[1]; p<pEnd; p++){
  116629. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  116630. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  116631. }
  116632. }
  116633. rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
  116634. }else{
  116635. rc = whereLoopAddBtree(pBuilder, mExtra);
  116636. }
  116637. if( rc==SQLITE_OK ){
  116638. rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
  116639. }
  116640. mPrior |= pNew->maskSelf;
  116641. if( rc || db->mallocFailed ) break;
  116642. }
  116643. whereLoopClear(db, pNew);
  116644. return rc;
  116645. }
  116646. /*
  116647. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  116648. ** parameters) to see if it outputs rows in the requested ORDER BY
  116649. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  116650. **
  116651. ** N>0: N terms of the ORDER BY clause are satisfied
  116652. ** N==0: No terms of the ORDER BY clause are satisfied
  116653. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  116654. **
  116655. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  116656. ** strict. With GROUP BY and DISTINCT the only requirement is that
  116657. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  116658. ** and DISTINCT do not require rows to appear in any particular order as long
  116659. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  116660. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  116661. ** pOrderBy terms must be matched in strict left-to-right order.
  116662. */
  116663. static i8 wherePathSatisfiesOrderBy(
  116664. WhereInfo *pWInfo, /* The WHERE clause */
  116665. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  116666. WherePath *pPath, /* The WherePath to check */
  116667. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  116668. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  116669. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  116670. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  116671. ){
  116672. u8 revSet; /* True if rev is known */
  116673. u8 rev; /* Composite sort order */
  116674. u8 revIdx; /* Index sort order */
  116675. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  116676. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  116677. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  116678. u16 nKeyCol; /* Number of key columns in pIndex */
  116679. u16 nColumn; /* Total number of ordered columns in the index */
  116680. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  116681. int iLoop; /* Index of WhereLoop in pPath being processed */
  116682. int i, j; /* Loop counters */
  116683. int iCur; /* Cursor number for current WhereLoop */
  116684. int iColumn; /* A column number within table iCur */
  116685. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  116686. WhereTerm *pTerm; /* A single term of the WHERE clause */
  116687. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  116688. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  116689. Index *pIndex; /* The index associated with pLoop */
  116690. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  116691. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  116692. Bitmask obDone; /* Mask of all ORDER BY terms */
  116693. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  116694. Bitmask ready; /* Mask of inner loops */
  116695. /*
  116696. ** We say the WhereLoop is "one-row" if it generates no more than one
  116697. ** row of output. A WhereLoop is one-row if all of the following are true:
  116698. ** (a) All index columns match with WHERE_COLUMN_EQ.
  116699. ** (b) The index is unique
  116700. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  116701. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  116702. **
  116703. ** We say the WhereLoop is "order-distinct" if the set of columns from
  116704. ** that WhereLoop that are in the ORDER BY clause are different for every
  116705. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  116706. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  116707. ** is not order-distinct. To be order-distinct is not quite the same as being
  116708. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  116709. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  116710. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  116711. **
  116712. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  116713. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  116714. ** automatically order-distinct.
  116715. */
  116716. assert( pOrderBy!=0 );
  116717. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  116718. nOrderBy = pOrderBy->nExpr;
  116719. testcase( nOrderBy==BMS-1 );
  116720. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  116721. isOrderDistinct = 1;
  116722. obDone = MASKBIT(nOrderBy)-1;
  116723. orderDistinctMask = 0;
  116724. ready = 0;
  116725. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  116726. if( iLoop>0 ) ready |= pLoop->maskSelf;
  116727. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  116728. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  116729. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  116730. break;
  116731. }
  116732. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  116733. /* Mark off any ORDER BY term X that is a column in the table of
  116734. ** the current loop for which there is term in the WHERE
  116735. ** clause of the form X IS NULL or X=? that reference only outer
  116736. ** loops.
  116737. */
  116738. for(i=0; i<nOrderBy; i++){
  116739. if( MASKBIT(i) & obSat ) continue;
  116740. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  116741. if( pOBExpr->op!=TK_COLUMN ) continue;
  116742. if( pOBExpr->iTable!=iCur ) continue;
  116743. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  116744. ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
  116745. if( pTerm==0 ) continue;
  116746. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  116747. const char *z1, *z2;
  116748. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  116749. if( !pColl ) pColl = db->pDfltColl;
  116750. z1 = pColl->zName;
  116751. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  116752. if( !pColl ) pColl = db->pDfltColl;
  116753. z2 = pColl->zName;
  116754. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  116755. testcase( pTerm->pExpr->op==TK_IS );
  116756. }
  116757. obSat |= MASKBIT(i);
  116758. }
  116759. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  116760. if( pLoop->wsFlags & WHERE_IPK ){
  116761. pIndex = 0;
  116762. nKeyCol = 0;
  116763. nColumn = 1;
  116764. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  116765. return 0;
  116766. }else{
  116767. nKeyCol = pIndex->nKeyCol;
  116768. nColumn = pIndex->nColumn;
  116769. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  116770. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  116771. || !HasRowid(pIndex->pTable));
  116772. isOrderDistinct = IsUniqueIndex(pIndex);
  116773. }
  116774. /* Loop through all columns of the index and deal with the ones
  116775. ** that are not constrained by == or IN.
  116776. */
  116777. rev = revSet = 0;
  116778. distinctColumns = 0;
  116779. for(j=0; j<nColumn; j++){
  116780. u8 bOnce; /* True to run the ORDER BY search loop */
  116781. /* Skip over == and IS NULL terms */
  116782. if( j<pLoop->u.btree.nEq
  116783. && pLoop->nSkip==0
  116784. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
  116785. ){
  116786. if( i & WO_ISNULL ){
  116787. testcase( isOrderDistinct );
  116788. isOrderDistinct = 0;
  116789. }
  116790. continue;
  116791. }
  116792. /* Get the column number in the table (iColumn) and sort order
  116793. ** (revIdx) for the j-th column of the index.
  116794. */
  116795. if( pIndex ){
  116796. iColumn = pIndex->aiColumn[j];
  116797. revIdx = pIndex->aSortOrder[j];
  116798. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  116799. }else{
  116800. iColumn = XN_ROWID;
  116801. revIdx = 0;
  116802. }
  116803. /* An unconstrained column that might be NULL means that this
  116804. ** WhereLoop is not well-ordered
  116805. */
  116806. if( isOrderDistinct
  116807. && iColumn>=0
  116808. && j>=pLoop->u.btree.nEq
  116809. && pIndex->pTable->aCol[iColumn].notNull==0
  116810. ){
  116811. isOrderDistinct = 0;
  116812. }
  116813. /* Find the ORDER BY term that corresponds to the j-th column
  116814. ** of the index and mark that ORDER BY term off
  116815. */
  116816. bOnce = 1;
  116817. isMatch = 0;
  116818. for(i=0; bOnce && i<nOrderBy; i++){
  116819. if( MASKBIT(i) & obSat ) continue;
  116820. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  116821. testcase( wctrlFlags & WHERE_GROUPBY );
  116822. testcase( wctrlFlags & WHERE_DISTINCTBY );
  116823. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  116824. if( iColumn>=(-1) ){
  116825. if( pOBExpr->op!=TK_COLUMN ) continue;
  116826. if( pOBExpr->iTable!=iCur ) continue;
  116827. if( pOBExpr->iColumn!=iColumn ) continue;
  116828. }else{
  116829. if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
  116830. continue;
  116831. }
  116832. }
  116833. if( iColumn>=0 ){
  116834. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  116835. if( !pColl ) pColl = db->pDfltColl;
  116836. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  116837. }
  116838. isMatch = 1;
  116839. break;
  116840. }
  116841. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  116842. /* Make sure the sort order is compatible in an ORDER BY clause.
  116843. ** Sort order is irrelevant for a GROUP BY clause. */
  116844. if( revSet ){
  116845. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  116846. }else{
  116847. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  116848. if( rev ) *pRevMask |= MASKBIT(iLoop);
  116849. revSet = 1;
  116850. }
  116851. }
  116852. if( isMatch ){
  116853. if( iColumn<0 ){
  116854. testcase( distinctColumns==0 );
  116855. distinctColumns = 1;
  116856. }
  116857. obSat |= MASKBIT(i);
  116858. }else{
  116859. /* No match found */
  116860. if( j==0 || j<nKeyCol ){
  116861. testcase( isOrderDistinct!=0 );
  116862. isOrderDistinct = 0;
  116863. }
  116864. break;
  116865. }
  116866. } /* end Loop over all index columns */
  116867. if( distinctColumns ){
  116868. testcase( isOrderDistinct==0 );
  116869. isOrderDistinct = 1;
  116870. }
  116871. } /* end-if not one-row */
  116872. /* Mark off any other ORDER BY terms that reference pLoop */
  116873. if( isOrderDistinct ){
  116874. orderDistinctMask |= pLoop->maskSelf;
  116875. for(i=0; i<nOrderBy; i++){
  116876. Expr *p;
  116877. Bitmask mTerm;
  116878. if( MASKBIT(i) & obSat ) continue;
  116879. p = pOrderBy->a[i].pExpr;
  116880. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  116881. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  116882. if( (mTerm&~orderDistinctMask)==0 ){
  116883. obSat |= MASKBIT(i);
  116884. }
  116885. }
  116886. }
  116887. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  116888. if( obSat==obDone ) return (i8)nOrderBy;
  116889. if( !isOrderDistinct ){
  116890. for(i=nOrderBy-1; i>0; i--){
  116891. Bitmask m = MASKBIT(i) - 1;
  116892. if( (obSat&m)==m ) return i;
  116893. }
  116894. return 0;
  116895. }
  116896. return -1;
  116897. }
  116898. /*
  116899. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  116900. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  116901. ** BY clause - and so any order that groups rows as required satisfies the
  116902. ** request.
  116903. **
  116904. ** Normally, in this case it is not possible for the caller to determine
  116905. ** whether or not the rows are really being delivered in sorted order, or
  116906. ** just in some other order that provides the required grouping. However,
  116907. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  116908. ** this function may be called on the returned WhereInfo object. It returns
  116909. ** true if the rows really will be sorted in the specified order, or false
  116910. ** otherwise.
  116911. **
  116912. ** For example, assuming:
  116913. **
  116914. ** CREATE INDEX i1 ON t1(x, Y);
  116915. **
  116916. ** then
  116917. **
  116918. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  116919. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  116920. */
  116921. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  116922. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  116923. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  116924. return pWInfo->sorted;
  116925. }
  116926. #ifdef WHERETRACE_ENABLED
  116927. /* For debugging use only: */
  116928. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  116929. static char zName[65];
  116930. int i;
  116931. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  116932. if( pLast ) zName[i++] = pLast->cId;
  116933. zName[i] = 0;
  116934. return zName;
  116935. }
  116936. #endif
  116937. /*
  116938. ** Return the cost of sorting nRow rows, assuming that the keys have
  116939. ** nOrderby columns and that the first nSorted columns are already in
  116940. ** order.
  116941. */
  116942. static LogEst whereSortingCost(
  116943. WhereInfo *pWInfo,
  116944. LogEst nRow,
  116945. int nOrderBy,
  116946. int nSorted
  116947. ){
  116948. /* TUNING: Estimated cost of a full external sort, where N is
  116949. ** the number of rows to sort is:
  116950. **
  116951. ** cost = (3.0 * N * log(N)).
  116952. **
  116953. ** Or, if the order-by clause has X terms but only the last Y
  116954. ** terms are out of order, then block-sorting will reduce the
  116955. ** sorting cost to:
  116956. **
  116957. ** cost = (3.0 * N * log(N)) * (Y/X)
  116958. **
  116959. ** The (Y/X) term is implemented using stack variable rScale
  116960. ** below. */
  116961. LogEst rScale, rSortCost;
  116962. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  116963. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  116964. rSortCost = nRow + estLog(nRow) + rScale + 16;
  116965. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  116966. ** similar but with a larger constant of proportionality.
  116967. ** Multiply by an additional factor of 3.0. */
  116968. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  116969. rSortCost += 16;
  116970. }
  116971. return rSortCost;
  116972. }
  116973. /*
  116974. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  116975. ** attempts to find the lowest cost path that visits each WhereLoop
  116976. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  116977. **
  116978. ** Assume that the total number of output rows that will need to be sorted
  116979. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  116980. ** costs if nRowEst==0.
  116981. **
  116982. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  116983. ** error occurs.
  116984. */
  116985. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  116986. int mxChoice; /* Maximum number of simultaneous paths tracked */
  116987. int nLoop; /* Number of terms in the join */
  116988. Parse *pParse; /* Parsing context */
  116989. sqlite3 *db; /* The database connection */
  116990. int iLoop; /* Loop counter over the terms of the join */
  116991. int ii, jj; /* Loop counters */
  116992. int mxI = 0; /* Index of next entry to replace */
  116993. int nOrderBy; /* Number of ORDER BY clause terms */
  116994. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  116995. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  116996. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  116997. WherePath *aFrom; /* All nFrom paths at the previous level */
  116998. WherePath *aTo; /* The nTo best paths at the current level */
  116999. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  117000. WherePath *pTo; /* An element of aTo[] that we are working on */
  117001. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  117002. WhereLoop **pX; /* Used to divy up the pSpace memory */
  117003. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  117004. char *pSpace; /* Temporary memory used by this routine */
  117005. int nSpace; /* Bytes of space allocated at pSpace */
  117006. pParse = pWInfo->pParse;
  117007. db = pParse->db;
  117008. nLoop = pWInfo->nLevel;
  117009. /* TUNING: For simple queries, only the best path is tracked.
  117010. ** For 2-way joins, the 5 best paths are followed.
  117011. ** For joins of 3 or more tables, track the 10 best paths */
  117012. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  117013. assert( nLoop<=pWInfo->pTabList->nSrc );
  117014. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  117015. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  117016. ** case the purpose of this call is to estimate the number of rows returned
  117017. ** by the overall query. Once this estimate has been obtained, the caller
  117018. ** will invoke this function a second time, passing the estimate as the
  117019. ** nRowEst parameter. */
  117020. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  117021. nOrderBy = 0;
  117022. }else{
  117023. nOrderBy = pWInfo->pOrderBy->nExpr;
  117024. }
  117025. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  117026. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  117027. nSpace += sizeof(LogEst) * nOrderBy;
  117028. pSpace = sqlite3DbMallocRaw(db, nSpace);
  117029. if( pSpace==0 ) return SQLITE_NOMEM;
  117030. aTo = (WherePath*)pSpace;
  117031. aFrom = aTo+mxChoice;
  117032. memset(aFrom, 0, sizeof(aFrom[0]));
  117033. pX = (WhereLoop**)(aFrom+mxChoice);
  117034. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  117035. pFrom->aLoop = pX;
  117036. }
  117037. if( nOrderBy ){
  117038. /* If there is an ORDER BY clause and it is not being ignored, set up
  117039. ** space for the aSortCost[] array. Each element of the aSortCost array
  117040. ** is either zero - meaning it has not yet been initialized - or the
  117041. ** cost of sorting nRowEst rows of data where the first X terms of
  117042. ** the ORDER BY clause are already in order, where X is the array
  117043. ** index. */
  117044. aSortCost = (LogEst*)pX;
  117045. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  117046. }
  117047. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  117048. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  117049. /* Seed the search with a single WherePath containing zero WhereLoops.
  117050. **
  117051. ** TUNING: Do not let the number of iterations go above 28. If the cost
  117052. ** of computing an automatic index is not paid back within the first 28
  117053. ** rows, then do not use the automatic index. */
  117054. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  117055. nFrom = 1;
  117056. assert( aFrom[0].isOrdered==0 );
  117057. if( nOrderBy ){
  117058. /* If nLoop is zero, then there are no FROM terms in the query. Since
  117059. ** in this case the query may return a maximum of one row, the results
  117060. ** are already in the requested order. Set isOrdered to nOrderBy to
  117061. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  117062. ** -1, indicating that the result set may or may not be ordered,
  117063. ** depending on the loops added to the current plan. */
  117064. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  117065. }
  117066. /* Compute successively longer WherePaths using the previous generation
  117067. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  117068. ** best paths at each generation */
  117069. for(iLoop=0; iLoop<nLoop; iLoop++){
  117070. nTo = 0;
  117071. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  117072. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  117073. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  117074. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  117075. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  117076. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  117077. Bitmask maskNew; /* Mask of src visited by (..) */
  117078. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  117079. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  117080. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  117081. /* At this point, pWLoop is a candidate to be the next loop.
  117082. ** Compute its cost */
  117083. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  117084. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  117085. nOut = pFrom->nRow + pWLoop->nOut;
  117086. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  117087. if( isOrdered<0 ){
  117088. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  117089. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  117090. iLoop, pWLoop, &revMask);
  117091. }else{
  117092. revMask = pFrom->revLoop;
  117093. }
  117094. if( isOrdered>=0 && isOrdered<nOrderBy ){
  117095. if( aSortCost[isOrdered]==0 ){
  117096. aSortCost[isOrdered] = whereSortingCost(
  117097. pWInfo, nRowEst, nOrderBy, isOrdered
  117098. );
  117099. }
  117100. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  117101. WHERETRACE(0x002,
  117102. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  117103. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  117104. rUnsorted, rCost));
  117105. }else{
  117106. rCost = rUnsorted;
  117107. }
  117108. /* Check to see if pWLoop should be added to the set of
  117109. ** mxChoice best-so-far paths.
  117110. **
  117111. ** First look for an existing path among best-so-far paths
  117112. ** that covers the same set of loops and has the same isOrdered
  117113. ** setting as the current path candidate.
  117114. **
  117115. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  117116. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  117117. ** of legal values for isOrdered, -1..64.
  117118. */
  117119. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  117120. if( pTo->maskLoop==maskNew
  117121. && ((pTo->isOrdered^isOrdered)&0x80)==0
  117122. ){
  117123. testcase( jj==nTo-1 );
  117124. break;
  117125. }
  117126. }
  117127. if( jj>=nTo ){
  117128. /* None of the existing best-so-far paths match the candidate. */
  117129. if( nTo>=mxChoice
  117130. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  117131. ){
  117132. /* The current candidate is no better than any of the mxChoice
  117133. ** paths currently in the best-so-far buffer. So discard
  117134. ** this candidate as not viable. */
  117135. #ifdef WHERETRACE_ENABLED /* 0x4 */
  117136. if( sqlite3WhereTrace&0x4 ){
  117137. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  117138. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  117139. isOrdered>=0 ? isOrdered+'0' : '?');
  117140. }
  117141. #endif
  117142. continue;
  117143. }
  117144. /* If we reach this points it means that the new candidate path
  117145. ** needs to be added to the set of best-so-far paths. */
  117146. if( nTo<mxChoice ){
  117147. /* Increase the size of the aTo set by one */
  117148. jj = nTo++;
  117149. }else{
  117150. /* New path replaces the prior worst to keep count below mxChoice */
  117151. jj = mxI;
  117152. }
  117153. pTo = &aTo[jj];
  117154. #ifdef WHERETRACE_ENABLED /* 0x4 */
  117155. if( sqlite3WhereTrace&0x4 ){
  117156. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  117157. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  117158. isOrdered>=0 ? isOrdered+'0' : '?');
  117159. }
  117160. #endif
  117161. }else{
  117162. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  117163. ** same set of loops and has the sam isOrdered setting as the
  117164. ** candidate path. Check to see if the candidate should replace
  117165. ** pTo or if the candidate should be skipped */
  117166. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  117167. #ifdef WHERETRACE_ENABLED /* 0x4 */
  117168. if( sqlite3WhereTrace&0x4 ){
  117169. sqlite3DebugPrintf(
  117170. "Skip %s cost=%-3d,%3d order=%c",
  117171. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  117172. isOrdered>=0 ? isOrdered+'0' : '?');
  117173. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  117174. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  117175. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  117176. }
  117177. #endif
  117178. /* Discard the candidate path from further consideration */
  117179. testcase( pTo->rCost==rCost );
  117180. continue;
  117181. }
  117182. testcase( pTo->rCost==rCost+1 );
  117183. /* Control reaches here if the candidate path is better than the
  117184. ** pTo path. Replace pTo with the candidate. */
  117185. #ifdef WHERETRACE_ENABLED /* 0x4 */
  117186. if( sqlite3WhereTrace&0x4 ){
  117187. sqlite3DebugPrintf(
  117188. "Update %s cost=%-3d,%3d order=%c",
  117189. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  117190. isOrdered>=0 ? isOrdered+'0' : '?');
  117191. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  117192. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  117193. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  117194. }
  117195. #endif
  117196. }
  117197. /* pWLoop is a winner. Add it to the set of best so far */
  117198. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  117199. pTo->revLoop = revMask;
  117200. pTo->nRow = nOut;
  117201. pTo->rCost = rCost;
  117202. pTo->rUnsorted = rUnsorted;
  117203. pTo->isOrdered = isOrdered;
  117204. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  117205. pTo->aLoop[iLoop] = pWLoop;
  117206. if( nTo>=mxChoice ){
  117207. mxI = 0;
  117208. mxCost = aTo[0].rCost;
  117209. mxUnsorted = aTo[0].nRow;
  117210. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  117211. if( pTo->rCost>mxCost
  117212. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  117213. ){
  117214. mxCost = pTo->rCost;
  117215. mxUnsorted = pTo->rUnsorted;
  117216. mxI = jj;
  117217. }
  117218. }
  117219. }
  117220. }
  117221. }
  117222. #ifdef WHERETRACE_ENABLED /* >=2 */
  117223. if( sqlite3WhereTrace & 0x02 ){
  117224. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  117225. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  117226. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  117227. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  117228. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  117229. if( pTo->isOrdered>0 ){
  117230. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  117231. }else{
  117232. sqlite3DebugPrintf("\n");
  117233. }
  117234. }
  117235. }
  117236. #endif
  117237. /* Swap the roles of aFrom and aTo for the next generation */
  117238. pFrom = aTo;
  117239. aTo = aFrom;
  117240. aFrom = pFrom;
  117241. nFrom = nTo;
  117242. }
  117243. if( nFrom==0 ){
  117244. sqlite3ErrorMsg(pParse, "no query solution");
  117245. sqlite3DbFree(db, pSpace);
  117246. return SQLITE_ERROR;
  117247. }
  117248. /* Find the lowest cost path. pFrom will be left pointing to that path */
  117249. pFrom = aFrom;
  117250. for(ii=1; ii<nFrom; ii++){
  117251. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  117252. }
  117253. assert( pWInfo->nLevel==nLoop );
  117254. /* Load the lowest cost path into pWInfo */
  117255. for(iLoop=0; iLoop<nLoop; iLoop++){
  117256. WhereLevel *pLevel = pWInfo->a + iLoop;
  117257. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  117258. pLevel->iFrom = pWLoop->iTab;
  117259. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  117260. }
  117261. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  117262. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  117263. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  117264. && nRowEst
  117265. ){
  117266. Bitmask notUsed;
  117267. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  117268. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  117269. if( rc==pWInfo->pResultSet->nExpr ){
  117270. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  117271. }
  117272. }
  117273. if( pWInfo->pOrderBy ){
  117274. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  117275. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  117276. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  117277. }
  117278. }else{
  117279. pWInfo->nOBSat = pFrom->isOrdered;
  117280. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  117281. pWInfo->revMask = pFrom->revLoop;
  117282. }
  117283. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  117284. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  117285. ){
  117286. Bitmask revMask = 0;
  117287. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  117288. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  117289. );
  117290. assert( pWInfo->sorted==0 );
  117291. if( nOrder==pWInfo->pOrderBy->nExpr ){
  117292. pWInfo->sorted = 1;
  117293. pWInfo->revMask = revMask;
  117294. }
  117295. }
  117296. }
  117297. pWInfo->nRowOut = pFrom->nRow;
  117298. /* Free temporary memory and return success */
  117299. sqlite3DbFree(db, pSpace);
  117300. return SQLITE_OK;
  117301. }
  117302. /*
  117303. ** Most queries use only a single table (they are not joins) and have
  117304. ** simple == constraints against indexed fields. This routine attempts
  117305. ** to plan those simple cases using much less ceremony than the
  117306. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  117307. ** times for the common case.
  117308. **
  117309. ** Return non-zero on success, if this query can be handled by this
  117310. ** no-frills query planner. Return zero if this query needs the
  117311. ** general-purpose query planner.
  117312. */
  117313. static int whereShortCut(WhereLoopBuilder *pBuilder){
  117314. WhereInfo *pWInfo;
  117315. struct SrcList_item *pItem;
  117316. WhereClause *pWC;
  117317. WhereTerm *pTerm;
  117318. WhereLoop *pLoop;
  117319. int iCur;
  117320. int j;
  117321. Table *pTab;
  117322. Index *pIdx;
  117323. pWInfo = pBuilder->pWInfo;
  117324. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  117325. assert( pWInfo->pTabList->nSrc>=1 );
  117326. pItem = pWInfo->pTabList->a;
  117327. pTab = pItem->pTab;
  117328. if( IsVirtual(pTab) ) return 0;
  117329. if( pItem->fg.isIndexedBy ) return 0;
  117330. iCur = pItem->iCursor;
  117331. pWC = &pWInfo->sWC;
  117332. pLoop = pBuilder->pNew;
  117333. pLoop->wsFlags = 0;
  117334. pLoop->nSkip = 0;
  117335. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  117336. if( pTerm ){
  117337. testcase( pTerm->eOperator & WO_IS );
  117338. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  117339. pLoop->aLTerm[0] = pTerm;
  117340. pLoop->nLTerm = 1;
  117341. pLoop->u.btree.nEq = 1;
  117342. /* TUNING: Cost of a rowid lookup is 10 */
  117343. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  117344. }else{
  117345. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  117346. int opMask;
  117347. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  117348. if( !IsUniqueIndex(pIdx)
  117349. || pIdx->pPartIdxWhere!=0
  117350. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  117351. ) continue;
  117352. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  117353. for(j=0; j<pIdx->nKeyCol; j++){
  117354. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  117355. if( pTerm==0 ) break;
  117356. testcase( pTerm->eOperator & WO_IS );
  117357. pLoop->aLTerm[j] = pTerm;
  117358. }
  117359. if( j!=pIdx->nKeyCol ) continue;
  117360. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  117361. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  117362. pLoop->wsFlags |= WHERE_IDX_ONLY;
  117363. }
  117364. pLoop->nLTerm = j;
  117365. pLoop->u.btree.nEq = j;
  117366. pLoop->u.btree.pIndex = pIdx;
  117367. /* TUNING: Cost of a unique index lookup is 15 */
  117368. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  117369. break;
  117370. }
  117371. }
  117372. if( pLoop->wsFlags ){
  117373. pLoop->nOut = (LogEst)1;
  117374. pWInfo->a[0].pWLoop = pLoop;
  117375. pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  117376. pWInfo->a[0].iTabCur = iCur;
  117377. pWInfo->nRowOut = 1;
  117378. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  117379. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  117380. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  117381. }
  117382. #ifdef SQLITE_DEBUG
  117383. pLoop->cId = '0';
  117384. #endif
  117385. return 1;
  117386. }
  117387. return 0;
  117388. }
  117389. /*
  117390. ** Generate the beginning of the loop used for WHERE clause processing.
  117391. ** The return value is a pointer to an opaque structure that contains
  117392. ** information needed to terminate the loop. Later, the calling routine
  117393. ** should invoke sqlite3WhereEnd() with the return value of this function
  117394. ** in order to complete the WHERE clause processing.
  117395. **
  117396. ** If an error occurs, this routine returns NULL.
  117397. **
  117398. ** The basic idea is to do a nested loop, one loop for each table in
  117399. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  117400. ** same as a SELECT with only a single table in the FROM clause.) For
  117401. ** example, if the SQL is this:
  117402. **
  117403. ** SELECT * FROM t1, t2, t3 WHERE ...;
  117404. **
  117405. ** Then the code generated is conceptually like the following:
  117406. **
  117407. ** foreach row1 in t1 do \ Code generated
  117408. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  117409. ** foreach row3 in t3 do /
  117410. ** ...
  117411. ** end \ Code generated
  117412. ** end |-- by sqlite3WhereEnd()
  117413. ** end /
  117414. **
  117415. ** Note that the loops might not be nested in the order in which they
  117416. ** appear in the FROM clause if a different order is better able to make
  117417. ** use of indices. Note also that when the IN operator appears in
  117418. ** the WHERE clause, it might result in additional nested loops for
  117419. ** scanning through all values on the right-hand side of the IN.
  117420. **
  117421. ** There are Btree cursors associated with each table. t1 uses cursor
  117422. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  117423. ** And so forth. This routine generates code to open those VDBE cursors
  117424. ** and sqlite3WhereEnd() generates the code to close them.
  117425. **
  117426. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  117427. ** in pTabList pointing at their appropriate entries. The [...] code
  117428. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  117429. ** data from the various tables of the loop.
  117430. **
  117431. ** If the WHERE clause is empty, the foreach loops must each scan their
  117432. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  117433. ** the tables have indices and there are terms in the WHERE clause that
  117434. ** refer to those indices, a complete table scan can be avoided and the
  117435. ** code will run much faster. Most of the work of this routine is checking
  117436. ** to see if there are indices that can be used to speed up the loop.
  117437. **
  117438. ** Terms of the WHERE clause are also used to limit which rows actually
  117439. ** make it to the "..." in the middle of the loop. After each "foreach",
  117440. ** terms of the WHERE clause that use only terms in that loop and outer
  117441. ** loops are evaluated and if false a jump is made around all subsequent
  117442. ** inner loops (or around the "..." if the test occurs within the inner-
  117443. ** most loop)
  117444. **
  117445. ** OUTER JOINS
  117446. **
  117447. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  117448. **
  117449. ** foreach row1 in t1 do
  117450. ** flag = 0
  117451. ** foreach row2 in t2 do
  117452. ** start:
  117453. ** ...
  117454. ** flag = 1
  117455. ** end
  117456. ** if flag==0 then
  117457. ** move the row2 cursor to a null row
  117458. ** goto start
  117459. ** fi
  117460. ** end
  117461. **
  117462. ** ORDER BY CLAUSE PROCESSING
  117463. **
  117464. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  117465. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  117466. ** if there is one. If there is no ORDER BY clause or if this routine
  117467. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  117468. **
  117469. ** The iIdxCur parameter is the cursor number of an index. If
  117470. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  117471. ** to use for OR clause processing. The WHERE clause should use this
  117472. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  117473. ** the first cursor in an array of cursors for all indices. iIdxCur should
  117474. ** be used to compute the appropriate cursor depending on which index is
  117475. ** used.
  117476. */
  117477. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  117478. Parse *pParse, /* The parser context */
  117479. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  117480. Expr *pWhere, /* The WHERE clause */
  117481. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  117482. ExprList *pResultSet, /* Result set of the query */
  117483. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  117484. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  117485. ){
  117486. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  117487. int nTabList; /* Number of elements in pTabList */
  117488. WhereInfo *pWInfo; /* Will become the return value of this function */
  117489. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  117490. Bitmask notReady; /* Cursors that are not yet positioned */
  117491. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  117492. WhereMaskSet *pMaskSet; /* The expression mask set */
  117493. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  117494. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  117495. int ii; /* Loop counter */
  117496. sqlite3 *db; /* Database connection */
  117497. int rc; /* Return code */
  117498. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  117499. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  117500. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  117501. ));
  117502. /* Variable initialization */
  117503. db = pParse->db;
  117504. memset(&sWLB, 0, sizeof(sWLB));
  117505. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  117506. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  117507. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  117508. sWLB.pOrderBy = pOrderBy;
  117509. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  117510. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  117511. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  117512. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  117513. }
  117514. /* The number of tables in the FROM clause is limited by the number of
  117515. ** bits in a Bitmask
  117516. */
  117517. testcase( pTabList->nSrc==BMS );
  117518. if( pTabList->nSrc>BMS ){
  117519. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  117520. return 0;
  117521. }
  117522. /* This function normally generates a nested loop for all tables in
  117523. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  117524. ** only generate code for the first table in pTabList and assume that
  117525. ** any cursors associated with subsequent tables are uninitialized.
  117526. */
  117527. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  117528. /* Allocate and initialize the WhereInfo structure that will become the
  117529. ** return value. A single allocation is used to store the WhereInfo
  117530. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  117531. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  117532. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  117533. ** some architectures. Hence the ROUND8() below.
  117534. */
  117535. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  117536. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  117537. if( db->mallocFailed ){
  117538. sqlite3DbFree(db, pWInfo);
  117539. pWInfo = 0;
  117540. goto whereBeginError;
  117541. }
  117542. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  117543. pWInfo->nLevel = nTabList;
  117544. pWInfo->pParse = pParse;
  117545. pWInfo->pTabList = pTabList;
  117546. pWInfo->pOrderBy = pOrderBy;
  117547. pWInfo->pResultSet = pResultSet;
  117548. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  117549. pWInfo->wctrlFlags = wctrlFlags;
  117550. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  117551. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  117552. pMaskSet = &pWInfo->sMaskSet;
  117553. sWLB.pWInfo = pWInfo;
  117554. sWLB.pWC = &pWInfo->sWC;
  117555. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  117556. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  117557. whereLoopInit(sWLB.pNew);
  117558. #ifdef SQLITE_DEBUG
  117559. sWLB.pNew->cId = '*';
  117560. #endif
  117561. /* Split the WHERE clause into separate subexpressions where each
  117562. ** subexpression is separated by an AND operator.
  117563. */
  117564. initMaskSet(pMaskSet);
  117565. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  117566. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  117567. /* Special case: a WHERE clause that is constant. Evaluate the
  117568. ** expression and either jump over all of the code or fall thru.
  117569. */
  117570. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  117571. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  117572. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  117573. SQLITE_JUMPIFNULL);
  117574. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  117575. }
  117576. }
  117577. /* Special case: No FROM clause
  117578. */
  117579. if( nTabList==0 ){
  117580. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  117581. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  117582. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  117583. }
  117584. }
  117585. /* Assign a bit from the bitmask to every term in the FROM clause.
  117586. **
  117587. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  117588. **
  117589. ** The rule of the previous sentence ensures thta if X is the bitmask for
  117590. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  117591. ** Knowing the bitmask for all tables to the left of a left join is
  117592. ** important. Ticket #3015.
  117593. **
  117594. ** Note that bitmasks are created for all pTabList->nSrc tables in
  117595. ** pTabList, not just the first nTabList tables. nTabList is normally
  117596. ** equal to pTabList->nSrc but might be shortened to 1 if the
  117597. ** WHERE_ONETABLE_ONLY flag is set.
  117598. */
  117599. for(ii=0; ii<pTabList->nSrc; ii++){
  117600. createMask(pMaskSet, pTabList->a[ii].iCursor);
  117601. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  117602. }
  117603. #ifdef SQLITE_DEBUG
  117604. for(ii=0; ii<pTabList->nSrc; ii++){
  117605. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  117606. assert( m==MASKBIT(ii) );
  117607. }
  117608. #endif
  117609. /* Analyze all of the subexpressions. */
  117610. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  117611. if( db->mallocFailed ) goto whereBeginError;
  117612. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  117613. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  117614. /* The DISTINCT marking is pointless. Ignore it. */
  117615. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  117616. }else if( pOrderBy==0 ){
  117617. /* Try to ORDER BY the result set to make distinct processing easier */
  117618. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  117619. pWInfo->pOrderBy = pResultSet;
  117620. }
  117621. }
  117622. /* Construct the WhereLoop objects */
  117623. WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
  117624. wctrlFlags));
  117625. #if defined(WHERETRACE_ENABLED)
  117626. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  117627. int i;
  117628. for(i=0; i<sWLB.pWC->nTerm; i++){
  117629. whereTermPrint(&sWLB.pWC->a[i], i);
  117630. }
  117631. }
  117632. #endif
  117633. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  117634. rc = whereLoopAddAll(&sWLB);
  117635. if( rc ) goto whereBeginError;
  117636. #ifdef WHERETRACE_ENABLED
  117637. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  117638. WhereLoop *p;
  117639. int i;
  117640. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  117641. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  117642. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  117643. p->cId = zLabel[i%sizeof(zLabel)];
  117644. whereLoopPrint(p, sWLB.pWC);
  117645. }
  117646. }
  117647. #endif
  117648. wherePathSolver(pWInfo, 0);
  117649. if( db->mallocFailed ) goto whereBeginError;
  117650. if( pWInfo->pOrderBy ){
  117651. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  117652. if( db->mallocFailed ) goto whereBeginError;
  117653. }
  117654. }
  117655. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  117656. pWInfo->revMask = (Bitmask)(-1);
  117657. }
  117658. if( pParse->nErr || NEVER(db->mallocFailed) ){
  117659. goto whereBeginError;
  117660. }
  117661. #ifdef WHERETRACE_ENABLED
  117662. if( sqlite3WhereTrace ){
  117663. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  117664. if( pWInfo->nOBSat>0 ){
  117665. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  117666. }
  117667. switch( pWInfo->eDistinct ){
  117668. case WHERE_DISTINCT_UNIQUE: {
  117669. sqlite3DebugPrintf(" DISTINCT=unique");
  117670. break;
  117671. }
  117672. case WHERE_DISTINCT_ORDERED: {
  117673. sqlite3DebugPrintf(" DISTINCT=ordered");
  117674. break;
  117675. }
  117676. case WHERE_DISTINCT_UNORDERED: {
  117677. sqlite3DebugPrintf(" DISTINCT=unordered");
  117678. break;
  117679. }
  117680. }
  117681. sqlite3DebugPrintf("\n");
  117682. for(ii=0; ii<pWInfo->nLevel; ii++){
  117683. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  117684. }
  117685. }
  117686. #endif
  117687. /* Attempt to omit tables from the join that do not effect the result */
  117688. if( pWInfo->nLevel>=2
  117689. && pResultSet!=0
  117690. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  117691. ){
  117692. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  117693. if( sWLB.pOrderBy ){
  117694. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  117695. }
  117696. while( pWInfo->nLevel>=2 ){
  117697. WhereTerm *pTerm, *pEnd;
  117698. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  117699. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  117700. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  117701. && (pLoop->wsFlags & WHERE_ONEROW)==0
  117702. ){
  117703. break;
  117704. }
  117705. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  117706. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  117707. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  117708. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  117709. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  117710. ){
  117711. break;
  117712. }
  117713. }
  117714. if( pTerm<pEnd ) break;
  117715. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  117716. pWInfo->nLevel--;
  117717. nTabList--;
  117718. }
  117719. }
  117720. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  117721. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  117722. /* If the caller is an UPDATE or DELETE statement that is requesting
  117723. ** to use a one-pass algorithm, determine if this is appropriate.
  117724. ** The one-pass algorithm only works if the WHERE clause constrains
  117725. ** the statement to update or delete a single row.
  117726. */
  117727. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  117728. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  117729. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  117730. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  117731. if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
  117732. && 0==(wsFlags & WHERE_VIRTUALTABLE)
  117733. )){
  117734. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  117735. if( HasRowid(pTabList->a[0].pTab) ){
  117736. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  117737. }
  117738. }
  117739. }
  117740. /* Open all tables in the pTabList and any indices selected for
  117741. ** searching those tables.
  117742. */
  117743. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  117744. Table *pTab; /* Table to open */
  117745. int iDb; /* Index of database containing table/index */
  117746. struct SrcList_item *pTabItem;
  117747. pTabItem = &pTabList->a[pLevel->iFrom];
  117748. pTab = pTabItem->pTab;
  117749. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117750. pLoop = pLevel->pWLoop;
  117751. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  117752. /* Do nothing */
  117753. }else
  117754. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117755. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  117756. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  117757. int iCur = pTabItem->iCursor;
  117758. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  117759. }else if( IsVirtual(pTab) ){
  117760. /* noop */
  117761. }else
  117762. #endif
  117763. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  117764. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  117765. int op = OP_OpenRead;
  117766. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  117767. op = OP_OpenWrite;
  117768. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  117769. };
  117770. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  117771. assert( pTabItem->iCursor==pLevel->iTabCur );
  117772. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  117773. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  117774. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  117775. Bitmask b = pTabItem->colUsed;
  117776. int n = 0;
  117777. for(; b; b=b>>1, n++){}
  117778. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  117779. SQLITE_INT_TO_PTR(n), P4_INT32);
  117780. assert( n<=pTab->nCol );
  117781. }
  117782. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  117783. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  117784. (const u8*)&pTabItem->colUsed, P4_INT64);
  117785. #endif
  117786. }else{
  117787. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  117788. }
  117789. if( pLoop->wsFlags & WHERE_INDEXED ){
  117790. Index *pIx = pLoop->u.btree.pIndex;
  117791. int iIndexCur;
  117792. int op = OP_OpenRead;
  117793. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  117794. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  117795. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  117796. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  117797. ){
  117798. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  117799. ** WITHOUT ROWID table. No need for a separate index */
  117800. iIndexCur = pLevel->iTabCur;
  117801. op = 0;
  117802. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  117803. Index *pJ = pTabItem->pTab->pIndex;
  117804. iIndexCur = iIdxCur;
  117805. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  117806. while( ALWAYS(pJ) && pJ!=pIx ){
  117807. iIndexCur++;
  117808. pJ = pJ->pNext;
  117809. }
  117810. op = OP_OpenWrite;
  117811. pWInfo->aiCurOnePass[1] = iIndexCur;
  117812. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  117813. iIndexCur = iIdxCur;
  117814. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  117815. }else{
  117816. iIndexCur = pParse->nTab++;
  117817. }
  117818. pLevel->iIdxCur = iIndexCur;
  117819. assert( pIx->pSchema==pTab->pSchema );
  117820. assert( iIndexCur>=0 );
  117821. if( op ){
  117822. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  117823. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  117824. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  117825. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  117826. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  117827. ){
  117828. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  117829. }
  117830. VdbeComment((v, "%s", pIx->zName));
  117831. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  117832. {
  117833. u64 colUsed = 0;
  117834. int ii, jj;
  117835. for(ii=0; ii<pIx->nColumn; ii++){
  117836. jj = pIx->aiColumn[ii];
  117837. if( jj<0 ) continue;
  117838. if( jj>63 ) jj = 63;
  117839. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  117840. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  117841. }
  117842. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  117843. (u8*)&colUsed, P4_INT64);
  117844. }
  117845. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  117846. }
  117847. }
  117848. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  117849. }
  117850. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  117851. if( db->mallocFailed ) goto whereBeginError;
  117852. /* Generate the code to do the search. Each iteration of the for
  117853. ** loop below generates code for a single nested loop of the VM
  117854. ** program.
  117855. */
  117856. notReady = ~(Bitmask)0;
  117857. for(ii=0; ii<nTabList; ii++){
  117858. int addrExplain;
  117859. int wsFlags;
  117860. pLevel = &pWInfo->a[ii];
  117861. wsFlags = pLevel->pWLoop->wsFlags;
  117862. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  117863. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  117864. constructAutomaticIndex(pParse, &pWInfo->sWC,
  117865. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  117866. if( db->mallocFailed ) goto whereBeginError;
  117867. }
  117868. #endif
  117869. addrExplain = sqlite3WhereExplainOneScan(
  117870. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  117871. );
  117872. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  117873. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  117874. pWInfo->iContinue = pLevel->addrCont;
  117875. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
  117876. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  117877. }
  117878. }
  117879. /* Done. */
  117880. VdbeModuleComment((v, "Begin WHERE-core"));
  117881. return pWInfo;
  117882. /* Jump here if malloc fails */
  117883. whereBeginError:
  117884. if( pWInfo ){
  117885. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  117886. whereInfoFree(db, pWInfo);
  117887. }
  117888. return 0;
  117889. }
  117890. /*
  117891. ** Generate the end of the WHERE loop. See comments on
  117892. ** sqlite3WhereBegin() for additional information.
  117893. */
  117894. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  117895. Parse *pParse = pWInfo->pParse;
  117896. Vdbe *v = pParse->pVdbe;
  117897. int i;
  117898. WhereLevel *pLevel;
  117899. WhereLoop *pLoop;
  117900. SrcList *pTabList = pWInfo->pTabList;
  117901. sqlite3 *db = pParse->db;
  117902. /* Generate loop termination code.
  117903. */
  117904. VdbeModuleComment((v, "End WHERE-core"));
  117905. sqlite3ExprCacheClear(pParse);
  117906. for(i=pWInfo->nLevel-1; i>=0; i--){
  117907. int addr;
  117908. pLevel = &pWInfo->a[i];
  117909. pLoop = pLevel->pWLoop;
  117910. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  117911. if( pLevel->op!=OP_Noop ){
  117912. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  117913. sqlite3VdbeChangeP5(v, pLevel->p5);
  117914. VdbeCoverage(v);
  117915. VdbeCoverageIf(v, pLevel->op==OP_Next);
  117916. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  117917. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  117918. }
  117919. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  117920. struct InLoop *pIn;
  117921. int j;
  117922. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  117923. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  117924. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  117925. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  117926. VdbeCoverage(v);
  117927. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  117928. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  117929. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  117930. }
  117931. }
  117932. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  117933. if( pLevel->addrSkip ){
  117934. sqlite3VdbeGoto(v, pLevel->addrSkip);
  117935. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  117936. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  117937. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  117938. }
  117939. if( pLevel->addrLikeRep ){
  117940. int op;
  117941. if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
  117942. op = OP_DecrJumpZero;
  117943. }else{
  117944. op = OP_JumpZeroIncr;
  117945. }
  117946. sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
  117947. VdbeCoverage(v);
  117948. }
  117949. if( pLevel->iLeftJoin ){
  117950. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  117951. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  117952. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  117953. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  117954. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  117955. }
  117956. if( pLoop->wsFlags & WHERE_INDEXED ){
  117957. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  117958. }
  117959. if( pLevel->op==OP_Return ){
  117960. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  117961. }else{
  117962. sqlite3VdbeGoto(v, pLevel->addrFirst);
  117963. }
  117964. sqlite3VdbeJumpHere(v, addr);
  117965. }
  117966. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  117967. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  117968. }
  117969. /* The "break" point is here, just past the end of the outer loop.
  117970. ** Set it.
  117971. */
  117972. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  117973. assert( pWInfo->nLevel<=pTabList->nSrc );
  117974. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  117975. int k, last;
  117976. VdbeOp *pOp;
  117977. Index *pIdx = 0;
  117978. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  117979. Table *pTab = pTabItem->pTab;
  117980. assert( pTab!=0 );
  117981. pLoop = pLevel->pWLoop;
  117982. /* For a co-routine, change all OP_Column references to the table of
  117983. ** the co-routine into OP_Copy of result contained in a register.
  117984. ** OP_Rowid becomes OP_Null.
  117985. */
  117986. if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
  117987. translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
  117988. pTabItem->regResult);
  117989. continue;
  117990. }
  117991. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  117992. ** Except, do not close cursors that will be reused by the OR optimization
  117993. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  117994. ** created for the ONEPASS optimization.
  117995. */
  117996. if( (pTab->tabFlags & TF_Ephemeral)==0
  117997. && pTab->pSelect==0
  117998. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  117999. ){
  118000. int ws = pLoop->wsFlags;
  118001. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  118002. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  118003. }
  118004. if( (ws & WHERE_INDEXED)!=0
  118005. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  118006. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  118007. ){
  118008. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  118009. }
  118010. }
  118011. /* If this scan uses an index, make VDBE code substitutions to read data
  118012. ** from the index instead of from the table where possible. In some cases
  118013. ** this optimization prevents the table from ever being read, which can
  118014. ** yield a significant performance boost.
  118015. **
  118016. ** Calls to the code generator in between sqlite3WhereBegin and
  118017. ** sqlite3WhereEnd will have created code that references the table
  118018. ** directly. This loop scans all that code looking for opcodes
  118019. ** that reference the table and converts them into opcodes that
  118020. ** reference the index.
  118021. */
  118022. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  118023. pIdx = pLoop->u.btree.pIndex;
  118024. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  118025. pIdx = pLevel->u.pCovidx;
  118026. }
  118027. if( pIdx
  118028. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  118029. && !db->mallocFailed
  118030. ){
  118031. last = sqlite3VdbeCurrentAddr(v);
  118032. k = pLevel->addrBody;
  118033. pOp = sqlite3VdbeGetOp(v, k);
  118034. for(; k<last; k++, pOp++){
  118035. if( pOp->p1!=pLevel->iTabCur ) continue;
  118036. if( pOp->opcode==OP_Column ){
  118037. int x = pOp->p2;
  118038. assert( pIdx->pTable==pTab );
  118039. if( !HasRowid(pTab) ){
  118040. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  118041. x = pPk->aiColumn[x];
  118042. assert( x>=0 );
  118043. }
  118044. x = sqlite3ColumnOfIndex(pIdx, x);
  118045. if( x>=0 ){
  118046. pOp->p2 = x;
  118047. pOp->p1 = pLevel->iIdxCur;
  118048. }
  118049. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  118050. }else if( pOp->opcode==OP_Rowid ){
  118051. pOp->p1 = pLevel->iIdxCur;
  118052. pOp->opcode = OP_IdxRowid;
  118053. }
  118054. }
  118055. }
  118056. }
  118057. /* Final cleanup
  118058. */
  118059. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  118060. whereInfoFree(db, pWInfo);
  118061. return;
  118062. }
  118063. /************** End of where.c ***********************************************/
  118064. /************** Begin file parse.c *******************************************/
  118065. /* Driver template for the LEMON parser generator.
  118066. ** The author disclaims copyright to this source code.
  118067. **
  118068. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  118069. ** The only modifications are the addition of a couple of NEVER()
  118070. ** macros to disable tests that are needed in the case of a general
  118071. ** LALR(1) grammar but which are always false in the
  118072. ** specific grammar used by SQLite.
  118073. */
  118074. /* First off, code is included that follows the "include" declaration
  118075. ** in the input grammar file. */
  118076. /* #include <stdio.h> */
  118077. /* #include "sqliteInt.h" */
  118078. /*
  118079. ** Disable all error recovery processing in the parser push-down
  118080. ** automaton.
  118081. */
  118082. #define YYNOERRORRECOVERY 1
  118083. /*
  118084. ** Make yytestcase() the same as testcase()
  118085. */
  118086. #define yytestcase(X) testcase(X)
  118087. /*
  118088. ** An instance of this structure holds information about the
  118089. ** LIMIT clause of a SELECT statement.
  118090. */
  118091. struct LimitVal {
  118092. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  118093. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  118094. };
  118095. /*
  118096. ** An instance of this structure is used to store the LIKE,
  118097. ** GLOB, NOT LIKE, and NOT GLOB operators.
  118098. */
  118099. struct LikeOp {
  118100. Token eOperator; /* "like" or "glob" or "regexp" */
  118101. int bNot; /* True if the NOT keyword is present */
  118102. };
  118103. /*
  118104. ** An instance of the following structure describes the event of a
  118105. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  118106. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  118107. **
  118108. ** UPDATE ON (a,b,c)
  118109. **
  118110. ** Then the "b" IdList records the list "a,b,c".
  118111. */
  118112. struct TrigEvent { int a; IdList * b; };
  118113. /*
  118114. ** An instance of this structure holds the ATTACH key and the key type.
  118115. */
  118116. struct AttachKey { int type; Token key; };
  118117. /*
  118118. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  118119. ** all elements in the list. And make sure list length does not exceed
  118120. ** SQLITE_LIMIT_COMPOUND_SELECT.
  118121. */
  118122. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  118123. if( p->pPrior ){
  118124. Select *pNext = 0, *pLoop;
  118125. int mxSelect, cnt = 0;
  118126. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  118127. pLoop->pNext = pNext;
  118128. pLoop->selFlags |= SF_Compound;
  118129. }
  118130. if( (p->selFlags & SF_MultiValue)==0 &&
  118131. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  118132. cnt>mxSelect
  118133. ){
  118134. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  118135. }
  118136. }
  118137. }
  118138. /* This is a utility routine used to set the ExprSpan.zStart and
  118139. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  118140. ** range of text beginning with pStart and going to the end of pEnd.
  118141. */
  118142. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  118143. pOut->zStart = pStart->z;
  118144. pOut->zEnd = &pEnd->z[pEnd->n];
  118145. }
  118146. /* Construct a new Expr object from a single identifier. Use the
  118147. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  118148. ** that created the expression.
  118149. */
  118150. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  118151. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  118152. pOut->zStart = pValue->z;
  118153. pOut->zEnd = &pValue->z[pValue->n];
  118154. }
  118155. /* This routine constructs a binary expression node out of two ExprSpan
  118156. ** objects and uses the result to populate a new ExprSpan object.
  118157. */
  118158. static void spanBinaryExpr(
  118159. ExprSpan *pOut, /* Write the result here */
  118160. Parse *pParse, /* The parsing context. Errors accumulate here */
  118161. int op, /* The binary operation */
  118162. ExprSpan *pLeft, /* The left operand */
  118163. ExprSpan *pRight /* The right operand */
  118164. ){
  118165. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  118166. pOut->zStart = pLeft->zStart;
  118167. pOut->zEnd = pRight->zEnd;
  118168. }
  118169. /* Construct an expression node for a unary postfix operator
  118170. */
  118171. static void spanUnaryPostfix(
  118172. ExprSpan *pOut, /* Write the new expression node here */
  118173. Parse *pParse, /* Parsing context to record errors */
  118174. int op, /* The operator */
  118175. ExprSpan *pOperand, /* The operand */
  118176. Token *pPostOp /* The operand token for setting the span */
  118177. ){
  118178. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  118179. pOut->zStart = pOperand->zStart;
  118180. pOut->zEnd = &pPostOp->z[pPostOp->n];
  118181. }
  118182. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  118183. ** unary TK_ISNULL or TK_NOTNULL expression. */
  118184. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  118185. sqlite3 *db = pParse->db;
  118186. if( pY && pA && pY->op==TK_NULL ){
  118187. pA->op = (u8)op;
  118188. sqlite3ExprDelete(db, pA->pRight);
  118189. pA->pRight = 0;
  118190. }
  118191. }
  118192. /* Construct an expression node for a unary prefix operator
  118193. */
  118194. static void spanUnaryPrefix(
  118195. ExprSpan *pOut, /* Write the new expression node here */
  118196. Parse *pParse, /* Parsing context to record errors */
  118197. int op, /* The operator */
  118198. ExprSpan *pOperand, /* The operand */
  118199. Token *pPreOp /* The operand token for setting the span */
  118200. ){
  118201. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  118202. pOut->zStart = pPreOp->z;
  118203. pOut->zEnd = pOperand->zEnd;
  118204. }
  118205. /* Add a single new term to an ExprList that is used to store a
  118206. ** list of identifiers. Report an error if the ID list contains
  118207. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  118208. ** error while parsing a legacy schema.
  118209. */
  118210. static ExprList *parserAddExprIdListTerm(
  118211. Parse *pParse,
  118212. ExprList *pPrior,
  118213. Token *pIdToken,
  118214. int hasCollate,
  118215. int sortOrder
  118216. ){
  118217. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  118218. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  118219. && pParse->db->init.busy==0
  118220. ){
  118221. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  118222. pIdToken->n, pIdToken->z);
  118223. }
  118224. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  118225. return p;
  118226. }
  118227. /* Next is all token values, in a form suitable for use by makeheaders.
  118228. ** This section will be null unless lemon is run with the -m switch.
  118229. */
  118230. /*
  118231. ** These constants (all generated automatically by the parser generator)
  118232. ** specify the various kinds of tokens (terminals) that the parser
  118233. ** understands.
  118234. **
  118235. ** Each symbol here is a terminal symbol in the grammar.
  118236. */
  118237. /* Make sure the INTERFACE macro is defined.
  118238. */
  118239. #ifndef INTERFACE
  118240. # define INTERFACE 1
  118241. #endif
  118242. /* The next thing included is series of defines which control
  118243. ** various aspects of the generated parser.
  118244. ** YYCODETYPE is the data type used for storing terminal
  118245. ** and nonterminal numbers. "unsigned char" is
  118246. ** used if there are fewer than 250 terminals
  118247. ** and nonterminals. "int" is used otherwise.
  118248. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  118249. ** to no legal terminal or nonterminal number. This
  118250. ** number is used to fill in empty slots of the hash
  118251. ** table.
  118252. ** YYFALLBACK If defined, this indicates that one or more tokens
  118253. ** have fall-back values which should be used if the
  118254. ** original value of the token will not parse.
  118255. ** YYACTIONTYPE is the data type used for storing terminal
  118256. ** and nonterminal numbers. "unsigned char" is
  118257. ** used if there are fewer than 250 rules and
  118258. ** states combined. "int" is used otherwise.
  118259. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  118260. ** directly to the parser from the tokenizer.
  118261. ** YYMINORTYPE is the data type used for all minor tokens.
  118262. ** This is typically a union of many types, one of
  118263. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  118264. ** for base tokens is called "yy0".
  118265. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  118266. ** zero the stack is dynamically sized using realloc()
  118267. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  118268. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  118269. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  118270. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  118271. ** YYERRORSYMBOL is the code number of the error symbol. If not
  118272. ** defined, then do no error processing.
  118273. ** YYNSTATE the combined number of states.
  118274. ** YYNRULE the number of rules in the grammar
  118275. ** YY_MAX_SHIFT Maximum value for shift actions
  118276. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  118277. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  118278. ** YY_MIN_REDUCE Maximum value for reduce actions
  118279. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  118280. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  118281. ** YY_NO_ACTION The yy_action[] code for no-op
  118282. */
  118283. #define YYCODETYPE unsigned char
  118284. #define YYNOCODE 254
  118285. #define YYACTIONTYPE unsigned short int
  118286. #define YYWILDCARD 70
  118287. #define sqlite3ParserTOKENTYPE Token
  118288. typedef union {
  118289. int yyinit;
  118290. sqlite3ParserTOKENTYPE yy0;
  118291. Select* yy3;
  118292. ExprList* yy14;
  118293. With* yy59;
  118294. SrcList* yy65;
  118295. struct LikeOp yy96;
  118296. Expr* yy132;
  118297. u8 yy186;
  118298. int yy328;
  118299. ExprSpan yy346;
  118300. struct TrigEvent yy378;
  118301. u16 yy381;
  118302. IdList* yy408;
  118303. struct {int value; int mask;} yy429;
  118304. TriggerStep* yy473;
  118305. struct LimitVal yy476;
  118306. } YYMINORTYPE;
  118307. #ifndef YYSTACKDEPTH
  118308. #define YYSTACKDEPTH 100
  118309. #endif
  118310. #define sqlite3ParserARG_SDECL Parse *pParse;
  118311. #define sqlite3ParserARG_PDECL ,Parse *pParse
  118312. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  118313. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  118314. #define YYFALLBACK 1
  118315. #define YYNSTATE 436
  118316. #define YYNRULE 328
  118317. #define YY_MAX_SHIFT 435
  118318. #define YY_MIN_SHIFTREDUCE 649
  118319. #define YY_MAX_SHIFTREDUCE 976
  118320. #define YY_MIN_REDUCE 977
  118321. #define YY_MAX_REDUCE 1304
  118322. #define YY_ERROR_ACTION 1305
  118323. #define YY_ACCEPT_ACTION 1306
  118324. #define YY_NO_ACTION 1307
  118325. /* The yyzerominor constant is used to initialize instances of
  118326. ** YYMINORTYPE objects to zero. */
  118327. static const YYMINORTYPE yyzerominor = { 0 };
  118328. /* Define the yytestcase() macro to be a no-op if is not already defined
  118329. ** otherwise.
  118330. **
  118331. ** Applications can choose to define yytestcase() in the %include section
  118332. ** to a macro that can assist in verifying code coverage. For production
  118333. ** code the yytestcase() macro should be turned off. But it is useful
  118334. ** for testing.
  118335. */
  118336. #ifndef yytestcase
  118337. # define yytestcase(X)
  118338. #endif
  118339. /* Next are the tables used to determine what action to take based on the
  118340. ** current state and lookahead token. These tables are used to implement
  118341. ** functions that take a state number and lookahead value and return an
  118342. ** action integer.
  118343. **
  118344. ** Suppose the action integer is N. Then the action is determined as
  118345. ** follows
  118346. **
  118347. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  118348. ** token onto the stack and goto state N.
  118349. **
  118350. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  118351. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  118352. **
  118353. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  118354. ** and YY_MAX_REDUCE
  118355. ** N == YY_ERROR_ACTION A syntax error has occurred.
  118356. **
  118357. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  118358. **
  118359. ** N == YY_NO_ACTION No such action. Denotes unused
  118360. ** slots in the yy_action[] table.
  118361. **
  118362. ** The action table is constructed as a single large table named yy_action[].
  118363. ** Given state S and lookahead X, the action is computed as
  118364. **
  118365. ** yy_action[ yy_shift_ofst[S] + X ]
  118366. **
  118367. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  118368. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  118369. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  118370. ** and that yy_default[S] should be used instead.
  118371. **
  118372. ** The formula above is for computing the action when the lookahead is
  118373. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  118374. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  118375. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  118376. ** YY_SHIFT_USE_DFLT.
  118377. **
  118378. ** The following are the tables generated in this section:
  118379. **
  118380. ** yy_action[] A single table containing all actions.
  118381. ** yy_lookahead[] A table containing the lookahead for each entry in
  118382. ** yy_action. Used to detect hash collisions.
  118383. ** yy_shift_ofst[] For each state, the offset into yy_action for
  118384. ** shifting terminals.
  118385. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  118386. ** shifting non-terminals after a reduce.
  118387. ** yy_default[] Default action for each state.
  118388. */
  118389. #define YY_ACTTAB_COUNT (1501)
  118390. static const YYACTIONTYPE yy_action[] = {
  118391. /* 0 */ 311, 1306, 145, 651, 2, 192, 652, 338, 780, 92,
  118392. /* 10 */ 92, 92, 92, 85, 90, 90, 90, 90, 89, 89,
  118393. /* 20 */ 88, 88, 88, 87, 335, 88, 88, 88, 87, 335,
  118394. /* 30 */ 327, 856, 856, 92, 92, 92, 92, 776, 90, 90,
  118395. /* 40 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 86,
  118396. /* 50 */ 83, 166, 93, 94, 84, 868, 871, 860, 860, 91,
  118397. /* 60 */ 91, 92, 92, 92, 92, 335, 90, 90, 90, 90,
  118398. /* 70 */ 89, 89, 88, 88, 88, 87, 335, 311, 780, 90,
  118399. /* 80 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
  118400. /* 90 */ 123, 808, 689, 689, 689, 689, 112, 230, 430, 257,
  118401. /* 100 */ 809, 698, 430, 86, 83, 166, 324, 55, 856, 856,
  118402. /* 110 */ 201, 158, 276, 387, 271, 386, 188, 689, 689, 828,
  118403. /* 120 */ 833, 49, 944, 269, 833, 49, 123, 87, 335, 93,
  118404. /* 130 */ 94, 84, 868, 871, 860, 860, 91, 91, 92, 92,
  118405. /* 140 */ 92, 92, 342, 90, 90, 90, 90, 89, 89, 88,
  118406. /* 150 */ 88, 88, 87, 335, 311, 328, 333, 332, 701, 408,
  118407. /* 160 */ 394, 69, 690, 691, 690, 691, 715, 910, 251, 354,
  118408. /* 170 */ 250, 698, 704, 430, 908, 430, 909, 89, 89, 88,
  118409. /* 180 */ 88, 88, 87, 335, 391, 856, 856, 690, 691, 183,
  118410. /* 190 */ 95, 340, 384, 381, 380, 833, 31, 833, 49, 912,
  118411. /* 200 */ 912, 333, 332, 379, 123, 311, 93, 94, 84, 868,
  118412. /* 210 */ 871, 860, 860, 91, 91, 92, 92, 92, 92, 114,
  118413. /* 220 */ 90, 90, 90, 90, 89, 89, 88, 88, 88, 87,
  118414. /* 230 */ 335, 430, 408, 399, 435, 657, 856, 856, 346, 57,
  118415. /* 240 */ 232, 828, 109, 20, 912, 912, 231, 393, 937, 760,
  118416. /* 250 */ 97, 751, 752, 833, 49, 708, 708, 93, 94, 84,
  118417. /* 260 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
  118418. /* 270 */ 707, 90, 90, 90, 90, 89, 89, 88, 88, 88,
  118419. /* 280 */ 87, 335, 311, 114, 22, 706, 688, 58, 408, 390,
  118420. /* 290 */ 251, 349, 240, 749, 752, 689, 689, 847, 685, 115,
  118421. /* 300 */ 21, 231, 393, 689, 689, 697, 183, 355, 430, 384,
  118422. /* 310 */ 381, 380, 192, 856, 856, 780, 123, 160, 159, 223,
  118423. /* 320 */ 379, 738, 25, 315, 362, 841, 143, 689, 689, 835,
  118424. /* 330 */ 833, 48, 339, 937, 93, 94, 84, 868, 871, 860,
  118425. /* 340 */ 860, 91, 91, 92, 92, 92, 92, 914, 90, 90,
  118426. /* 350 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 311,
  118427. /* 360 */ 840, 840, 840, 266, 430, 690, 691, 778, 114, 1300,
  118428. /* 370 */ 1300, 430, 1, 690, 691, 697, 688, 689, 689, 689,
  118429. /* 380 */ 689, 689, 689, 287, 298, 780, 833, 10, 686, 115,
  118430. /* 390 */ 856, 856, 355, 833, 10, 828, 366, 690, 691, 363,
  118431. /* 400 */ 321, 76, 123, 74, 23, 737, 807, 323, 356, 353,
  118432. /* 410 */ 847, 93, 94, 84, 868, 871, 860, 860, 91, 91,
  118433. /* 420 */ 92, 92, 92, 92, 940, 90, 90, 90, 90, 89,
  118434. /* 430 */ 89, 88, 88, 88, 87, 335, 311, 806, 841, 429,
  118435. /* 440 */ 713, 941, 835, 430, 251, 354, 250, 690, 691, 690,
  118436. /* 450 */ 691, 690, 691, 86, 83, 166, 24, 942, 151, 753,
  118437. /* 460 */ 285, 907, 403, 907, 164, 833, 10, 856, 856, 965,
  118438. /* 470 */ 306, 754, 679, 840, 840, 840, 795, 216, 794, 222,
  118439. /* 480 */ 906, 344, 906, 904, 86, 83, 166, 286, 93, 94,
  118440. /* 490 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
  118441. /* 500 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
  118442. /* 510 */ 88, 87, 335, 311, 430, 724, 352, 705, 427, 699,
  118443. /* 520 */ 700, 376, 210, 833, 49, 793, 397, 857, 857, 940,
  118444. /* 530 */ 213, 762, 727, 334, 699, 700, 833, 10, 86, 83,
  118445. /* 540 */ 166, 345, 396, 902, 856, 856, 941, 385, 833, 9,
  118446. /* 550 */ 406, 869, 872, 187, 890, 728, 347, 398, 404, 977,
  118447. /* 560 */ 652, 338, 942, 954, 413, 93, 94, 84, 868, 871,
  118448. /* 570 */ 860, 860, 91, 91, 92, 92, 92, 92, 861, 90,
  118449. /* 580 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
  118450. /* 590 */ 311, 1219, 114, 430, 834, 430, 5, 165, 192, 688,
  118451. /* 600 */ 832, 780, 430, 723, 430, 234, 325, 189, 163, 316,
  118452. /* 610 */ 356, 955, 115, 235, 269, 833, 35, 833, 36, 747,
  118453. /* 620 */ 720, 856, 856, 793, 833, 12, 833, 27, 745, 174,
  118454. /* 630 */ 968, 1290, 968, 1291, 1290, 310, 1291, 693, 317, 245,
  118455. /* 640 */ 264, 311, 93, 94, 84, 868, 871, 860, 860, 91,
  118456. /* 650 */ 91, 92, 92, 92, 92, 832, 90, 90, 90, 90,
  118457. /* 660 */ 89, 89, 88, 88, 88, 87, 335, 430, 320, 213,
  118458. /* 670 */ 762, 780, 856, 856, 920, 920, 369, 257, 966, 220,
  118459. /* 680 */ 966, 396, 663, 664, 665, 242, 259, 244, 262, 833,
  118460. /* 690 */ 37, 650, 2, 93, 94, 84, 868, 871, 860, 860,
  118461. /* 700 */ 91, 91, 92, 92, 92, 92, 430, 90, 90, 90,
  118462. /* 710 */ 90, 89, 89, 88, 88, 88, 87, 335, 311, 430,
  118463. /* 720 */ 239, 430, 917, 368, 430, 238, 916, 793, 833, 38,
  118464. /* 730 */ 430, 825, 430, 66, 430, 392, 430, 766, 766, 430,
  118465. /* 740 */ 367, 833, 39, 833, 28, 430, 833, 29, 68, 856,
  118466. /* 750 */ 856, 900, 833, 40, 833, 41, 833, 42, 833, 11,
  118467. /* 760 */ 72, 833, 43, 243, 305, 970, 114, 833, 99, 961,
  118468. /* 770 */ 93, 94, 84, 868, 871, 860, 860, 91, 91, 92,
  118469. /* 780 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
  118470. /* 790 */ 88, 88, 88, 87, 335, 311, 430, 361, 430, 165,
  118471. /* 800 */ 147, 430, 186, 185, 184, 833, 44, 430, 289, 430,
  118472. /* 810 */ 246, 430, 971, 430, 212, 163, 430, 357, 833, 45,
  118473. /* 820 */ 833, 32, 932, 833, 46, 793, 856, 856, 718, 833,
  118474. /* 830 */ 47, 833, 33, 833, 117, 833, 118, 75, 833, 119,
  118475. /* 840 */ 288, 305, 967, 214, 935, 322, 311, 93, 94, 84,
  118476. /* 850 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
  118477. /* 860 */ 430, 90, 90, 90, 90, 89, 89, 88, 88, 88,
  118478. /* 870 */ 87, 335, 430, 832, 426, 317, 288, 856, 856, 114,
  118479. /* 880 */ 763, 257, 833, 53, 930, 219, 364, 257, 257, 971,
  118480. /* 890 */ 361, 396, 257, 257, 833, 34, 257, 311, 93, 94,
  118481. /* 900 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
  118482. /* 910 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
  118483. /* 920 */ 88, 87, 335, 430, 217, 318, 124, 253, 856, 856,
  118484. /* 930 */ 218, 943, 257, 833, 100, 898, 759, 774, 361, 755,
  118485. /* 940 */ 423, 329, 758, 1017, 289, 833, 50, 682, 311, 93,
  118486. /* 950 */ 82, 84, 868, 871, 860, 860, 91, 91, 92, 92,
  118487. /* 960 */ 92, 92, 430, 90, 90, 90, 90, 89, 89, 88,
  118488. /* 970 */ 88, 88, 87, 335, 430, 256, 419, 114, 249, 856,
  118489. /* 980 */ 856, 331, 114, 400, 833, 101, 359, 187, 1064, 726,
  118490. /* 990 */ 725, 739, 401, 416, 420, 360, 833, 102, 424, 311,
  118491. /* 1000 */ 258, 94, 84, 868, 871, 860, 860, 91, 91, 92,
  118492. /* 1010 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
  118493. /* 1020 */ 88, 88, 88, 87, 335, 430, 221, 261, 114, 114,
  118494. /* 1030 */ 856, 856, 808, 114, 156, 833, 98, 772, 733, 734,
  118495. /* 1040 */ 275, 809, 771, 316, 263, 265, 960, 833, 116, 307,
  118496. /* 1050 */ 741, 274, 722, 84, 868, 871, 860, 860, 91, 91,
  118497. /* 1060 */ 92, 92, 92, 92, 430, 90, 90, 90, 90, 89,
  118498. /* 1070 */ 89, 88, 88, 88, 87, 335, 80, 425, 830, 3,
  118499. /* 1080 */ 1214, 191, 430, 721, 336, 336, 833, 113, 252, 80,
  118500. /* 1090 */ 425, 68, 3, 913, 913, 428, 270, 336, 336, 430,
  118501. /* 1100 */ 377, 784, 430, 197, 833, 106, 430, 716, 428, 430,
  118502. /* 1110 */ 267, 430, 897, 68, 414, 430, 769, 409, 430, 71,
  118503. /* 1120 */ 430, 833, 105, 123, 833, 103, 847, 414, 833, 49,
  118504. /* 1130 */ 843, 833, 104, 833, 52, 800, 123, 833, 54, 847,
  118505. /* 1140 */ 833, 51, 833, 26, 831, 802, 77, 78, 191, 389,
  118506. /* 1150 */ 430, 372, 114, 79, 432, 431, 911, 911, 835, 77,
  118507. /* 1160 */ 78, 779, 893, 408, 410, 197, 79, 432, 431, 791,
  118508. /* 1170 */ 226, 835, 833, 30, 772, 80, 425, 716, 3, 771,
  118509. /* 1180 */ 411, 412, 897, 336, 336, 290, 291, 839, 703, 840,
  118510. /* 1190 */ 840, 840, 842, 19, 428, 695, 684, 672, 111, 671,
  118511. /* 1200 */ 843, 673, 840, 840, 840, 842, 19, 207, 661, 278,
  118512. /* 1210 */ 148, 304, 280, 414, 282, 6, 822, 348, 248, 241,
  118513. /* 1220 */ 358, 934, 720, 80, 425, 847, 3, 161, 382, 273,
  118514. /* 1230 */ 284, 336, 336, 415, 296, 958, 895, 894, 157, 674,
  118515. /* 1240 */ 107, 194, 428, 948, 135, 77, 78, 777, 953, 951,
  118516. /* 1250 */ 56, 319, 79, 432, 431, 121, 66, 835, 59, 128,
  118517. /* 1260 */ 146, 414, 350, 130, 351, 819, 131, 132, 133, 375,
  118518. /* 1270 */ 173, 149, 138, 847, 936, 365, 178, 70, 425, 827,
  118519. /* 1280 */ 3, 889, 62, 371, 915, 336, 336, 792, 840, 840,
  118520. /* 1290 */ 840, 842, 19, 77, 78, 208, 428, 144, 179, 373,
  118521. /* 1300 */ 79, 432, 431, 255, 180, 835, 260, 675, 181, 308,
  118522. /* 1310 */ 388, 744, 326, 743, 742, 414, 731, 718, 712, 402,
  118523. /* 1320 */ 309, 711, 788, 65, 277, 272, 789, 847, 730, 710,
  118524. /* 1330 */ 709, 279, 193, 787, 281, 876, 840, 840, 840, 842,
  118525. /* 1340 */ 19, 786, 283, 73, 418, 330, 422, 77, 78, 227,
  118526. /* 1350 */ 96, 407, 67, 405, 79, 432, 431, 292, 228, 835,
  118527. /* 1360 */ 215, 202, 229, 293, 767, 303, 302, 301, 204, 299,
  118528. /* 1370 */ 294, 295, 676, 7, 681, 433, 669, 206, 110, 224,
  118529. /* 1380 */ 203, 205, 434, 667, 666, 658, 120, 168, 656, 237,
  118530. /* 1390 */ 840, 840, 840, 842, 19, 337, 155, 233, 236, 341,
  118531. /* 1400 */ 167, 905, 108, 313, 903, 826, 314, 125, 126, 127,
  118532. /* 1410 */ 129, 170, 247, 756, 172, 928, 134, 136, 171, 60,
  118533. /* 1420 */ 61, 123, 169, 137, 175, 933, 176, 927, 8, 13,
  118534. /* 1430 */ 177, 254, 191, 918, 139, 370, 924, 140, 678, 150,
  118535. /* 1440 */ 374, 274, 182, 378, 141, 122, 63, 14, 383, 729,
  118536. /* 1450 */ 268, 15, 64, 225, 846, 845, 874, 16, 765, 770,
  118537. /* 1460 */ 4, 162, 209, 395, 211, 142, 878, 796, 801, 312,
  118538. /* 1470 */ 190, 71, 68, 875, 873, 939, 199, 938, 17, 195,
  118539. /* 1480 */ 18, 196, 417, 975, 152, 653, 976, 198, 153, 421,
  118540. /* 1490 */ 877, 154, 200, 844, 696, 81, 343, 297, 1019, 1018,
  118541. /* 1500 */ 300,
  118542. };
  118543. static const YYCODETYPE yy_lookahead[] = {
  118544. /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
  118545. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  118546. /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
  118547. /* 30 */ 19, 50, 51, 80, 81, 82, 83, 212, 85, 86,
  118548. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 224,
  118549. /* 50 */ 225, 226, 71, 72, 73, 74, 75, 76, 77, 78,
  118550. /* 60 */ 79, 80, 81, 82, 83, 95, 85, 86, 87, 88,
  118551. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
  118552. /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  118553. /* 90 */ 66, 33, 27, 28, 27, 28, 22, 201, 152, 152,
  118554. /* 100 */ 42, 27, 152, 224, 225, 226, 95, 211, 50, 51,
  118555. /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 59,
  118556. /* 120 */ 174, 175, 243, 112, 174, 175, 66, 94, 95, 71,
  118557. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  118558. /* 140 */ 82, 83, 195, 85, 86, 87, 88, 89, 90, 91,
  118559. /* 150 */ 92, 93, 94, 95, 19, 209, 89, 90, 173, 209,
  118560. /* 160 */ 210, 26, 97, 98, 97, 98, 181, 100, 108, 109,
  118561. /* 170 */ 110, 97, 174, 152, 107, 152, 109, 89, 90, 91,
  118562. /* 180 */ 92, 93, 94, 95, 163, 50, 51, 97, 98, 99,
  118563. /* 190 */ 55, 244, 102, 103, 104, 174, 175, 174, 175, 132,
  118564. /* 200 */ 133, 89, 90, 113, 66, 19, 71, 72, 73, 74,
  118565. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 198,
  118566. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  118567. /* 230 */ 95, 152, 209, 210, 148, 149, 50, 51, 100, 53,
  118568. /* 240 */ 154, 59, 156, 22, 132, 133, 119, 120, 163, 163,
  118569. /* 250 */ 22, 192, 193, 174, 175, 27, 28, 71, 72, 73,
  118570. /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  118571. /* 270 */ 174, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  118572. /* 280 */ 94, 95, 19, 198, 198, 174, 152, 24, 209, 210,
  118573. /* 290 */ 108, 109, 110, 192, 193, 27, 28, 69, 164, 165,
  118574. /* 300 */ 79, 119, 120, 27, 28, 27, 99, 222, 152, 102,
  118575. /* 310 */ 103, 104, 24, 50, 51, 27, 66, 89, 90, 185,
  118576. /* 320 */ 113, 187, 22, 157, 239, 97, 58, 27, 28, 101,
  118577. /* 330 */ 174, 175, 246, 163, 71, 72, 73, 74, 75, 76,
  118578. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
  118579. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  118580. /* 360 */ 132, 133, 134, 23, 152, 97, 98, 91, 198, 119,
  118581. /* 370 */ 120, 152, 22, 97, 98, 97, 152, 27, 28, 27,
  118582. /* 380 */ 28, 27, 28, 227, 160, 97, 174, 175, 164, 165,
  118583. /* 390 */ 50, 51, 222, 174, 175, 59, 230, 97, 98, 233,
  118584. /* 400 */ 188, 137, 66, 139, 234, 187, 177, 188, 152, 239,
  118585. /* 410 */ 69, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  118586. /* 420 */ 80, 81, 82, 83, 12, 85, 86, 87, 88, 89,
  118587. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 177, 97, 152,
  118588. /* 440 */ 23, 29, 101, 152, 108, 109, 110, 97, 98, 97,
  118589. /* 450 */ 98, 97, 98, 224, 225, 226, 22, 45, 24, 47,
  118590. /* 460 */ 152, 152, 152, 152, 152, 174, 175, 50, 51, 249,
  118591. /* 470 */ 250, 59, 21, 132, 133, 134, 124, 221, 124, 188,
  118592. /* 480 */ 171, 172, 171, 172, 224, 225, 226, 152, 71, 72,
  118593. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  118594. /* 500 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  118595. /* 510 */ 93, 94, 95, 19, 152, 183, 65, 23, 170, 171,
  118596. /* 520 */ 172, 19, 23, 174, 175, 26, 152, 50, 51, 12,
  118597. /* 530 */ 196, 197, 37, 170, 171, 172, 174, 175, 224, 225,
  118598. /* 540 */ 226, 232, 208, 232, 50, 51, 29, 52, 174, 175,
  118599. /* 550 */ 188, 74, 75, 51, 103, 60, 222, 163, 209, 0,
  118600. /* 560 */ 1, 2, 45, 152, 47, 71, 72, 73, 74, 75,
  118601. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 101, 85,
  118602. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  118603. /* 590 */ 19, 140, 198, 152, 23, 152, 22, 98, 24, 152,
  118604. /* 600 */ 152, 27, 152, 183, 152, 152, 111, 213, 214, 107,
  118605. /* 610 */ 152, 164, 165, 152, 112, 174, 175, 174, 175, 181,
  118606. /* 620 */ 182, 50, 51, 124, 174, 175, 174, 175, 190, 26,
  118607. /* 630 */ 22, 23, 22, 23, 26, 166, 26, 168, 169, 16,
  118608. /* 640 */ 16, 19, 71, 72, 73, 74, 75, 76, 77, 78,
  118609. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  118610. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 152, 220, 196,
  118611. /* 670 */ 197, 97, 50, 51, 108, 109, 110, 152, 70, 221,
  118612. /* 680 */ 70, 208, 7, 8, 9, 62, 62, 64, 64, 174,
  118613. /* 690 */ 175, 146, 147, 71, 72, 73, 74, 75, 76, 77,
  118614. /* 700 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
  118615. /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
  118616. /* 720 */ 195, 152, 31, 220, 152, 152, 35, 26, 174, 175,
  118617. /* 730 */ 152, 163, 152, 130, 152, 115, 152, 117, 118, 152,
  118618. /* 740 */ 49, 174, 175, 174, 175, 152, 174, 175, 26, 50,
  118619. /* 750 */ 51, 152, 174, 175, 174, 175, 174, 175, 174, 175,
  118620. /* 760 */ 138, 174, 175, 140, 22, 23, 198, 174, 175, 152,
  118621. /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  118622. /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  118623. /* 790 */ 91, 92, 93, 94, 95, 19, 152, 152, 152, 98,
  118624. /* 800 */ 24, 152, 108, 109, 110, 174, 175, 152, 152, 152,
  118625. /* 810 */ 152, 152, 70, 152, 213, 214, 152, 152, 174, 175,
  118626. /* 820 */ 174, 175, 152, 174, 175, 124, 50, 51, 106, 174,
  118627. /* 830 */ 175, 174, 175, 174, 175, 174, 175, 138, 174, 175,
  118628. /* 840 */ 152, 22, 23, 22, 163, 189, 19, 71, 72, 73,
  118629. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  118630. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  118631. /* 870 */ 94, 95, 152, 152, 168, 169, 152, 50, 51, 198,
  118632. /* 880 */ 197, 152, 174, 175, 152, 240, 152, 152, 152, 70,
  118633. /* 890 */ 152, 208, 152, 152, 174, 175, 152, 19, 71, 72,
  118634. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  118635. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  118636. /* 920 */ 93, 94, 95, 152, 195, 247, 248, 152, 50, 51,
  118637. /* 930 */ 195, 195, 152, 174, 175, 195, 195, 26, 152, 195,
  118638. /* 940 */ 252, 220, 163, 122, 152, 174, 175, 163, 19, 71,
  118639. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  118640. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  118641. /* 970 */ 92, 93, 94, 95, 152, 195, 252, 198, 240, 50,
  118642. /* 980 */ 51, 189, 198, 19, 174, 175, 19, 51, 23, 100,
  118643. /* 990 */ 101, 26, 28, 163, 163, 28, 174, 175, 163, 19,
  118644. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  118645. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  118646. /* 1020 */ 91, 92, 93, 94, 95, 152, 240, 152, 198, 198,
  118647. /* 1030 */ 50, 51, 33, 198, 123, 174, 175, 116, 7, 8,
  118648. /* 1040 */ 101, 42, 121, 107, 152, 152, 23, 174, 175, 26,
  118649. /* 1050 */ 152, 112, 183, 73, 74, 75, 76, 77, 78, 79,
  118650. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  118651. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 23, 22,
  118652. /* 1080 */ 23, 26, 152, 152, 27, 28, 174, 175, 23, 19,
  118653. /* 1090 */ 20, 26, 22, 132, 133, 38, 152, 27, 28, 152,
  118654. /* 1100 */ 23, 215, 152, 26, 174, 175, 152, 27, 38, 152,
  118655. /* 1110 */ 23, 152, 27, 26, 57, 152, 23, 163, 152, 26,
  118656. /* 1120 */ 152, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  118657. /* 1130 */ 27, 174, 175, 174, 175, 152, 66, 174, 175, 69,
  118658. /* 1140 */ 174, 175, 174, 175, 152, 23, 89, 90, 26, 91,
  118659. /* 1150 */ 152, 236, 198, 96, 97, 98, 132, 133, 101, 89,
  118660. /* 1160 */ 90, 152, 23, 209, 210, 26, 96, 97, 98, 152,
  118661. /* 1170 */ 212, 101, 174, 175, 116, 19, 20, 97, 22, 121,
  118662. /* 1180 */ 152, 193, 97, 27, 28, 152, 152, 152, 152, 132,
  118663. /* 1190 */ 133, 134, 135, 136, 38, 23, 152, 152, 26, 152,
  118664. /* 1200 */ 97, 152, 132, 133, 134, 135, 136, 235, 152, 212,
  118665. /* 1210 */ 199, 150, 212, 57, 212, 200, 203, 216, 241, 216,
  118666. /* 1220 */ 241, 203, 182, 19, 20, 69, 22, 186, 178, 177,
  118667. /* 1230 */ 216, 27, 28, 229, 202, 39, 177, 177, 200, 155,
  118668. /* 1240 */ 245, 122, 38, 41, 22, 89, 90, 91, 159, 159,
  118669. /* 1250 */ 242, 159, 96, 97, 98, 71, 130, 101, 242, 191,
  118670. /* 1260 */ 223, 57, 18, 194, 159, 203, 194, 194, 194, 18,
  118671. /* 1270 */ 158, 223, 191, 69, 203, 159, 158, 19, 20, 191,
  118672. /* 1280 */ 22, 203, 137, 46, 238, 27, 28, 159, 132, 133,
  118673. /* 1290 */ 134, 135, 136, 89, 90, 159, 38, 22, 158, 179,
  118674. /* 1300 */ 96, 97, 98, 237, 158, 101, 159, 159, 158, 179,
  118675. /* 1310 */ 107, 176, 48, 176, 176, 57, 184, 106, 176, 125,
  118676. /* 1320 */ 179, 178, 218, 107, 217, 176, 218, 69, 184, 176,
  118677. /* 1330 */ 176, 217, 159, 218, 217, 159, 132, 133, 134, 135,
  118678. /* 1340 */ 136, 218, 217, 137, 179, 95, 179, 89, 90, 228,
  118679. /* 1350 */ 129, 126, 128, 127, 96, 97, 98, 206, 231, 101,
  118680. /* 1360 */ 5, 25, 231, 205, 207, 10, 11, 12, 13, 14,
  118681. /* 1370 */ 204, 203, 17, 26, 162, 161, 13, 6, 180, 180,
  118682. /* 1380 */ 153, 153, 151, 151, 151, 151, 167, 32, 4, 34,
  118683. /* 1390 */ 132, 133, 134, 135, 136, 3, 22, 142, 43, 68,
  118684. /* 1400 */ 15, 23, 16, 251, 23, 120, 251, 248, 131, 111,
  118685. /* 1410 */ 123, 56, 16, 20, 125, 1, 123, 131, 63, 79,
  118686. /* 1420 */ 79, 66, 67, 111, 36, 28, 122, 1, 5, 22,
  118687. /* 1430 */ 107, 140, 26, 54, 54, 44, 61, 107, 20, 24,
  118688. /* 1440 */ 19, 112, 105, 53, 22, 40, 22, 22, 53, 30,
  118689. /* 1450 */ 23, 22, 22, 53, 23, 23, 23, 22, 116, 23,
  118690. /* 1460 */ 22, 122, 23, 26, 23, 22, 11, 124, 28, 114,
  118691. /* 1470 */ 36, 26, 26, 23, 23, 23, 122, 23, 36, 26,
  118692. /* 1480 */ 36, 22, 24, 23, 22, 1, 23, 26, 22, 24,
  118693. /* 1490 */ 23, 22, 122, 23, 23, 22, 141, 23, 122, 122,
  118694. /* 1500 */ 15,
  118695. };
  118696. #define YY_SHIFT_USE_DFLT (-72)
  118697. #define YY_SHIFT_COUNT (435)
  118698. #define YY_SHIFT_MIN (-71)
  118699. #define YY_SHIFT_MAX (1485)
  118700. static const short yy_shift_ofst[] = {
  118701. /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 90, 60, -19,
  118702. /* 10 */ 58, 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  118703. /* 20 */ 67, 67, 182, 336, 65, 250, 135, 263, 340, 417,
  118704. /* 30 */ 494, 571, 622, 699, 776, 827, 827, 827, 827, 827,
  118705. /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  118706. /* 50 */ 878, 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204,
  118707. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  118708. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  118709. /* 80 */ 1204, 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204,
  118710. /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47,
  118711. /* 100 */ -47, -47, -47, -47, -6, 88, -66, 65, 65, 451,
  118712. /* 110 */ 502, 112, 112, 33, 127, 278, -30, -72, -72, -72,
  118713. /* 120 */ 11, 412, 412, 268, 608, 610, 65, 65, 65, 65,
  118714. /* 130 */ 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
  118715. /* 140 */ 65, 65, 65, 65, 65, 559, 138, 278, 127, 24,
  118716. /* 150 */ 24, 24, 24, 24, 24, -72, -72, -72, 228, 341,
  118717. /* 160 */ 341, 207, 276, 300, 352, 354, 350, 65, 65, 65,
  118718. /* 170 */ 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
  118719. /* 180 */ 65, 65, 65, 65, 495, 495, 495, 65, 65, 499,
  118720. /* 190 */ 65, 65, 65, 574, 65, 65, 517, 65, 65, 65,
  118721. /* 200 */ 65, 65, 65, 65, 65, 65, 65, 566, 691, 288,
  118722. /* 210 */ 288, 288, 701, 620, 1058, 675, 603, 964, 964, 967,
  118723. /* 220 */ 603, 967, 722, 965, 936, 999, 964, 264, 999, 999,
  118724. /* 230 */ 911, 921, 434, 1196, 1119, 1119, 1202, 1202, 1119, 1222,
  118725. /* 240 */ 1184, 1126, 1244, 1244, 1244, 1244, 1119, 1251, 1126, 1222,
  118726. /* 250 */ 1184, 1184, 1126, 1119, 1251, 1145, 1237, 1119, 1119, 1251,
  118727. /* 260 */ 1275, 1119, 1251, 1119, 1251, 1275, 1203, 1203, 1203, 1264,
  118728. /* 270 */ 1275, 1203, 1211, 1203, 1264, 1203, 1203, 1194, 1216, 1194,
  118729. /* 280 */ 1216, 1194, 1216, 1194, 1216, 1119, 1119, 1206, 1275, 1250,
  118730. /* 290 */ 1250, 1275, 1221, 1225, 1224, 1226, 1126, 1336, 1347, 1363,
  118731. /* 300 */ 1363, 1371, 1371, 1371, 1371, -72, -72, -72, -72, -72,
  118732. /* 310 */ -72, 477, 623, 742, 819, 624, 694, 74, 1023, 221,
  118733. /* 320 */ 1055, 1065, 1077, 1087, 1080, 889, 1031, 939, 1093, 1122,
  118734. /* 330 */ 1085, 1139, 961, 1024, 1172, 1103, 821, 1384, 1392, 1374,
  118735. /* 340 */ 1255, 1385, 1331, 1386, 1378, 1381, 1285, 1277, 1298, 1287,
  118736. /* 350 */ 1393, 1289, 1396, 1414, 1293, 1286, 1340, 1341, 1312, 1397,
  118737. /* 360 */ 1388, 1304, 1426, 1423, 1407, 1323, 1291, 1379, 1406, 1380,
  118738. /* 370 */ 1375, 1391, 1330, 1415, 1418, 1421, 1329, 1337, 1422, 1390,
  118739. /* 380 */ 1424, 1425, 1427, 1429, 1395, 1419, 1430, 1400, 1405, 1431,
  118740. /* 390 */ 1432, 1433, 1342, 1435, 1436, 1438, 1437, 1339, 1439, 1441,
  118741. /* 400 */ 1440, 1434, 1443, 1343, 1445, 1442, 1446, 1444, 1445, 1450,
  118742. /* 410 */ 1451, 1452, 1453, 1454, 1459, 1455, 1460, 1462, 1458, 1461,
  118743. /* 420 */ 1463, 1466, 1465, 1461, 1467, 1469, 1470, 1471, 1473, 1354,
  118744. /* 430 */ 1370, 1376, 1377, 1474, 1485, 1484,
  118745. };
  118746. #define YY_REDUCE_USE_DFLT (-176)
  118747. #define YY_REDUCE_COUNT (310)
  118748. #define YY_REDUCE_MIN (-175)
  118749. #define YY_REDUCE_MAX (1234)
  118750. static const short yy_reduce_ofst[] = {
  118751. /* 0 */ -143, 954, 86, 21, -50, 23, 79, 134, 170, -175,
  118752. /* 10 */ 229, 260, -121, 212, 219, 291, -54, 349, 362, 156,
  118753. /* 20 */ 309, 311, 334, 85, 224, 394, 314, 314, 314, 314,
  118754. /* 30 */ 314, 314, 314, 314, 314, 314, 314, 314, 314, 314,
  118755. /* 40 */ 314, 314, 314, 314, 314, 314, 314, 314, 314, 314,
  118756. /* 50 */ 314, 314, 314, 314, 314, 374, 441, 443, 450, 452,
  118757. /* 60 */ 515, 554, 567, 569, 572, 578, 580, 582, 584, 587,
  118758. /* 70 */ 593, 631, 644, 646, 649, 655, 657, 659, 661, 664,
  118759. /* 80 */ 708, 720, 759, 771, 810, 822, 861, 873, 912, 930,
  118760. /* 90 */ 947, 950, 957, 959, 963, 966, 968, 998, 314, 314,
  118761. /* 100 */ 314, 314, 314, 314, 314, 314, 314, 447, -53, 166,
  118762. /* 110 */ 438, 348, 363, 314, 473, 469, 314, 314, 314, 314,
  118763. /* 120 */ -15, 59, 101, 688, 220, 220, 525, 256, 729, 735,
  118764. /* 130 */ 736, 740, 741, 744, 645, 448, 738, 458, 786, 503,
  118765. /* 140 */ 780, 656, 721, 724, 792, 545, 568, 706, 683, 681,
  118766. /* 150 */ 779, 784, 830, 831, 835, 678, 601, -104, -2, 96,
  118767. /* 160 */ 111, 218, 287, 308, 310, 312, 335, 411, 453, 461,
  118768. /* 170 */ 573, 599, 617, 658, 665, 670, 732, 734, 775, 848,
  118769. /* 180 */ 875, 892, 893, 898, 332, 420, 869, 931, 944, 886,
  118770. /* 190 */ 983, 992, 1009, 958, 1017, 1028, 988, 1033, 1034, 1035,
  118771. /* 200 */ 287, 1036, 1044, 1045, 1047, 1049, 1056, 915, 972, 997,
  118772. /* 210 */ 1000, 1002, 886, 1011, 1015, 1061, 1013, 1001, 1003, 977,
  118773. /* 220 */ 1018, 979, 1050, 1041, 1040, 1052, 1014, 1004, 1059, 1060,
  118774. /* 230 */ 1032, 1038, 1084, 995, 1089, 1090, 1008, 1016, 1092, 1037,
  118775. /* 240 */ 1068, 1062, 1069, 1072, 1073, 1074, 1105, 1112, 1071, 1048,
  118776. /* 250 */ 1081, 1088, 1078, 1116, 1118, 1046, 1066, 1128, 1136, 1140,
  118777. /* 260 */ 1120, 1147, 1146, 1148, 1150, 1130, 1135, 1137, 1138, 1132,
  118778. /* 270 */ 1141, 1142, 1143, 1149, 1144, 1153, 1154, 1104, 1107, 1108,
  118779. /* 280 */ 1114, 1115, 1117, 1123, 1125, 1173, 1176, 1121, 1165, 1127,
  118780. /* 290 */ 1131, 1167, 1157, 1151, 1158, 1166, 1168, 1212, 1214, 1227,
  118781. /* 300 */ 1228, 1231, 1232, 1233, 1234, 1152, 1155, 1159, 1198, 1199,
  118782. /* 310 */ 1219,
  118783. };
  118784. static const YYACTIONTYPE yy_default[] = {
  118785. /* 0 */ 982, 1300, 1300, 1300, 1214, 1214, 1214, 1305, 1300, 1109,
  118786. /* 10 */ 1138, 1138, 1274, 1305, 1305, 1305, 1305, 1305, 1305, 1212,
  118787. /* 20 */ 1305, 1305, 1305, 1300, 1305, 1113, 1144, 1305, 1305, 1305,
  118788. /* 30 */ 1305, 1305, 1305, 1305, 1305, 1273, 1275, 1152, 1151, 1254,
  118789. /* 40 */ 1125, 1149, 1142, 1146, 1215, 1208, 1209, 1207, 1211, 1216,
  118790. /* 50 */ 1305, 1145, 1177, 1192, 1176, 1305, 1305, 1305, 1305, 1305,
  118791. /* 60 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118792. /* 70 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118793. /* 80 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118794. /* 90 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1186, 1191,
  118795. /* 100 */ 1198, 1190, 1187, 1179, 1178, 1180, 1181, 1305, 1305, 1008,
  118796. /* 110 */ 1074, 1305, 1305, 1182, 1305, 1020, 1183, 1195, 1194, 1193,
  118797. /* 120 */ 1015, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118798. /* 130 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118799. /* 140 */ 1305, 1305, 1305, 1305, 1305, 982, 1300, 1305, 1305, 1300,
  118800. /* 150 */ 1300, 1300, 1300, 1300, 1300, 1292, 1113, 1103, 1305, 1305,
  118801. /* 160 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1280, 1278,
  118802. /* 170 */ 1305, 1227, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118803. /* 180 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118804. /* 190 */ 1305, 1305, 1305, 1109, 1305, 1305, 1305, 1305, 1305, 1305,
  118805. /* 200 */ 1305, 1305, 1305, 1305, 1305, 1305, 988, 1305, 1247, 1109,
  118806. /* 210 */ 1109, 1109, 1111, 1089, 1101, 990, 1148, 1127, 1127, 1259,
  118807. /* 220 */ 1148, 1259, 1045, 1068, 1042, 1138, 1127, 1210, 1138, 1138,
  118808. /* 230 */ 1110, 1101, 1305, 1285, 1118, 1118, 1277, 1277, 1118, 1157,
  118809. /* 240 */ 1078, 1148, 1085, 1085, 1085, 1085, 1118, 1005, 1148, 1157,
  118810. /* 250 */ 1078, 1078, 1148, 1118, 1005, 1253, 1251, 1118, 1118, 1005,
  118811. /* 260 */ 1220, 1118, 1005, 1118, 1005, 1220, 1076, 1076, 1076, 1060,
  118812. /* 270 */ 1220, 1076, 1045, 1076, 1060, 1076, 1076, 1131, 1126, 1131,
  118813. /* 280 */ 1126, 1131, 1126, 1131, 1126, 1118, 1118, 1305, 1220, 1224,
  118814. /* 290 */ 1224, 1220, 1143, 1132, 1141, 1139, 1148, 1011, 1063, 998,
  118815. /* 300 */ 998, 987, 987, 987, 987, 1297, 1297, 1292, 1047, 1047,
  118816. /* 310 */ 1030, 1305, 1305, 1305, 1305, 1305, 1305, 1022, 1305, 1229,
  118817. /* 320 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118818. /* 330 */ 1305, 1305, 1305, 1305, 1305, 1305, 1164, 1305, 983, 1287,
  118819. /* 340 */ 1305, 1305, 1284, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118820. /* 350 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118821. /* 360 */ 1305, 1257, 1305, 1305, 1305, 1305, 1305, 1305, 1250, 1249,
  118822. /* 370 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118823. /* 380 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  118824. /* 390 */ 1305, 1305, 1092, 1305, 1305, 1305, 1096, 1305, 1305, 1305,
  118825. /* 400 */ 1305, 1305, 1305, 1305, 1140, 1305, 1133, 1305, 1213, 1305,
  118826. /* 410 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1302,
  118827. /* 420 */ 1305, 1305, 1305, 1301, 1305, 1305, 1305, 1305, 1305, 1166,
  118828. /* 430 */ 1305, 1165, 1169, 1305, 996, 1305,
  118829. };
  118830. /* The next table maps tokens into fallback tokens. If a construct
  118831. ** like the following:
  118832. **
  118833. ** %fallback ID X Y Z.
  118834. **
  118835. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  118836. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  118837. ** but it does not parse, the type of the token is changed to ID and
  118838. ** the parse is retried before an error is thrown.
  118839. */
  118840. #ifdef YYFALLBACK
  118841. static const YYCODETYPE yyFallback[] = {
  118842. 0, /* $ => nothing */
  118843. 0, /* SEMI => nothing */
  118844. 27, /* EXPLAIN => ID */
  118845. 27, /* QUERY => ID */
  118846. 27, /* PLAN => ID */
  118847. 27, /* BEGIN => ID */
  118848. 0, /* TRANSACTION => nothing */
  118849. 27, /* DEFERRED => ID */
  118850. 27, /* IMMEDIATE => ID */
  118851. 27, /* EXCLUSIVE => ID */
  118852. 0, /* COMMIT => nothing */
  118853. 27, /* END => ID */
  118854. 27, /* ROLLBACK => ID */
  118855. 27, /* SAVEPOINT => ID */
  118856. 27, /* RELEASE => ID */
  118857. 0, /* TO => nothing */
  118858. 0, /* TABLE => nothing */
  118859. 0, /* CREATE => nothing */
  118860. 27, /* IF => ID */
  118861. 0, /* NOT => nothing */
  118862. 0, /* EXISTS => nothing */
  118863. 27, /* TEMP => ID */
  118864. 0, /* LP => nothing */
  118865. 0, /* RP => nothing */
  118866. 0, /* AS => nothing */
  118867. 27, /* WITHOUT => ID */
  118868. 0, /* COMMA => nothing */
  118869. 0, /* ID => nothing */
  118870. 0, /* INDEXED => nothing */
  118871. 27, /* ABORT => ID */
  118872. 27, /* ACTION => ID */
  118873. 27, /* AFTER => ID */
  118874. 27, /* ANALYZE => ID */
  118875. 27, /* ASC => ID */
  118876. 27, /* ATTACH => ID */
  118877. 27, /* BEFORE => ID */
  118878. 27, /* BY => ID */
  118879. 27, /* CASCADE => ID */
  118880. 27, /* CAST => ID */
  118881. 27, /* COLUMNKW => ID */
  118882. 27, /* CONFLICT => ID */
  118883. 27, /* DATABASE => ID */
  118884. 27, /* DESC => ID */
  118885. 27, /* DETACH => ID */
  118886. 27, /* EACH => ID */
  118887. 27, /* FAIL => ID */
  118888. 27, /* FOR => ID */
  118889. 27, /* IGNORE => ID */
  118890. 27, /* INITIALLY => ID */
  118891. 27, /* INSTEAD => ID */
  118892. 27, /* LIKE_KW => ID */
  118893. 27, /* MATCH => ID */
  118894. 27, /* NO => ID */
  118895. 27, /* KEY => ID */
  118896. 27, /* OF => ID */
  118897. 27, /* OFFSET => ID */
  118898. 27, /* PRAGMA => ID */
  118899. 27, /* RAISE => ID */
  118900. 27, /* RECURSIVE => ID */
  118901. 27, /* REPLACE => ID */
  118902. 27, /* RESTRICT => ID */
  118903. 27, /* ROW => ID */
  118904. 27, /* TRIGGER => ID */
  118905. 27, /* VACUUM => ID */
  118906. 27, /* VIEW => ID */
  118907. 27, /* VIRTUAL => ID */
  118908. 27, /* WITH => ID */
  118909. 27, /* REINDEX => ID */
  118910. 27, /* RENAME => ID */
  118911. 27, /* CTIME_KW => ID */
  118912. };
  118913. #endif /* YYFALLBACK */
  118914. /* The following structure represents a single element of the
  118915. ** parser's stack. Information stored includes:
  118916. **
  118917. ** + The state number for the parser at this level of the stack.
  118918. **
  118919. ** + The value of the token stored at this level of the stack.
  118920. ** (In other words, the "major" token.)
  118921. **
  118922. ** + The semantic value stored at this level of the stack. This is
  118923. ** the information used by the action routines in the grammar.
  118924. ** It is sometimes called the "minor" token.
  118925. **
  118926. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  118927. ** actually contains the reduce action for the second half of the
  118928. ** SHIFTREDUCE.
  118929. */
  118930. struct yyStackEntry {
  118931. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  118932. YYCODETYPE major; /* The major token value. This is the code
  118933. ** number for the token at this stack level */
  118934. YYMINORTYPE minor; /* The user-supplied minor token value. This
  118935. ** is the value of the token */
  118936. };
  118937. typedef struct yyStackEntry yyStackEntry;
  118938. /* The state of the parser is completely contained in an instance of
  118939. ** the following structure */
  118940. struct yyParser {
  118941. int yyidx; /* Index of top element in stack */
  118942. #ifdef YYTRACKMAXSTACKDEPTH
  118943. int yyidxMax; /* Maximum value of yyidx */
  118944. #endif
  118945. int yyerrcnt; /* Shifts left before out of the error */
  118946. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  118947. #if YYSTACKDEPTH<=0
  118948. int yystksz; /* Current side of the stack */
  118949. yyStackEntry *yystack; /* The parser's stack */
  118950. #else
  118951. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  118952. #endif
  118953. };
  118954. typedef struct yyParser yyParser;
  118955. #ifndef NDEBUG
  118956. /* #include <stdio.h> */
  118957. static FILE *yyTraceFILE = 0;
  118958. static char *yyTracePrompt = 0;
  118959. #endif /* NDEBUG */
  118960. #ifndef NDEBUG
  118961. /*
  118962. ** Turn parser tracing on by giving a stream to which to write the trace
  118963. ** and a prompt to preface each trace message. Tracing is turned off
  118964. ** by making either argument NULL
  118965. **
  118966. ** Inputs:
  118967. ** <ul>
  118968. ** <li> A FILE* to which trace output should be written.
  118969. ** If NULL, then tracing is turned off.
  118970. ** <li> A prefix string written at the beginning of every
  118971. ** line of trace output. If NULL, then tracing is
  118972. ** turned off.
  118973. ** </ul>
  118974. **
  118975. ** Outputs:
  118976. ** None.
  118977. */
  118978. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  118979. yyTraceFILE = TraceFILE;
  118980. yyTracePrompt = zTracePrompt;
  118981. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  118982. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  118983. }
  118984. #endif /* NDEBUG */
  118985. #ifndef NDEBUG
  118986. /* For tracing shifts, the names of all terminals and nonterminals
  118987. ** are required. The following table supplies these names */
  118988. static const char *const yyTokenName[] = {
  118989. "$", "SEMI", "EXPLAIN", "QUERY",
  118990. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  118991. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  118992. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  118993. "TABLE", "CREATE", "IF", "NOT",
  118994. "EXISTS", "TEMP", "LP", "RP",
  118995. "AS", "WITHOUT", "COMMA", "ID",
  118996. "INDEXED", "ABORT", "ACTION", "AFTER",
  118997. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  118998. "BY", "CASCADE", "CAST", "COLUMNKW",
  118999. "CONFLICT", "DATABASE", "DESC", "DETACH",
  119000. "EACH", "FAIL", "FOR", "IGNORE",
  119001. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  119002. "NO", "KEY", "OF", "OFFSET",
  119003. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  119004. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  119005. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  119006. "RENAME", "CTIME_KW", "ANY", "OR",
  119007. "AND", "IS", "BETWEEN", "IN",
  119008. "ISNULL", "NOTNULL", "NE", "EQ",
  119009. "GT", "LE", "LT", "GE",
  119010. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  119011. "RSHIFT", "PLUS", "MINUS", "STAR",
  119012. "SLASH", "REM", "CONCAT", "COLLATE",
  119013. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  119014. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  119015. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  119016. "INSERT", "DELETE", "UPDATE", "SET",
  119017. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  119018. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  119019. "VALUES", "DISTINCT", "DOT", "FROM",
  119020. "JOIN", "USING", "ORDER", "GROUP",
  119021. "HAVING", "LIMIT", "WHERE", "INTO",
  119022. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  119023. "CASE", "WHEN", "THEN", "ELSE",
  119024. "INDEX", "ALTER", "ADD", "error",
  119025. "input", "cmdlist", "ecmd", "explain",
  119026. "cmdx", "cmd", "transtype", "trans_opt",
  119027. "nm", "savepoint_opt", "create_table", "create_table_args",
  119028. "createkw", "temp", "ifnotexists", "dbnm",
  119029. "columnlist", "conslist_opt", "table_options", "select",
  119030. "column", "columnid", "type", "carglist",
  119031. "typetoken", "typename", "signed", "plus_num",
  119032. "minus_num", "ccons", "term", "expr",
  119033. "onconf", "sortorder", "autoinc", "eidlist_opt",
  119034. "refargs", "defer_subclause", "refarg", "refact",
  119035. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  119036. "sortlist", "eidlist", "defer_subclause_opt", "orconf",
  119037. "resolvetype", "raisetype", "ifexists", "fullname",
  119038. "selectnowith", "oneselect", "with", "multiselect_op",
  119039. "distinct", "selcollist", "from", "where_opt",
  119040. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  119041. "values", "nexprlist", "exprlist", "sclp",
  119042. "as", "seltablist", "stl_prefix", "joinop",
  119043. "indexed_opt", "on_opt", "using_opt", "joinop2",
  119044. "idlist", "setlist", "insert_cmd", "idlist_opt",
  119045. "likeop", "between_op", "in_op", "case_operand",
  119046. "case_exprlist", "case_else", "uniqueflag", "collate",
  119047. "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
  119048. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  119049. "trnm", "tridxby", "database_kw_opt", "key_opt",
  119050. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  119051. "vtabarg", "vtabargtoken", "lp", "anylist",
  119052. "wqlist",
  119053. };
  119054. #endif /* NDEBUG */
  119055. #ifndef NDEBUG
  119056. /* For tracing reduce actions, the names of all rules are required.
  119057. */
  119058. static const char *const yyRuleName[] = {
  119059. /* 0 */ "input ::= cmdlist",
  119060. /* 1 */ "cmdlist ::= cmdlist ecmd",
  119061. /* 2 */ "cmdlist ::= ecmd",
  119062. /* 3 */ "ecmd ::= SEMI",
  119063. /* 4 */ "ecmd ::= explain cmdx SEMI",
  119064. /* 5 */ "explain ::=",
  119065. /* 6 */ "explain ::= EXPLAIN",
  119066. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  119067. /* 8 */ "cmdx ::= cmd",
  119068. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  119069. /* 10 */ "trans_opt ::=",
  119070. /* 11 */ "trans_opt ::= TRANSACTION",
  119071. /* 12 */ "trans_opt ::= TRANSACTION nm",
  119072. /* 13 */ "transtype ::=",
  119073. /* 14 */ "transtype ::= DEFERRED",
  119074. /* 15 */ "transtype ::= IMMEDIATE",
  119075. /* 16 */ "transtype ::= EXCLUSIVE",
  119076. /* 17 */ "cmd ::= COMMIT trans_opt",
  119077. /* 18 */ "cmd ::= END trans_opt",
  119078. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  119079. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  119080. /* 21 */ "savepoint_opt ::=",
  119081. /* 22 */ "cmd ::= SAVEPOINT nm",
  119082. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  119083. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  119084. /* 25 */ "cmd ::= create_table create_table_args",
  119085. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  119086. /* 27 */ "createkw ::= CREATE",
  119087. /* 28 */ "ifnotexists ::=",
  119088. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  119089. /* 30 */ "temp ::= TEMP",
  119090. /* 31 */ "temp ::=",
  119091. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  119092. /* 33 */ "create_table_args ::= AS select",
  119093. /* 34 */ "table_options ::=",
  119094. /* 35 */ "table_options ::= WITHOUT nm",
  119095. /* 36 */ "columnlist ::= columnlist COMMA column",
  119096. /* 37 */ "columnlist ::= column",
  119097. /* 38 */ "column ::= columnid type carglist",
  119098. /* 39 */ "columnid ::= nm",
  119099. /* 40 */ "nm ::= ID|INDEXED",
  119100. /* 41 */ "nm ::= STRING",
  119101. /* 42 */ "nm ::= JOIN_KW",
  119102. /* 43 */ "type ::=",
  119103. /* 44 */ "type ::= typetoken",
  119104. /* 45 */ "typetoken ::= typename",
  119105. /* 46 */ "typetoken ::= typename LP signed RP",
  119106. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  119107. /* 48 */ "typename ::= ID|STRING",
  119108. /* 49 */ "typename ::= typename ID|STRING",
  119109. /* 50 */ "signed ::= plus_num",
  119110. /* 51 */ "signed ::= minus_num",
  119111. /* 52 */ "carglist ::= carglist ccons",
  119112. /* 53 */ "carglist ::=",
  119113. /* 54 */ "ccons ::= CONSTRAINT nm",
  119114. /* 55 */ "ccons ::= DEFAULT term",
  119115. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  119116. /* 57 */ "ccons ::= DEFAULT PLUS term",
  119117. /* 58 */ "ccons ::= DEFAULT MINUS term",
  119118. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  119119. /* 60 */ "ccons ::= NULL onconf",
  119120. /* 61 */ "ccons ::= NOT NULL onconf",
  119121. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  119122. /* 63 */ "ccons ::= UNIQUE onconf",
  119123. /* 64 */ "ccons ::= CHECK LP expr RP",
  119124. /* 65 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  119125. /* 66 */ "ccons ::= defer_subclause",
  119126. /* 67 */ "ccons ::= COLLATE ID|STRING",
  119127. /* 68 */ "autoinc ::=",
  119128. /* 69 */ "autoinc ::= AUTOINCR",
  119129. /* 70 */ "refargs ::=",
  119130. /* 71 */ "refargs ::= refargs refarg",
  119131. /* 72 */ "refarg ::= MATCH nm",
  119132. /* 73 */ "refarg ::= ON INSERT refact",
  119133. /* 74 */ "refarg ::= ON DELETE refact",
  119134. /* 75 */ "refarg ::= ON UPDATE refact",
  119135. /* 76 */ "refact ::= SET NULL",
  119136. /* 77 */ "refact ::= SET DEFAULT",
  119137. /* 78 */ "refact ::= CASCADE",
  119138. /* 79 */ "refact ::= RESTRICT",
  119139. /* 80 */ "refact ::= NO ACTION",
  119140. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  119141. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  119142. /* 83 */ "init_deferred_pred_opt ::=",
  119143. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  119144. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  119145. /* 86 */ "conslist_opt ::=",
  119146. /* 87 */ "conslist_opt ::= COMMA conslist",
  119147. /* 88 */ "conslist ::= conslist tconscomma tcons",
  119148. /* 89 */ "conslist ::= tcons",
  119149. /* 90 */ "tconscomma ::= COMMA",
  119150. /* 91 */ "tconscomma ::=",
  119151. /* 92 */ "tcons ::= CONSTRAINT nm",
  119152. /* 93 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  119153. /* 94 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  119154. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  119155. /* 96 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  119156. /* 97 */ "defer_subclause_opt ::=",
  119157. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  119158. /* 99 */ "onconf ::=",
  119159. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  119160. /* 101 */ "orconf ::=",
  119161. /* 102 */ "orconf ::= OR resolvetype",
  119162. /* 103 */ "resolvetype ::= raisetype",
  119163. /* 104 */ "resolvetype ::= IGNORE",
  119164. /* 105 */ "resolvetype ::= REPLACE",
  119165. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  119166. /* 107 */ "ifexists ::= IF EXISTS",
  119167. /* 108 */ "ifexists ::=",
  119168. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  119169. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  119170. /* 111 */ "cmd ::= select",
  119171. /* 112 */ "select ::= with selectnowith",
  119172. /* 113 */ "selectnowith ::= oneselect",
  119173. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  119174. /* 115 */ "multiselect_op ::= UNION",
  119175. /* 116 */ "multiselect_op ::= UNION ALL",
  119176. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  119177. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  119178. /* 119 */ "oneselect ::= values",
  119179. /* 120 */ "values ::= VALUES LP nexprlist RP",
  119180. /* 121 */ "values ::= values COMMA LP exprlist RP",
  119181. /* 122 */ "distinct ::= DISTINCT",
  119182. /* 123 */ "distinct ::= ALL",
  119183. /* 124 */ "distinct ::=",
  119184. /* 125 */ "sclp ::= selcollist COMMA",
  119185. /* 126 */ "sclp ::=",
  119186. /* 127 */ "selcollist ::= sclp expr as",
  119187. /* 128 */ "selcollist ::= sclp STAR",
  119188. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  119189. /* 130 */ "as ::= AS nm",
  119190. /* 131 */ "as ::= ID|STRING",
  119191. /* 132 */ "as ::=",
  119192. /* 133 */ "from ::=",
  119193. /* 134 */ "from ::= FROM seltablist",
  119194. /* 135 */ "stl_prefix ::= seltablist joinop",
  119195. /* 136 */ "stl_prefix ::=",
  119196. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  119197. /* 138 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  119198. /* 139 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  119199. /* 140 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  119200. /* 141 */ "dbnm ::=",
  119201. /* 142 */ "dbnm ::= DOT nm",
  119202. /* 143 */ "fullname ::= nm dbnm",
  119203. /* 144 */ "joinop ::= COMMA|JOIN",
  119204. /* 145 */ "joinop ::= JOIN_KW JOIN",
  119205. /* 146 */ "joinop ::= JOIN_KW nm JOIN",
  119206. /* 147 */ "joinop ::= JOIN_KW nm nm JOIN",
  119207. /* 148 */ "on_opt ::= ON expr",
  119208. /* 149 */ "on_opt ::=",
  119209. /* 150 */ "indexed_opt ::=",
  119210. /* 151 */ "indexed_opt ::= INDEXED BY nm",
  119211. /* 152 */ "indexed_opt ::= NOT INDEXED",
  119212. /* 153 */ "using_opt ::= USING LP idlist RP",
  119213. /* 154 */ "using_opt ::=",
  119214. /* 155 */ "orderby_opt ::=",
  119215. /* 156 */ "orderby_opt ::= ORDER BY sortlist",
  119216. /* 157 */ "sortlist ::= sortlist COMMA expr sortorder",
  119217. /* 158 */ "sortlist ::= expr sortorder",
  119218. /* 159 */ "sortorder ::= ASC",
  119219. /* 160 */ "sortorder ::= DESC",
  119220. /* 161 */ "sortorder ::=",
  119221. /* 162 */ "groupby_opt ::=",
  119222. /* 163 */ "groupby_opt ::= GROUP BY nexprlist",
  119223. /* 164 */ "having_opt ::=",
  119224. /* 165 */ "having_opt ::= HAVING expr",
  119225. /* 166 */ "limit_opt ::=",
  119226. /* 167 */ "limit_opt ::= LIMIT expr",
  119227. /* 168 */ "limit_opt ::= LIMIT expr OFFSET expr",
  119228. /* 169 */ "limit_opt ::= LIMIT expr COMMA expr",
  119229. /* 170 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  119230. /* 171 */ "where_opt ::=",
  119231. /* 172 */ "where_opt ::= WHERE expr",
  119232. /* 173 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  119233. /* 174 */ "setlist ::= setlist COMMA nm EQ expr",
  119234. /* 175 */ "setlist ::= nm EQ expr",
  119235. /* 176 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  119236. /* 177 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  119237. /* 178 */ "insert_cmd ::= INSERT orconf",
  119238. /* 179 */ "insert_cmd ::= REPLACE",
  119239. /* 180 */ "idlist_opt ::=",
  119240. /* 181 */ "idlist_opt ::= LP idlist RP",
  119241. /* 182 */ "idlist ::= idlist COMMA nm",
  119242. /* 183 */ "idlist ::= nm",
  119243. /* 184 */ "expr ::= term",
  119244. /* 185 */ "expr ::= LP expr RP",
  119245. /* 186 */ "term ::= NULL",
  119246. /* 187 */ "expr ::= ID|INDEXED",
  119247. /* 188 */ "expr ::= JOIN_KW",
  119248. /* 189 */ "expr ::= nm DOT nm",
  119249. /* 190 */ "expr ::= nm DOT nm DOT nm",
  119250. /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
  119251. /* 192 */ "term ::= STRING",
  119252. /* 193 */ "expr ::= VARIABLE",
  119253. /* 194 */ "expr ::= expr COLLATE ID|STRING",
  119254. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  119255. /* 196 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  119256. /* 197 */ "expr ::= ID|INDEXED LP STAR RP",
  119257. /* 198 */ "term ::= CTIME_KW",
  119258. /* 199 */ "expr ::= expr AND expr",
  119259. /* 200 */ "expr ::= expr OR expr",
  119260. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  119261. /* 202 */ "expr ::= expr EQ|NE expr",
  119262. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  119263. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  119264. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  119265. /* 206 */ "expr ::= expr CONCAT expr",
  119266. /* 207 */ "likeop ::= LIKE_KW|MATCH",
  119267. /* 208 */ "likeop ::= NOT LIKE_KW|MATCH",
  119268. /* 209 */ "expr ::= expr likeop expr",
  119269. /* 210 */ "expr ::= expr likeop expr ESCAPE expr",
  119270. /* 211 */ "expr ::= expr ISNULL|NOTNULL",
  119271. /* 212 */ "expr ::= expr NOT NULL",
  119272. /* 213 */ "expr ::= expr IS expr",
  119273. /* 214 */ "expr ::= expr IS NOT expr",
  119274. /* 215 */ "expr ::= NOT expr",
  119275. /* 216 */ "expr ::= BITNOT expr",
  119276. /* 217 */ "expr ::= MINUS expr",
  119277. /* 218 */ "expr ::= PLUS expr",
  119278. /* 219 */ "between_op ::= BETWEEN",
  119279. /* 220 */ "between_op ::= NOT BETWEEN",
  119280. /* 221 */ "expr ::= expr between_op expr AND expr",
  119281. /* 222 */ "in_op ::= IN",
  119282. /* 223 */ "in_op ::= NOT IN",
  119283. /* 224 */ "expr ::= expr in_op LP exprlist RP",
  119284. /* 225 */ "expr ::= LP select RP",
  119285. /* 226 */ "expr ::= expr in_op LP select RP",
  119286. /* 227 */ "expr ::= expr in_op nm dbnm",
  119287. /* 228 */ "expr ::= EXISTS LP select RP",
  119288. /* 229 */ "expr ::= CASE case_operand case_exprlist case_else END",
  119289. /* 230 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  119290. /* 231 */ "case_exprlist ::= WHEN expr THEN expr",
  119291. /* 232 */ "case_else ::= ELSE expr",
  119292. /* 233 */ "case_else ::=",
  119293. /* 234 */ "case_operand ::= expr",
  119294. /* 235 */ "case_operand ::=",
  119295. /* 236 */ "exprlist ::= nexprlist",
  119296. /* 237 */ "exprlist ::=",
  119297. /* 238 */ "nexprlist ::= nexprlist COMMA expr",
  119298. /* 239 */ "nexprlist ::= expr",
  119299. /* 240 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  119300. /* 241 */ "uniqueflag ::= UNIQUE",
  119301. /* 242 */ "uniqueflag ::=",
  119302. /* 243 */ "eidlist_opt ::=",
  119303. /* 244 */ "eidlist_opt ::= LP eidlist RP",
  119304. /* 245 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  119305. /* 246 */ "eidlist ::= nm collate sortorder",
  119306. /* 247 */ "collate ::=",
  119307. /* 248 */ "collate ::= COLLATE ID|STRING",
  119308. /* 249 */ "cmd ::= DROP INDEX ifexists fullname",
  119309. /* 250 */ "cmd ::= VACUUM",
  119310. /* 251 */ "cmd ::= VACUUM nm",
  119311. /* 252 */ "cmd ::= PRAGMA nm dbnm",
  119312. /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  119313. /* 254 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  119314. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  119315. /* 256 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  119316. /* 257 */ "nmnum ::= plus_num",
  119317. /* 258 */ "nmnum ::= nm",
  119318. /* 259 */ "nmnum ::= ON",
  119319. /* 260 */ "nmnum ::= DELETE",
  119320. /* 261 */ "nmnum ::= DEFAULT",
  119321. /* 262 */ "plus_num ::= PLUS INTEGER|FLOAT",
  119322. /* 263 */ "plus_num ::= INTEGER|FLOAT",
  119323. /* 264 */ "minus_num ::= MINUS INTEGER|FLOAT",
  119324. /* 265 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  119325. /* 266 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  119326. /* 267 */ "trigger_time ::= BEFORE",
  119327. /* 268 */ "trigger_time ::= AFTER",
  119328. /* 269 */ "trigger_time ::= INSTEAD OF",
  119329. /* 270 */ "trigger_time ::=",
  119330. /* 271 */ "trigger_event ::= DELETE|INSERT",
  119331. /* 272 */ "trigger_event ::= UPDATE",
  119332. /* 273 */ "trigger_event ::= UPDATE OF idlist",
  119333. /* 274 */ "foreach_clause ::=",
  119334. /* 275 */ "foreach_clause ::= FOR EACH ROW",
  119335. /* 276 */ "when_clause ::=",
  119336. /* 277 */ "when_clause ::= WHEN expr",
  119337. /* 278 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  119338. /* 279 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  119339. /* 280 */ "trnm ::= nm",
  119340. /* 281 */ "trnm ::= nm DOT nm",
  119341. /* 282 */ "tridxby ::=",
  119342. /* 283 */ "tridxby ::= INDEXED BY nm",
  119343. /* 284 */ "tridxby ::= NOT INDEXED",
  119344. /* 285 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  119345. /* 286 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  119346. /* 287 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  119347. /* 288 */ "trigger_cmd ::= select",
  119348. /* 289 */ "expr ::= RAISE LP IGNORE RP",
  119349. /* 290 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  119350. /* 291 */ "raisetype ::= ROLLBACK",
  119351. /* 292 */ "raisetype ::= ABORT",
  119352. /* 293 */ "raisetype ::= FAIL",
  119353. /* 294 */ "cmd ::= DROP TRIGGER ifexists fullname",
  119354. /* 295 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  119355. /* 296 */ "cmd ::= DETACH database_kw_opt expr",
  119356. /* 297 */ "key_opt ::=",
  119357. /* 298 */ "key_opt ::= KEY expr",
  119358. /* 299 */ "database_kw_opt ::= DATABASE",
  119359. /* 300 */ "database_kw_opt ::=",
  119360. /* 301 */ "cmd ::= REINDEX",
  119361. /* 302 */ "cmd ::= REINDEX nm dbnm",
  119362. /* 303 */ "cmd ::= ANALYZE",
  119363. /* 304 */ "cmd ::= ANALYZE nm dbnm",
  119364. /* 305 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  119365. /* 306 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  119366. /* 307 */ "add_column_fullname ::= fullname",
  119367. /* 308 */ "kwcolumn_opt ::=",
  119368. /* 309 */ "kwcolumn_opt ::= COLUMNKW",
  119369. /* 310 */ "cmd ::= create_vtab",
  119370. /* 311 */ "cmd ::= create_vtab LP vtabarglist RP",
  119371. /* 312 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  119372. /* 313 */ "vtabarglist ::= vtabarg",
  119373. /* 314 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  119374. /* 315 */ "vtabarg ::=",
  119375. /* 316 */ "vtabarg ::= vtabarg vtabargtoken",
  119376. /* 317 */ "vtabargtoken ::= ANY",
  119377. /* 318 */ "vtabargtoken ::= lp anylist RP",
  119378. /* 319 */ "lp ::= LP",
  119379. /* 320 */ "anylist ::=",
  119380. /* 321 */ "anylist ::= anylist LP anylist RP",
  119381. /* 322 */ "anylist ::= anylist ANY",
  119382. /* 323 */ "with ::=",
  119383. /* 324 */ "with ::= WITH wqlist",
  119384. /* 325 */ "with ::= WITH RECURSIVE wqlist",
  119385. /* 326 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  119386. /* 327 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  119387. };
  119388. #endif /* NDEBUG */
  119389. #if YYSTACKDEPTH<=0
  119390. /*
  119391. ** Try to increase the size of the parser stack.
  119392. */
  119393. static void yyGrowStack(yyParser *p){
  119394. int newSize;
  119395. yyStackEntry *pNew;
  119396. newSize = p->yystksz*2 + 100;
  119397. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  119398. if( pNew ){
  119399. p->yystack = pNew;
  119400. p->yystksz = newSize;
  119401. #ifndef NDEBUG
  119402. if( yyTraceFILE ){
  119403. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  119404. yyTracePrompt, p->yystksz);
  119405. }
  119406. #endif
  119407. }
  119408. }
  119409. #endif
  119410. /*
  119411. ** This function allocates a new parser.
  119412. ** The only argument is a pointer to a function which works like
  119413. ** malloc.
  119414. **
  119415. ** Inputs:
  119416. ** A pointer to the function used to allocate memory.
  119417. **
  119418. ** Outputs:
  119419. ** A pointer to a parser. This pointer is used in subsequent calls
  119420. ** to sqlite3Parser and sqlite3ParserFree.
  119421. */
  119422. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
  119423. yyParser *pParser;
  119424. pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
  119425. if( pParser ){
  119426. pParser->yyidx = -1;
  119427. #ifdef YYTRACKMAXSTACKDEPTH
  119428. pParser->yyidxMax = 0;
  119429. #endif
  119430. #if YYSTACKDEPTH<=0
  119431. pParser->yystack = NULL;
  119432. pParser->yystksz = 0;
  119433. yyGrowStack(pParser);
  119434. #endif
  119435. }
  119436. return pParser;
  119437. }
  119438. /* The following function deletes the value associated with a
  119439. ** symbol. The symbol can be either a terminal or nonterminal.
  119440. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  119441. ** the value.
  119442. */
  119443. static void yy_destructor(
  119444. yyParser *yypParser, /* The parser */
  119445. YYCODETYPE yymajor, /* Type code for object to destroy */
  119446. YYMINORTYPE *yypminor /* The object to be destroyed */
  119447. ){
  119448. sqlite3ParserARG_FETCH;
  119449. switch( yymajor ){
  119450. /* Here is inserted the actions which take place when a
  119451. ** terminal or non-terminal is destroyed. This can happen
  119452. ** when the symbol is popped from the stack during a
  119453. ** reduce or during error processing or when a parser is
  119454. ** being destroyed before it is finished parsing.
  119455. **
  119456. ** Note: during a reduce, the only symbols destroyed are those
  119457. ** which appear on the RHS of the rule, but which are not used
  119458. ** inside the C code.
  119459. */
  119460. case 163: /* select */
  119461. case 196: /* selectnowith */
  119462. case 197: /* oneselect */
  119463. case 208: /* values */
  119464. {
  119465. sqlite3SelectDelete(pParse->db, (yypminor->yy3));
  119466. }
  119467. break;
  119468. case 174: /* term */
  119469. case 175: /* expr */
  119470. {
  119471. sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
  119472. }
  119473. break;
  119474. case 179: /* eidlist_opt */
  119475. case 188: /* sortlist */
  119476. case 189: /* eidlist */
  119477. case 201: /* selcollist */
  119478. case 204: /* groupby_opt */
  119479. case 206: /* orderby_opt */
  119480. case 209: /* nexprlist */
  119481. case 210: /* exprlist */
  119482. case 211: /* sclp */
  119483. case 221: /* setlist */
  119484. case 228: /* case_exprlist */
  119485. {
  119486. sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
  119487. }
  119488. break;
  119489. case 195: /* fullname */
  119490. case 202: /* from */
  119491. case 213: /* seltablist */
  119492. case 214: /* stl_prefix */
  119493. {
  119494. sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
  119495. }
  119496. break;
  119497. case 198: /* with */
  119498. case 252: /* wqlist */
  119499. {
  119500. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  119501. }
  119502. break;
  119503. case 203: /* where_opt */
  119504. case 205: /* having_opt */
  119505. case 217: /* on_opt */
  119506. case 227: /* case_operand */
  119507. case 229: /* case_else */
  119508. case 238: /* when_clause */
  119509. case 243: /* key_opt */
  119510. {
  119511. sqlite3ExprDelete(pParse->db, (yypminor->yy132));
  119512. }
  119513. break;
  119514. case 218: /* using_opt */
  119515. case 220: /* idlist */
  119516. case 223: /* idlist_opt */
  119517. {
  119518. sqlite3IdListDelete(pParse->db, (yypminor->yy408));
  119519. }
  119520. break;
  119521. case 234: /* trigger_cmd_list */
  119522. case 239: /* trigger_cmd */
  119523. {
  119524. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
  119525. }
  119526. break;
  119527. case 236: /* trigger_event */
  119528. {
  119529. sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
  119530. }
  119531. break;
  119532. default: break; /* If no destructor action specified: do nothing */
  119533. }
  119534. }
  119535. /*
  119536. ** Pop the parser's stack once.
  119537. **
  119538. ** If there is a destructor routine associated with the token which
  119539. ** is popped from the stack, then call it.
  119540. **
  119541. ** Return the major token number for the symbol popped.
  119542. */
  119543. static int yy_pop_parser_stack(yyParser *pParser){
  119544. YYCODETYPE yymajor;
  119545. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  119546. /* There is no mechanism by which the parser stack can be popped below
  119547. ** empty in SQLite. */
  119548. assert( pParser->yyidx>=0 );
  119549. #ifndef NDEBUG
  119550. if( yyTraceFILE && pParser->yyidx>=0 ){
  119551. fprintf(yyTraceFILE,"%sPopping %s\n",
  119552. yyTracePrompt,
  119553. yyTokenName[yytos->major]);
  119554. }
  119555. #endif
  119556. yymajor = yytos->major;
  119557. yy_destructor(pParser, yymajor, &yytos->minor);
  119558. pParser->yyidx--;
  119559. return yymajor;
  119560. }
  119561. /*
  119562. ** Deallocate and destroy a parser. Destructors are all called for
  119563. ** all stack elements before shutting the parser down.
  119564. **
  119565. ** Inputs:
  119566. ** <ul>
  119567. ** <li> A pointer to the parser. This should be a pointer
  119568. ** obtained from sqlite3ParserAlloc.
  119569. ** <li> A pointer to a function used to reclaim memory obtained
  119570. ** from malloc.
  119571. ** </ul>
  119572. */
  119573. SQLITE_PRIVATE void sqlite3ParserFree(
  119574. void *p, /* The parser to be deleted */
  119575. void (*freeProc)(void*) /* Function used to reclaim memory */
  119576. ){
  119577. yyParser *pParser = (yyParser*)p;
  119578. /* In SQLite, we never try to destroy a parser that was not successfully
  119579. ** created in the first place. */
  119580. if( NEVER(pParser==0) ) return;
  119581. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  119582. #if YYSTACKDEPTH<=0
  119583. free(pParser->yystack);
  119584. #endif
  119585. (*freeProc)((void*)pParser);
  119586. }
  119587. /*
  119588. ** Return the peak depth of the stack for a parser.
  119589. */
  119590. #ifdef YYTRACKMAXSTACKDEPTH
  119591. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  119592. yyParser *pParser = (yyParser*)p;
  119593. return pParser->yyidxMax;
  119594. }
  119595. #endif
  119596. /*
  119597. ** Find the appropriate action for a parser given the terminal
  119598. ** look-ahead token iLookAhead.
  119599. **
  119600. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  119601. ** independent of the look-ahead. If it is, return the action, otherwise
  119602. ** return YY_NO_ACTION.
  119603. */
  119604. static int yy_find_shift_action(
  119605. yyParser *pParser, /* The parser */
  119606. YYCODETYPE iLookAhead /* The look-ahead token */
  119607. ){
  119608. int i;
  119609. int stateno = pParser->yystack[pParser->yyidx].stateno;
  119610. if( stateno>=YY_MIN_REDUCE ) return stateno;
  119611. assert( stateno <= YY_SHIFT_COUNT );
  119612. i = yy_shift_ofst[stateno];
  119613. if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
  119614. assert( iLookAhead!=YYNOCODE );
  119615. i += iLookAhead;
  119616. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  119617. if( iLookAhead>0 ){
  119618. #ifdef YYFALLBACK
  119619. YYCODETYPE iFallback; /* Fallback token */
  119620. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  119621. && (iFallback = yyFallback[iLookAhead])!=0 ){
  119622. #ifndef NDEBUG
  119623. if( yyTraceFILE ){
  119624. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  119625. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  119626. }
  119627. #endif
  119628. return yy_find_shift_action(pParser, iFallback);
  119629. }
  119630. #endif
  119631. #ifdef YYWILDCARD
  119632. {
  119633. int j = i - iLookAhead + YYWILDCARD;
  119634. if(
  119635. #if YY_SHIFT_MIN+YYWILDCARD<0
  119636. j>=0 &&
  119637. #endif
  119638. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  119639. j<YY_ACTTAB_COUNT &&
  119640. #endif
  119641. yy_lookahead[j]==YYWILDCARD
  119642. ){
  119643. #ifndef NDEBUG
  119644. if( yyTraceFILE ){
  119645. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  119646. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  119647. }
  119648. #endif /* NDEBUG */
  119649. return yy_action[j];
  119650. }
  119651. }
  119652. #endif /* YYWILDCARD */
  119653. }
  119654. return yy_default[stateno];
  119655. }else{
  119656. return yy_action[i];
  119657. }
  119658. }
  119659. /*
  119660. ** Find the appropriate action for a parser given the non-terminal
  119661. ** look-ahead token iLookAhead.
  119662. **
  119663. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  119664. ** independent of the look-ahead. If it is, return the action, otherwise
  119665. ** return YY_NO_ACTION.
  119666. */
  119667. static int yy_find_reduce_action(
  119668. int stateno, /* Current state number */
  119669. YYCODETYPE iLookAhead /* The look-ahead token */
  119670. ){
  119671. int i;
  119672. #ifdef YYERRORSYMBOL
  119673. if( stateno>YY_REDUCE_COUNT ){
  119674. return yy_default[stateno];
  119675. }
  119676. #else
  119677. assert( stateno<=YY_REDUCE_COUNT );
  119678. #endif
  119679. i = yy_reduce_ofst[stateno];
  119680. assert( i!=YY_REDUCE_USE_DFLT );
  119681. assert( iLookAhead!=YYNOCODE );
  119682. i += iLookAhead;
  119683. #ifdef YYERRORSYMBOL
  119684. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  119685. return yy_default[stateno];
  119686. }
  119687. #else
  119688. assert( i>=0 && i<YY_ACTTAB_COUNT );
  119689. assert( yy_lookahead[i]==iLookAhead );
  119690. #endif
  119691. return yy_action[i];
  119692. }
  119693. /*
  119694. ** The following routine is called if the stack overflows.
  119695. */
  119696. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  119697. sqlite3ParserARG_FETCH;
  119698. yypParser->yyidx--;
  119699. #ifndef NDEBUG
  119700. if( yyTraceFILE ){
  119701. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  119702. }
  119703. #endif
  119704. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  119705. /* Here code is inserted which will execute if the parser
  119706. ** stack every overflows */
  119707. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  119708. sqlite3ErrorMsg(pParse, "parser stack overflow");
  119709. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  119710. }
  119711. /*
  119712. ** Print tracing information for a SHIFT action
  119713. */
  119714. #ifndef NDEBUG
  119715. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  119716. if( yyTraceFILE ){
  119717. int i;
  119718. if( yyNewState<YYNSTATE ){
  119719. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  119720. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  119721. for(i=1; i<=yypParser->yyidx; i++)
  119722. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  119723. fprintf(yyTraceFILE,"\n");
  119724. }else{
  119725. fprintf(yyTraceFILE,"%sShift *\n",yyTracePrompt);
  119726. }
  119727. }
  119728. }
  119729. #else
  119730. # define yyTraceShift(X,Y)
  119731. #endif
  119732. /*
  119733. ** Perform a shift action. Return the number of errors.
  119734. */
  119735. static void yy_shift(
  119736. yyParser *yypParser, /* The parser to be shifted */
  119737. int yyNewState, /* The new state to shift in */
  119738. int yyMajor, /* The major token to shift in */
  119739. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  119740. ){
  119741. yyStackEntry *yytos;
  119742. yypParser->yyidx++;
  119743. #ifdef YYTRACKMAXSTACKDEPTH
  119744. if( yypParser->yyidx>yypParser->yyidxMax ){
  119745. yypParser->yyidxMax = yypParser->yyidx;
  119746. }
  119747. #endif
  119748. #if YYSTACKDEPTH>0
  119749. if( yypParser->yyidx>=YYSTACKDEPTH ){
  119750. yyStackOverflow(yypParser, yypMinor);
  119751. return;
  119752. }
  119753. #else
  119754. if( yypParser->yyidx>=yypParser->yystksz ){
  119755. yyGrowStack(yypParser);
  119756. if( yypParser->yyidx>=yypParser->yystksz ){
  119757. yyStackOverflow(yypParser, yypMinor);
  119758. return;
  119759. }
  119760. }
  119761. #endif
  119762. yytos = &yypParser->yystack[yypParser->yyidx];
  119763. yytos->stateno = (YYACTIONTYPE)yyNewState;
  119764. yytos->major = (YYCODETYPE)yyMajor;
  119765. yytos->minor = *yypMinor;
  119766. yyTraceShift(yypParser, yyNewState);
  119767. }
  119768. /* The following table contains information about every rule that
  119769. ** is used during the reduce.
  119770. */
  119771. static const struct {
  119772. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  119773. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  119774. } yyRuleInfo[] = {
  119775. { 144, 1 },
  119776. { 145, 2 },
  119777. { 145, 1 },
  119778. { 146, 1 },
  119779. { 146, 3 },
  119780. { 147, 0 },
  119781. { 147, 1 },
  119782. { 147, 3 },
  119783. { 148, 1 },
  119784. { 149, 3 },
  119785. { 151, 0 },
  119786. { 151, 1 },
  119787. { 151, 2 },
  119788. { 150, 0 },
  119789. { 150, 1 },
  119790. { 150, 1 },
  119791. { 150, 1 },
  119792. { 149, 2 },
  119793. { 149, 2 },
  119794. { 149, 2 },
  119795. { 153, 1 },
  119796. { 153, 0 },
  119797. { 149, 2 },
  119798. { 149, 3 },
  119799. { 149, 5 },
  119800. { 149, 2 },
  119801. { 154, 6 },
  119802. { 156, 1 },
  119803. { 158, 0 },
  119804. { 158, 3 },
  119805. { 157, 1 },
  119806. { 157, 0 },
  119807. { 155, 5 },
  119808. { 155, 2 },
  119809. { 162, 0 },
  119810. { 162, 2 },
  119811. { 160, 3 },
  119812. { 160, 1 },
  119813. { 164, 3 },
  119814. { 165, 1 },
  119815. { 152, 1 },
  119816. { 152, 1 },
  119817. { 152, 1 },
  119818. { 166, 0 },
  119819. { 166, 1 },
  119820. { 168, 1 },
  119821. { 168, 4 },
  119822. { 168, 6 },
  119823. { 169, 1 },
  119824. { 169, 2 },
  119825. { 170, 1 },
  119826. { 170, 1 },
  119827. { 167, 2 },
  119828. { 167, 0 },
  119829. { 173, 2 },
  119830. { 173, 2 },
  119831. { 173, 4 },
  119832. { 173, 3 },
  119833. { 173, 3 },
  119834. { 173, 2 },
  119835. { 173, 2 },
  119836. { 173, 3 },
  119837. { 173, 5 },
  119838. { 173, 2 },
  119839. { 173, 4 },
  119840. { 173, 4 },
  119841. { 173, 1 },
  119842. { 173, 2 },
  119843. { 178, 0 },
  119844. { 178, 1 },
  119845. { 180, 0 },
  119846. { 180, 2 },
  119847. { 182, 2 },
  119848. { 182, 3 },
  119849. { 182, 3 },
  119850. { 182, 3 },
  119851. { 183, 2 },
  119852. { 183, 2 },
  119853. { 183, 1 },
  119854. { 183, 1 },
  119855. { 183, 2 },
  119856. { 181, 3 },
  119857. { 181, 2 },
  119858. { 184, 0 },
  119859. { 184, 2 },
  119860. { 184, 2 },
  119861. { 161, 0 },
  119862. { 161, 2 },
  119863. { 185, 3 },
  119864. { 185, 1 },
  119865. { 186, 1 },
  119866. { 186, 0 },
  119867. { 187, 2 },
  119868. { 187, 7 },
  119869. { 187, 5 },
  119870. { 187, 5 },
  119871. { 187, 10 },
  119872. { 190, 0 },
  119873. { 190, 1 },
  119874. { 176, 0 },
  119875. { 176, 3 },
  119876. { 191, 0 },
  119877. { 191, 2 },
  119878. { 192, 1 },
  119879. { 192, 1 },
  119880. { 192, 1 },
  119881. { 149, 4 },
  119882. { 194, 2 },
  119883. { 194, 0 },
  119884. { 149, 9 },
  119885. { 149, 4 },
  119886. { 149, 1 },
  119887. { 163, 2 },
  119888. { 196, 1 },
  119889. { 196, 3 },
  119890. { 199, 1 },
  119891. { 199, 2 },
  119892. { 199, 1 },
  119893. { 197, 9 },
  119894. { 197, 1 },
  119895. { 208, 4 },
  119896. { 208, 5 },
  119897. { 200, 1 },
  119898. { 200, 1 },
  119899. { 200, 0 },
  119900. { 211, 2 },
  119901. { 211, 0 },
  119902. { 201, 3 },
  119903. { 201, 2 },
  119904. { 201, 4 },
  119905. { 212, 2 },
  119906. { 212, 1 },
  119907. { 212, 0 },
  119908. { 202, 0 },
  119909. { 202, 2 },
  119910. { 214, 2 },
  119911. { 214, 0 },
  119912. { 213, 7 },
  119913. { 213, 9 },
  119914. { 213, 7 },
  119915. { 213, 7 },
  119916. { 159, 0 },
  119917. { 159, 2 },
  119918. { 195, 2 },
  119919. { 215, 1 },
  119920. { 215, 2 },
  119921. { 215, 3 },
  119922. { 215, 4 },
  119923. { 217, 2 },
  119924. { 217, 0 },
  119925. { 216, 0 },
  119926. { 216, 3 },
  119927. { 216, 2 },
  119928. { 218, 4 },
  119929. { 218, 0 },
  119930. { 206, 0 },
  119931. { 206, 3 },
  119932. { 188, 4 },
  119933. { 188, 2 },
  119934. { 177, 1 },
  119935. { 177, 1 },
  119936. { 177, 0 },
  119937. { 204, 0 },
  119938. { 204, 3 },
  119939. { 205, 0 },
  119940. { 205, 2 },
  119941. { 207, 0 },
  119942. { 207, 2 },
  119943. { 207, 4 },
  119944. { 207, 4 },
  119945. { 149, 6 },
  119946. { 203, 0 },
  119947. { 203, 2 },
  119948. { 149, 8 },
  119949. { 221, 5 },
  119950. { 221, 3 },
  119951. { 149, 6 },
  119952. { 149, 7 },
  119953. { 222, 2 },
  119954. { 222, 1 },
  119955. { 223, 0 },
  119956. { 223, 3 },
  119957. { 220, 3 },
  119958. { 220, 1 },
  119959. { 175, 1 },
  119960. { 175, 3 },
  119961. { 174, 1 },
  119962. { 175, 1 },
  119963. { 175, 1 },
  119964. { 175, 3 },
  119965. { 175, 5 },
  119966. { 174, 1 },
  119967. { 174, 1 },
  119968. { 175, 1 },
  119969. { 175, 3 },
  119970. { 175, 6 },
  119971. { 175, 5 },
  119972. { 175, 4 },
  119973. { 174, 1 },
  119974. { 175, 3 },
  119975. { 175, 3 },
  119976. { 175, 3 },
  119977. { 175, 3 },
  119978. { 175, 3 },
  119979. { 175, 3 },
  119980. { 175, 3 },
  119981. { 175, 3 },
  119982. { 224, 1 },
  119983. { 224, 2 },
  119984. { 175, 3 },
  119985. { 175, 5 },
  119986. { 175, 2 },
  119987. { 175, 3 },
  119988. { 175, 3 },
  119989. { 175, 4 },
  119990. { 175, 2 },
  119991. { 175, 2 },
  119992. { 175, 2 },
  119993. { 175, 2 },
  119994. { 225, 1 },
  119995. { 225, 2 },
  119996. { 175, 5 },
  119997. { 226, 1 },
  119998. { 226, 2 },
  119999. { 175, 5 },
  120000. { 175, 3 },
  120001. { 175, 5 },
  120002. { 175, 4 },
  120003. { 175, 4 },
  120004. { 175, 5 },
  120005. { 228, 5 },
  120006. { 228, 4 },
  120007. { 229, 2 },
  120008. { 229, 0 },
  120009. { 227, 1 },
  120010. { 227, 0 },
  120011. { 210, 1 },
  120012. { 210, 0 },
  120013. { 209, 3 },
  120014. { 209, 1 },
  120015. { 149, 12 },
  120016. { 230, 1 },
  120017. { 230, 0 },
  120018. { 179, 0 },
  120019. { 179, 3 },
  120020. { 189, 5 },
  120021. { 189, 3 },
  120022. { 231, 0 },
  120023. { 231, 2 },
  120024. { 149, 4 },
  120025. { 149, 1 },
  120026. { 149, 2 },
  120027. { 149, 3 },
  120028. { 149, 5 },
  120029. { 149, 6 },
  120030. { 149, 5 },
  120031. { 149, 6 },
  120032. { 232, 1 },
  120033. { 232, 1 },
  120034. { 232, 1 },
  120035. { 232, 1 },
  120036. { 232, 1 },
  120037. { 171, 2 },
  120038. { 171, 1 },
  120039. { 172, 2 },
  120040. { 149, 5 },
  120041. { 233, 11 },
  120042. { 235, 1 },
  120043. { 235, 1 },
  120044. { 235, 2 },
  120045. { 235, 0 },
  120046. { 236, 1 },
  120047. { 236, 1 },
  120048. { 236, 3 },
  120049. { 237, 0 },
  120050. { 237, 3 },
  120051. { 238, 0 },
  120052. { 238, 2 },
  120053. { 234, 3 },
  120054. { 234, 2 },
  120055. { 240, 1 },
  120056. { 240, 3 },
  120057. { 241, 0 },
  120058. { 241, 3 },
  120059. { 241, 2 },
  120060. { 239, 7 },
  120061. { 239, 5 },
  120062. { 239, 5 },
  120063. { 239, 1 },
  120064. { 175, 4 },
  120065. { 175, 6 },
  120066. { 193, 1 },
  120067. { 193, 1 },
  120068. { 193, 1 },
  120069. { 149, 4 },
  120070. { 149, 6 },
  120071. { 149, 3 },
  120072. { 243, 0 },
  120073. { 243, 2 },
  120074. { 242, 1 },
  120075. { 242, 0 },
  120076. { 149, 1 },
  120077. { 149, 3 },
  120078. { 149, 1 },
  120079. { 149, 3 },
  120080. { 149, 6 },
  120081. { 149, 6 },
  120082. { 244, 1 },
  120083. { 245, 0 },
  120084. { 245, 1 },
  120085. { 149, 1 },
  120086. { 149, 4 },
  120087. { 246, 8 },
  120088. { 247, 1 },
  120089. { 247, 3 },
  120090. { 248, 0 },
  120091. { 248, 2 },
  120092. { 249, 1 },
  120093. { 249, 3 },
  120094. { 250, 1 },
  120095. { 251, 0 },
  120096. { 251, 4 },
  120097. { 251, 2 },
  120098. { 198, 0 },
  120099. { 198, 2 },
  120100. { 198, 3 },
  120101. { 252, 6 },
  120102. { 252, 8 },
  120103. };
  120104. static void yy_accept(yyParser*); /* Forward Declaration */
  120105. /*
  120106. ** Perform a reduce action and the shift that must immediately
  120107. ** follow the reduce.
  120108. */
  120109. static void yy_reduce(
  120110. yyParser *yypParser, /* The parser */
  120111. int yyruleno /* Number of the rule by which to reduce */
  120112. ){
  120113. int yygoto; /* The next state */
  120114. int yyact; /* The next action */
  120115. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  120116. yyStackEntry *yymsp; /* The top of the parser's stack */
  120117. int yysize; /* Amount to pop the stack */
  120118. sqlite3ParserARG_FETCH;
  120119. yymsp = &yypParser->yystack[yypParser->yyidx];
  120120. #ifndef NDEBUG
  120121. if( yyTraceFILE && yyruleno>=0
  120122. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  120123. yysize = yyRuleInfo[yyruleno].nrhs;
  120124. fprintf(yyTraceFILE, "%sReduce [%s] -> state %d.\n", yyTracePrompt,
  120125. yyRuleName[yyruleno], yymsp[-yysize].stateno);
  120126. }
  120127. #endif /* NDEBUG */
  120128. /* Silence complaints from purify about yygotominor being uninitialized
  120129. ** in some cases when it is copied into the stack after the following
  120130. ** switch. yygotominor is uninitialized when a rule reduces that does
  120131. ** not set the value of its left-hand side nonterminal. Leaving the
  120132. ** value of the nonterminal uninitialized is utterly harmless as long
  120133. ** as the value is never used. So really the only thing this code
  120134. ** accomplishes is to quieten purify.
  120135. **
  120136. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  120137. ** without this code, their parser segfaults. I'm not sure what there
  120138. ** parser is doing to make this happen. This is the second bug report
  120139. ** from wireshark this week. Clearly they are stressing Lemon in ways
  120140. ** that it has not been previously stressed... (SQLite ticket #2172)
  120141. */
  120142. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  120143. yygotominor = yyzerominor;
  120144. switch( yyruleno ){
  120145. /* Beginning here are the reduction cases. A typical example
  120146. ** follows:
  120147. ** case 0:
  120148. ** #line <lineno> <grammarfile>
  120149. ** { ... } // User supplied code
  120150. ** #line <lineno> <thisfile>
  120151. ** break;
  120152. */
  120153. case 5: /* explain ::= */
  120154. { sqlite3BeginParse(pParse, 0); }
  120155. break;
  120156. case 6: /* explain ::= EXPLAIN */
  120157. { sqlite3BeginParse(pParse, 1); }
  120158. break;
  120159. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  120160. { sqlite3BeginParse(pParse, 2); }
  120161. break;
  120162. case 8: /* cmdx ::= cmd */
  120163. { sqlite3FinishCoding(pParse); }
  120164. break;
  120165. case 9: /* cmd ::= BEGIN transtype trans_opt */
  120166. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
  120167. break;
  120168. case 13: /* transtype ::= */
  120169. {yygotominor.yy328 = TK_DEFERRED;}
  120170. break;
  120171. case 14: /* transtype ::= DEFERRED */
  120172. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  120173. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  120174. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  120175. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  120176. {yygotominor.yy328 = yymsp[0].major;}
  120177. break;
  120178. case 17: /* cmd ::= COMMIT trans_opt */
  120179. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  120180. {sqlite3CommitTransaction(pParse);}
  120181. break;
  120182. case 19: /* cmd ::= ROLLBACK trans_opt */
  120183. {sqlite3RollbackTransaction(pParse);}
  120184. break;
  120185. case 22: /* cmd ::= SAVEPOINT nm */
  120186. {
  120187. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  120188. }
  120189. break;
  120190. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  120191. {
  120192. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  120193. }
  120194. break;
  120195. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  120196. {
  120197. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  120198. }
  120199. break;
  120200. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  120201. {
  120202. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
  120203. }
  120204. break;
  120205. case 27: /* createkw ::= CREATE */
  120206. {
  120207. pParse->db->lookaside.bEnabled = 0;
  120208. yygotominor.yy0 = yymsp[0].minor.yy0;
  120209. }
  120210. break;
  120211. case 28: /* ifnotexists ::= */
  120212. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  120213. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  120214. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  120215. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  120216. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  120217. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  120218. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  120219. case 219: /* between_op ::= BETWEEN */ yytestcase(yyruleno==219);
  120220. case 222: /* in_op ::= IN */ yytestcase(yyruleno==222);
  120221. case 247: /* collate ::= */ yytestcase(yyruleno==247);
  120222. {yygotominor.yy328 = 0;}
  120223. break;
  120224. case 29: /* ifnotexists ::= IF NOT EXISTS */
  120225. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  120226. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  120227. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  120228. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  120229. case 220: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==220);
  120230. case 223: /* in_op ::= NOT IN */ yytestcase(yyruleno==223);
  120231. case 248: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==248);
  120232. {yygotominor.yy328 = 1;}
  120233. break;
  120234. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  120235. {
  120236. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
  120237. }
  120238. break;
  120239. case 33: /* create_table_args ::= AS select */
  120240. {
  120241. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
  120242. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  120243. }
  120244. break;
  120245. case 34: /* table_options ::= */
  120246. {yygotominor.yy186 = 0;}
  120247. break;
  120248. case 35: /* table_options ::= WITHOUT nm */
  120249. {
  120250. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  120251. yygotominor.yy186 = TF_WithoutRowid | TF_NoVisibleRowid;
  120252. }else{
  120253. yygotominor.yy186 = 0;
  120254. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  120255. }
  120256. }
  120257. break;
  120258. case 38: /* column ::= columnid type carglist */
  120259. {
  120260. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  120261. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  120262. }
  120263. break;
  120264. case 39: /* columnid ::= nm */
  120265. {
  120266. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  120267. yygotominor.yy0 = yymsp[0].minor.yy0;
  120268. pParse->constraintName.n = 0;
  120269. }
  120270. break;
  120271. case 40: /* nm ::= ID|INDEXED */
  120272. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  120273. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  120274. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  120275. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  120276. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  120277. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  120278. case 142: /* dbnm ::= DOT nm */ yytestcase(yyruleno==142);
  120279. case 151: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==151);
  120280. case 257: /* nmnum ::= plus_num */ yytestcase(yyruleno==257);
  120281. case 258: /* nmnum ::= nm */ yytestcase(yyruleno==258);
  120282. case 259: /* nmnum ::= ON */ yytestcase(yyruleno==259);
  120283. case 260: /* nmnum ::= DELETE */ yytestcase(yyruleno==260);
  120284. case 261: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==261);
  120285. case 262: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==262);
  120286. case 263: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==263);
  120287. case 264: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==264);
  120288. case 280: /* trnm ::= nm */ yytestcase(yyruleno==280);
  120289. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  120290. break;
  120291. case 44: /* type ::= typetoken */
  120292. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  120293. break;
  120294. case 46: /* typetoken ::= typename LP signed RP */
  120295. {
  120296. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  120297. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  120298. }
  120299. break;
  120300. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  120301. {
  120302. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  120303. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  120304. }
  120305. break;
  120306. case 49: /* typename ::= typename ID|STRING */
  120307. {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  120308. break;
  120309. case 54: /* ccons ::= CONSTRAINT nm */
  120310. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  120311. {pParse->constraintName = yymsp[0].minor.yy0;}
  120312. break;
  120313. case 55: /* ccons ::= DEFAULT term */
  120314. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  120315. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
  120316. break;
  120317. case 56: /* ccons ::= DEFAULT LP expr RP */
  120318. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
  120319. break;
  120320. case 58: /* ccons ::= DEFAULT MINUS term */
  120321. {
  120322. ExprSpan v;
  120323. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
  120324. v.zStart = yymsp[-1].minor.yy0.z;
  120325. v.zEnd = yymsp[0].minor.yy346.zEnd;
  120326. sqlite3AddDefaultValue(pParse,&v);
  120327. }
  120328. break;
  120329. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  120330. {
  120331. ExprSpan v;
  120332. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  120333. sqlite3AddDefaultValue(pParse,&v);
  120334. }
  120335. break;
  120336. case 61: /* ccons ::= NOT NULL onconf */
  120337. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
  120338. break;
  120339. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  120340. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
  120341. break;
  120342. case 63: /* ccons ::= UNIQUE onconf */
  120343. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
  120344. break;
  120345. case 64: /* ccons ::= CHECK LP expr RP */
  120346. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
  120347. break;
  120348. case 65: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  120349. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
  120350. break;
  120351. case 66: /* ccons ::= defer_subclause */
  120352. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
  120353. break;
  120354. case 67: /* ccons ::= COLLATE ID|STRING */
  120355. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  120356. break;
  120357. case 70: /* refargs ::= */
  120358. { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
  120359. break;
  120360. case 71: /* refargs ::= refargs refarg */
  120361. { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
  120362. break;
  120363. case 72: /* refarg ::= MATCH nm */
  120364. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  120365. { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
  120366. break;
  120367. case 74: /* refarg ::= ON DELETE refact */
  120368. { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
  120369. break;
  120370. case 75: /* refarg ::= ON UPDATE refact */
  120371. { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
  120372. break;
  120373. case 76: /* refact ::= SET NULL */
  120374. { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
  120375. break;
  120376. case 77: /* refact ::= SET DEFAULT */
  120377. { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
  120378. break;
  120379. case 78: /* refact ::= CASCADE */
  120380. { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
  120381. break;
  120382. case 79: /* refact ::= RESTRICT */
  120383. { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
  120384. break;
  120385. case 80: /* refact ::= NO ACTION */
  120386. { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
  120387. break;
  120388. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  120389. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  120390. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  120391. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  120392. {yygotominor.yy328 = yymsp[0].minor.yy328;}
  120393. break;
  120394. case 86: /* conslist_opt ::= */
  120395. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  120396. break;
  120397. case 87: /* conslist_opt ::= COMMA conslist */
  120398. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  120399. break;
  120400. case 90: /* tconscomma ::= COMMA */
  120401. {pParse->constraintName.n = 0;}
  120402. break;
  120403. case 93: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  120404. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
  120405. break;
  120406. case 94: /* tcons ::= UNIQUE LP sortlist RP onconf */
  120407. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
  120408. break;
  120409. case 95: /* tcons ::= CHECK LP expr RP onconf */
  120410. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
  120411. break;
  120412. case 96: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  120413. {
  120414. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
  120415. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
  120416. }
  120417. break;
  120418. case 99: /* onconf ::= */
  120419. {yygotominor.yy328 = OE_Default;}
  120420. break;
  120421. case 101: /* orconf ::= */
  120422. {yygotominor.yy186 = OE_Default;}
  120423. break;
  120424. case 102: /* orconf ::= OR resolvetype */
  120425. {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
  120426. break;
  120427. case 104: /* resolvetype ::= IGNORE */
  120428. {yygotominor.yy328 = OE_Ignore;}
  120429. break;
  120430. case 105: /* resolvetype ::= REPLACE */
  120431. {yygotominor.yy328 = OE_Replace;}
  120432. break;
  120433. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  120434. {
  120435. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
  120436. }
  120437. break;
  120438. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  120439. {
  120440. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[0].minor.yy3, yymsp[-7].minor.yy328, yymsp[-5].minor.yy328);
  120441. }
  120442. break;
  120443. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  120444. {
  120445. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
  120446. }
  120447. break;
  120448. case 111: /* cmd ::= select */
  120449. {
  120450. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  120451. sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
  120452. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  120453. }
  120454. break;
  120455. case 112: /* select ::= with selectnowith */
  120456. {
  120457. Select *p = yymsp[0].minor.yy3;
  120458. if( p ){
  120459. p->pWith = yymsp[-1].minor.yy59;
  120460. parserDoubleLinkSelect(pParse, p);
  120461. }else{
  120462. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  120463. }
  120464. yygotominor.yy3 = p;
  120465. }
  120466. break;
  120467. case 113: /* selectnowith ::= oneselect */
  120468. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  120469. {yygotominor.yy3 = yymsp[0].minor.yy3;}
  120470. break;
  120471. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  120472. {
  120473. Select *pRhs = yymsp[0].minor.yy3;
  120474. Select *pLhs = yymsp[-2].minor.yy3;
  120475. if( pRhs && pRhs->pPrior ){
  120476. SrcList *pFrom;
  120477. Token x;
  120478. x.n = 0;
  120479. parserDoubleLinkSelect(pParse, pRhs);
  120480. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  120481. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  120482. }
  120483. if( pRhs ){
  120484. pRhs->op = (u8)yymsp[-1].minor.yy328;
  120485. pRhs->pPrior = pLhs;
  120486. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  120487. pRhs->selFlags &= ~SF_MultiValue;
  120488. if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
  120489. }else{
  120490. sqlite3SelectDelete(pParse->db, pLhs);
  120491. }
  120492. yygotominor.yy3 = pRhs;
  120493. }
  120494. break;
  120495. case 116: /* multiselect_op ::= UNION ALL */
  120496. {yygotominor.yy328 = TK_ALL;}
  120497. break;
  120498. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  120499. {
  120500. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
  120501. #if SELECTTRACE_ENABLED
  120502. /* Populate the Select.zSelName[] string that is used to help with
  120503. ** query planner debugging, to differentiate between multiple Select
  120504. ** objects in a complex query.
  120505. **
  120506. ** If the SELECT keyword is immediately followed by a C-style comment
  120507. ** then extract the first few alphanumeric characters from within that
  120508. ** comment to be the zSelName value. Otherwise, the label is #N where
  120509. ** is an integer that is incremented with each SELECT statement seen.
  120510. */
  120511. if( yygotominor.yy3!=0 ){
  120512. const char *z = yymsp[-8].minor.yy0.z+6;
  120513. int i;
  120514. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
  120515. ++pParse->nSelect);
  120516. while( z[0]==' ' ) z++;
  120517. if( z[0]=='/' && z[1]=='*' ){
  120518. z += 2;
  120519. while( z[0]==' ' ) z++;
  120520. for(i=0; sqlite3Isalnum(z[i]); i++){}
  120521. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
  120522. }
  120523. }
  120524. #endif /* SELECTRACE_ENABLED */
  120525. }
  120526. break;
  120527. case 120: /* values ::= VALUES LP nexprlist RP */
  120528. {
  120529. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  120530. }
  120531. break;
  120532. case 121: /* values ::= values COMMA LP exprlist RP */
  120533. {
  120534. Select *pRight, *pLeft = yymsp[-4].minor.yy3;
  120535. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  120536. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  120537. if( pRight ){
  120538. pRight->op = TK_ALL;
  120539. pLeft = yymsp[-4].minor.yy3;
  120540. pRight->pPrior = pLeft;
  120541. yygotominor.yy3 = pRight;
  120542. }else{
  120543. yygotominor.yy3 = pLeft;
  120544. }
  120545. }
  120546. break;
  120547. case 122: /* distinct ::= DISTINCT */
  120548. {yygotominor.yy381 = SF_Distinct;}
  120549. break;
  120550. case 123: /* distinct ::= ALL */
  120551. {yygotominor.yy381 = SF_All;}
  120552. break;
  120553. case 124: /* distinct ::= */
  120554. {yygotominor.yy381 = 0;}
  120555. break;
  120556. case 125: /* sclp ::= selcollist COMMA */
  120557. case 244: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==244);
  120558. {yygotominor.yy14 = yymsp[-1].minor.yy14;}
  120559. break;
  120560. case 126: /* sclp ::= */
  120561. case 155: /* orderby_opt ::= */ yytestcase(yyruleno==155);
  120562. case 162: /* groupby_opt ::= */ yytestcase(yyruleno==162);
  120563. case 237: /* exprlist ::= */ yytestcase(yyruleno==237);
  120564. case 243: /* eidlist_opt ::= */ yytestcase(yyruleno==243);
  120565. {yygotominor.yy14 = 0;}
  120566. break;
  120567. case 127: /* selcollist ::= sclp expr as */
  120568. {
  120569. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
  120570. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
  120571. sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
  120572. }
  120573. break;
  120574. case 128: /* selcollist ::= sclp STAR */
  120575. {
  120576. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  120577. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
  120578. }
  120579. break;
  120580. case 129: /* selcollist ::= sclp nm DOT STAR */
  120581. {
  120582. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  120583. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  120584. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  120585. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
  120586. }
  120587. break;
  120588. case 132: /* as ::= */
  120589. {yygotominor.yy0.n = 0;}
  120590. break;
  120591. case 133: /* from ::= */
  120592. {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
  120593. break;
  120594. case 134: /* from ::= FROM seltablist */
  120595. {
  120596. yygotominor.yy65 = yymsp[0].minor.yy65;
  120597. sqlite3SrcListShiftJoinType(yygotominor.yy65);
  120598. }
  120599. break;
  120600. case 135: /* stl_prefix ::= seltablist joinop */
  120601. {
  120602. yygotominor.yy65 = yymsp[-1].minor.yy65;
  120603. if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy328;
  120604. }
  120605. break;
  120606. case 136: /* stl_prefix ::= */
  120607. {yygotominor.yy65 = 0;}
  120608. break;
  120609. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  120610. {
  120611. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  120612. sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
  120613. }
  120614. break;
  120615. case 138: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  120616. {
  120617. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy65,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  120618. sqlite3SrcListFuncArgs(pParse, yygotominor.yy65, yymsp[-4].minor.yy14);
  120619. }
  120620. break;
  120621. case 139: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  120622. {
  120623. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  120624. }
  120625. break;
  120626. case 140: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  120627. {
  120628. if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
  120629. yygotominor.yy65 = yymsp[-4].minor.yy65;
  120630. }else if( yymsp[-4].minor.yy65->nSrc==1 ){
  120631. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  120632. if( yygotominor.yy65 ){
  120633. struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
  120634. struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
  120635. pNew->zName = pOld->zName;
  120636. pNew->zDatabase = pOld->zDatabase;
  120637. pNew->pSelect = pOld->pSelect;
  120638. pOld->zName = pOld->zDatabase = 0;
  120639. pOld->pSelect = 0;
  120640. }
  120641. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
  120642. }else{
  120643. Select *pSubquery;
  120644. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
  120645. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
  120646. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  120647. }
  120648. }
  120649. break;
  120650. case 141: /* dbnm ::= */
  120651. case 150: /* indexed_opt ::= */ yytestcase(yyruleno==150);
  120652. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  120653. break;
  120654. case 143: /* fullname ::= nm dbnm */
  120655. {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  120656. break;
  120657. case 144: /* joinop ::= COMMA|JOIN */
  120658. { yygotominor.yy328 = JT_INNER; }
  120659. break;
  120660. case 145: /* joinop ::= JOIN_KW JOIN */
  120661. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  120662. break;
  120663. case 146: /* joinop ::= JOIN_KW nm JOIN */
  120664. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  120665. break;
  120666. case 147: /* joinop ::= JOIN_KW nm nm JOIN */
  120667. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  120668. break;
  120669. case 148: /* on_opt ::= ON expr */
  120670. case 165: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==165);
  120671. case 172: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==172);
  120672. case 232: /* case_else ::= ELSE expr */ yytestcase(yyruleno==232);
  120673. case 234: /* case_operand ::= expr */ yytestcase(yyruleno==234);
  120674. {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
  120675. break;
  120676. case 149: /* on_opt ::= */
  120677. case 164: /* having_opt ::= */ yytestcase(yyruleno==164);
  120678. case 171: /* where_opt ::= */ yytestcase(yyruleno==171);
  120679. case 233: /* case_else ::= */ yytestcase(yyruleno==233);
  120680. case 235: /* case_operand ::= */ yytestcase(yyruleno==235);
  120681. {yygotominor.yy132 = 0;}
  120682. break;
  120683. case 152: /* indexed_opt ::= NOT INDEXED */
  120684. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  120685. break;
  120686. case 153: /* using_opt ::= USING LP idlist RP */
  120687. case 181: /* idlist_opt ::= LP idlist RP */ yytestcase(yyruleno==181);
  120688. {yygotominor.yy408 = yymsp[-1].minor.yy408;}
  120689. break;
  120690. case 154: /* using_opt ::= */
  120691. case 180: /* idlist_opt ::= */ yytestcase(yyruleno==180);
  120692. {yygotominor.yy408 = 0;}
  120693. break;
  120694. case 156: /* orderby_opt ::= ORDER BY sortlist */
  120695. case 163: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==163);
  120696. case 236: /* exprlist ::= nexprlist */ yytestcase(yyruleno==236);
  120697. {yygotominor.yy14 = yymsp[0].minor.yy14;}
  120698. break;
  120699. case 157: /* sortlist ::= sortlist COMMA expr sortorder */
  120700. {
  120701. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
  120702. sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
  120703. }
  120704. break;
  120705. case 158: /* sortlist ::= expr sortorder */
  120706. {
  120707. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
  120708. sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
  120709. }
  120710. break;
  120711. case 159: /* sortorder ::= ASC */
  120712. {yygotominor.yy328 = SQLITE_SO_ASC;}
  120713. break;
  120714. case 160: /* sortorder ::= DESC */
  120715. {yygotominor.yy328 = SQLITE_SO_DESC;}
  120716. break;
  120717. case 161: /* sortorder ::= */
  120718. {yygotominor.yy328 = SQLITE_SO_UNDEFINED;}
  120719. break;
  120720. case 166: /* limit_opt ::= */
  120721. {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
  120722. break;
  120723. case 167: /* limit_opt ::= LIMIT expr */
  120724. {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
  120725. break;
  120726. case 168: /* limit_opt ::= LIMIT expr OFFSET expr */
  120727. {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
  120728. break;
  120729. case 169: /* limit_opt ::= LIMIT expr COMMA expr */
  120730. {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
  120731. break;
  120732. case 170: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  120733. {
  120734. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  120735. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
  120736. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
  120737. }
  120738. break;
  120739. case 173: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  120740. {
  120741. sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
  120742. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
  120743. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
  120744. sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
  120745. }
  120746. break;
  120747. case 174: /* setlist ::= setlist COMMA nm EQ expr */
  120748. {
  120749. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
  120750. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  120751. }
  120752. break;
  120753. case 175: /* setlist ::= nm EQ expr */
  120754. {
  120755. yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
  120756. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  120757. }
  120758. break;
  120759. case 176: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  120760. {
  120761. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  120762. sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
  120763. }
  120764. break;
  120765. case 177: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  120766. {
  120767. sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
  120768. sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
  120769. }
  120770. break;
  120771. case 178: /* insert_cmd ::= INSERT orconf */
  120772. {yygotominor.yy186 = yymsp[0].minor.yy186;}
  120773. break;
  120774. case 179: /* insert_cmd ::= REPLACE */
  120775. {yygotominor.yy186 = OE_Replace;}
  120776. break;
  120777. case 182: /* idlist ::= idlist COMMA nm */
  120778. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
  120779. break;
  120780. case 183: /* idlist ::= nm */
  120781. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  120782. break;
  120783. case 184: /* expr ::= term */
  120784. {yygotominor.yy346 = yymsp[0].minor.yy346;}
  120785. break;
  120786. case 185: /* expr ::= LP expr RP */
  120787. {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  120788. break;
  120789. case 186: /* term ::= NULL */
  120790. case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
  120791. case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
  120792. {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  120793. break;
  120794. case 187: /* expr ::= ID|INDEXED */
  120795. case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
  120796. {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
  120797. break;
  120798. case 189: /* expr ::= nm DOT nm */
  120799. {
  120800. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  120801. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  120802. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  120803. spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  120804. }
  120805. break;
  120806. case 190: /* expr ::= nm DOT nm DOT nm */
  120807. {
  120808. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  120809. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  120810. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  120811. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  120812. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  120813. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  120814. }
  120815. break;
  120816. case 193: /* expr ::= VARIABLE */
  120817. {
  120818. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  120819. /* When doing a nested parse, one can include terms in an expression
  120820. ** that look like this: #1 #2 ... These terms refer to registers
  120821. ** in the virtual machine. #N is the N-th register. */
  120822. if( pParse->nested==0 ){
  120823. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  120824. yygotominor.yy346.pExpr = 0;
  120825. }else{
  120826. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  120827. if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
  120828. }
  120829. }else{
  120830. spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  120831. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
  120832. }
  120833. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  120834. }
  120835. break;
  120836. case 194: /* expr ::= expr COLLATE ID|STRING */
  120837. {
  120838. yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
  120839. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  120840. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  120841. }
  120842. break;
  120843. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  120844. {
  120845. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
  120846. spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  120847. }
  120848. break;
  120849. case 196: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  120850. {
  120851. if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  120852. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  120853. }
  120854. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
  120855. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  120856. if( yymsp[-2].minor.yy381==SF_Distinct && yygotominor.yy346.pExpr ){
  120857. yygotominor.yy346.pExpr->flags |= EP_Distinct;
  120858. }
  120859. }
  120860. break;
  120861. case 197: /* expr ::= ID|INDEXED LP STAR RP */
  120862. {
  120863. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  120864. spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  120865. }
  120866. break;
  120867. case 198: /* term ::= CTIME_KW */
  120868. {
  120869. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  120870. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  120871. }
  120872. break;
  120873. case 199: /* expr ::= expr AND expr */
  120874. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  120875. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  120876. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  120877. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  120878. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  120879. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  120880. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  120881. {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
  120882. break;
  120883. case 207: /* likeop ::= LIKE_KW|MATCH */
  120884. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
  120885. break;
  120886. case 208: /* likeop ::= NOT LIKE_KW|MATCH */
  120887. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
  120888. break;
  120889. case 209: /* expr ::= expr likeop expr */
  120890. {
  120891. ExprList *pList;
  120892. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
  120893. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
  120894. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
  120895. if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  120896. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  120897. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  120898. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  120899. }
  120900. break;
  120901. case 210: /* expr ::= expr likeop expr ESCAPE expr */
  120902. {
  120903. ExprList *pList;
  120904. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  120905. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
  120906. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  120907. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
  120908. if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  120909. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  120910. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  120911. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  120912. }
  120913. break;
  120914. case 211: /* expr ::= expr ISNULL|NOTNULL */
  120915. {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
  120916. break;
  120917. case 212: /* expr ::= expr NOT NULL */
  120918. {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
  120919. break;
  120920. case 213: /* expr ::= expr IS expr */
  120921. {
  120922. spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
  120923. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
  120924. }
  120925. break;
  120926. case 214: /* expr ::= expr IS NOT expr */
  120927. {
  120928. spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
  120929. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
  120930. }
  120931. break;
  120932. case 215: /* expr ::= NOT expr */
  120933. case 216: /* expr ::= BITNOT expr */ yytestcase(yyruleno==216);
  120934. {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  120935. break;
  120936. case 217: /* expr ::= MINUS expr */
  120937. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  120938. break;
  120939. case 218: /* expr ::= PLUS expr */
  120940. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  120941. break;
  120942. case 221: /* expr ::= expr between_op expr AND expr */
  120943. {
  120944. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  120945. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  120946. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  120947. if( yygotominor.yy346.pExpr ){
  120948. yygotominor.yy346.pExpr->x.pList = pList;
  120949. }else{
  120950. sqlite3ExprListDelete(pParse->db, pList);
  120951. }
  120952. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  120953. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  120954. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  120955. }
  120956. break;
  120957. case 224: /* expr ::= expr in_op LP exprlist RP */
  120958. {
  120959. if( yymsp[-1].minor.yy14==0 ){
  120960. /* Expressions of the form
  120961. **
  120962. ** expr1 IN ()
  120963. ** expr1 NOT IN ()
  120964. **
  120965. ** simplify to constants 0 (false) and 1 (true), respectively,
  120966. ** regardless of the value of expr1.
  120967. */
  120968. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
  120969. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
  120970. }else if( yymsp[-1].minor.yy14->nExpr==1 ){
  120971. /* Expressions of the form:
  120972. **
  120973. ** expr1 IN (?1)
  120974. ** expr1 NOT IN (?2)
  120975. **
  120976. ** with exactly one value on the RHS can be simplified to something
  120977. ** like this:
  120978. **
  120979. ** expr1 == ?1
  120980. ** expr1 <> ?2
  120981. **
  120982. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  120983. ** so that it may not contribute to the computation of comparison
  120984. ** affinity or the collating sequence to use for comparison. Otherwise,
  120985. ** the semantics would be subtly different from IN or NOT IN.
  120986. */
  120987. Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
  120988. yymsp[-1].minor.yy14->a[0].pExpr = 0;
  120989. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  120990. /* pRHS cannot be NULL because a malloc error would have been detected
  120991. ** before now and control would have never reached this point */
  120992. if( ALWAYS(pRHS) ){
  120993. pRHS->flags &= ~EP_Collate;
  120994. pRHS->flags |= EP_Generic;
  120995. }
  120996. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
  120997. }else{
  120998. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  120999. if( yygotominor.yy346.pExpr ){
  121000. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
  121001. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  121002. }else{
  121003. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  121004. }
  121005. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  121006. }
  121007. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  121008. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121009. }
  121010. break;
  121011. case 225: /* expr ::= LP select RP */
  121012. {
  121013. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  121014. if( yygotominor.yy346.pExpr ){
  121015. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  121016. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  121017. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  121018. }else{
  121019. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  121020. }
  121021. yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
  121022. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121023. }
  121024. break;
  121025. case 226: /* expr ::= expr in_op LP select RP */
  121026. {
  121027. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  121028. if( yygotominor.yy346.pExpr ){
  121029. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  121030. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  121031. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  121032. }else{
  121033. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  121034. }
  121035. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  121036. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  121037. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121038. }
  121039. break;
  121040. case 227: /* expr ::= expr in_op nm dbnm */
  121041. {
  121042. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  121043. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
  121044. if( yygotominor.yy346.pExpr ){
  121045. yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  121046. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  121047. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  121048. }else{
  121049. sqlite3SrcListDelete(pParse->db, pSrc);
  121050. }
  121051. if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  121052. yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
  121053. yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  121054. }
  121055. break;
  121056. case 228: /* expr ::= EXISTS LP select RP */
  121057. {
  121058. Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  121059. if( p ){
  121060. p->x.pSelect = yymsp[-1].minor.yy3;
  121061. ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
  121062. sqlite3ExprSetHeightAndFlags(pParse, p);
  121063. }else{
  121064. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  121065. }
  121066. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  121067. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121068. }
  121069. break;
  121070. case 229: /* expr ::= CASE case_operand case_exprlist case_else END */
  121071. {
  121072. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
  121073. if( yygotominor.yy346.pExpr ){
  121074. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
  121075. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  121076. }else{
  121077. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
  121078. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
  121079. }
  121080. yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
  121081. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121082. }
  121083. break;
  121084. case 230: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  121085. {
  121086. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
  121087. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  121088. }
  121089. break;
  121090. case 231: /* case_exprlist ::= WHEN expr THEN expr */
  121091. {
  121092. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  121093. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  121094. }
  121095. break;
  121096. case 238: /* nexprlist ::= nexprlist COMMA expr */
  121097. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
  121098. break;
  121099. case 239: /* nexprlist ::= expr */
  121100. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
  121101. break;
  121102. case 240: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  121103. {
  121104. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  121105. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
  121106. &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
  121107. }
  121108. break;
  121109. case 241: /* uniqueflag ::= UNIQUE */
  121110. case 292: /* raisetype ::= ABORT */ yytestcase(yyruleno==292);
  121111. {yygotominor.yy328 = OE_Abort;}
  121112. break;
  121113. case 242: /* uniqueflag ::= */
  121114. {yygotominor.yy328 = OE_None;}
  121115. break;
  121116. case 245: /* eidlist ::= eidlist COMMA nm collate sortorder */
  121117. {
  121118. yygotominor.yy14 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy14, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
  121119. }
  121120. break;
  121121. case 246: /* eidlist ::= nm collate sortorder */
  121122. {
  121123. yygotominor.yy14 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
  121124. }
  121125. break;
  121126. case 249: /* cmd ::= DROP INDEX ifexists fullname */
  121127. {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
  121128. break;
  121129. case 250: /* cmd ::= VACUUM */
  121130. case 251: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==251);
  121131. {sqlite3Vacuum(pParse);}
  121132. break;
  121133. case 252: /* cmd ::= PRAGMA nm dbnm */
  121134. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  121135. break;
  121136. case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  121137. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  121138. break;
  121139. case 254: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  121140. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  121141. break;
  121142. case 255: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  121143. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  121144. break;
  121145. case 256: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  121146. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  121147. break;
  121148. case 265: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  121149. {
  121150. Token all;
  121151. all.z = yymsp[-3].minor.yy0.z;
  121152. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  121153. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
  121154. }
  121155. break;
  121156. case 266: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  121157. {
  121158. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
  121159. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  121160. }
  121161. break;
  121162. case 267: /* trigger_time ::= BEFORE */
  121163. case 270: /* trigger_time ::= */ yytestcase(yyruleno==270);
  121164. { yygotominor.yy328 = TK_BEFORE; }
  121165. break;
  121166. case 268: /* trigger_time ::= AFTER */
  121167. { yygotominor.yy328 = TK_AFTER; }
  121168. break;
  121169. case 269: /* trigger_time ::= INSTEAD OF */
  121170. { yygotominor.yy328 = TK_INSTEAD;}
  121171. break;
  121172. case 271: /* trigger_event ::= DELETE|INSERT */
  121173. case 272: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==272);
  121174. {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
  121175. break;
  121176. case 273: /* trigger_event ::= UPDATE OF idlist */
  121177. {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
  121178. break;
  121179. case 276: /* when_clause ::= */
  121180. case 297: /* key_opt ::= */ yytestcase(yyruleno==297);
  121181. { yygotominor.yy132 = 0; }
  121182. break;
  121183. case 277: /* when_clause ::= WHEN expr */
  121184. case 298: /* key_opt ::= KEY expr */ yytestcase(yyruleno==298);
  121185. { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
  121186. break;
  121187. case 278: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  121188. {
  121189. assert( yymsp[-2].minor.yy473!=0 );
  121190. yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
  121191. yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
  121192. yygotominor.yy473 = yymsp[-2].minor.yy473;
  121193. }
  121194. break;
  121195. case 279: /* trigger_cmd_list ::= trigger_cmd SEMI */
  121196. {
  121197. assert( yymsp[-1].minor.yy473!=0 );
  121198. yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
  121199. yygotominor.yy473 = yymsp[-1].minor.yy473;
  121200. }
  121201. break;
  121202. case 281: /* trnm ::= nm DOT nm */
  121203. {
  121204. yygotominor.yy0 = yymsp[0].minor.yy0;
  121205. sqlite3ErrorMsg(pParse,
  121206. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  121207. "statements within triggers");
  121208. }
  121209. break;
  121210. case 283: /* tridxby ::= INDEXED BY nm */
  121211. {
  121212. sqlite3ErrorMsg(pParse,
  121213. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  121214. "within triggers");
  121215. }
  121216. break;
  121217. case 284: /* tridxby ::= NOT INDEXED */
  121218. {
  121219. sqlite3ErrorMsg(pParse,
  121220. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  121221. "within triggers");
  121222. }
  121223. break;
  121224. case 285: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  121225. { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
  121226. break;
  121227. case 286: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  121228. {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
  121229. break;
  121230. case 287: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  121231. {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
  121232. break;
  121233. case 288: /* trigger_cmd ::= select */
  121234. {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
  121235. break;
  121236. case 289: /* expr ::= RAISE LP IGNORE RP */
  121237. {
  121238. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  121239. if( yygotominor.yy346.pExpr ){
  121240. yygotominor.yy346.pExpr->affinity = OE_Ignore;
  121241. }
  121242. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  121243. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121244. }
  121245. break;
  121246. case 290: /* expr ::= RAISE LP raisetype COMMA nm RP */
  121247. {
  121248. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  121249. if( yygotominor.yy346.pExpr ) {
  121250. yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
  121251. }
  121252. yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
  121253. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  121254. }
  121255. break;
  121256. case 291: /* raisetype ::= ROLLBACK */
  121257. {yygotominor.yy328 = OE_Rollback;}
  121258. break;
  121259. case 293: /* raisetype ::= FAIL */
  121260. {yygotominor.yy328 = OE_Fail;}
  121261. break;
  121262. case 294: /* cmd ::= DROP TRIGGER ifexists fullname */
  121263. {
  121264. sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
  121265. }
  121266. break;
  121267. case 295: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  121268. {
  121269. sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
  121270. }
  121271. break;
  121272. case 296: /* cmd ::= DETACH database_kw_opt expr */
  121273. {
  121274. sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
  121275. }
  121276. break;
  121277. case 301: /* cmd ::= REINDEX */
  121278. {sqlite3Reindex(pParse, 0, 0);}
  121279. break;
  121280. case 302: /* cmd ::= REINDEX nm dbnm */
  121281. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  121282. break;
  121283. case 303: /* cmd ::= ANALYZE */
  121284. {sqlite3Analyze(pParse, 0, 0);}
  121285. break;
  121286. case 304: /* cmd ::= ANALYZE nm dbnm */
  121287. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  121288. break;
  121289. case 305: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  121290. {
  121291. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
  121292. }
  121293. break;
  121294. case 306: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  121295. {
  121296. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  121297. }
  121298. break;
  121299. case 307: /* add_column_fullname ::= fullname */
  121300. {
  121301. pParse->db->lookaside.bEnabled = 0;
  121302. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
  121303. }
  121304. break;
  121305. case 310: /* cmd ::= create_vtab */
  121306. {sqlite3VtabFinishParse(pParse,0);}
  121307. break;
  121308. case 311: /* cmd ::= create_vtab LP vtabarglist RP */
  121309. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  121310. break;
  121311. case 312: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  121312. {
  121313. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
  121314. }
  121315. break;
  121316. case 315: /* vtabarg ::= */
  121317. {sqlite3VtabArgInit(pParse);}
  121318. break;
  121319. case 317: /* vtabargtoken ::= ANY */
  121320. case 318: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==318);
  121321. case 319: /* lp ::= LP */ yytestcase(yyruleno==319);
  121322. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  121323. break;
  121324. case 323: /* with ::= */
  121325. {yygotominor.yy59 = 0;}
  121326. break;
  121327. case 324: /* with ::= WITH wqlist */
  121328. case 325: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==325);
  121329. { yygotominor.yy59 = yymsp[0].minor.yy59; }
  121330. break;
  121331. case 326: /* wqlist ::= nm eidlist_opt AS LP select RP */
  121332. {
  121333. yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  121334. }
  121335. break;
  121336. case 327: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  121337. {
  121338. yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  121339. }
  121340. break;
  121341. default:
  121342. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  121343. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  121344. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  121345. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  121346. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  121347. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  121348. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  121349. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  121350. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  121351. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  121352. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  121353. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  121354. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  121355. /* (43) type ::= */ yytestcase(yyruleno==43);
  121356. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  121357. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  121358. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  121359. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  121360. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  121361. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  121362. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  121363. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  121364. /* (274) foreach_clause ::= */ yytestcase(yyruleno==274);
  121365. /* (275) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==275);
  121366. /* (282) tridxby ::= */ yytestcase(yyruleno==282);
  121367. /* (299) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==299);
  121368. /* (300) database_kw_opt ::= */ yytestcase(yyruleno==300);
  121369. /* (308) kwcolumn_opt ::= */ yytestcase(yyruleno==308);
  121370. /* (309) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==309);
  121371. /* (313) vtabarglist ::= vtabarg */ yytestcase(yyruleno==313);
  121372. /* (314) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==314);
  121373. /* (316) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==316);
  121374. /* (320) anylist ::= */ yytestcase(yyruleno==320);
  121375. /* (321) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==321);
  121376. /* (322) anylist ::= anylist ANY */ yytestcase(yyruleno==322);
  121377. break;
  121378. };
  121379. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  121380. yygoto = yyRuleInfo[yyruleno].lhs;
  121381. yysize = yyRuleInfo[yyruleno].nrhs;
  121382. yypParser->yyidx -= yysize;
  121383. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  121384. if( yyact <= YY_MAX_SHIFTREDUCE ){
  121385. if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  121386. /* If the reduce action popped at least
  121387. ** one element off the stack, then we can push the new element back
  121388. ** onto the stack here, and skip the stack overflow test in yy_shift().
  121389. ** That gives a significant speed improvement. */
  121390. if( yysize ){
  121391. yypParser->yyidx++;
  121392. yymsp -= yysize-1;
  121393. yymsp->stateno = (YYACTIONTYPE)yyact;
  121394. yymsp->major = (YYCODETYPE)yygoto;
  121395. yymsp->minor = yygotominor;
  121396. yyTraceShift(yypParser, yyact);
  121397. }else{
  121398. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  121399. }
  121400. }else{
  121401. assert( yyact == YY_ACCEPT_ACTION );
  121402. yy_accept(yypParser);
  121403. }
  121404. }
  121405. /*
  121406. ** The following code executes when the parse fails
  121407. */
  121408. #ifndef YYNOERRORRECOVERY
  121409. static void yy_parse_failed(
  121410. yyParser *yypParser /* The parser */
  121411. ){
  121412. sqlite3ParserARG_FETCH;
  121413. #ifndef NDEBUG
  121414. if( yyTraceFILE ){
  121415. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  121416. }
  121417. #endif
  121418. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  121419. /* Here code is inserted which will be executed whenever the
  121420. ** parser fails */
  121421. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  121422. }
  121423. #endif /* YYNOERRORRECOVERY */
  121424. /*
  121425. ** The following code executes when a syntax error first occurs.
  121426. */
  121427. static void yy_syntax_error(
  121428. yyParser *yypParser, /* The parser */
  121429. int yymajor, /* The major type of the error token */
  121430. YYMINORTYPE yyminor /* The minor type of the error token */
  121431. ){
  121432. sqlite3ParserARG_FETCH;
  121433. #define TOKEN (yyminor.yy0)
  121434. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  121435. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  121436. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  121437. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  121438. }
  121439. /*
  121440. ** The following is executed when the parser accepts
  121441. */
  121442. static void yy_accept(
  121443. yyParser *yypParser /* The parser */
  121444. ){
  121445. sqlite3ParserARG_FETCH;
  121446. #ifndef NDEBUG
  121447. if( yyTraceFILE ){
  121448. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  121449. }
  121450. #endif
  121451. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  121452. /* Here code is inserted which will be executed whenever the
  121453. ** parser accepts */
  121454. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  121455. }
  121456. /* The main parser program.
  121457. ** The first argument is a pointer to a structure obtained from
  121458. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  121459. ** The second argument is the major token number. The third is
  121460. ** the minor token. The fourth optional argument is whatever the
  121461. ** user wants (and specified in the grammar) and is available for
  121462. ** use by the action routines.
  121463. **
  121464. ** Inputs:
  121465. ** <ul>
  121466. ** <li> A pointer to the parser (an opaque structure.)
  121467. ** <li> The major token number.
  121468. ** <li> The minor token number.
  121469. ** <li> An option argument of a grammar-specified type.
  121470. ** </ul>
  121471. **
  121472. ** Outputs:
  121473. ** None.
  121474. */
  121475. SQLITE_PRIVATE void sqlite3Parser(
  121476. void *yyp, /* The parser */
  121477. int yymajor, /* The major token code number */
  121478. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  121479. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  121480. ){
  121481. YYMINORTYPE yyminorunion;
  121482. int yyact; /* The parser action. */
  121483. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  121484. int yyendofinput; /* True if we are at the end of input */
  121485. #endif
  121486. #ifdef YYERRORSYMBOL
  121487. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  121488. #endif
  121489. yyParser *yypParser; /* The parser */
  121490. /* (re)initialize the parser, if necessary */
  121491. yypParser = (yyParser*)yyp;
  121492. if( yypParser->yyidx<0 ){
  121493. #if YYSTACKDEPTH<=0
  121494. if( yypParser->yystksz <=0 ){
  121495. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  121496. yyminorunion = yyzerominor;
  121497. yyStackOverflow(yypParser, &yyminorunion);
  121498. return;
  121499. }
  121500. #endif
  121501. yypParser->yyidx = 0;
  121502. yypParser->yyerrcnt = -1;
  121503. yypParser->yystack[0].stateno = 0;
  121504. yypParser->yystack[0].major = 0;
  121505. }
  121506. yyminorunion.yy0 = yyminor;
  121507. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  121508. yyendofinput = (yymajor==0);
  121509. #endif
  121510. sqlite3ParserARG_STORE;
  121511. #ifndef NDEBUG
  121512. if( yyTraceFILE ){
  121513. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  121514. }
  121515. #endif
  121516. do{
  121517. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  121518. if( yyact <= YY_MAX_SHIFTREDUCE ){
  121519. if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  121520. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  121521. yypParser->yyerrcnt--;
  121522. yymajor = YYNOCODE;
  121523. }else if( yyact <= YY_MAX_REDUCE ){
  121524. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  121525. }else{
  121526. assert( yyact == YY_ERROR_ACTION );
  121527. #ifdef YYERRORSYMBOL
  121528. int yymx;
  121529. #endif
  121530. #ifndef NDEBUG
  121531. if( yyTraceFILE ){
  121532. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  121533. }
  121534. #endif
  121535. #ifdef YYERRORSYMBOL
  121536. /* A syntax error has occurred.
  121537. ** The response to an error depends upon whether or not the
  121538. ** grammar defines an error token "ERROR".
  121539. **
  121540. ** This is what we do if the grammar does define ERROR:
  121541. **
  121542. ** * Call the %syntax_error function.
  121543. **
  121544. ** * Begin popping the stack until we enter a state where
  121545. ** it is legal to shift the error symbol, then shift
  121546. ** the error symbol.
  121547. **
  121548. ** * Set the error count to three.
  121549. **
  121550. ** * Begin accepting and shifting new tokens. No new error
  121551. ** processing will occur until three tokens have been
  121552. ** shifted successfully.
  121553. **
  121554. */
  121555. if( yypParser->yyerrcnt<0 ){
  121556. yy_syntax_error(yypParser,yymajor,yyminorunion);
  121557. }
  121558. yymx = yypParser->yystack[yypParser->yyidx].major;
  121559. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  121560. #ifndef NDEBUG
  121561. if( yyTraceFILE ){
  121562. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  121563. yyTracePrompt,yyTokenName[yymajor]);
  121564. }
  121565. #endif
  121566. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  121567. yymajor = YYNOCODE;
  121568. }else{
  121569. while(
  121570. yypParser->yyidx >= 0 &&
  121571. yymx != YYERRORSYMBOL &&
  121572. (yyact = yy_find_reduce_action(
  121573. yypParser->yystack[yypParser->yyidx].stateno,
  121574. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  121575. ){
  121576. yy_pop_parser_stack(yypParser);
  121577. }
  121578. if( yypParser->yyidx < 0 || yymajor==0 ){
  121579. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  121580. yy_parse_failed(yypParser);
  121581. yymajor = YYNOCODE;
  121582. }else if( yymx!=YYERRORSYMBOL ){
  121583. YYMINORTYPE u2;
  121584. u2.YYERRSYMDT = 0;
  121585. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  121586. }
  121587. }
  121588. yypParser->yyerrcnt = 3;
  121589. yyerrorhit = 1;
  121590. #elif defined(YYNOERRORRECOVERY)
  121591. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  121592. ** do any kind of error recovery. Instead, simply invoke the syntax
  121593. ** error routine and continue going as if nothing had happened.
  121594. **
  121595. ** Applications can set this macro (for example inside %include) if
  121596. ** they intend to abandon the parse upon the first syntax error seen.
  121597. */
  121598. yy_syntax_error(yypParser,yymajor,yyminorunion);
  121599. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  121600. yymajor = YYNOCODE;
  121601. #else /* YYERRORSYMBOL is not defined */
  121602. /* This is what we do if the grammar does not define ERROR:
  121603. **
  121604. ** * Report an error message, and throw away the input token.
  121605. **
  121606. ** * If the input token is $, then fail the parse.
  121607. **
  121608. ** As before, subsequent error messages are suppressed until
  121609. ** three input tokens have been successfully shifted.
  121610. */
  121611. if( yypParser->yyerrcnt<=0 ){
  121612. yy_syntax_error(yypParser,yymajor,yyminorunion);
  121613. }
  121614. yypParser->yyerrcnt = 3;
  121615. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  121616. if( yyendofinput ){
  121617. yy_parse_failed(yypParser);
  121618. }
  121619. yymajor = YYNOCODE;
  121620. #endif
  121621. }
  121622. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  121623. #ifndef NDEBUG
  121624. if( yyTraceFILE ){
  121625. fprintf(yyTraceFILE,"%sReturn\n",yyTracePrompt);
  121626. }
  121627. #endif
  121628. return;
  121629. }
  121630. /************** End of parse.c ***********************************************/
  121631. /************** Begin file tokenize.c ****************************************/
  121632. /*
  121633. ** 2001 September 15
  121634. **
  121635. ** The author disclaims copyright to this source code. In place of
  121636. ** a legal notice, here is a blessing:
  121637. **
  121638. ** May you do good and not evil.
  121639. ** May you find forgiveness for yourself and forgive others.
  121640. ** May you share freely, never taking more than you give.
  121641. **
  121642. *************************************************************************
  121643. ** An tokenizer for SQL
  121644. **
  121645. ** This file contains C code that splits an SQL input string up into
  121646. ** individual tokens and sends those tokens one-by-one over to the
  121647. ** parser for analysis.
  121648. */
  121649. /* #include "sqliteInt.h" */
  121650. /* #include <stdlib.h> */
  121651. /*
  121652. ** The charMap() macro maps alphabetic characters into their
  121653. ** lower-case ASCII equivalent. On ASCII machines, this is just
  121654. ** an upper-to-lower case map. On EBCDIC machines we also need
  121655. ** to adjust the encoding. Only alphabetic characters and underscores
  121656. ** need to be translated.
  121657. */
  121658. #ifdef SQLITE_ASCII
  121659. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  121660. #endif
  121661. #ifdef SQLITE_EBCDIC
  121662. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  121663. const unsigned char ebcdicToAscii[] = {
  121664. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  121665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  121673. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  121674. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  121675. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  121677. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  121678. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  121679. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  121681. };
  121682. #endif
  121683. /*
  121684. ** The sqlite3KeywordCode function looks up an identifier to determine if
  121685. ** it is a keyword. If it is a keyword, the token code of that keyword is
  121686. ** returned. If the input is not a keyword, TK_ID is returned.
  121687. **
  121688. ** The implementation of this routine was generated by a program,
  121689. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  121690. ** The output of the mkkeywordhash.c program is written into a file
  121691. ** named keywordhash.h and then included into this source file by
  121692. ** the #include below.
  121693. */
  121694. /************** Include keywordhash.h in the middle of tokenize.c ************/
  121695. /************** Begin file keywordhash.h *************************************/
  121696. /***** This file contains automatically generated code ******
  121697. **
  121698. ** The code in this file has been automatically generated by
  121699. **
  121700. ** sqlite/tool/mkkeywordhash.c
  121701. **
  121702. ** The code in this file implements a function that determines whether
  121703. ** or not a given identifier is really an SQL keyword. The same thing
  121704. ** might be implemented more directly using a hand-written hash table.
  121705. ** But by using this automatically generated code, the size of the code
  121706. ** is substantially reduced. This is important for embedded applications
  121707. ** on platforms with limited memory.
  121708. */
  121709. /* Hash score: 182 */
  121710. static int keywordCode(const char *z, int n){
  121711. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  121712. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  121713. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  121714. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  121715. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  121716. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  121717. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  121718. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  121719. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  121720. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  121721. /* VACUUMVIEWINITIALLY */
  121722. static const char zText[553] = {
  121723. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  121724. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  121725. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  121726. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  121727. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  121728. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  121729. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  121730. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  121731. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  121732. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  121733. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  121734. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  121735. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  121736. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  121737. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  121738. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  121739. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  121740. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  121741. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  121742. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  121743. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  121744. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  121745. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  121746. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  121747. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  121748. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  121749. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  121750. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  121751. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  121752. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  121753. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  121754. };
  121755. static const unsigned char aHash[127] = {
  121756. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  121757. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  121758. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  121759. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  121760. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  121761. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  121762. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  121763. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  121764. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  121765. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  121766. };
  121767. static const unsigned char aNext[124] = {
  121768. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  121770. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  121772. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  121773. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  121774. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  121775. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  121776. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  121777. 73, 83, 0, 35, 68, 0, 0,
  121778. };
  121779. static const unsigned char aLen[124] = {
  121780. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  121781. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  121782. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  121783. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  121784. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  121785. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  121786. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  121787. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  121788. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  121789. 3, 5, 5, 6, 4, 9, 3,
  121790. };
  121791. static const unsigned short int aOffset[124] = {
  121792. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  121793. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  121794. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  121795. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  121796. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  121797. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  121798. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  121799. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  121800. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  121801. 521, 524, 529, 534, 540, 544, 549,
  121802. };
  121803. static const unsigned char aCode[124] = {
  121804. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  121805. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  121806. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  121807. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  121808. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  121809. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  121810. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  121811. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  121812. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  121813. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  121814. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  121815. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  121816. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  121817. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  121818. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  121819. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  121820. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  121821. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  121822. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  121823. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  121824. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  121825. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  121826. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  121827. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  121828. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  121829. };
  121830. int h, i;
  121831. if( n<2 ) return TK_ID;
  121832. h = ((charMap(z[0])*4) ^
  121833. (charMap(z[n-1])*3) ^
  121834. n) % 127;
  121835. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  121836. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  121837. testcase( i==0 ); /* REINDEX */
  121838. testcase( i==1 ); /* INDEXED */
  121839. testcase( i==2 ); /* INDEX */
  121840. testcase( i==3 ); /* DESC */
  121841. testcase( i==4 ); /* ESCAPE */
  121842. testcase( i==5 ); /* EACH */
  121843. testcase( i==6 ); /* CHECK */
  121844. testcase( i==7 ); /* KEY */
  121845. testcase( i==8 ); /* BEFORE */
  121846. testcase( i==9 ); /* FOREIGN */
  121847. testcase( i==10 ); /* FOR */
  121848. testcase( i==11 ); /* IGNORE */
  121849. testcase( i==12 ); /* REGEXP */
  121850. testcase( i==13 ); /* EXPLAIN */
  121851. testcase( i==14 ); /* INSTEAD */
  121852. testcase( i==15 ); /* ADD */
  121853. testcase( i==16 ); /* DATABASE */
  121854. testcase( i==17 ); /* AS */
  121855. testcase( i==18 ); /* SELECT */
  121856. testcase( i==19 ); /* TABLE */
  121857. testcase( i==20 ); /* LEFT */
  121858. testcase( i==21 ); /* THEN */
  121859. testcase( i==22 ); /* END */
  121860. testcase( i==23 ); /* DEFERRABLE */
  121861. testcase( i==24 ); /* ELSE */
  121862. testcase( i==25 ); /* EXCEPT */
  121863. testcase( i==26 ); /* TRANSACTION */
  121864. testcase( i==27 ); /* ACTION */
  121865. testcase( i==28 ); /* ON */
  121866. testcase( i==29 ); /* NATURAL */
  121867. testcase( i==30 ); /* ALTER */
  121868. testcase( i==31 ); /* RAISE */
  121869. testcase( i==32 ); /* EXCLUSIVE */
  121870. testcase( i==33 ); /* EXISTS */
  121871. testcase( i==34 ); /* SAVEPOINT */
  121872. testcase( i==35 ); /* INTERSECT */
  121873. testcase( i==36 ); /* TRIGGER */
  121874. testcase( i==37 ); /* REFERENCES */
  121875. testcase( i==38 ); /* CONSTRAINT */
  121876. testcase( i==39 ); /* INTO */
  121877. testcase( i==40 ); /* OFFSET */
  121878. testcase( i==41 ); /* OF */
  121879. testcase( i==42 ); /* SET */
  121880. testcase( i==43 ); /* TEMPORARY */
  121881. testcase( i==44 ); /* TEMP */
  121882. testcase( i==45 ); /* OR */
  121883. testcase( i==46 ); /* UNIQUE */
  121884. testcase( i==47 ); /* QUERY */
  121885. testcase( i==48 ); /* WITHOUT */
  121886. testcase( i==49 ); /* WITH */
  121887. testcase( i==50 ); /* OUTER */
  121888. testcase( i==51 ); /* RELEASE */
  121889. testcase( i==52 ); /* ATTACH */
  121890. testcase( i==53 ); /* HAVING */
  121891. testcase( i==54 ); /* GROUP */
  121892. testcase( i==55 ); /* UPDATE */
  121893. testcase( i==56 ); /* BEGIN */
  121894. testcase( i==57 ); /* INNER */
  121895. testcase( i==58 ); /* RECURSIVE */
  121896. testcase( i==59 ); /* BETWEEN */
  121897. testcase( i==60 ); /* NOTNULL */
  121898. testcase( i==61 ); /* NOT */
  121899. testcase( i==62 ); /* NO */
  121900. testcase( i==63 ); /* NULL */
  121901. testcase( i==64 ); /* LIKE */
  121902. testcase( i==65 ); /* CASCADE */
  121903. testcase( i==66 ); /* ASC */
  121904. testcase( i==67 ); /* DELETE */
  121905. testcase( i==68 ); /* CASE */
  121906. testcase( i==69 ); /* COLLATE */
  121907. testcase( i==70 ); /* CREATE */
  121908. testcase( i==71 ); /* CURRENT_DATE */
  121909. testcase( i==72 ); /* DETACH */
  121910. testcase( i==73 ); /* IMMEDIATE */
  121911. testcase( i==74 ); /* JOIN */
  121912. testcase( i==75 ); /* INSERT */
  121913. testcase( i==76 ); /* MATCH */
  121914. testcase( i==77 ); /* PLAN */
  121915. testcase( i==78 ); /* ANALYZE */
  121916. testcase( i==79 ); /* PRAGMA */
  121917. testcase( i==80 ); /* ABORT */
  121918. testcase( i==81 ); /* VALUES */
  121919. testcase( i==82 ); /* VIRTUAL */
  121920. testcase( i==83 ); /* LIMIT */
  121921. testcase( i==84 ); /* WHEN */
  121922. testcase( i==85 ); /* WHERE */
  121923. testcase( i==86 ); /* RENAME */
  121924. testcase( i==87 ); /* AFTER */
  121925. testcase( i==88 ); /* REPLACE */
  121926. testcase( i==89 ); /* AND */
  121927. testcase( i==90 ); /* DEFAULT */
  121928. testcase( i==91 ); /* AUTOINCREMENT */
  121929. testcase( i==92 ); /* TO */
  121930. testcase( i==93 ); /* IN */
  121931. testcase( i==94 ); /* CAST */
  121932. testcase( i==95 ); /* COLUMN */
  121933. testcase( i==96 ); /* COMMIT */
  121934. testcase( i==97 ); /* CONFLICT */
  121935. testcase( i==98 ); /* CROSS */
  121936. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  121937. testcase( i==100 ); /* CURRENT_TIME */
  121938. testcase( i==101 ); /* PRIMARY */
  121939. testcase( i==102 ); /* DEFERRED */
  121940. testcase( i==103 ); /* DISTINCT */
  121941. testcase( i==104 ); /* IS */
  121942. testcase( i==105 ); /* DROP */
  121943. testcase( i==106 ); /* FAIL */
  121944. testcase( i==107 ); /* FROM */
  121945. testcase( i==108 ); /* FULL */
  121946. testcase( i==109 ); /* GLOB */
  121947. testcase( i==110 ); /* BY */
  121948. testcase( i==111 ); /* IF */
  121949. testcase( i==112 ); /* ISNULL */
  121950. testcase( i==113 ); /* ORDER */
  121951. testcase( i==114 ); /* RESTRICT */
  121952. testcase( i==115 ); /* RIGHT */
  121953. testcase( i==116 ); /* ROLLBACK */
  121954. testcase( i==117 ); /* ROW */
  121955. testcase( i==118 ); /* UNION */
  121956. testcase( i==119 ); /* USING */
  121957. testcase( i==120 ); /* VACUUM */
  121958. testcase( i==121 ); /* VIEW */
  121959. testcase( i==122 ); /* INITIALLY */
  121960. testcase( i==123 ); /* ALL */
  121961. return aCode[i];
  121962. }
  121963. }
  121964. return TK_ID;
  121965. }
  121966. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  121967. return keywordCode((char*)z, n);
  121968. }
  121969. #define SQLITE_N_KEYWORD 124
  121970. /************** End of keywordhash.h *****************************************/
  121971. /************** Continuing where we left off in tokenize.c *******************/
  121972. /*
  121973. ** If X is a character that can be used in an identifier then
  121974. ** IdChar(X) will be true. Otherwise it is false.
  121975. **
  121976. ** For ASCII, any character with the high-order bit set is
  121977. ** allowed in an identifier. For 7-bit characters,
  121978. ** sqlite3IsIdChar[X] must be 1.
  121979. **
  121980. ** For EBCDIC, the rules are more complex but have the same
  121981. ** end result.
  121982. **
  121983. ** Ticket #1066. the SQL standard does not allow '$' in the
  121984. ** middle of identifiers. But many SQL implementations do.
  121985. ** SQLite will allow '$' in identifiers for compatibility.
  121986. ** But the feature is undocumented.
  121987. */
  121988. #ifdef SQLITE_ASCII
  121989. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  121990. #endif
  121991. #ifdef SQLITE_EBCDIC
  121992. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  121993. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  121994. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  121995. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  121996. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  121997. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  121998. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  121999. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  122000. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  122002. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  122003. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  122004. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  122005. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  122006. };
  122007. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  122008. #endif
  122009. /* Make the IdChar function accessible from ctime.c */
  122010. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  122011. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  122012. #endif
  122013. /*
  122014. ** Return the length of the token that begins at z[0].
  122015. ** Store the token type in *tokenType before returning.
  122016. */
  122017. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  122018. int i, c;
  122019. switch( *z ){
  122020. case ' ': case '\t': case '\n': case '\f': case '\r': {
  122021. testcase( z[0]==' ' );
  122022. testcase( z[0]=='\t' );
  122023. testcase( z[0]=='\n' );
  122024. testcase( z[0]=='\f' );
  122025. testcase( z[0]=='\r' );
  122026. for(i=1; sqlite3Isspace(z[i]); i++){}
  122027. *tokenType = TK_SPACE;
  122028. return i;
  122029. }
  122030. case '-': {
  122031. if( z[1]=='-' ){
  122032. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  122033. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  122034. return i;
  122035. }
  122036. *tokenType = TK_MINUS;
  122037. return 1;
  122038. }
  122039. case '(': {
  122040. *tokenType = TK_LP;
  122041. return 1;
  122042. }
  122043. case ')': {
  122044. *tokenType = TK_RP;
  122045. return 1;
  122046. }
  122047. case ';': {
  122048. *tokenType = TK_SEMI;
  122049. return 1;
  122050. }
  122051. case '+': {
  122052. *tokenType = TK_PLUS;
  122053. return 1;
  122054. }
  122055. case '*': {
  122056. *tokenType = TK_STAR;
  122057. return 1;
  122058. }
  122059. case '/': {
  122060. if( z[1]!='*' || z[2]==0 ){
  122061. *tokenType = TK_SLASH;
  122062. return 1;
  122063. }
  122064. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  122065. if( c ) i++;
  122066. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  122067. return i;
  122068. }
  122069. case '%': {
  122070. *tokenType = TK_REM;
  122071. return 1;
  122072. }
  122073. case '=': {
  122074. *tokenType = TK_EQ;
  122075. return 1 + (z[1]=='=');
  122076. }
  122077. case '<': {
  122078. if( (c=z[1])=='=' ){
  122079. *tokenType = TK_LE;
  122080. return 2;
  122081. }else if( c=='>' ){
  122082. *tokenType = TK_NE;
  122083. return 2;
  122084. }else if( c=='<' ){
  122085. *tokenType = TK_LSHIFT;
  122086. return 2;
  122087. }else{
  122088. *tokenType = TK_LT;
  122089. return 1;
  122090. }
  122091. }
  122092. case '>': {
  122093. if( (c=z[1])=='=' ){
  122094. *tokenType = TK_GE;
  122095. return 2;
  122096. }else if( c=='>' ){
  122097. *tokenType = TK_RSHIFT;
  122098. return 2;
  122099. }else{
  122100. *tokenType = TK_GT;
  122101. return 1;
  122102. }
  122103. }
  122104. case '!': {
  122105. if( z[1]!='=' ){
  122106. *tokenType = TK_ILLEGAL;
  122107. return 2;
  122108. }else{
  122109. *tokenType = TK_NE;
  122110. return 2;
  122111. }
  122112. }
  122113. case '|': {
  122114. if( z[1]!='|' ){
  122115. *tokenType = TK_BITOR;
  122116. return 1;
  122117. }else{
  122118. *tokenType = TK_CONCAT;
  122119. return 2;
  122120. }
  122121. }
  122122. case ',': {
  122123. *tokenType = TK_COMMA;
  122124. return 1;
  122125. }
  122126. case '&': {
  122127. *tokenType = TK_BITAND;
  122128. return 1;
  122129. }
  122130. case '~': {
  122131. *tokenType = TK_BITNOT;
  122132. return 1;
  122133. }
  122134. case '`':
  122135. case '\'':
  122136. case '"': {
  122137. int delim = z[0];
  122138. testcase( delim=='`' );
  122139. testcase( delim=='\'' );
  122140. testcase( delim=='"' );
  122141. for(i=1; (c=z[i])!=0; i++){
  122142. if( c==delim ){
  122143. if( z[i+1]==delim ){
  122144. i++;
  122145. }else{
  122146. break;
  122147. }
  122148. }
  122149. }
  122150. if( c=='\'' ){
  122151. *tokenType = TK_STRING;
  122152. return i+1;
  122153. }else if( c!=0 ){
  122154. *tokenType = TK_ID;
  122155. return i+1;
  122156. }else{
  122157. *tokenType = TK_ILLEGAL;
  122158. return i;
  122159. }
  122160. }
  122161. case '.': {
  122162. #ifndef SQLITE_OMIT_FLOATING_POINT
  122163. if( !sqlite3Isdigit(z[1]) )
  122164. #endif
  122165. {
  122166. *tokenType = TK_DOT;
  122167. return 1;
  122168. }
  122169. /* If the next character is a digit, this is a floating point
  122170. ** number that begins with ".". Fall thru into the next case */
  122171. }
  122172. case '0': case '1': case '2': case '3': case '4':
  122173. case '5': case '6': case '7': case '8': case '9': {
  122174. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  122175. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  122176. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  122177. testcase( z[0]=='9' );
  122178. *tokenType = TK_INTEGER;
  122179. #ifndef SQLITE_OMIT_HEX_INTEGER
  122180. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  122181. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  122182. return i;
  122183. }
  122184. #endif
  122185. for(i=0; sqlite3Isdigit(z[i]); i++){}
  122186. #ifndef SQLITE_OMIT_FLOATING_POINT
  122187. if( z[i]=='.' ){
  122188. i++;
  122189. while( sqlite3Isdigit(z[i]) ){ i++; }
  122190. *tokenType = TK_FLOAT;
  122191. }
  122192. if( (z[i]=='e' || z[i]=='E') &&
  122193. ( sqlite3Isdigit(z[i+1])
  122194. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  122195. )
  122196. ){
  122197. i += 2;
  122198. while( sqlite3Isdigit(z[i]) ){ i++; }
  122199. *tokenType = TK_FLOAT;
  122200. }
  122201. #endif
  122202. while( IdChar(z[i]) ){
  122203. *tokenType = TK_ILLEGAL;
  122204. i++;
  122205. }
  122206. return i;
  122207. }
  122208. case '[': {
  122209. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  122210. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  122211. return i;
  122212. }
  122213. case '?': {
  122214. *tokenType = TK_VARIABLE;
  122215. for(i=1; sqlite3Isdigit(z[i]); i++){}
  122216. return i;
  122217. }
  122218. #ifndef SQLITE_OMIT_TCL_VARIABLE
  122219. case '$':
  122220. #endif
  122221. case '@': /* For compatibility with MS SQL Server */
  122222. case '#':
  122223. case ':': {
  122224. int n = 0;
  122225. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  122226. testcase( z[0]==':' ); testcase( z[0]=='#' );
  122227. *tokenType = TK_VARIABLE;
  122228. for(i=1; (c=z[i])!=0; i++){
  122229. if( IdChar(c) ){
  122230. n++;
  122231. #ifndef SQLITE_OMIT_TCL_VARIABLE
  122232. }else if( c=='(' && n>0 ){
  122233. do{
  122234. i++;
  122235. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  122236. if( c==')' ){
  122237. i++;
  122238. }else{
  122239. *tokenType = TK_ILLEGAL;
  122240. }
  122241. break;
  122242. }else if( c==':' && z[i+1]==':' ){
  122243. i++;
  122244. #endif
  122245. }else{
  122246. break;
  122247. }
  122248. }
  122249. if( n==0 ) *tokenType = TK_ILLEGAL;
  122250. return i;
  122251. }
  122252. #ifndef SQLITE_OMIT_BLOB_LITERAL
  122253. case 'x': case 'X': {
  122254. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  122255. if( z[1]=='\'' ){
  122256. *tokenType = TK_BLOB;
  122257. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  122258. if( z[i]!='\'' || i%2 ){
  122259. *tokenType = TK_ILLEGAL;
  122260. while( z[i] && z[i]!='\'' ){ i++; }
  122261. }
  122262. if( z[i] ) i++;
  122263. return i;
  122264. }
  122265. /* Otherwise fall through to the next case */
  122266. }
  122267. #endif
  122268. default: {
  122269. if( !IdChar(*z) ){
  122270. break;
  122271. }
  122272. for(i=1; IdChar(z[i]); i++){}
  122273. *tokenType = keywordCode((char*)z, i);
  122274. return i;
  122275. }
  122276. }
  122277. *tokenType = TK_ILLEGAL;
  122278. return 1;
  122279. }
  122280. /*
  122281. ** Run the parser on the given SQL string. The parser structure is
  122282. ** passed in. An SQLITE_ status code is returned. If an error occurs
  122283. ** then an and attempt is made to write an error message into
  122284. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  122285. ** error message.
  122286. */
  122287. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  122288. int nErr = 0; /* Number of errors encountered */
  122289. int i; /* Loop counter */
  122290. void *pEngine; /* The LEMON-generated LALR(1) parser */
  122291. int tokenType; /* type of the next token */
  122292. int lastTokenParsed = -1; /* type of the previous token */
  122293. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  122294. sqlite3 *db = pParse->db; /* The database connection */
  122295. int mxSqlLen; /* Max length of an SQL string */
  122296. assert( zSql!=0 );
  122297. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  122298. if( db->nVdbeActive==0 ){
  122299. db->u1.isInterrupted = 0;
  122300. }
  122301. pParse->rc = SQLITE_OK;
  122302. pParse->zTail = zSql;
  122303. i = 0;
  122304. assert( pzErrMsg!=0 );
  122305. /* sqlite3ParserTrace(stdout, "parser: "); */
  122306. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  122307. if( pEngine==0 ){
  122308. db->mallocFailed = 1;
  122309. return SQLITE_NOMEM;
  122310. }
  122311. assert( pParse->pNewTable==0 );
  122312. assert( pParse->pNewTrigger==0 );
  122313. assert( pParse->nVar==0 );
  122314. assert( pParse->nzVar==0 );
  122315. assert( pParse->azVar==0 );
  122316. enableLookaside = db->lookaside.bEnabled;
  122317. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  122318. while( !db->mallocFailed && zSql[i]!=0 ){
  122319. assert( i>=0 );
  122320. pParse->sLastToken.z = &zSql[i];
  122321. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  122322. i += pParse->sLastToken.n;
  122323. if( i>mxSqlLen ){
  122324. pParse->rc = SQLITE_TOOBIG;
  122325. break;
  122326. }
  122327. switch( tokenType ){
  122328. case TK_SPACE: {
  122329. if( db->u1.isInterrupted ){
  122330. sqlite3ErrorMsg(pParse, "interrupt");
  122331. pParse->rc = SQLITE_INTERRUPT;
  122332. goto abort_parse;
  122333. }
  122334. break;
  122335. }
  122336. case TK_ILLEGAL: {
  122337. sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
  122338. &pParse->sLastToken);
  122339. goto abort_parse;
  122340. }
  122341. case TK_SEMI: {
  122342. pParse->zTail = &zSql[i];
  122343. /* Fall thru into the default case */
  122344. }
  122345. default: {
  122346. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  122347. lastTokenParsed = tokenType;
  122348. if( pParse->rc!=SQLITE_OK ){
  122349. goto abort_parse;
  122350. }
  122351. break;
  122352. }
  122353. }
  122354. }
  122355. abort_parse:
  122356. assert( nErr==0 );
  122357. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  122358. assert( zSql[i]==0 );
  122359. if( lastTokenParsed!=TK_SEMI ){
  122360. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  122361. pParse->zTail = &zSql[i];
  122362. }
  122363. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  122364. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  122365. }
  122366. }
  122367. #ifdef YYTRACKMAXSTACKDEPTH
  122368. sqlite3_mutex_enter(sqlite3MallocMutex());
  122369. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  122370. sqlite3ParserStackPeak(pEngine)
  122371. );
  122372. sqlite3_mutex_leave(sqlite3MallocMutex());
  122373. #endif /* YYDEBUG */
  122374. sqlite3ParserFree(pEngine, sqlite3_free);
  122375. db->lookaside.bEnabled = enableLookaside;
  122376. if( db->mallocFailed ){
  122377. pParse->rc = SQLITE_NOMEM;
  122378. }
  122379. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  122380. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  122381. }
  122382. assert( pzErrMsg!=0 );
  122383. if( pParse->zErrMsg ){
  122384. *pzErrMsg = pParse->zErrMsg;
  122385. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  122386. pParse->zErrMsg = 0;
  122387. nErr++;
  122388. }
  122389. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  122390. sqlite3VdbeDelete(pParse->pVdbe);
  122391. pParse->pVdbe = 0;
  122392. }
  122393. #ifndef SQLITE_OMIT_SHARED_CACHE
  122394. if( pParse->nested==0 ){
  122395. sqlite3DbFree(db, pParse->aTableLock);
  122396. pParse->aTableLock = 0;
  122397. pParse->nTableLock = 0;
  122398. }
  122399. #endif
  122400. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122401. sqlite3_free(pParse->apVtabLock);
  122402. #endif
  122403. if( !IN_DECLARE_VTAB ){
  122404. /* If the pParse->declareVtab flag is set, do not delete any table
  122405. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  122406. ** will take responsibility for freeing the Table structure.
  122407. */
  122408. sqlite3DeleteTable(db, pParse->pNewTable);
  122409. }
  122410. if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
  122411. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  122412. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  122413. sqlite3DbFree(db, pParse->azVar);
  122414. while( pParse->pAinc ){
  122415. AutoincInfo *p = pParse->pAinc;
  122416. pParse->pAinc = p->pNext;
  122417. sqlite3DbFree(db, p);
  122418. }
  122419. while( pParse->pZombieTab ){
  122420. Table *p = pParse->pZombieTab;
  122421. pParse->pZombieTab = p->pNextZombie;
  122422. sqlite3DeleteTable(db, p);
  122423. }
  122424. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  122425. return nErr;
  122426. }
  122427. /************** End of tokenize.c ********************************************/
  122428. /************** Begin file complete.c ****************************************/
  122429. /*
  122430. ** 2001 September 15
  122431. **
  122432. ** The author disclaims copyright to this source code. In place of
  122433. ** a legal notice, here is a blessing:
  122434. **
  122435. ** May you do good and not evil.
  122436. ** May you find forgiveness for yourself and forgive others.
  122437. ** May you share freely, never taking more than you give.
  122438. **
  122439. *************************************************************************
  122440. ** An tokenizer for SQL
  122441. **
  122442. ** This file contains C code that implements the sqlite3_complete() API.
  122443. ** This code used to be part of the tokenizer.c source file. But by
  122444. ** separating it out, the code will be automatically omitted from
  122445. ** static links that do not use it.
  122446. */
  122447. /* #include "sqliteInt.h" */
  122448. #ifndef SQLITE_OMIT_COMPLETE
  122449. /*
  122450. ** This is defined in tokenize.c. We just have to import the definition.
  122451. */
  122452. #ifndef SQLITE_AMALGAMATION
  122453. #ifdef SQLITE_ASCII
  122454. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  122455. #endif
  122456. #ifdef SQLITE_EBCDIC
  122457. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  122458. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  122459. #endif
  122460. #endif /* SQLITE_AMALGAMATION */
  122461. /*
  122462. ** Token types used by the sqlite3_complete() routine. See the header
  122463. ** comments on that procedure for additional information.
  122464. */
  122465. #define tkSEMI 0
  122466. #define tkWS 1
  122467. #define tkOTHER 2
  122468. #ifndef SQLITE_OMIT_TRIGGER
  122469. #define tkEXPLAIN 3
  122470. #define tkCREATE 4
  122471. #define tkTEMP 5
  122472. #define tkTRIGGER 6
  122473. #define tkEND 7
  122474. #endif
  122475. /*
  122476. ** Return TRUE if the given SQL string ends in a semicolon.
  122477. **
  122478. ** Special handling is require for CREATE TRIGGER statements.
  122479. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  122480. ** must end with ";END;".
  122481. **
  122482. ** This implementation uses a state machine with 8 states:
  122483. **
  122484. ** (0) INVALID We have not yet seen a non-whitespace character.
  122485. **
  122486. ** (1) START At the beginning or end of an SQL statement. This routine
  122487. ** returns 1 if it ends in the START state and 0 if it ends
  122488. ** in any other state.
  122489. **
  122490. ** (2) NORMAL We are in the middle of statement which ends with a single
  122491. ** semicolon.
  122492. **
  122493. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  122494. ** a statement.
  122495. **
  122496. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  122497. ** statement, possibly preceded by EXPLAIN and/or followed by
  122498. ** TEMP or TEMPORARY
  122499. **
  122500. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  122501. ** ended by a semicolon, the keyword END, and another semicolon.
  122502. **
  122503. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  122504. ** the end of a trigger definition.
  122505. **
  122506. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  122507. ** of a trigger definition.
  122508. **
  122509. ** Transitions between states above are determined by tokens extracted
  122510. ** from the input. The following tokens are significant:
  122511. **
  122512. ** (0) tkSEMI A semicolon.
  122513. ** (1) tkWS Whitespace.
  122514. ** (2) tkOTHER Any other SQL token.
  122515. ** (3) tkEXPLAIN The "explain" keyword.
  122516. ** (4) tkCREATE The "create" keyword.
  122517. ** (5) tkTEMP The "temp" or "temporary" keyword.
  122518. ** (6) tkTRIGGER The "trigger" keyword.
  122519. ** (7) tkEND The "end" keyword.
  122520. **
  122521. ** Whitespace never causes a state transition and is always ignored.
  122522. ** This means that a SQL string of all whitespace is invalid.
  122523. **
  122524. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  122525. ** to recognize the end of a trigger can be omitted. All we have to do
  122526. ** is look for a semicolon that is not part of an string or comment.
  122527. */
  122528. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
  122529. u8 state = 0; /* Current state, using numbers defined in header comment */
  122530. u8 token; /* Value of the next token */
  122531. #ifndef SQLITE_OMIT_TRIGGER
  122532. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  122533. ** statement. This is the normal case.
  122534. */
  122535. static const u8 trans[8][8] = {
  122536. /* Token: */
  122537. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  122538. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  122539. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  122540. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  122541. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  122542. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  122543. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  122544. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  122545. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  122546. };
  122547. #else
  122548. /* If triggers are not supported by this compile then the statement machine
  122549. ** used to detect the end of a statement is much simpler
  122550. */
  122551. static const u8 trans[3][3] = {
  122552. /* Token: */
  122553. /* State: ** SEMI WS OTHER */
  122554. /* 0 INVALID: */ { 1, 0, 2, },
  122555. /* 1 START: */ { 1, 1, 2, },
  122556. /* 2 NORMAL: */ { 1, 2, 2, },
  122557. };
  122558. #endif /* SQLITE_OMIT_TRIGGER */
  122559. #ifdef SQLITE_ENABLE_API_ARMOR
  122560. if( zSql==0 ){
  122561. (void)SQLITE_MISUSE_BKPT;
  122562. return 0;
  122563. }
  122564. #endif
  122565. while( *zSql ){
  122566. switch( *zSql ){
  122567. case ';': { /* A semicolon */
  122568. token = tkSEMI;
  122569. break;
  122570. }
  122571. case ' ':
  122572. case '\r':
  122573. case '\t':
  122574. case '\n':
  122575. case '\f': { /* White space is ignored */
  122576. token = tkWS;
  122577. break;
  122578. }
  122579. case '/': { /* C-style comments */
  122580. if( zSql[1]!='*' ){
  122581. token = tkOTHER;
  122582. break;
  122583. }
  122584. zSql += 2;
  122585. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  122586. if( zSql[0]==0 ) return 0;
  122587. zSql++;
  122588. token = tkWS;
  122589. break;
  122590. }
  122591. case '-': { /* SQL-style comments from "--" to end of line */
  122592. if( zSql[1]!='-' ){
  122593. token = tkOTHER;
  122594. break;
  122595. }
  122596. while( *zSql && *zSql!='\n' ){ zSql++; }
  122597. if( *zSql==0 ) return state==1;
  122598. token = tkWS;
  122599. break;
  122600. }
  122601. case '[': { /* Microsoft-style identifiers in [...] */
  122602. zSql++;
  122603. while( *zSql && *zSql!=']' ){ zSql++; }
  122604. if( *zSql==0 ) return 0;
  122605. token = tkOTHER;
  122606. break;
  122607. }
  122608. case '`': /* Grave-accent quoted symbols used by MySQL */
  122609. case '"': /* single- and double-quoted strings */
  122610. case '\'': {
  122611. int c = *zSql;
  122612. zSql++;
  122613. while( *zSql && *zSql!=c ){ zSql++; }
  122614. if( *zSql==0 ) return 0;
  122615. token = tkOTHER;
  122616. break;
  122617. }
  122618. default: {
  122619. #ifdef SQLITE_EBCDIC
  122620. unsigned char c;
  122621. #endif
  122622. if( IdChar((u8)*zSql) ){
  122623. /* Keywords and unquoted identifiers */
  122624. int nId;
  122625. for(nId=1; IdChar(zSql[nId]); nId++){}
  122626. #ifdef SQLITE_OMIT_TRIGGER
  122627. token = tkOTHER;
  122628. #else
  122629. switch( *zSql ){
  122630. case 'c': case 'C': {
  122631. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  122632. token = tkCREATE;
  122633. }else{
  122634. token = tkOTHER;
  122635. }
  122636. break;
  122637. }
  122638. case 't': case 'T': {
  122639. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  122640. token = tkTRIGGER;
  122641. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  122642. token = tkTEMP;
  122643. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  122644. token = tkTEMP;
  122645. }else{
  122646. token = tkOTHER;
  122647. }
  122648. break;
  122649. }
  122650. case 'e': case 'E': {
  122651. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  122652. token = tkEND;
  122653. }else
  122654. #ifndef SQLITE_OMIT_EXPLAIN
  122655. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  122656. token = tkEXPLAIN;
  122657. }else
  122658. #endif
  122659. {
  122660. token = tkOTHER;
  122661. }
  122662. break;
  122663. }
  122664. default: {
  122665. token = tkOTHER;
  122666. break;
  122667. }
  122668. }
  122669. #endif /* SQLITE_OMIT_TRIGGER */
  122670. zSql += nId-1;
  122671. }else{
  122672. /* Operators and special symbols */
  122673. token = tkOTHER;
  122674. }
  122675. break;
  122676. }
  122677. }
  122678. state = trans[state][token];
  122679. zSql++;
  122680. }
  122681. return state==1;
  122682. }
  122683. #ifndef SQLITE_OMIT_UTF16
  122684. /*
  122685. ** This routine is the same as the sqlite3_complete() routine described
  122686. ** above, except that the parameter is required to be UTF-16 encoded, not
  122687. ** UTF-8.
  122688. */
  122689. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
  122690. sqlite3_value *pVal;
  122691. char const *zSql8;
  122692. int rc;
  122693. #ifndef SQLITE_OMIT_AUTOINIT
  122694. rc = sqlite3_initialize();
  122695. if( rc ) return rc;
  122696. #endif
  122697. pVal = sqlite3ValueNew(0);
  122698. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  122699. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  122700. if( zSql8 ){
  122701. rc = sqlite3_complete(zSql8);
  122702. }else{
  122703. rc = SQLITE_NOMEM;
  122704. }
  122705. sqlite3ValueFree(pVal);
  122706. return rc & 0xff;
  122707. }
  122708. #endif /* SQLITE_OMIT_UTF16 */
  122709. #endif /* SQLITE_OMIT_COMPLETE */
  122710. /************** End of complete.c ********************************************/
  122711. /************** Begin file main.c ********************************************/
  122712. /*
  122713. ** 2001 September 15
  122714. **
  122715. ** The author disclaims copyright to this source code. In place of
  122716. ** a legal notice, here is a blessing:
  122717. **
  122718. ** May you do good and not evil.
  122719. ** May you find forgiveness for yourself and forgive others.
  122720. ** May you share freely, never taking more than you give.
  122721. **
  122722. *************************************************************************
  122723. ** Main file for the SQLite library. The routines in this file
  122724. ** implement the programmer interface to the library. Routines in
  122725. ** other files are for internal use by SQLite and should not be
  122726. ** accessed by users of the library.
  122727. */
  122728. /* #include "sqliteInt.h" */
  122729. #ifdef SQLITE_ENABLE_FTS3
  122730. /************** Include fts3.h in the middle of main.c ***********************/
  122731. /************** Begin file fts3.h ********************************************/
  122732. /*
  122733. ** 2006 Oct 10
  122734. **
  122735. ** The author disclaims copyright to this source code. In place of
  122736. ** a legal notice, here is a blessing:
  122737. **
  122738. ** May you do good and not evil.
  122739. ** May you find forgiveness for yourself and forgive others.
  122740. ** May you share freely, never taking more than you give.
  122741. **
  122742. ******************************************************************************
  122743. **
  122744. ** This header file is used by programs that want to link against the
  122745. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  122746. */
  122747. /* #include "sqlite3.h" */
  122748. #if 0
  122749. extern "C" {
  122750. #endif /* __cplusplus */
  122751. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  122752. #if 0
  122753. } /* extern "C" */
  122754. #endif /* __cplusplus */
  122755. /************** End of fts3.h ************************************************/
  122756. /************** Continuing where we left off in main.c ***********************/
  122757. #endif
  122758. #ifdef SQLITE_ENABLE_RTREE
  122759. /************** Include rtree.h in the middle of main.c **********************/
  122760. /************** Begin file rtree.h *******************************************/
  122761. /*
  122762. ** 2008 May 26
  122763. **
  122764. ** The author disclaims copyright to this source code. In place of
  122765. ** a legal notice, here is a blessing:
  122766. **
  122767. ** May you do good and not evil.
  122768. ** May you find forgiveness for yourself and forgive others.
  122769. ** May you share freely, never taking more than you give.
  122770. **
  122771. ******************************************************************************
  122772. **
  122773. ** This header file is used by programs that want to link against the
  122774. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  122775. */
  122776. /* #include "sqlite3.h" */
  122777. #if 0
  122778. extern "C" {
  122779. #endif /* __cplusplus */
  122780. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  122781. #if 0
  122782. } /* extern "C" */
  122783. #endif /* __cplusplus */
  122784. /************** End of rtree.h ***********************************************/
  122785. /************** Continuing where we left off in main.c ***********************/
  122786. #endif
  122787. #ifdef SQLITE_ENABLE_ICU
  122788. /************** Include sqliteicu.h in the middle of main.c ******************/
  122789. /************** Begin file sqliteicu.h ***************************************/
  122790. /*
  122791. ** 2008 May 26
  122792. **
  122793. ** The author disclaims copyright to this source code. In place of
  122794. ** a legal notice, here is a blessing:
  122795. **
  122796. ** May you do good and not evil.
  122797. ** May you find forgiveness for yourself and forgive others.
  122798. ** May you share freely, never taking more than you give.
  122799. **
  122800. ******************************************************************************
  122801. **
  122802. ** This header file is used by programs that want to link against the
  122803. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  122804. */
  122805. /* #include "sqlite3.h" */
  122806. #if 0
  122807. extern "C" {
  122808. #endif /* __cplusplus */
  122809. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  122810. #if 0
  122811. } /* extern "C" */
  122812. #endif /* __cplusplus */
  122813. /************** End of sqliteicu.h *******************************************/
  122814. /************** Continuing where we left off in main.c ***********************/
  122815. #endif
  122816. #ifdef SQLITE_ENABLE_JSON1
  122817. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  122818. #endif
  122819. #ifdef SQLITE_ENABLE_FTS5
  122820. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  122821. #endif
  122822. #ifndef SQLITE_AMALGAMATION
  122823. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  122824. ** contains the text of SQLITE_VERSION macro.
  122825. */
  122826. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  122827. #endif
  122828. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  122829. ** a pointer to the to the sqlite3_version[] string constant.
  122830. */
  122831. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
  122832. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  122833. ** pointer to a string constant whose value is the same as the
  122834. ** SQLITE_SOURCE_ID C preprocessor macro.
  122835. */
  122836. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  122837. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  122838. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  122839. */
  122840. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  122841. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  122842. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  122843. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  122844. */
  122845. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  122846. /*
  122847. ** When compiling the test fixture or with debugging enabled (on Win32),
  122848. ** this variable being set to non-zero will cause OSTRACE macros to emit
  122849. ** extra diagnostic information.
  122850. */
  122851. #ifdef SQLITE_HAVE_OS_TRACE
  122852. # ifndef SQLITE_DEBUG_OS_TRACE
  122853. # define SQLITE_DEBUG_OS_TRACE 0
  122854. # endif
  122855. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  122856. #endif
  122857. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  122858. /*
  122859. ** If the following function pointer is not NULL and if
  122860. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  122861. ** I/O active are written using this function. These messages
  122862. ** are intended for debugging activity only.
  122863. */
  122864. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  122865. #endif
  122866. /*
  122867. ** If the following global variable points to a string which is the
  122868. ** name of a directory, then that directory will be used to store
  122869. ** temporary files.
  122870. **
  122871. ** See also the "PRAGMA temp_store_directory" SQL command.
  122872. */
  122873. SQLITE_API char *sqlite3_temp_directory = 0;
  122874. /*
  122875. ** If the following global variable points to a string which is the
  122876. ** name of a directory, then that directory will be used to store
  122877. ** all database files specified with a relative pathname.
  122878. **
  122879. ** See also the "PRAGMA data_store_directory" SQL command.
  122880. */
  122881. SQLITE_API char *sqlite3_data_directory = 0;
  122882. /*
  122883. ** Initialize SQLite.
  122884. **
  122885. ** This routine must be called to initialize the memory allocation,
  122886. ** VFS, and mutex subsystems prior to doing any serious work with
  122887. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  122888. ** this routine will be called automatically by key routines such as
  122889. ** sqlite3_open().
  122890. **
  122891. ** This routine is a no-op except on its very first call for the process,
  122892. ** or for the first call after a call to sqlite3_shutdown.
  122893. **
  122894. ** The first thread to call this routine runs the initialization to
  122895. ** completion. If subsequent threads call this routine before the first
  122896. ** thread has finished the initialization process, then the subsequent
  122897. ** threads must block until the first thread finishes with the initialization.
  122898. **
  122899. ** The first thread might call this routine recursively. Recursive
  122900. ** calls to this routine should not block, of course. Otherwise the
  122901. ** initialization process would never complete.
  122902. **
  122903. ** Let X be the first thread to enter this routine. Let Y be some other
  122904. ** thread. Then while the initial invocation of this routine by X is
  122905. ** incomplete, it is required that:
  122906. **
  122907. ** * Calls to this routine from Y must block until the outer-most
  122908. ** call by X completes.
  122909. **
  122910. ** * Recursive calls to this routine from thread X return immediately
  122911. ** without blocking.
  122912. */
  122913. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
  122914. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  122915. int rc; /* Result code */
  122916. #ifdef SQLITE_EXTRA_INIT
  122917. int bRunExtraInit = 0; /* Extra initialization needed */
  122918. #endif
  122919. #ifdef SQLITE_OMIT_WSD
  122920. rc = sqlite3_wsd_init(4096, 24);
  122921. if( rc!=SQLITE_OK ){
  122922. return rc;
  122923. }
  122924. #endif
  122925. /* If the following assert() fails on some obscure processor/compiler
  122926. ** combination, the work-around is to set the correct pointer
  122927. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  122928. assert( SQLITE_PTRSIZE==sizeof(char*) );
  122929. /* If SQLite is already completely initialized, then this call
  122930. ** to sqlite3_initialize() should be a no-op. But the initialization
  122931. ** must be complete. So isInit must not be set until the very end
  122932. ** of this routine.
  122933. */
  122934. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  122935. /* Make sure the mutex subsystem is initialized. If unable to
  122936. ** initialize the mutex subsystem, return early with the error.
  122937. ** If the system is so sick that we are unable to allocate a mutex,
  122938. ** there is not much SQLite is going to be able to do.
  122939. **
  122940. ** The mutex subsystem must take care of serializing its own
  122941. ** initialization.
  122942. */
  122943. rc = sqlite3MutexInit();
  122944. if( rc ) return rc;
  122945. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  122946. ** This operation is protected by the STATIC_MASTER mutex. Note that
  122947. ** MutexAlloc() is called for a static mutex prior to initializing the
  122948. ** malloc subsystem - this implies that the allocation of a static
  122949. ** mutex must not require support from the malloc subsystem.
  122950. */
  122951. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  122952. sqlite3_mutex_enter(pMaster);
  122953. sqlite3GlobalConfig.isMutexInit = 1;
  122954. if( !sqlite3GlobalConfig.isMallocInit ){
  122955. rc = sqlite3MallocInit();
  122956. }
  122957. if( rc==SQLITE_OK ){
  122958. sqlite3GlobalConfig.isMallocInit = 1;
  122959. if( !sqlite3GlobalConfig.pInitMutex ){
  122960. sqlite3GlobalConfig.pInitMutex =
  122961. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  122962. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  122963. rc = SQLITE_NOMEM;
  122964. }
  122965. }
  122966. }
  122967. if( rc==SQLITE_OK ){
  122968. sqlite3GlobalConfig.nRefInitMutex++;
  122969. }
  122970. sqlite3_mutex_leave(pMaster);
  122971. /* If rc is not SQLITE_OK at this point, then either the malloc
  122972. ** subsystem could not be initialized or the system failed to allocate
  122973. ** the pInitMutex mutex. Return an error in either case. */
  122974. if( rc!=SQLITE_OK ){
  122975. return rc;
  122976. }
  122977. /* Do the rest of the initialization under the recursive mutex so
  122978. ** that we will be able to handle recursive calls into
  122979. ** sqlite3_initialize(). The recursive calls normally come through
  122980. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  122981. ** recursive calls might also be possible.
  122982. **
  122983. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  122984. ** to the xInit method, so the xInit method need not be threadsafe.
  122985. **
  122986. ** The following mutex is what serializes access to the appdef pcache xInit
  122987. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  122988. ** call to sqlite3PcacheInitialize().
  122989. */
  122990. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  122991. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  122992. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  122993. sqlite3GlobalConfig.inProgress = 1;
  122994. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  122995. sqlite3RegisterGlobalFunctions();
  122996. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  122997. rc = sqlite3PcacheInitialize();
  122998. }
  122999. if( rc==SQLITE_OK ){
  123000. sqlite3GlobalConfig.isPCacheInit = 1;
  123001. rc = sqlite3OsInit();
  123002. }
  123003. if( rc==SQLITE_OK ){
  123004. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  123005. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  123006. sqlite3GlobalConfig.isInit = 1;
  123007. #ifdef SQLITE_EXTRA_INIT
  123008. bRunExtraInit = 1;
  123009. #endif
  123010. }
  123011. sqlite3GlobalConfig.inProgress = 0;
  123012. }
  123013. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  123014. /* Go back under the static mutex and clean up the recursive
  123015. ** mutex to prevent a resource leak.
  123016. */
  123017. sqlite3_mutex_enter(pMaster);
  123018. sqlite3GlobalConfig.nRefInitMutex--;
  123019. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  123020. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  123021. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  123022. sqlite3GlobalConfig.pInitMutex = 0;
  123023. }
  123024. sqlite3_mutex_leave(pMaster);
  123025. /* The following is just a sanity check to make sure SQLite has
  123026. ** been compiled correctly. It is important to run this code, but
  123027. ** we don't want to run it too often and soak up CPU cycles for no
  123028. ** reason. So we run it once during initialization.
  123029. */
  123030. #ifndef NDEBUG
  123031. #ifndef SQLITE_OMIT_FLOATING_POINT
  123032. /* This section of code's only "output" is via assert() statements. */
  123033. if ( rc==SQLITE_OK ){
  123034. u64 x = (((u64)1)<<63)-1;
  123035. double y;
  123036. assert(sizeof(x)==8);
  123037. assert(sizeof(x)==sizeof(y));
  123038. memcpy(&y, &x, 8);
  123039. assert( sqlite3IsNaN(y) );
  123040. }
  123041. #endif
  123042. #endif
  123043. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  123044. ** compile-time option.
  123045. */
  123046. #ifdef SQLITE_EXTRA_INIT
  123047. if( bRunExtraInit ){
  123048. int SQLITE_EXTRA_INIT(const char*);
  123049. rc = SQLITE_EXTRA_INIT(0);
  123050. }
  123051. #endif
  123052. return rc;
  123053. }
  123054. /*
  123055. ** Undo the effects of sqlite3_initialize(). Must not be called while
  123056. ** there are outstanding database connections or memory allocations or
  123057. ** while any part of SQLite is otherwise in use in any thread. This
  123058. ** routine is not threadsafe. But it is safe to invoke this routine
  123059. ** on when SQLite is already shut down. If SQLite is already shut down
  123060. ** when this routine is invoked, then this routine is a harmless no-op.
  123061. */
  123062. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
  123063. #ifdef SQLITE_OMIT_WSD
  123064. int rc = sqlite3_wsd_init(4096, 24);
  123065. if( rc!=SQLITE_OK ){
  123066. return rc;
  123067. }
  123068. #endif
  123069. if( sqlite3GlobalConfig.isInit ){
  123070. #ifdef SQLITE_EXTRA_SHUTDOWN
  123071. void SQLITE_EXTRA_SHUTDOWN(void);
  123072. SQLITE_EXTRA_SHUTDOWN();
  123073. #endif
  123074. sqlite3_os_end();
  123075. sqlite3_reset_auto_extension();
  123076. sqlite3GlobalConfig.isInit = 0;
  123077. }
  123078. if( sqlite3GlobalConfig.isPCacheInit ){
  123079. sqlite3PcacheShutdown();
  123080. sqlite3GlobalConfig.isPCacheInit = 0;
  123081. }
  123082. if( sqlite3GlobalConfig.isMallocInit ){
  123083. sqlite3MallocEnd();
  123084. sqlite3GlobalConfig.isMallocInit = 0;
  123085. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  123086. /* The heap subsystem has now been shutdown and these values are supposed
  123087. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  123088. ** which would rely on that heap subsystem; therefore, make sure these
  123089. ** values cannot refer to heap memory that was just invalidated when the
  123090. ** heap subsystem was shutdown. This is only done if the current call to
  123091. ** this function resulted in the heap subsystem actually being shutdown.
  123092. */
  123093. sqlite3_data_directory = 0;
  123094. sqlite3_temp_directory = 0;
  123095. #endif
  123096. }
  123097. if( sqlite3GlobalConfig.isMutexInit ){
  123098. sqlite3MutexEnd();
  123099. sqlite3GlobalConfig.isMutexInit = 0;
  123100. }
  123101. return SQLITE_OK;
  123102. }
  123103. /*
  123104. ** This API allows applications to modify the global configuration of
  123105. ** the SQLite library at run-time.
  123106. **
  123107. ** This routine should only be called when there are no outstanding
  123108. ** database connections or memory allocations. This routine is not
  123109. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  123110. ** behavior.
  123111. */
  123112. SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
  123113. va_list ap;
  123114. int rc = SQLITE_OK;
  123115. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  123116. ** the SQLite library is in use. */
  123117. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  123118. va_start(ap, op);
  123119. switch( op ){
  123120. /* Mutex configuration options are only available in a threadsafe
  123121. ** compile.
  123122. */
  123123. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  123124. case SQLITE_CONFIG_SINGLETHREAD: {
  123125. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  123126. ** Single-thread. */
  123127. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  123128. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  123129. break;
  123130. }
  123131. #endif
  123132. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  123133. case SQLITE_CONFIG_MULTITHREAD: {
  123134. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  123135. ** Multi-thread. */
  123136. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  123137. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  123138. break;
  123139. }
  123140. #endif
  123141. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  123142. case SQLITE_CONFIG_SERIALIZED: {
  123143. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  123144. ** Serialized. */
  123145. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  123146. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  123147. break;
  123148. }
  123149. #endif
  123150. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  123151. case SQLITE_CONFIG_MUTEX: {
  123152. /* Specify an alternative mutex implementation */
  123153. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  123154. break;
  123155. }
  123156. #endif
  123157. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  123158. case SQLITE_CONFIG_GETMUTEX: {
  123159. /* Retrieve the current mutex implementation */
  123160. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  123161. break;
  123162. }
  123163. #endif
  123164. case SQLITE_CONFIG_MALLOC: {
  123165. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  123166. ** single argument which is a pointer to an instance of the
  123167. ** sqlite3_mem_methods structure. The argument specifies alternative
  123168. ** low-level memory allocation routines to be used in place of the memory
  123169. ** allocation routines built into SQLite. */
  123170. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  123171. break;
  123172. }
  123173. case SQLITE_CONFIG_GETMALLOC: {
  123174. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  123175. ** single argument which is a pointer to an instance of the
  123176. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  123177. ** filled with the currently defined memory allocation routines. */
  123178. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  123179. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  123180. break;
  123181. }
  123182. case SQLITE_CONFIG_MEMSTATUS: {
  123183. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  123184. ** single argument of type int, interpreted as a boolean, which enables
  123185. ** or disables the collection of memory allocation statistics. */
  123186. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  123187. break;
  123188. }
  123189. case SQLITE_CONFIG_SCRATCH: {
  123190. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  123191. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  123192. ** which the scratch allocations will be drawn, the size of each scratch
  123193. ** allocation (sz), and the maximum number of scratch allocations (N). */
  123194. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  123195. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  123196. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  123197. break;
  123198. }
  123199. case SQLITE_CONFIG_PAGECACHE: {
  123200. /* EVIDENCE-OF: R-31408-40510 There are three arguments to
  123201. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
  123202. ** of each page buffer (sz), and the number of pages (N). */
  123203. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  123204. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  123205. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  123206. break;
  123207. }
  123208. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  123209. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  123210. ** a single parameter which is a pointer to an integer and writes into
  123211. ** that integer the number of extra bytes per page required for each page
  123212. ** in SQLITE_CONFIG_PAGECACHE. */
  123213. *va_arg(ap, int*) =
  123214. sqlite3HeaderSizeBtree() +
  123215. sqlite3HeaderSizePcache() +
  123216. sqlite3HeaderSizePcache1();
  123217. break;
  123218. }
  123219. case SQLITE_CONFIG_PCACHE: {
  123220. /* no-op */
  123221. break;
  123222. }
  123223. case SQLITE_CONFIG_GETPCACHE: {
  123224. /* now an error */
  123225. rc = SQLITE_ERROR;
  123226. break;
  123227. }
  123228. case SQLITE_CONFIG_PCACHE2: {
  123229. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  123230. ** single argument which is a pointer to an sqlite3_pcache_methods2
  123231. ** object. This object specifies the interface to a custom page cache
  123232. ** implementation. */
  123233. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  123234. break;
  123235. }
  123236. case SQLITE_CONFIG_GETPCACHE2: {
  123237. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  123238. ** single argument which is a pointer to an sqlite3_pcache_methods2
  123239. ** object. SQLite copies of the current page cache implementation into
  123240. ** that object. */
  123241. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  123242. sqlite3PCacheSetDefault();
  123243. }
  123244. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  123245. break;
  123246. }
  123247. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  123248. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  123249. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  123250. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  123251. case SQLITE_CONFIG_HEAP: {
  123252. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  123253. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  123254. ** number of bytes in the memory buffer, and the minimum allocation size.
  123255. */
  123256. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  123257. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  123258. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  123259. if( sqlite3GlobalConfig.mnReq<1 ){
  123260. sqlite3GlobalConfig.mnReq = 1;
  123261. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  123262. /* cap min request size at 2^12 */
  123263. sqlite3GlobalConfig.mnReq = (1<<12);
  123264. }
  123265. if( sqlite3GlobalConfig.pHeap==0 ){
  123266. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  123267. ** is NULL, then SQLite reverts to using its default memory allocator
  123268. ** (the system malloc() implementation), undoing any prior invocation of
  123269. ** SQLITE_CONFIG_MALLOC.
  123270. **
  123271. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  123272. ** revert to its default implementation when sqlite3_initialize() is run
  123273. */
  123274. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  123275. }else{
  123276. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  123277. ** alternative memory allocator is engaged to handle all of SQLites
  123278. ** memory allocation needs. */
  123279. #ifdef SQLITE_ENABLE_MEMSYS3
  123280. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  123281. #endif
  123282. #ifdef SQLITE_ENABLE_MEMSYS5
  123283. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  123284. #endif
  123285. }
  123286. break;
  123287. }
  123288. #endif
  123289. case SQLITE_CONFIG_LOOKASIDE: {
  123290. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  123291. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  123292. break;
  123293. }
  123294. /* Record a pointer to the logger function and its first argument.
  123295. ** The default is NULL. Logging is disabled if the function pointer is
  123296. ** NULL.
  123297. */
  123298. case SQLITE_CONFIG_LOG: {
  123299. /* MSVC is picky about pulling func ptrs from va lists.
  123300. ** http://support.microsoft.com/kb/47961
  123301. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  123302. */
  123303. typedef void(*LOGFUNC_t)(void*,int,const char*);
  123304. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  123305. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  123306. break;
  123307. }
  123308. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  123309. ** can be changed at start-time using the
  123310. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  123311. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  123312. */
  123313. case SQLITE_CONFIG_URI: {
  123314. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  123315. ** argument of type int. If non-zero, then URI handling is globally
  123316. ** enabled. If the parameter is zero, then URI handling is globally
  123317. ** disabled. */
  123318. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  123319. break;
  123320. }
  123321. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  123322. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  123323. ** option takes a single integer argument which is interpreted as a
  123324. ** boolean in order to enable or disable the use of covering indices for
  123325. ** full table scans in the query optimizer. */
  123326. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  123327. break;
  123328. }
  123329. #ifdef SQLITE_ENABLE_SQLLOG
  123330. case SQLITE_CONFIG_SQLLOG: {
  123331. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  123332. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  123333. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  123334. break;
  123335. }
  123336. #endif
  123337. case SQLITE_CONFIG_MMAP_SIZE: {
  123338. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  123339. ** integer (sqlite3_int64) values that are the default mmap size limit
  123340. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  123341. ** mmap size limit. */
  123342. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  123343. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  123344. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  123345. ** negative, then that argument is changed to its compile-time default.
  123346. **
  123347. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  123348. ** silently truncated if necessary so that it does not exceed the
  123349. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  123350. ** compile-time option.
  123351. */
  123352. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  123353. mxMmap = SQLITE_MAX_MMAP_SIZE;
  123354. }
  123355. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  123356. if( szMmap>mxMmap) szMmap = mxMmap;
  123357. sqlite3GlobalConfig.mxMmap = mxMmap;
  123358. sqlite3GlobalConfig.szMmap = szMmap;
  123359. break;
  123360. }
  123361. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  123362. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  123363. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  123364. ** unsigned integer value that specifies the maximum size of the created
  123365. ** heap. */
  123366. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  123367. break;
  123368. }
  123369. #endif
  123370. case SQLITE_CONFIG_PMASZ: {
  123371. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  123372. break;
  123373. }
  123374. default: {
  123375. rc = SQLITE_ERROR;
  123376. break;
  123377. }
  123378. }
  123379. va_end(ap);
  123380. return rc;
  123381. }
  123382. /*
  123383. ** Set up the lookaside buffers for a database connection.
  123384. ** Return SQLITE_OK on success.
  123385. ** If lookaside is already active, return SQLITE_BUSY.
  123386. **
  123387. ** The sz parameter is the number of bytes in each lookaside slot.
  123388. ** The cnt parameter is the number of slots. If pStart is NULL the
  123389. ** space for the lookaside memory is obtained from sqlite3_malloc().
  123390. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  123391. ** the lookaside memory.
  123392. */
  123393. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  123394. #ifndef SQLITE_OMIT_LOOKASIDE
  123395. void *pStart;
  123396. if( db->lookaside.nOut ){
  123397. return SQLITE_BUSY;
  123398. }
  123399. /* Free any existing lookaside buffer for this handle before
  123400. ** allocating a new one so we don't have to have space for
  123401. ** both at the same time.
  123402. */
  123403. if( db->lookaside.bMalloced ){
  123404. sqlite3_free(db->lookaside.pStart);
  123405. }
  123406. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  123407. ** than a pointer to be useful.
  123408. */
  123409. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  123410. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  123411. if( cnt<0 ) cnt = 0;
  123412. if( sz==0 || cnt==0 ){
  123413. sz = 0;
  123414. pStart = 0;
  123415. }else if( pBuf==0 ){
  123416. sqlite3BeginBenignMalloc();
  123417. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  123418. sqlite3EndBenignMalloc();
  123419. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  123420. }else{
  123421. pStart = pBuf;
  123422. }
  123423. db->lookaside.pStart = pStart;
  123424. db->lookaside.pFree = 0;
  123425. db->lookaside.sz = (u16)sz;
  123426. if( pStart ){
  123427. int i;
  123428. LookasideSlot *p;
  123429. assert( sz > (int)sizeof(LookasideSlot*) );
  123430. p = (LookasideSlot*)pStart;
  123431. for(i=cnt-1; i>=0; i--){
  123432. p->pNext = db->lookaside.pFree;
  123433. db->lookaside.pFree = p;
  123434. p = (LookasideSlot*)&((u8*)p)[sz];
  123435. }
  123436. db->lookaside.pEnd = p;
  123437. db->lookaside.bEnabled = 1;
  123438. db->lookaside.bMalloced = pBuf==0 ?1:0;
  123439. }else{
  123440. db->lookaside.pStart = db;
  123441. db->lookaside.pEnd = db;
  123442. db->lookaside.bEnabled = 0;
  123443. db->lookaside.bMalloced = 0;
  123444. }
  123445. #endif /* SQLITE_OMIT_LOOKASIDE */
  123446. return SQLITE_OK;
  123447. }
  123448. /*
  123449. ** Return the mutex associated with a database connection.
  123450. */
  123451. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
  123452. #ifdef SQLITE_ENABLE_API_ARMOR
  123453. if( !sqlite3SafetyCheckOk(db) ){
  123454. (void)SQLITE_MISUSE_BKPT;
  123455. return 0;
  123456. }
  123457. #endif
  123458. return db->mutex;
  123459. }
  123460. /*
  123461. ** Free up as much memory as we can from the given database
  123462. ** connection.
  123463. */
  123464. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
  123465. int i;
  123466. #ifdef SQLITE_ENABLE_API_ARMOR
  123467. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123468. #endif
  123469. sqlite3_mutex_enter(db->mutex);
  123470. sqlite3BtreeEnterAll(db);
  123471. for(i=0; i<db->nDb; i++){
  123472. Btree *pBt = db->aDb[i].pBt;
  123473. if( pBt ){
  123474. Pager *pPager = sqlite3BtreePager(pBt);
  123475. sqlite3PagerShrink(pPager);
  123476. }
  123477. }
  123478. sqlite3BtreeLeaveAll(db);
  123479. sqlite3_mutex_leave(db->mutex);
  123480. return SQLITE_OK;
  123481. }
  123482. /*
  123483. ** Configuration settings for an individual database connection
  123484. */
  123485. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
  123486. va_list ap;
  123487. int rc;
  123488. va_start(ap, op);
  123489. switch( op ){
  123490. case SQLITE_DBCONFIG_LOOKASIDE: {
  123491. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  123492. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  123493. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  123494. rc = setupLookaside(db, pBuf, sz, cnt);
  123495. break;
  123496. }
  123497. default: {
  123498. static const struct {
  123499. int op; /* The opcode */
  123500. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  123501. } aFlagOp[] = {
  123502. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  123503. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  123504. };
  123505. unsigned int i;
  123506. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  123507. for(i=0; i<ArraySize(aFlagOp); i++){
  123508. if( aFlagOp[i].op==op ){
  123509. int onoff = va_arg(ap, int);
  123510. int *pRes = va_arg(ap, int*);
  123511. int oldFlags = db->flags;
  123512. if( onoff>0 ){
  123513. db->flags |= aFlagOp[i].mask;
  123514. }else if( onoff==0 ){
  123515. db->flags &= ~aFlagOp[i].mask;
  123516. }
  123517. if( oldFlags!=db->flags ){
  123518. sqlite3ExpirePreparedStatements(db);
  123519. }
  123520. if( pRes ){
  123521. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  123522. }
  123523. rc = SQLITE_OK;
  123524. break;
  123525. }
  123526. }
  123527. break;
  123528. }
  123529. }
  123530. va_end(ap);
  123531. return rc;
  123532. }
  123533. /*
  123534. ** Return true if the buffer z[0..n-1] contains all spaces.
  123535. */
  123536. static int allSpaces(const char *z, int n){
  123537. while( n>0 && z[n-1]==' ' ){ n--; }
  123538. return n==0;
  123539. }
  123540. /*
  123541. ** This is the default collating function named "BINARY" which is always
  123542. ** available.
  123543. **
  123544. ** If the padFlag argument is not NULL then space padding at the end
  123545. ** of strings is ignored. This implements the RTRIM collation.
  123546. */
  123547. static int binCollFunc(
  123548. void *padFlag,
  123549. int nKey1, const void *pKey1,
  123550. int nKey2, const void *pKey2
  123551. ){
  123552. int rc, n;
  123553. n = nKey1<nKey2 ? nKey1 : nKey2;
  123554. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  123555. ** strings byte by byte using the memcmp() function from the standard C
  123556. ** library. */
  123557. rc = memcmp(pKey1, pKey2, n);
  123558. if( rc==0 ){
  123559. if( padFlag
  123560. && allSpaces(((char*)pKey1)+n, nKey1-n)
  123561. && allSpaces(((char*)pKey2)+n, nKey2-n)
  123562. ){
  123563. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  123564. ** spaces at the end of either string do not change the result. In other
  123565. ** words, strings will compare equal to one another as long as they
  123566. ** differ only in the number of spaces at the end.
  123567. */
  123568. }else{
  123569. rc = nKey1 - nKey2;
  123570. }
  123571. }
  123572. return rc;
  123573. }
  123574. /*
  123575. ** Another built-in collating sequence: NOCASE.
  123576. **
  123577. ** This collating sequence is intended to be used for "case independent
  123578. ** comparison". SQLite's knowledge of upper and lower case equivalents
  123579. ** extends only to the 26 characters used in the English language.
  123580. **
  123581. ** At the moment there is only a UTF-8 implementation.
  123582. */
  123583. static int nocaseCollatingFunc(
  123584. void *NotUsed,
  123585. int nKey1, const void *pKey1,
  123586. int nKey2, const void *pKey2
  123587. ){
  123588. int r = sqlite3StrNICmp(
  123589. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  123590. UNUSED_PARAMETER(NotUsed);
  123591. if( 0==r ){
  123592. r = nKey1-nKey2;
  123593. }
  123594. return r;
  123595. }
  123596. /*
  123597. ** Return the ROWID of the most recent insert
  123598. */
  123599. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
  123600. #ifdef SQLITE_ENABLE_API_ARMOR
  123601. if( !sqlite3SafetyCheckOk(db) ){
  123602. (void)SQLITE_MISUSE_BKPT;
  123603. return 0;
  123604. }
  123605. #endif
  123606. return db->lastRowid;
  123607. }
  123608. /*
  123609. ** Return the number of changes in the most recent call to sqlite3_exec().
  123610. */
  123611. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
  123612. #ifdef SQLITE_ENABLE_API_ARMOR
  123613. if( !sqlite3SafetyCheckOk(db) ){
  123614. (void)SQLITE_MISUSE_BKPT;
  123615. return 0;
  123616. }
  123617. #endif
  123618. return db->nChange;
  123619. }
  123620. /*
  123621. ** Return the number of changes since the database handle was opened.
  123622. */
  123623. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
  123624. #ifdef SQLITE_ENABLE_API_ARMOR
  123625. if( !sqlite3SafetyCheckOk(db) ){
  123626. (void)SQLITE_MISUSE_BKPT;
  123627. return 0;
  123628. }
  123629. #endif
  123630. return db->nTotalChange;
  123631. }
  123632. /*
  123633. ** Close all open savepoints. This function only manipulates fields of the
  123634. ** database handle object, it does not close any savepoints that may be open
  123635. ** at the b-tree/pager level.
  123636. */
  123637. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  123638. while( db->pSavepoint ){
  123639. Savepoint *pTmp = db->pSavepoint;
  123640. db->pSavepoint = pTmp->pNext;
  123641. sqlite3DbFree(db, pTmp);
  123642. }
  123643. db->nSavepoint = 0;
  123644. db->nStatement = 0;
  123645. db->isTransactionSavepoint = 0;
  123646. }
  123647. /*
  123648. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  123649. ** if this is not the last copy of the function, do not invoke it. Multiple
  123650. ** copies of a single function are created when create_function() is called
  123651. ** with SQLITE_ANY as the encoding.
  123652. */
  123653. static void functionDestroy(sqlite3 *db, FuncDef *p){
  123654. FuncDestructor *pDestructor = p->pDestructor;
  123655. if( pDestructor ){
  123656. pDestructor->nRef--;
  123657. if( pDestructor->nRef==0 ){
  123658. pDestructor->xDestroy(pDestructor->pUserData);
  123659. sqlite3DbFree(db, pDestructor);
  123660. }
  123661. }
  123662. }
  123663. /*
  123664. ** Disconnect all sqlite3_vtab objects that belong to database connection
  123665. ** db. This is called when db is being closed.
  123666. */
  123667. static void disconnectAllVtab(sqlite3 *db){
  123668. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123669. int i;
  123670. HashElem *p;
  123671. sqlite3BtreeEnterAll(db);
  123672. for(i=0; i<db->nDb; i++){
  123673. Schema *pSchema = db->aDb[i].pSchema;
  123674. if( db->aDb[i].pSchema ){
  123675. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  123676. Table *pTab = (Table *)sqliteHashData(p);
  123677. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  123678. }
  123679. }
  123680. }
  123681. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  123682. Module *pMod = (Module *)sqliteHashData(p);
  123683. if( pMod->pEpoTab ){
  123684. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  123685. }
  123686. }
  123687. sqlite3VtabUnlockList(db);
  123688. sqlite3BtreeLeaveAll(db);
  123689. #else
  123690. UNUSED_PARAMETER(db);
  123691. #endif
  123692. }
  123693. /*
  123694. ** Return TRUE if database connection db has unfinalized prepared
  123695. ** statements or unfinished sqlite3_backup objects.
  123696. */
  123697. static int connectionIsBusy(sqlite3 *db){
  123698. int j;
  123699. assert( sqlite3_mutex_held(db->mutex) );
  123700. if( db->pVdbe ) return 1;
  123701. for(j=0; j<db->nDb; j++){
  123702. Btree *pBt = db->aDb[j].pBt;
  123703. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  123704. }
  123705. return 0;
  123706. }
  123707. /*
  123708. ** Close an existing SQLite database
  123709. */
  123710. static int sqlite3Close(sqlite3 *db, int forceZombie){
  123711. if( !db ){
  123712. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  123713. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  123714. return SQLITE_OK;
  123715. }
  123716. if( !sqlite3SafetyCheckSickOrOk(db) ){
  123717. return SQLITE_MISUSE_BKPT;
  123718. }
  123719. sqlite3_mutex_enter(db->mutex);
  123720. /* Force xDisconnect calls on all virtual tables */
  123721. disconnectAllVtab(db);
  123722. /* If a transaction is open, the disconnectAllVtab() call above
  123723. ** will not have called the xDisconnect() method on any virtual
  123724. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  123725. ** call will do so. We need to do this before the check for active
  123726. ** SQL statements below, as the v-table implementation may be storing
  123727. ** some prepared statements internally.
  123728. */
  123729. sqlite3VtabRollback(db);
  123730. /* Legacy behavior (sqlite3_close() behavior) is to return
  123731. ** SQLITE_BUSY if the connection can not be closed immediately.
  123732. */
  123733. if( !forceZombie && connectionIsBusy(db) ){
  123734. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  123735. "statements or unfinished backups");
  123736. sqlite3_mutex_leave(db->mutex);
  123737. return SQLITE_BUSY;
  123738. }
  123739. #ifdef SQLITE_ENABLE_SQLLOG
  123740. if( sqlite3GlobalConfig.xSqllog ){
  123741. /* Closing the handle. Fourth parameter is passed the value 2. */
  123742. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  123743. }
  123744. #endif
  123745. /* Convert the connection into a zombie and then close it.
  123746. */
  123747. db->magic = SQLITE_MAGIC_ZOMBIE;
  123748. sqlite3LeaveMutexAndCloseZombie(db);
  123749. return SQLITE_OK;
  123750. }
  123751. /*
  123752. ** Two variations on the public interface for closing a database
  123753. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  123754. ** leaves the connection option if there are unfinalized prepared
  123755. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  123756. ** version forces the connection to become a zombie if there are
  123757. ** unclosed resources, and arranges for deallocation when the last
  123758. ** prepare statement or sqlite3_backup closes.
  123759. */
  123760. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  123761. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  123762. /*
  123763. ** Close the mutex on database connection db.
  123764. **
  123765. ** Furthermore, if database connection db is a zombie (meaning that there
  123766. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  123767. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  123768. ** finished, then free all resources.
  123769. */
  123770. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  123771. HashElem *i; /* Hash table iterator */
  123772. int j;
  123773. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  123774. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  123775. ** then just leave the mutex and return.
  123776. */
  123777. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  123778. sqlite3_mutex_leave(db->mutex);
  123779. return;
  123780. }
  123781. /* If we reach this point, it means that the database connection has
  123782. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  123783. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  123784. ** go ahead and free all resources.
  123785. */
  123786. /* If a transaction is open, roll it back. This also ensures that if
  123787. ** any database schemas have been modified by an uncommitted transaction
  123788. ** they are reset. And that the required b-tree mutex is held to make
  123789. ** the pager rollback and schema reset an atomic operation. */
  123790. sqlite3RollbackAll(db, SQLITE_OK);
  123791. /* Free any outstanding Savepoint structures. */
  123792. sqlite3CloseSavepoints(db);
  123793. /* Close all database connections */
  123794. for(j=0; j<db->nDb; j++){
  123795. struct Db *pDb = &db->aDb[j];
  123796. if( pDb->pBt ){
  123797. sqlite3BtreeClose(pDb->pBt);
  123798. pDb->pBt = 0;
  123799. if( j!=1 ){
  123800. pDb->pSchema = 0;
  123801. }
  123802. }
  123803. }
  123804. /* Clear the TEMP schema separately and last */
  123805. if( db->aDb[1].pSchema ){
  123806. sqlite3SchemaClear(db->aDb[1].pSchema);
  123807. }
  123808. sqlite3VtabUnlockList(db);
  123809. /* Free up the array of auxiliary databases */
  123810. sqlite3CollapseDatabaseArray(db);
  123811. assert( db->nDb<=2 );
  123812. assert( db->aDb==db->aDbStatic );
  123813. /* Tell the code in notify.c that the connection no longer holds any
  123814. ** locks and does not require any further unlock-notify callbacks.
  123815. */
  123816. sqlite3ConnectionClosed(db);
  123817. for(j=0; j<ArraySize(db->aFunc.a); j++){
  123818. FuncDef *pNext, *pHash, *p;
  123819. for(p=db->aFunc.a[j]; p; p=pHash){
  123820. pHash = p->pHash;
  123821. while( p ){
  123822. functionDestroy(db, p);
  123823. pNext = p->pNext;
  123824. sqlite3DbFree(db, p);
  123825. p = pNext;
  123826. }
  123827. }
  123828. }
  123829. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  123830. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  123831. /* Invoke any destructors registered for collation sequence user data. */
  123832. for(j=0; j<3; j++){
  123833. if( pColl[j].xDel ){
  123834. pColl[j].xDel(pColl[j].pUser);
  123835. }
  123836. }
  123837. sqlite3DbFree(db, pColl);
  123838. }
  123839. sqlite3HashClear(&db->aCollSeq);
  123840. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123841. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  123842. Module *pMod = (Module *)sqliteHashData(i);
  123843. if( pMod->xDestroy ){
  123844. pMod->xDestroy(pMod->pAux);
  123845. }
  123846. sqlite3VtabEponymousTableClear(db, pMod);
  123847. sqlite3DbFree(db, pMod);
  123848. }
  123849. sqlite3HashClear(&db->aModule);
  123850. #endif
  123851. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  123852. sqlite3ValueFree(db->pErr);
  123853. sqlite3CloseExtensions(db);
  123854. #if SQLITE_USER_AUTHENTICATION
  123855. sqlite3_free(db->auth.zAuthUser);
  123856. sqlite3_free(db->auth.zAuthPW);
  123857. #endif
  123858. db->magic = SQLITE_MAGIC_ERROR;
  123859. /* The temp-database schema is allocated differently from the other schema
  123860. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  123861. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  123862. ** the same sqliteMalloc() as the one that allocates the database
  123863. ** structure?
  123864. */
  123865. sqlite3DbFree(db, db->aDb[1].pSchema);
  123866. sqlite3_mutex_leave(db->mutex);
  123867. db->magic = SQLITE_MAGIC_CLOSED;
  123868. sqlite3_mutex_free(db->mutex);
  123869. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  123870. if( db->lookaside.bMalloced ){
  123871. sqlite3_free(db->lookaside.pStart);
  123872. }
  123873. sqlite3_free(db);
  123874. }
  123875. /*
  123876. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  123877. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  123878. ** breaker") and made to return tripCode if there are any further
  123879. ** attempts to use that cursor. Read cursors remain open and valid
  123880. ** but are "saved" in case the table pages are moved around.
  123881. */
  123882. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  123883. int i;
  123884. int inTrans = 0;
  123885. int schemaChange;
  123886. assert( sqlite3_mutex_held(db->mutex) );
  123887. sqlite3BeginBenignMalloc();
  123888. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  123889. ** This is important in case the transaction being rolled back has
  123890. ** modified the database schema. If the b-tree mutexes are not taken
  123891. ** here, then another shared-cache connection might sneak in between
  123892. ** the database rollback and schema reset, which can cause false
  123893. ** corruption reports in some cases. */
  123894. sqlite3BtreeEnterAll(db);
  123895. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  123896. for(i=0; i<db->nDb; i++){
  123897. Btree *p = db->aDb[i].pBt;
  123898. if( p ){
  123899. if( sqlite3BtreeIsInTrans(p) ){
  123900. inTrans = 1;
  123901. }
  123902. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  123903. }
  123904. }
  123905. sqlite3VtabRollback(db);
  123906. sqlite3EndBenignMalloc();
  123907. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  123908. sqlite3ExpirePreparedStatements(db);
  123909. sqlite3ResetAllSchemasOfConnection(db);
  123910. }
  123911. sqlite3BtreeLeaveAll(db);
  123912. /* Any deferred constraint violations have now been resolved. */
  123913. db->nDeferredCons = 0;
  123914. db->nDeferredImmCons = 0;
  123915. db->flags &= ~SQLITE_DeferFKs;
  123916. /* If one has been configured, invoke the rollback-hook callback */
  123917. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  123918. db->xRollbackCallback(db->pRollbackArg);
  123919. }
  123920. }
  123921. /*
  123922. ** Return a static string containing the name corresponding to the error code
  123923. ** specified in the argument.
  123924. */
  123925. #if defined(SQLITE_NEED_ERR_NAME)
  123926. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  123927. const char *zName = 0;
  123928. int i, origRc = rc;
  123929. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  123930. switch( rc ){
  123931. case SQLITE_OK: zName = "SQLITE_OK"; break;
  123932. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  123933. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  123934. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  123935. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  123936. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  123937. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  123938. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  123939. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  123940. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  123941. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  123942. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  123943. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  123944. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  123945. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  123946. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  123947. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  123948. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  123949. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  123950. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  123951. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  123952. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  123953. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  123954. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  123955. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  123956. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  123957. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  123958. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  123959. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  123960. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  123961. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  123962. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  123963. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  123964. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  123965. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  123966. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  123967. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  123968. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  123969. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  123970. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  123971. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  123972. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  123973. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  123974. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  123975. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  123976. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  123977. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  123978. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  123979. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  123980. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  123981. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  123982. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  123983. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  123984. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  123985. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  123986. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  123987. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  123988. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  123989. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  123990. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  123991. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  123992. case SQLITE_CONSTRAINT_FOREIGNKEY:
  123993. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  123994. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  123995. case SQLITE_CONSTRAINT_PRIMARYKEY:
  123996. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  123997. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  123998. case SQLITE_CONSTRAINT_COMMITHOOK:
  123999. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  124000. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  124001. case SQLITE_CONSTRAINT_FUNCTION:
  124002. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  124003. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  124004. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  124005. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  124006. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  124007. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  124008. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  124009. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  124010. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  124011. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  124012. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  124013. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  124014. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  124015. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  124016. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  124017. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  124018. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  124019. }
  124020. }
  124021. if( zName==0 ){
  124022. static char zBuf[50];
  124023. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  124024. zName = zBuf;
  124025. }
  124026. return zName;
  124027. }
  124028. #endif
  124029. /*
  124030. ** Return a static string that describes the kind of error specified in the
  124031. ** argument.
  124032. */
  124033. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  124034. static const char* const aMsg[] = {
  124035. /* SQLITE_OK */ "not an error",
  124036. /* SQLITE_ERROR */ "SQL logic error or missing database",
  124037. /* SQLITE_INTERNAL */ 0,
  124038. /* SQLITE_PERM */ "access permission denied",
  124039. /* SQLITE_ABORT */ "callback requested query abort",
  124040. /* SQLITE_BUSY */ "database is locked",
  124041. /* SQLITE_LOCKED */ "database table is locked",
  124042. /* SQLITE_NOMEM */ "out of memory",
  124043. /* SQLITE_READONLY */ "attempt to write a readonly database",
  124044. /* SQLITE_INTERRUPT */ "interrupted",
  124045. /* SQLITE_IOERR */ "disk I/O error",
  124046. /* SQLITE_CORRUPT */ "database disk image is malformed",
  124047. /* SQLITE_NOTFOUND */ "unknown operation",
  124048. /* SQLITE_FULL */ "database or disk is full",
  124049. /* SQLITE_CANTOPEN */ "unable to open database file",
  124050. /* SQLITE_PROTOCOL */ "locking protocol",
  124051. /* SQLITE_EMPTY */ "table contains no data",
  124052. /* SQLITE_SCHEMA */ "database schema has changed",
  124053. /* SQLITE_TOOBIG */ "string or blob too big",
  124054. /* SQLITE_CONSTRAINT */ "constraint failed",
  124055. /* SQLITE_MISMATCH */ "datatype mismatch",
  124056. /* SQLITE_MISUSE */ "library routine called out of sequence",
  124057. /* SQLITE_NOLFS */ "large file support is disabled",
  124058. /* SQLITE_AUTH */ "authorization denied",
  124059. /* SQLITE_FORMAT */ "auxiliary database format error",
  124060. /* SQLITE_RANGE */ "bind or column index out of range",
  124061. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  124062. };
  124063. const char *zErr = "unknown error";
  124064. switch( rc ){
  124065. case SQLITE_ABORT_ROLLBACK: {
  124066. zErr = "abort due to ROLLBACK";
  124067. break;
  124068. }
  124069. default: {
  124070. rc &= 0xff;
  124071. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  124072. zErr = aMsg[rc];
  124073. }
  124074. break;
  124075. }
  124076. }
  124077. return zErr;
  124078. }
  124079. /*
  124080. ** This routine implements a busy callback that sleeps and tries
  124081. ** again until a timeout value is reached. The timeout value is
  124082. ** an integer number of milliseconds passed in as the first
  124083. ** argument.
  124084. */
  124085. static int sqliteDefaultBusyCallback(
  124086. void *ptr, /* Database connection */
  124087. int count /* Number of times table has been busy */
  124088. ){
  124089. #if SQLITE_OS_WIN || HAVE_USLEEP
  124090. static const u8 delays[] =
  124091. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  124092. static const u8 totals[] =
  124093. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  124094. # define NDELAY ArraySize(delays)
  124095. sqlite3 *db = (sqlite3 *)ptr;
  124096. int timeout = db->busyTimeout;
  124097. int delay, prior;
  124098. assert( count>=0 );
  124099. if( count < NDELAY ){
  124100. delay = delays[count];
  124101. prior = totals[count];
  124102. }else{
  124103. delay = delays[NDELAY-1];
  124104. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  124105. }
  124106. if( prior + delay > timeout ){
  124107. delay = timeout - prior;
  124108. if( delay<=0 ) return 0;
  124109. }
  124110. sqlite3OsSleep(db->pVfs, delay*1000);
  124111. return 1;
  124112. #else
  124113. sqlite3 *db = (sqlite3 *)ptr;
  124114. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  124115. if( (count+1)*1000 > timeout ){
  124116. return 0;
  124117. }
  124118. sqlite3OsSleep(db->pVfs, 1000000);
  124119. return 1;
  124120. #endif
  124121. }
  124122. /*
  124123. ** Invoke the given busy handler.
  124124. **
  124125. ** This routine is called when an operation failed with a lock.
  124126. ** If this routine returns non-zero, the lock is retried. If it
  124127. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  124128. */
  124129. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  124130. int rc;
  124131. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  124132. rc = p->xFunc(p->pArg, p->nBusy);
  124133. if( rc==0 ){
  124134. p->nBusy = -1;
  124135. }else{
  124136. p->nBusy++;
  124137. }
  124138. return rc;
  124139. }
  124140. /*
  124141. ** This routine sets the busy callback for an Sqlite database to the
  124142. ** given callback function with the given argument.
  124143. */
  124144. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
  124145. sqlite3 *db,
  124146. int (*xBusy)(void*,int),
  124147. void *pArg
  124148. ){
  124149. #ifdef SQLITE_ENABLE_API_ARMOR
  124150. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124151. #endif
  124152. sqlite3_mutex_enter(db->mutex);
  124153. db->busyHandler.xFunc = xBusy;
  124154. db->busyHandler.pArg = pArg;
  124155. db->busyHandler.nBusy = 0;
  124156. db->busyTimeout = 0;
  124157. sqlite3_mutex_leave(db->mutex);
  124158. return SQLITE_OK;
  124159. }
  124160. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  124161. /*
  124162. ** This routine sets the progress callback for an Sqlite database to the
  124163. ** given callback function with the given argument. The progress callback will
  124164. ** be invoked every nOps opcodes.
  124165. */
  124166. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
  124167. sqlite3 *db,
  124168. int nOps,
  124169. int (*xProgress)(void*),
  124170. void *pArg
  124171. ){
  124172. #ifdef SQLITE_ENABLE_API_ARMOR
  124173. if( !sqlite3SafetyCheckOk(db) ){
  124174. (void)SQLITE_MISUSE_BKPT;
  124175. return;
  124176. }
  124177. #endif
  124178. sqlite3_mutex_enter(db->mutex);
  124179. if( nOps>0 ){
  124180. db->xProgress = xProgress;
  124181. db->nProgressOps = (unsigned)nOps;
  124182. db->pProgressArg = pArg;
  124183. }else{
  124184. db->xProgress = 0;
  124185. db->nProgressOps = 0;
  124186. db->pProgressArg = 0;
  124187. }
  124188. sqlite3_mutex_leave(db->mutex);
  124189. }
  124190. #endif
  124191. /*
  124192. ** This routine installs a default busy handler that waits for the
  124193. ** specified number of milliseconds before returning 0.
  124194. */
  124195. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
  124196. #ifdef SQLITE_ENABLE_API_ARMOR
  124197. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124198. #endif
  124199. if( ms>0 ){
  124200. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  124201. db->busyTimeout = ms;
  124202. }else{
  124203. sqlite3_busy_handler(db, 0, 0);
  124204. }
  124205. return SQLITE_OK;
  124206. }
  124207. /*
  124208. ** Cause any pending operation to stop at its earliest opportunity.
  124209. */
  124210. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
  124211. #ifdef SQLITE_ENABLE_API_ARMOR
  124212. if( !sqlite3SafetyCheckOk(db) ){
  124213. (void)SQLITE_MISUSE_BKPT;
  124214. return;
  124215. }
  124216. #endif
  124217. db->u1.isInterrupted = 1;
  124218. }
  124219. /*
  124220. ** This function is exactly the same as sqlite3_create_function(), except
  124221. ** that it is designed to be called by internal code. The difference is
  124222. ** that if a malloc() fails in sqlite3_create_function(), an error code
  124223. ** is returned and the mallocFailed flag cleared.
  124224. */
  124225. SQLITE_PRIVATE int sqlite3CreateFunc(
  124226. sqlite3 *db,
  124227. const char *zFunctionName,
  124228. int nArg,
  124229. int enc,
  124230. void *pUserData,
  124231. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  124232. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  124233. void (*xFinal)(sqlite3_context*),
  124234. FuncDestructor *pDestructor
  124235. ){
  124236. FuncDef *p;
  124237. int nName;
  124238. int extraFlags;
  124239. assert( sqlite3_mutex_held(db->mutex) );
  124240. if( zFunctionName==0 ||
  124241. (xFunc && (xFinal || xStep)) ||
  124242. (!xFunc && (xFinal && !xStep)) ||
  124243. (!xFunc && (!xFinal && xStep)) ||
  124244. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  124245. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  124246. return SQLITE_MISUSE_BKPT;
  124247. }
  124248. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  124249. extraFlags = enc & SQLITE_DETERMINISTIC;
  124250. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  124251. #ifndef SQLITE_OMIT_UTF16
  124252. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  124253. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  124254. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  124255. **
  124256. ** If SQLITE_ANY is specified, add three versions of the function
  124257. ** to the hash table.
  124258. */
  124259. if( enc==SQLITE_UTF16 ){
  124260. enc = SQLITE_UTF16NATIVE;
  124261. }else if( enc==SQLITE_ANY ){
  124262. int rc;
  124263. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  124264. pUserData, xFunc, xStep, xFinal, pDestructor);
  124265. if( rc==SQLITE_OK ){
  124266. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  124267. pUserData, xFunc, xStep, xFinal, pDestructor);
  124268. }
  124269. if( rc!=SQLITE_OK ){
  124270. return rc;
  124271. }
  124272. enc = SQLITE_UTF16BE;
  124273. }
  124274. #else
  124275. enc = SQLITE_UTF8;
  124276. #endif
  124277. /* Check if an existing function is being overridden or deleted. If so,
  124278. ** and there are active VMs, then return SQLITE_BUSY. If a function
  124279. ** is being overridden/deleted but there are no active VMs, allow the
  124280. ** operation to continue but invalidate all precompiled statements.
  124281. */
  124282. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  124283. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  124284. if( db->nVdbeActive ){
  124285. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  124286. "unable to delete/modify user-function due to active statements");
  124287. assert( !db->mallocFailed );
  124288. return SQLITE_BUSY;
  124289. }else{
  124290. sqlite3ExpirePreparedStatements(db);
  124291. }
  124292. }
  124293. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  124294. assert(p || db->mallocFailed);
  124295. if( !p ){
  124296. return SQLITE_NOMEM;
  124297. }
  124298. /* If an older version of the function with a configured destructor is
  124299. ** being replaced invoke the destructor function here. */
  124300. functionDestroy(db, p);
  124301. if( pDestructor ){
  124302. pDestructor->nRef++;
  124303. }
  124304. p->pDestructor = pDestructor;
  124305. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  124306. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  124307. p->xFunc = xFunc;
  124308. p->xStep = xStep;
  124309. p->xFinalize = xFinal;
  124310. p->pUserData = pUserData;
  124311. p->nArg = (u16)nArg;
  124312. return SQLITE_OK;
  124313. }
  124314. /*
  124315. ** Create new user functions.
  124316. */
  124317. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  124318. sqlite3 *db,
  124319. const char *zFunc,
  124320. int nArg,
  124321. int enc,
  124322. void *p,
  124323. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  124324. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  124325. void (*xFinal)(sqlite3_context*)
  124326. ){
  124327. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  124328. xFinal, 0);
  124329. }
  124330. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  124331. sqlite3 *db,
  124332. const char *zFunc,
  124333. int nArg,
  124334. int enc,
  124335. void *p,
  124336. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  124337. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  124338. void (*xFinal)(sqlite3_context*),
  124339. void (*xDestroy)(void *)
  124340. ){
  124341. int rc = SQLITE_ERROR;
  124342. FuncDestructor *pArg = 0;
  124343. #ifdef SQLITE_ENABLE_API_ARMOR
  124344. if( !sqlite3SafetyCheckOk(db) ){
  124345. return SQLITE_MISUSE_BKPT;
  124346. }
  124347. #endif
  124348. sqlite3_mutex_enter(db->mutex);
  124349. if( xDestroy ){
  124350. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  124351. if( !pArg ){
  124352. xDestroy(p);
  124353. goto out;
  124354. }
  124355. pArg->xDestroy = xDestroy;
  124356. pArg->pUserData = p;
  124357. }
  124358. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  124359. if( pArg && pArg->nRef==0 ){
  124360. assert( rc!=SQLITE_OK );
  124361. xDestroy(p);
  124362. sqlite3DbFree(db, pArg);
  124363. }
  124364. out:
  124365. rc = sqlite3ApiExit(db, rc);
  124366. sqlite3_mutex_leave(db->mutex);
  124367. return rc;
  124368. }
  124369. #ifndef SQLITE_OMIT_UTF16
  124370. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  124371. sqlite3 *db,
  124372. const void *zFunctionName,
  124373. int nArg,
  124374. int eTextRep,
  124375. void *p,
  124376. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  124377. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  124378. void (*xFinal)(sqlite3_context*)
  124379. ){
  124380. int rc;
  124381. char *zFunc8;
  124382. #ifdef SQLITE_ENABLE_API_ARMOR
  124383. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  124384. #endif
  124385. sqlite3_mutex_enter(db->mutex);
  124386. assert( !db->mallocFailed );
  124387. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  124388. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  124389. sqlite3DbFree(db, zFunc8);
  124390. rc = sqlite3ApiExit(db, rc);
  124391. sqlite3_mutex_leave(db->mutex);
  124392. return rc;
  124393. }
  124394. #endif
  124395. /*
  124396. ** Declare that a function has been overloaded by a virtual table.
  124397. **
  124398. ** If the function already exists as a regular global function, then
  124399. ** this routine is a no-op. If the function does not exist, then create
  124400. ** a new one that always throws a run-time error.
  124401. **
  124402. ** When virtual tables intend to provide an overloaded function, they
  124403. ** should call this routine to make sure the global function exists.
  124404. ** A global function must exist in order for name resolution to work
  124405. ** properly.
  124406. */
  124407. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
  124408. sqlite3 *db,
  124409. const char *zName,
  124410. int nArg
  124411. ){
  124412. int nName = sqlite3Strlen30(zName);
  124413. int rc = SQLITE_OK;
  124414. #ifdef SQLITE_ENABLE_API_ARMOR
  124415. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  124416. return SQLITE_MISUSE_BKPT;
  124417. }
  124418. #endif
  124419. sqlite3_mutex_enter(db->mutex);
  124420. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  124421. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  124422. 0, sqlite3InvalidFunction, 0, 0, 0);
  124423. }
  124424. rc = sqlite3ApiExit(db, rc);
  124425. sqlite3_mutex_leave(db->mutex);
  124426. return rc;
  124427. }
  124428. #ifndef SQLITE_OMIT_TRACE
  124429. /*
  124430. ** Register a trace function. The pArg from the previously registered trace
  124431. ** is returned.
  124432. **
  124433. ** A NULL trace function means that no tracing is executes. A non-NULL
  124434. ** trace is a pointer to a function that is invoked at the start of each
  124435. ** SQL statement.
  124436. */
  124437. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  124438. void *pOld;
  124439. #ifdef SQLITE_ENABLE_API_ARMOR
  124440. if( !sqlite3SafetyCheckOk(db) ){
  124441. (void)SQLITE_MISUSE_BKPT;
  124442. return 0;
  124443. }
  124444. #endif
  124445. sqlite3_mutex_enter(db->mutex);
  124446. pOld = db->pTraceArg;
  124447. db->xTrace = xTrace;
  124448. db->pTraceArg = pArg;
  124449. sqlite3_mutex_leave(db->mutex);
  124450. return pOld;
  124451. }
  124452. /*
  124453. ** Register a profile function. The pArg from the previously registered
  124454. ** profile function is returned.
  124455. **
  124456. ** A NULL profile function means that no profiling is executes. A non-NULL
  124457. ** profile is a pointer to a function that is invoked at the conclusion of
  124458. ** each SQL statement that is run.
  124459. */
  124460. SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
  124461. sqlite3 *db,
  124462. void (*xProfile)(void*,const char*,sqlite_uint64),
  124463. void *pArg
  124464. ){
  124465. void *pOld;
  124466. #ifdef SQLITE_ENABLE_API_ARMOR
  124467. if( !sqlite3SafetyCheckOk(db) ){
  124468. (void)SQLITE_MISUSE_BKPT;
  124469. return 0;
  124470. }
  124471. #endif
  124472. sqlite3_mutex_enter(db->mutex);
  124473. pOld = db->pProfileArg;
  124474. db->xProfile = xProfile;
  124475. db->pProfileArg = pArg;
  124476. sqlite3_mutex_leave(db->mutex);
  124477. return pOld;
  124478. }
  124479. #endif /* SQLITE_OMIT_TRACE */
  124480. /*
  124481. ** Register a function to be invoked when a transaction commits.
  124482. ** If the invoked function returns non-zero, then the commit becomes a
  124483. ** rollback.
  124484. */
  124485. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
  124486. sqlite3 *db, /* Attach the hook to this database */
  124487. int (*xCallback)(void*), /* Function to invoke on each commit */
  124488. void *pArg /* Argument to the function */
  124489. ){
  124490. void *pOld;
  124491. #ifdef SQLITE_ENABLE_API_ARMOR
  124492. if( !sqlite3SafetyCheckOk(db) ){
  124493. (void)SQLITE_MISUSE_BKPT;
  124494. return 0;
  124495. }
  124496. #endif
  124497. sqlite3_mutex_enter(db->mutex);
  124498. pOld = db->pCommitArg;
  124499. db->xCommitCallback = xCallback;
  124500. db->pCommitArg = pArg;
  124501. sqlite3_mutex_leave(db->mutex);
  124502. return pOld;
  124503. }
  124504. /*
  124505. ** Register a callback to be invoked each time a row is updated,
  124506. ** inserted or deleted using this database connection.
  124507. */
  124508. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  124509. sqlite3 *db, /* Attach the hook to this database */
  124510. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  124511. void *pArg /* Argument to the function */
  124512. ){
  124513. void *pRet;
  124514. #ifdef SQLITE_ENABLE_API_ARMOR
  124515. if( !sqlite3SafetyCheckOk(db) ){
  124516. (void)SQLITE_MISUSE_BKPT;
  124517. return 0;
  124518. }
  124519. #endif
  124520. sqlite3_mutex_enter(db->mutex);
  124521. pRet = db->pUpdateArg;
  124522. db->xUpdateCallback = xCallback;
  124523. db->pUpdateArg = pArg;
  124524. sqlite3_mutex_leave(db->mutex);
  124525. return pRet;
  124526. }
  124527. /*
  124528. ** Register a callback to be invoked each time a transaction is rolled
  124529. ** back by this database connection.
  124530. */
  124531. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
  124532. sqlite3 *db, /* Attach the hook to this database */
  124533. void (*xCallback)(void*), /* Callback function */
  124534. void *pArg /* Argument to the function */
  124535. ){
  124536. void *pRet;
  124537. #ifdef SQLITE_ENABLE_API_ARMOR
  124538. if( !sqlite3SafetyCheckOk(db) ){
  124539. (void)SQLITE_MISUSE_BKPT;
  124540. return 0;
  124541. }
  124542. #endif
  124543. sqlite3_mutex_enter(db->mutex);
  124544. pRet = db->pRollbackArg;
  124545. db->xRollbackCallback = xCallback;
  124546. db->pRollbackArg = pArg;
  124547. sqlite3_mutex_leave(db->mutex);
  124548. return pRet;
  124549. }
  124550. #ifndef SQLITE_OMIT_WAL
  124551. /*
  124552. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  124553. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  124554. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  124555. ** wal_autocheckpoint()).
  124556. */
  124557. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  124558. void *pClientData, /* Argument */
  124559. sqlite3 *db, /* Connection */
  124560. const char *zDb, /* Database */
  124561. int nFrame /* Size of WAL */
  124562. ){
  124563. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  124564. sqlite3BeginBenignMalloc();
  124565. sqlite3_wal_checkpoint(db, zDb);
  124566. sqlite3EndBenignMalloc();
  124567. }
  124568. return SQLITE_OK;
  124569. }
  124570. #endif /* SQLITE_OMIT_WAL */
  124571. /*
  124572. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  124573. ** a database after committing a transaction if there are nFrame or
  124574. ** more frames in the log file. Passing zero or a negative value as the
  124575. ** nFrame parameter disables automatic checkpoints entirely.
  124576. **
  124577. ** The callback registered by this function replaces any existing callback
  124578. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  124579. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  124580. ** configured by this function.
  124581. */
  124582. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  124583. #ifdef SQLITE_OMIT_WAL
  124584. UNUSED_PARAMETER(db);
  124585. UNUSED_PARAMETER(nFrame);
  124586. #else
  124587. #ifdef SQLITE_ENABLE_API_ARMOR
  124588. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124589. #endif
  124590. if( nFrame>0 ){
  124591. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  124592. }else{
  124593. sqlite3_wal_hook(db, 0, 0);
  124594. }
  124595. #endif
  124596. return SQLITE_OK;
  124597. }
  124598. /*
  124599. ** Register a callback to be invoked each time a transaction is written
  124600. ** into the write-ahead-log by this database connection.
  124601. */
  124602. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  124603. sqlite3 *db, /* Attach the hook to this db handle */
  124604. int(*xCallback)(void *, sqlite3*, const char*, int),
  124605. void *pArg /* First argument passed to xCallback() */
  124606. ){
  124607. #ifndef SQLITE_OMIT_WAL
  124608. void *pRet;
  124609. #ifdef SQLITE_ENABLE_API_ARMOR
  124610. if( !sqlite3SafetyCheckOk(db) ){
  124611. (void)SQLITE_MISUSE_BKPT;
  124612. return 0;
  124613. }
  124614. #endif
  124615. sqlite3_mutex_enter(db->mutex);
  124616. pRet = db->pWalArg;
  124617. db->xWalCallback = xCallback;
  124618. db->pWalArg = pArg;
  124619. sqlite3_mutex_leave(db->mutex);
  124620. return pRet;
  124621. #else
  124622. return 0;
  124623. #endif
  124624. }
  124625. /*
  124626. ** Checkpoint database zDb.
  124627. */
  124628. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  124629. sqlite3 *db, /* Database handle */
  124630. const char *zDb, /* Name of attached database (or NULL) */
  124631. int eMode, /* SQLITE_CHECKPOINT_* value */
  124632. int *pnLog, /* OUT: Size of WAL log in frames */
  124633. int *pnCkpt /* OUT: Total number of frames checkpointed */
  124634. ){
  124635. #ifdef SQLITE_OMIT_WAL
  124636. return SQLITE_OK;
  124637. #else
  124638. int rc; /* Return code */
  124639. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  124640. #ifdef SQLITE_ENABLE_API_ARMOR
  124641. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124642. #endif
  124643. /* Initialize the output variables to -1 in case an error occurs. */
  124644. if( pnLog ) *pnLog = -1;
  124645. if( pnCkpt ) *pnCkpt = -1;
  124646. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  124647. assert( SQLITE_CHECKPOINT_FULL==1 );
  124648. assert( SQLITE_CHECKPOINT_RESTART==2 );
  124649. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  124650. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  124651. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  124652. ** mode: */
  124653. return SQLITE_MISUSE;
  124654. }
  124655. sqlite3_mutex_enter(db->mutex);
  124656. if( zDb && zDb[0] ){
  124657. iDb = sqlite3FindDbName(db, zDb);
  124658. }
  124659. if( iDb<0 ){
  124660. rc = SQLITE_ERROR;
  124661. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  124662. }else{
  124663. db->busyHandler.nBusy = 0;
  124664. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  124665. sqlite3Error(db, rc);
  124666. }
  124667. rc = sqlite3ApiExit(db, rc);
  124668. sqlite3_mutex_leave(db->mutex);
  124669. return rc;
  124670. #endif
  124671. }
  124672. /*
  124673. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  124674. ** to contains a zero-length string, all attached databases are
  124675. ** checkpointed.
  124676. */
  124677. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  124678. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  124679. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  124680. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  124681. }
  124682. #ifndef SQLITE_OMIT_WAL
  124683. /*
  124684. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  124685. ** not currently open in WAL mode.
  124686. **
  124687. ** If a transaction is open on the database being checkpointed, this
  124688. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  124689. ** an error occurs while running the checkpoint, an SQLite error code is
  124690. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  124691. **
  124692. ** The mutex on database handle db should be held by the caller. The mutex
  124693. ** associated with the specific b-tree being checkpointed is taken by
  124694. ** this function while the checkpoint is running.
  124695. **
  124696. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  124697. ** checkpointed. If an error is encountered it is returned immediately -
  124698. ** no attempt is made to checkpoint any remaining databases.
  124699. **
  124700. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  124701. */
  124702. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  124703. int rc = SQLITE_OK; /* Return code */
  124704. int i; /* Used to iterate through attached dbs */
  124705. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  124706. assert( sqlite3_mutex_held(db->mutex) );
  124707. assert( !pnLog || *pnLog==-1 );
  124708. assert( !pnCkpt || *pnCkpt==-1 );
  124709. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  124710. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  124711. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  124712. pnLog = 0;
  124713. pnCkpt = 0;
  124714. if( rc==SQLITE_BUSY ){
  124715. bBusy = 1;
  124716. rc = SQLITE_OK;
  124717. }
  124718. }
  124719. }
  124720. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  124721. }
  124722. #endif /* SQLITE_OMIT_WAL */
  124723. /*
  124724. ** This function returns true if main-memory should be used instead of
  124725. ** a temporary file for transient pager files and statement journals.
  124726. ** The value returned depends on the value of db->temp_store (runtime
  124727. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  124728. ** following table describes the relationship between these two values
  124729. ** and this functions return value.
  124730. **
  124731. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  124732. ** ----------------- -------------- ------------------------------
  124733. ** 0 any file (return 0)
  124734. ** 1 1 file (return 0)
  124735. ** 1 2 memory (return 1)
  124736. ** 1 0 file (return 0)
  124737. ** 2 1 file (return 0)
  124738. ** 2 2 memory (return 1)
  124739. ** 2 0 memory (return 1)
  124740. ** 3 any memory (return 1)
  124741. */
  124742. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  124743. #if SQLITE_TEMP_STORE==1
  124744. return ( db->temp_store==2 );
  124745. #endif
  124746. #if SQLITE_TEMP_STORE==2
  124747. return ( db->temp_store!=1 );
  124748. #endif
  124749. #if SQLITE_TEMP_STORE==3
  124750. UNUSED_PARAMETER(db);
  124751. return 1;
  124752. #endif
  124753. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  124754. UNUSED_PARAMETER(db);
  124755. return 0;
  124756. #endif
  124757. }
  124758. /*
  124759. ** Return UTF-8 encoded English language explanation of the most recent
  124760. ** error.
  124761. */
  124762. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
  124763. const char *z;
  124764. if( !db ){
  124765. return sqlite3ErrStr(SQLITE_NOMEM);
  124766. }
  124767. if( !sqlite3SafetyCheckSickOrOk(db) ){
  124768. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  124769. }
  124770. sqlite3_mutex_enter(db->mutex);
  124771. if( db->mallocFailed ){
  124772. z = sqlite3ErrStr(SQLITE_NOMEM);
  124773. }else{
  124774. testcase( db->pErr==0 );
  124775. z = (char*)sqlite3_value_text(db->pErr);
  124776. assert( !db->mallocFailed );
  124777. if( z==0 ){
  124778. z = sqlite3ErrStr(db->errCode);
  124779. }
  124780. }
  124781. sqlite3_mutex_leave(db->mutex);
  124782. return z;
  124783. }
  124784. #ifndef SQLITE_OMIT_UTF16
  124785. /*
  124786. ** Return UTF-16 encoded English language explanation of the most recent
  124787. ** error.
  124788. */
  124789. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
  124790. static const u16 outOfMem[] = {
  124791. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  124792. };
  124793. static const u16 misuse[] = {
  124794. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  124795. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  124796. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  124797. 'o', 'u', 't', ' ',
  124798. 'o', 'f', ' ',
  124799. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  124800. };
  124801. const void *z;
  124802. if( !db ){
  124803. return (void *)outOfMem;
  124804. }
  124805. if( !sqlite3SafetyCheckSickOrOk(db) ){
  124806. return (void *)misuse;
  124807. }
  124808. sqlite3_mutex_enter(db->mutex);
  124809. if( db->mallocFailed ){
  124810. z = (void *)outOfMem;
  124811. }else{
  124812. z = sqlite3_value_text16(db->pErr);
  124813. if( z==0 ){
  124814. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  124815. z = sqlite3_value_text16(db->pErr);
  124816. }
  124817. /* A malloc() may have failed within the call to sqlite3_value_text16()
  124818. ** above. If this is the case, then the db->mallocFailed flag needs to
  124819. ** be cleared before returning. Do this directly, instead of via
  124820. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  124821. */
  124822. db->mallocFailed = 0;
  124823. }
  124824. sqlite3_mutex_leave(db->mutex);
  124825. return z;
  124826. }
  124827. #endif /* SQLITE_OMIT_UTF16 */
  124828. /*
  124829. ** Return the most recent error code generated by an SQLite routine. If NULL is
  124830. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  124831. */
  124832. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
  124833. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  124834. return SQLITE_MISUSE_BKPT;
  124835. }
  124836. if( !db || db->mallocFailed ){
  124837. return SQLITE_NOMEM;
  124838. }
  124839. return db->errCode & db->errMask;
  124840. }
  124841. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
  124842. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  124843. return SQLITE_MISUSE_BKPT;
  124844. }
  124845. if( !db || db->mallocFailed ){
  124846. return SQLITE_NOMEM;
  124847. }
  124848. return db->errCode;
  124849. }
  124850. /*
  124851. ** Return a string that describes the kind of error specified in the
  124852. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  124853. ** function.
  124854. */
  124855. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
  124856. return sqlite3ErrStr(rc);
  124857. }
  124858. /*
  124859. ** Create a new collating function for database "db". The name is zName
  124860. ** and the encoding is enc.
  124861. */
  124862. static int createCollation(
  124863. sqlite3* db,
  124864. const char *zName,
  124865. u8 enc,
  124866. void* pCtx,
  124867. int(*xCompare)(void*,int,const void*,int,const void*),
  124868. void(*xDel)(void*)
  124869. ){
  124870. CollSeq *pColl;
  124871. int enc2;
  124872. assert( sqlite3_mutex_held(db->mutex) );
  124873. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  124874. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  124875. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  124876. */
  124877. enc2 = enc;
  124878. testcase( enc2==SQLITE_UTF16 );
  124879. testcase( enc2==SQLITE_UTF16_ALIGNED );
  124880. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  124881. enc2 = SQLITE_UTF16NATIVE;
  124882. }
  124883. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  124884. return SQLITE_MISUSE_BKPT;
  124885. }
  124886. /* Check if this call is removing or replacing an existing collation
  124887. ** sequence. If so, and there are active VMs, return busy. If there
  124888. ** are no active VMs, invalidate any pre-compiled statements.
  124889. */
  124890. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  124891. if( pColl && pColl->xCmp ){
  124892. if( db->nVdbeActive ){
  124893. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  124894. "unable to delete/modify collation sequence due to active statements");
  124895. return SQLITE_BUSY;
  124896. }
  124897. sqlite3ExpirePreparedStatements(db);
  124898. /* If collation sequence pColl was created directly by a call to
  124899. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  124900. ** then any copies made by synthCollSeq() need to be invalidated.
  124901. ** Also, collation destructor - CollSeq.xDel() - function may need
  124902. ** to be called.
  124903. */
  124904. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  124905. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  124906. int j;
  124907. for(j=0; j<3; j++){
  124908. CollSeq *p = &aColl[j];
  124909. if( p->enc==pColl->enc ){
  124910. if( p->xDel ){
  124911. p->xDel(p->pUser);
  124912. }
  124913. p->xCmp = 0;
  124914. }
  124915. }
  124916. }
  124917. }
  124918. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  124919. if( pColl==0 ) return SQLITE_NOMEM;
  124920. pColl->xCmp = xCompare;
  124921. pColl->pUser = pCtx;
  124922. pColl->xDel = xDel;
  124923. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  124924. sqlite3Error(db, SQLITE_OK);
  124925. return SQLITE_OK;
  124926. }
  124927. /*
  124928. ** This array defines hard upper bounds on limit values. The
  124929. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  124930. ** #defines in sqlite3.h.
  124931. */
  124932. static const int aHardLimit[] = {
  124933. SQLITE_MAX_LENGTH,
  124934. SQLITE_MAX_SQL_LENGTH,
  124935. SQLITE_MAX_COLUMN,
  124936. SQLITE_MAX_EXPR_DEPTH,
  124937. SQLITE_MAX_COMPOUND_SELECT,
  124938. SQLITE_MAX_VDBE_OP,
  124939. SQLITE_MAX_FUNCTION_ARG,
  124940. SQLITE_MAX_ATTACHED,
  124941. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  124942. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  124943. SQLITE_MAX_TRIGGER_DEPTH,
  124944. SQLITE_MAX_WORKER_THREADS,
  124945. };
  124946. /*
  124947. ** Make sure the hard limits are set to reasonable values
  124948. */
  124949. #if SQLITE_MAX_LENGTH<100
  124950. # error SQLITE_MAX_LENGTH must be at least 100
  124951. #endif
  124952. #if SQLITE_MAX_SQL_LENGTH<100
  124953. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  124954. #endif
  124955. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  124956. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  124957. #endif
  124958. #if SQLITE_MAX_COMPOUND_SELECT<2
  124959. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  124960. #endif
  124961. #if SQLITE_MAX_VDBE_OP<40
  124962. # error SQLITE_MAX_VDBE_OP must be at least 40
  124963. #endif
  124964. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  124965. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  124966. #endif
  124967. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  124968. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  124969. #endif
  124970. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  124971. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  124972. #endif
  124973. #if SQLITE_MAX_COLUMN>32767
  124974. # error SQLITE_MAX_COLUMN must not exceed 32767
  124975. #endif
  124976. #if SQLITE_MAX_TRIGGER_DEPTH<1
  124977. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  124978. #endif
  124979. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  124980. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  124981. #endif
  124982. /*
  124983. ** Change the value of a limit. Report the old value.
  124984. ** If an invalid limit index is supplied, report -1.
  124985. ** Make no changes but still report the old value if the
  124986. ** new limit is negative.
  124987. **
  124988. ** A new lower limit does not shrink existing constructs.
  124989. ** It merely prevents new constructs that exceed the limit
  124990. ** from forming.
  124991. */
  124992. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  124993. int oldLimit;
  124994. #ifdef SQLITE_ENABLE_API_ARMOR
  124995. if( !sqlite3SafetyCheckOk(db) ){
  124996. (void)SQLITE_MISUSE_BKPT;
  124997. return -1;
  124998. }
  124999. #endif
  125000. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  125001. ** there is a hard upper bound set at compile-time by a C preprocessor
  125002. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  125003. ** "_MAX_".)
  125004. */
  125005. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  125006. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  125007. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  125008. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  125009. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  125010. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  125011. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  125012. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  125013. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  125014. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  125015. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  125016. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  125017. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  125018. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  125019. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  125020. return -1;
  125021. }
  125022. oldLimit = db->aLimit[limitId];
  125023. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  125024. if( newLimit>aHardLimit[limitId] ){
  125025. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  125026. }
  125027. db->aLimit[limitId] = newLimit;
  125028. }
  125029. return oldLimit; /* IMP: R-53341-35419 */
  125030. }
  125031. /*
  125032. ** This function is used to parse both URIs and non-URI filenames passed by the
  125033. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  125034. ** URIs specified as part of ATTACH statements.
  125035. **
  125036. ** The first argument to this function is the name of the VFS to use (or
  125037. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  125038. ** query parameter. The second argument contains the URI (or non-URI filename)
  125039. ** itself. When this function is called the *pFlags variable should contain
  125040. ** the default flags to open the database handle with. The value stored in
  125041. ** *pFlags may be updated before returning if the URI filename contains
  125042. ** "cache=xxx" or "mode=xxx" query parameters.
  125043. **
  125044. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  125045. ** the VFS that should be used to open the database file. *pzFile is set to
  125046. ** point to a buffer containing the name of the file to open. It is the
  125047. ** responsibility of the caller to eventually call sqlite3_free() to release
  125048. ** this buffer.
  125049. **
  125050. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  125051. ** may be set to point to a buffer containing an English language error
  125052. ** message. It is the responsibility of the caller to eventually release
  125053. ** this buffer by calling sqlite3_free().
  125054. */
  125055. SQLITE_PRIVATE int sqlite3ParseUri(
  125056. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  125057. const char *zUri, /* Nul-terminated URI to parse */
  125058. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  125059. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  125060. char **pzFile, /* OUT: Filename component of URI */
  125061. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  125062. ){
  125063. int rc = SQLITE_OK;
  125064. unsigned int flags = *pFlags;
  125065. const char *zVfs = zDefaultVfs;
  125066. char *zFile;
  125067. char c;
  125068. int nUri = sqlite3Strlen30(zUri);
  125069. assert( *pzErrMsg==0 );
  125070. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  125071. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  125072. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  125073. ){
  125074. char *zOpt;
  125075. int eState; /* Parser state when parsing URI */
  125076. int iIn; /* Input character index */
  125077. int iOut = 0; /* Output character index */
  125078. u64 nByte = nUri+2; /* Bytes of space to allocate */
  125079. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  125080. ** method that there may be extra parameters following the file-name. */
  125081. flags |= SQLITE_OPEN_URI;
  125082. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  125083. zFile = sqlite3_malloc64(nByte);
  125084. if( !zFile ) return SQLITE_NOMEM;
  125085. iIn = 5;
  125086. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  125087. if( strncmp(zUri+5, "///", 3)==0 ){
  125088. iIn = 7;
  125089. /* The following condition causes URIs with five leading / characters
  125090. ** like file://///host/path to be converted into UNCs like //host/path.
  125091. ** The correct URI for that UNC has only two or four leading / characters
  125092. ** file://host/path or file:////host/path. But 5 leading slashes is a
  125093. ** common error, we are told, so we handle it as a special case. */
  125094. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  125095. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  125096. iIn = 16;
  125097. }
  125098. #else
  125099. /* Discard the scheme and authority segments of the URI. */
  125100. if( zUri[5]=='/' && zUri[6]=='/' ){
  125101. iIn = 7;
  125102. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  125103. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  125104. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  125105. iIn-7, &zUri[7]);
  125106. rc = SQLITE_ERROR;
  125107. goto parse_uri_out;
  125108. }
  125109. }
  125110. #endif
  125111. /* Copy the filename and any query parameters into the zFile buffer.
  125112. ** Decode %HH escape codes along the way.
  125113. **
  125114. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  125115. ** on the parsing context. As follows:
  125116. **
  125117. ** 0: Parsing file-name.
  125118. ** 1: Parsing name section of a name=value query parameter.
  125119. ** 2: Parsing value section of a name=value query parameter.
  125120. */
  125121. eState = 0;
  125122. while( (c = zUri[iIn])!=0 && c!='#' ){
  125123. iIn++;
  125124. if( c=='%'
  125125. && sqlite3Isxdigit(zUri[iIn])
  125126. && sqlite3Isxdigit(zUri[iIn+1])
  125127. ){
  125128. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  125129. octet += sqlite3HexToInt(zUri[iIn++]);
  125130. assert( octet>=0 && octet<256 );
  125131. if( octet==0 ){
  125132. /* This branch is taken when "%00" appears within the URI. In this
  125133. ** case we ignore all text in the remainder of the path, name or
  125134. ** value currently being parsed. So ignore the current character
  125135. ** and skip to the next "?", "=" or "&", as appropriate. */
  125136. while( (c = zUri[iIn])!=0 && c!='#'
  125137. && (eState!=0 || c!='?')
  125138. && (eState!=1 || (c!='=' && c!='&'))
  125139. && (eState!=2 || c!='&')
  125140. ){
  125141. iIn++;
  125142. }
  125143. continue;
  125144. }
  125145. c = octet;
  125146. }else if( eState==1 && (c=='&' || c=='=') ){
  125147. if( zFile[iOut-1]==0 ){
  125148. /* An empty option name. Ignore this option altogether. */
  125149. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  125150. continue;
  125151. }
  125152. if( c=='&' ){
  125153. zFile[iOut++] = '\0';
  125154. }else{
  125155. eState = 2;
  125156. }
  125157. c = 0;
  125158. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  125159. c = 0;
  125160. eState = 1;
  125161. }
  125162. zFile[iOut++] = c;
  125163. }
  125164. if( eState==1 ) zFile[iOut++] = '\0';
  125165. zFile[iOut++] = '\0';
  125166. zFile[iOut++] = '\0';
  125167. /* Check if there were any options specified that should be interpreted
  125168. ** here. Options that are interpreted here include "vfs" and those that
  125169. ** correspond to flags that may be passed to the sqlite3_open_v2()
  125170. ** method. */
  125171. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  125172. while( zOpt[0] ){
  125173. int nOpt = sqlite3Strlen30(zOpt);
  125174. char *zVal = &zOpt[nOpt+1];
  125175. int nVal = sqlite3Strlen30(zVal);
  125176. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  125177. zVfs = zVal;
  125178. }else{
  125179. struct OpenMode {
  125180. const char *z;
  125181. int mode;
  125182. } *aMode = 0;
  125183. char *zModeType = 0;
  125184. int mask = 0;
  125185. int limit = 0;
  125186. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  125187. static struct OpenMode aCacheMode[] = {
  125188. { "shared", SQLITE_OPEN_SHAREDCACHE },
  125189. { "private", SQLITE_OPEN_PRIVATECACHE },
  125190. { 0, 0 }
  125191. };
  125192. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  125193. aMode = aCacheMode;
  125194. limit = mask;
  125195. zModeType = "cache";
  125196. }
  125197. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  125198. static struct OpenMode aOpenMode[] = {
  125199. { "ro", SQLITE_OPEN_READONLY },
  125200. { "rw", SQLITE_OPEN_READWRITE },
  125201. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  125202. { "memory", SQLITE_OPEN_MEMORY },
  125203. { 0, 0 }
  125204. };
  125205. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  125206. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  125207. aMode = aOpenMode;
  125208. limit = mask & flags;
  125209. zModeType = "access";
  125210. }
  125211. if( aMode ){
  125212. int i;
  125213. int mode = 0;
  125214. for(i=0; aMode[i].z; i++){
  125215. const char *z = aMode[i].z;
  125216. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  125217. mode = aMode[i].mode;
  125218. break;
  125219. }
  125220. }
  125221. if( mode==0 ){
  125222. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  125223. rc = SQLITE_ERROR;
  125224. goto parse_uri_out;
  125225. }
  125226. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  125227. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  125228. zModeType, zVal);
  125229. rc = SQLITE_PERM;
  125230. goto parse_uri_out;
  125231. }
  125232. flags = (flags & ~mask) | mode;
  125233. }
  125234. }
  125235. zOpt = &zVal[nVal+1];
  125236. }
  125237. }else{
  125238. zFile = sqlite3_malloc64(nUri+2);
  125239. if( !zFile ) return SQLITE_NOMEM;
  125240. memcpy(zFile, zUri, nUri);
  125241. zFile[nUri] = '\0';
  125242. zFile[nUri+1] = '\0';
  125243. flags &= ~SQLITE_OPEN_URI;
  125244. }
  125245. *ppVfs = sqlite3_vfs_find(zVfs);
  125246. if( *ppVfs==0 ){
  125247. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  125248. rc = SQLITE_ERROR;
  125249. }
  125250. parse_uri_out:
  125251. if( rc!=SQLITE_OK ){
  125252. sqlite3_free(zFile);
  125253. zFile = 0;
  125254. }
  125255. *pFlags = flags;
  125256. *pzFile = zFile;
  125257. return rc;
  125258. }
  125259. /*
  125260. ** This routine does the work of opening a database on behalf of
  125261. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  125262. ** is UTF-8 encoded.
  125263. */
  125264. static int openDatabase(
  125265. const char *zFilename, /* Database filename UTF-8 encoded */
  125266. sqlite3 **ppDb, /* OUT: Returned database handle */
  125267. unsigned int flags, /* Operational flags */
  125268. const char *zVfs /* Name of the VFS to use */
  125269. ){
  125270. sqlite3 *db; /* Store allocated handle here */
  125271. int rc; /* Return code */
  125272. int isThreadsafe; /* True for threadsafe connections */
  125273. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  125274. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  125275. #ifdef SQLITE_ENABLE_API_ARMOR
  125276. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  125277. #endif
  125278. *ppDb = 0;
  125279. #ifndef SQLITE_OMIT_AUTOINIT
  125280. rc = sqlite3_initialize();
  125281. if( rc ) return rc;
  125282. #endif
  125283. /* Only allow sensible combinations of bits in the flags argument.
  125284. ** Throw an error if any non-sense combination is used. If we
  125285. ** do not block illegal combinations here, it could trigger
  125286. ** assert() statements in deeper layers. Sensible combinations
  125287. ** are:
  125288. **
  125289. ** 1: SQLITE_OPEN_READONLY
  125290. ** 2: SQLITE_OPEN_READWRITE
  125291. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  125292. */
  125293. assert( SQLITE_OPEN_READONLY == 0x01 );
  125294. assert( SQLITE_OPEN_READWRITE == 0x02 );
  125295. assert( SQLITE_OPEN_CREATE == 0x04 );
  125296. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  125297. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  125298. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  125299. if( ((1<<(flags&7)) & 0x46)==0 ){
  125300. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  125301. }
  125302. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  125303. isThreadsafe = 0;
  125304. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  125305. isThreadsafe = 0;
  125306. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  125307. isThreadsafe = 1;
  125308. }else{
  125309. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  125310. }
  125311. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  125312. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  125313. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  125314. flags |= SQLITE_OPEN_SHAREDCACHE;
  125315. }
  125316. /* Remove harmful bits from the flags parameter
  125317. **
  125318. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  125319. ** dealt with in the previous code block. Besides these, the only
  125320. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  125321. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  125322. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  125323. ** off all other flags.
  125324. */
  125325. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  125326. SQLITE_OPEN_EXCLUSIVE |
  125327. SQLITE_OPEN_MAIN_DB |
  125328. SQLITE_OPEN_TEMP_DB |
  125329. SQLITE_OPEN_TRANSIENT_DB |
  125330. SQLITE_OPEN_MAIN_JOURNAL |
  125331. SQLITE_OPEN_TEMP_JOURNAL |
  125332. SQLITE_OPEN_SUBJOURNAL |
  125333. SQLITE_OPEN_MASTER_JOURNAL |
  125334. SQLITE_OPEN_NOMUTEX |
  125335. SQLITE_OPEN_FULLMUTEX |
  125336. SQLITE_OPEN_WAL
  125337. );
  125338. /* Allocate the sqlite data structure */
  125339. db = sqlite3MallocZero( sizeof(sqlite3) );
  125340. if( db==0 ) goto opendb_out;
  125341. if( isThreadsafe ){
  125342. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  125343. if( db->mutex==0 ){
  125344. sqlite3_free(db);
  125345. db = 0;
  125346. goto opendb_out;
  125347. }
  125348. }
  125349. sqlite3_mutex_enter(db->mutex);
  125350. db->errMask = 0xff;
  125351. db->nDb = 2;
  125352. db->magic = SQLITE_MAGIC_BUSY;
  125353. db->aDb = db->aDbStatic;
  125354. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  125355. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  125356. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  125357. db->autoCommit = 1;
  125358. db->nextAutovac = -1;
  125359. db->szMmap = sqlite3GlobalConfig.szMmap;
  125360. db->nextPagesize = 0;
  125361. db->nMaxSorterMmap = 0x7FFFFFFF;
  125362. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  125363. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  125364. | SQLITE_AutoIndex
  125365. #endif
  125366. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  125367. | SQLITE_CkptFullFSync
  125368. #endif
  125369. #if SQLITE_DEFAULT_FILE_FORMAT<4
  125370. | SQLITE_LegacyFileFmt
  125371. #endif
  125372. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  125373. | SQLITE_LoadExtension
  125374. #endif
  125375. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  125376. | SQLITE_RecTriggers
  125377. #endif
  125378. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  125379. | SQLITE_ForeignKeys
  125380. #endif
  125381. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  125382. | SQLITE_ReverseOrder
  125383. #endif
  125384. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  125385. | SQLITE_CellSizeCk
  125386. #endif
  125387. ;
  125388. sqlite3HashInit(&db->aCollSeq);
  125389. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125390. sqlite3HashInit(&db->aModule);
  125391. #endif
  125392. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  125393. ** and UTF-16, so add a version for each to avoid any unnecessary
  125394. ** conversions. The only error that can occur here is a malloc() failure.
  125395. **
  125396. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  125397. ** functions:
  125398. */
  125399. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  125400. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  125401. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  125402. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  125403. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  125404. if( db->mallocFailed ){
  125405. goto opendb_out;
  125406. }
  125407. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  125408. ** strings is BINARY.
  125409. */
  125410. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  125411. assert( db->pDfltColl!=0 );
  125412. /* Parse the filename/URI argument. */
  125413. db->openFlags = flags;
  125414. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  125415. if( rc!=SQLITE_OK ){
  125416. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  125417. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  125418. sqlite3_free(zErrMsg);
  125419. goto opendb_out;
  125420. }
  125421. /* Open the backend database driver */
  125422. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  125423. flags | SQLITE_OPEN_MAIN_DB);
  125424. if( rc!=SQLITE_OK ){
  125425. if( rc==SQLITE_IOERR_NOMEM ){
  125426. rc = SQLITE_NOMEM;
  125427. }
  125428. sqlite3Error(db, rc);
  125429. goto opendb_out;
  125430. }
  125431. sqlite3BtreeEnter(db->aDb[0].pBt);
  125432. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  125433. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  125434. sqlite3BtreeLeave(db->aDb[0].pBt);
  125435. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  125436. /* The default safety_level for the main database is 'full'; for the temp
  125437. ** database it is 'NONE'. This matches the pager layer defaults.
  125438. */
  125439. db->aDb[0].zName = "main";
  125440. db->aDb[0].safety_level = 3;
  125441. db->aDb[1].zName = "temp";
  125442. db->aDb[1].safety_level = 1;
  125443. db->magic = SQLITE_MAGIC_OPEN;
  125444. if( db->mallocFailed ){
  125445. goto opendb_out;
  125446. }
  125447. /* Register all built-in functions, but do not attempt to read the
  125448. ** database schema yet. This is delayed until the first time the database
  125449. ** is accessed.
  125450. */
  125451. sqlite3Error(db, SQLITE_OK);
  125452. sqlite3RegisterBuiltinFunctions(db);
  125453. /* Load automatic extensions - extensions that have been registered
  125454. ** using the sqlite3_automatic_extension() API.
  125455. */
  125456. rc = sqlite3_errcode(db);
  125457. if( rc==SQLITE_OK ){
  125458. sqlite3AutoLoadExtensions(db);
  125459. rc = sqlite3_errcode(db);
  125460. if( rc!=SQLITE_OK ){
  125461. goto opendb_out;
  125462. }
  125463. }
  125464. #ifdef SQLITE_ENABLE_FTS1
  125465. if( !db->mallocFailed ){
  125466. extern int sqlite3Fts1Init(sqlite3*);
  125467. rc = sqlite3Fts1Init(db);
  125468. }
  125469. #endif
  125470. #ifdef SQLITE_ENABLE_FTS2
  125471. if( !db->mallocFailed && rc==SQLITE_OK ){
  125472. extern int sqlite3Fts2Init(sqlite3*);
  125473. rc = sqlite3Fts2Init(db);
  125474. }
  125475. #endif
  125476. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  125477. if( !db->mallocFailed && rc==SQLITE_OK ){
  125478. rc = sqlite3Fts3Init(db);
  125479. }
  125480. #endif
  125481. #ifdef SQLITE_ENABLE_FTS5
  125482. if( !db->mallocFailed && rc==SQLITE_OK ){
  125483. rc = sqlite3Fts5Init(db);
  125484. }
  125485. #endif
  125486. #ifdef SQLITE_ENABLE_ICU
  125487. if( !db->mallocFailed && rc==SQLITE_OK ){
  125488. rc = sqlite3IcuInit(db);
  125489. }
  125490. #endif
  125491. #ifdef SQLITE_ENABLE_RTREE
  125492. if( !db->mallocFailed && rc==SQLITE_OK){
  125493. rc = sqlite3RtreeInit(db);
  125494. }
  125495. #endif
  125496. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  125497. if( !db->mallocFailed && rc==SQLITE_OK){
  125498. rc = sqlite3DbstatRegister(db);
  125499. }
  125500. #endif
  125501. #ifdef SQLITE_ENABLE_JSON1
  125502. if( !db->mallocFailed && rc==SQLITE_OK){
  125503. rc = sqlite3Json1Init(db);
  125504. }
  125505. #endif
  125506. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  125507. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  125508. ** mode. Doing nothing at all also makes NORMAL the default.
  125509. */
  125510. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  125511. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  125512. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  125513. SQLITE_DEFAULT_LOCKING_MODE);
  125514. #endif
  125515. if( rc ) sqlite3Error(db, rc);
  125516. /* Enable the lookaside-malloc subsystem */
  125517. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  125518. sqlite3GlobalConfig.nLookaside);
  125519. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  125520. opendb_out:
  125521. sqlite3_free(zOpen);
  125522. if( db ){
  125523. assert( db->mutex!=0 || isThreadsafe==0
  125524. || sqlite3GlobalConfig.bFullMutex==0 );
  125525. sqlite3_mutex_leave(db->mutex);
  125526. }
  125527. rc = sqlite3_errcode(db);
  125528. assert( db!=0 || rc==SQLITE_NOMEM );
  125529. if( rc==SQLITE_NOMEM ){
  125530. sqlite3_close(db);
  125531. db = 0;
  125532. }else if( rc!=SQLITE_OK ){
  125533. db->magic = SQLITE_MAGIC_SICK;
  125534. }
  125535. *ppDb = db;
  125536. #ifdef SQLITE_ENABLE_SQLLOG
  125537. if( sqlite3GlobalConfig.xSqllog ){
  125538. /* Opening a db handle. Fourth parameter is passed 0. */
  125539. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  125540. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  125541. }
  125542. #endif
  125543. return rc & 0xff;
  125544. }
  125545. /*
  125546. ** Open a new database handle.
  125547. */
  125548. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  125549. const char *zFilename,
  125550. sqlite3 **ppDb
  125551. ){
  125552. return openDatabase(zFilename, ppDb,
  125553. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  125554. }
  125555. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  125556. const char *filename, /* Database filename (UTF-8) */
  125557. sqlite3 **ppDb, /* OUT: SQLite db handle */
  125558. int flags, /* Flags */
  125559. const char *zVfs /* Name of VFS module to use */
  125560. ){
  125561. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  125562. }
  125563. #ifndef SQLITE_OMIT_UTF16
  125564. /*
  125565. ** Open a new database handle.
  125566. */
  125567. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  125568. const void *zFilename,
  125569. sqlite3 **ppDb
  125570. ){
  125571. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  125572. sqlite3_value *pVal;
  125573. int rc;
  125574. #ifdef SQLITE_ENABLE_API_ARMOR
  125575. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  125576. #endif
  125577. *ppDb = 0;
  125578. #ifndef SQLITE_OMIT_AUTOINIT
  125579. rc = sqlite3_initialize();
  125580. if( rc ) return rc;
  125581. #endif
  125582. if( zFilename==0 ) zFilename = "\000\000";
  125583. pVal = sqlite3ValueNew(0);
  125584. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  125585. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  125586. if( zFilename8 ){
  125587. rc = openDatabase(zFilename8, ppDb,
  125588. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  125589. assert( *ppDb || rc==SQLITE_NOMEM );
  125590. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  125591. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  125592. }
  125593. }else{
  125594. rc = SQLITE_NOMEM;
  125595. }
  125596. sqlite3ValueFree(pVal);
  125597. return rc & 0xff;
  125598. }
  125599. #endif /* SQLITE_OMIT_UTF16 */
  125600. /*
  125601. ** Register a new collation sequence with the database handle db.
  125602. */
  125603. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  125604. sqlite3* db,
  125605. const char *zName,
  125606. int enc,
  125607. void* pCtx,
  125608. int(*xCompare)(void*,int,const void*,int,const void*)
  125609. ){
  125610. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  125611. }
  125612. /*
  125613. ** Register a new collation sequence with the database handle db.
  125614. */
  125615. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  125616. sqlite3* db,
  125617. const char *zName,
  125618. int enc,
  125619. void* pCtx,
  125620. int(*xCompare)(void*,int,const void*,int,const void*),
  125621. void(*xDel)(void*)
  125622. ){
  125623. int rc;
  125624. #ifdef SQLITE_ENABLE_API_ARMOR
  125625. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  125626. #endif
  125627. sqlite3_mutex_enter(db->mutex);
  125628. assert( !db->mallocFailed );
  125629. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  125630. rc = sqlite3ApiExit(db, rc);
  125631. sqlite3_mutex_leave(db->mutex);
  125632. return rc;
  125633. }
  125634. #ifndef SQLITE_OMIT_UTF16
  125635. /*
  125636. ** Register a new collation sequence with the database handle db.
  125637. */
  125638. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  125639. sqlite3* db,
  125640. const void *zName,
  125641. int enc,
  125642. void* pCtx,
  125643. int(*xCompare)(void*,int,const void*,int,const void*)
  125644. ){
  125645. int rc = SQLITE_OK;
  125646. char *zName8;
  125647. #ifdef SQLITE_ENABLE_API_ARMOR
  125648. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  125649. #endif
  125650. sqlite3_mutex_enter(db->mutex);
  125651. assert( !db->mallocFailed );
  125652. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  125653. if( zName8 ){
  125654. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  125655. sqlite3DbFree(db, zName8);
  125656. }
  125657. rc = sqlite3ApiExit(db, rc);
  125658. sqlite3_mutex_leave(db->mutex);
  125659. return rc;
  125660. }
  125661. #endif /* SQLITE_OMIT_UTF16 */
  125662. /*
  125663. ** Register a collation sequence factory callback with the database handle
  125664. ** db. Replace any previously installed collation sequence factory.
  125665. */
  125666. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  125667. sqlite3 *db,
  125668. void *pCollNeededArg,
  125669. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  125670. ){
  125671. #ifdef SQLITE_ENABLE_API_ARMOR
  125672. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125673. #endif
  125674. sqlite3_mutex_enter(db->mutex);
  125675. db->xCollNeeded = xCollNeeded;
  125676. db->xCollNeeded16 = 0;
  125677. db->pCollNeededArg = pCollNeededArg;
  125678. sqlite3_mutex_leave(db->mutex);
  125679. return SQLITE_OK;
  125680. }
  125681. #ifndef SQLITE_OMIT_UTF16
  125682. /*
  125683. ** Register a collation sequence factory callback with the database handle
  125684. ** db. Replace any previously installed collation sequence factory.
  125685. */
  125686. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  125687. sqlite3 *db,
  125688. void *pCollNeededArg,
  125689. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  125690. ){
  125691. #ifdef SQLITE_ENABLE_API_ARMOR
  125692. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125693. #endif
  125694. sqlite3_mutex_enter(db->mutex);
  125695. db->xCollNeeded = 0;
  125696. db->xCollNeeded16 = xCollNeeded16;
  125697. db->pCollNeededArg = pCollNeededArg;
  125698. sqlite3_mutex_leave(db->mutex);
  125699. return SQLITE_OK;
  125700. }
  125701. #endif /* SQLITE_OMIT_UTF16 */
  125702. #ifndef SQLITE_OMIT_DEPRECATED
  125703. /*
  125704. ** This function is now an anachronism. It used to be used to recover from a
  125705. ** malloc() failure, but SQLite now does this automatically.
  125706. */
  125707. SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
  125708. return SQLITE_OK;
  125709. }
  125710. #endif
  125711. /*
  125712. ** Test to see whether or not the database connection is in autocommit
  125713. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  125714. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  125715. ** by the next COMMIT or ROLLBACK.
  125716. */
  125717. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
  125718. #ifdef SQLITE_ENABLE_API_ARMOR
  125719. if( !sqlite3SafetyCheckOk(db) ){
  125720. (void)SQLITE_MISUSE_BKPT;
  125721. return 0;
  125722. }
  125723. #endif
  125724. return db->autoCommit;
  125725. }
  125726. /*
  125727. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  125728. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  125729. ** constants. They serve two purposes:
  125730. **
  125731. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  125732. ** to detect when version error conditions occurs.
  125733. **
  125734. ** 2. Invoke sqlite3_log() to provide the source code location where
  125735. ** a low-level error is first detected.
  125736. */
  125737. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  125738. testcase( sqlite3GlobalConfig.xLog!=0 );
  125739. sqlite3_log(SQLITE_CORRUPT,
  125740. "database corruption at line %d of [%.10s]",
  125741. lineno, 20+sqlite3_sourceid());
  125742. return SQLITE_CORRUPT;
  125743. }
  125744. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  125745. testcase( sqlite3GlobalConfig.xLog!=0 );
  125746. sqlite3_log(SQLITE_MISUSE,
  125747. "misuse at line %d of [%.10s]",
  125748. lineno, 20+sqlite3_sourceid());
  125749. return SQLITE_MISUSE;
  125750. }
  125751. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  125752. testcase( sqlite3GlobalConfig.xLog!=0 );
  125753. sqlite3_log(SQLITE_CANTOPEN,
  125754. "cannot open file at line %d of [%.10s]",
  125755. lineno, 20+sqlite3_sourceid());
  125756. return SQLITE_CANTOPEN;
  125757. }
  125758. #ifndef SQLITE_OMIT_DEPRECATED
  125759. /*
  125760. ** This is a convenience routine that makes sure that all thread-specific
  125761. ** data for this thread has been deallocated.
  125762. **
  125763. ** SQLite no longer uses thread-specific data so this routine is now a
  125764. ** no-op. It is retained for historical compatibility.
  125765. */
  125766. SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
  125767. }
  125768. #endif
  125769. /*
  125770. ** Return meta information about a specific column of a database table.
  125771. ** See comment in sqlite3.h (sqlite.h.in) for details.
  125772. */
  125773. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  125774. sqlite3 *db, /* Connection handle */
  125775. const char *zDbName, /* Database name or NULL */
  125776. const char *zTableName, /* Table name */
  125777. const char *zColumnName, /* Column name */
  125778. char const **pzDataType, /* OUTPUT: Declared data type */
  125779. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  125780. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  125781. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  125782. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  125783. ){
  125784. int rc;
  125785. char *zErrMsg = 0;
  125786. Table *pTab = 0;
  125787. Column *pCol = 0;
  125788. int iCol = 0;
  125789. char const *zDataType = 0;
  125790. char const *zCollSeq = 0;
  125791. int notnull = 0;
  125792. int primarykey = 0;
  125793. int autoinc = 0;
  125794. #ifdef SQLITE_ENABLE_API_ARMOR
  125795. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  125796. return SQLITE_MISUSE_BKPT;
  125797. }
  125798. #endif
  125799. /* Ensure the database schema has been loaded */
  125800. sqlite3_mutex_enter(db->mutex);
  125801. sqlite3BtreeEnterAll(db);
  125802. rc = sqlite3Init(db, &zErrMsg);
  125803. if( SQLITE_OK!=rc ){
  125804. goto error_out;
  125805. }
  125806. /* Locate the table in question */
  125807. pTab = sqlite3FindTable(db, zTableName, zDbName);
  125808. if( !pTab || pTab->pSelect ){
  125809. pTab = 0;
  125810. goto error_out;
  125811. }
  125812. /* Find the column for which info is requested */
  125813. if( zColumnName==0 ){
  125814. /* Query for existance of table only */
  125815. }else{
  125816. for(iCol=0; iCol<pTab->nCol; iCol++){
  125817. pCol = &pTab->aCol[iCol];
  125818. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  125819. break;
  125820. }
  125821. }
  125822. if( iCol==pTab->nCol ){
  125823. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  125824. iCol = pTab->iPKey;
  125825. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  125826. }else{
  125827. pTab = 0;
  125828. goto error_out;
  125829. }
  125830. }
  125831. }
  125832. /* The following block stores the meta information that will be returned
  125833. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  125834. ** and autoinc. At this point there are two possibilities:
  125835. **
  125836. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  125837. ** and there is no explicitly declared IPK column.
  125838. **
  125839. ** 2. The table is not a view and the column name identified an
  125840. ** explicitly declared column. Copy meta information from *pCol.
  125841. */
  125842. if( pCol ){
  125843. zDataType = pCol->zType;
  125844. zCollSeq = pCol->zColl;
  125845. notnull = pCol->notNull!=0;
  125846. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  125847. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  125848. }else{
  125849. zDataType = "INTEGER";
  125850. primarykey = 1;
  125851. }
  125852. if( !zCollSeq ){
  125853. zCollSeq = "BINARY";
  125854. }
  125855. error_out:
  125856. sqlite3BtreeLeaveAll(db);
  125857. /* Whether the function call succeeded or failed, set the output parameters
  125858. ** to whatever their local counterparts contain. If an error did occur,
  125859. ** this has the effect of zeroing all output parameters.
  125860. */
  125861. if( pzDataType ) *pzDataType = zDataType;
  125862. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  125863. if( pNotNull ) *pNotNull = notnull;
  125864. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  125865. if( pAutoinc ) *pAutoinc = autoinc;
  125866. if( SQLITE_OK==rc && !pTab ){
  125867. sqlite3DbFree(db, zErrMsg);
  125868. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  125869. zColumnName);
  125870. rc = SQLITE_ERROR;
  125871. }
  125872. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  125873. sqlite3DbFree(db, zErrMsg);
  125874. rc = sqlite3ApiExit(db, rc);
  125875. sqlite3_mutex_leave(db->mutex);
  125876. return rc;
  125877. }
  125878. /*
  125879. ** Sleep for a little while. Return the amount of time slept.
  125880. */
  125881. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
  125882. sqlite3_vfs *pVfs;
  125883. int rc;
  125884. pVfs = sqlite3_vfs_find(0);
  125885. if( pVfs==0 ) return 0;
  125886. /* This function works in milliseconds, but the underlying OsSleep()
  125887. ** API uses microseconds. Hence the 1000's.
  125888. */
  125889. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  125890. return rc;
  125891. }
  125892. /*
  125893. ** Enable or disable the extended result codes.
  125894. */
  125895. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  125896. #ifdef SQLITE_ENABLE_API_ARMOR
  125897. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125898. #endif
  125899. sqlite3_mutex_enter(db->mutex);
  125900. db->errMask = onoff ? 0xffffffff : 0xff;
  125901. sqlite3_mutex_leave(db->mutex);
  125902. return SQLITE_OK;
  125903. }
  125904. /*
  125905. ** Invoke the xFileControl method on a particular database.
  125906. */
  125907. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  125908. int rc = SQLITE_ERROR;
  125909. Btree *pBtree;
  125910. #ifdef SQLITE_ENABLE_API_ARMOR
  125911. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125912. #endif
  125913. sqlite3_mutex_enter(db->mutex);
  125914. pBtree = sqlite3DbNameToBtree(db, zDbName);
  125915. if( pBtree ){
  125916. Pager *pPager;
  125917. sqlite3_file *fd;
  125918. sqlite3BtreeEnter(pBtree);
  125919. pPager = sqlite3BtreePager(pBtree);
  125920. assert( pPager!=0 );
  125921. fd = sqlite3PagerFile(pPager);
  125922. assert( fd!=0 );
  125923. if( op==SQLITE_FCNTL_FILE_POINTER ){
  125924. *(sqlite3_file**)pArg = fd;
  125925. rc = SQLITE_OK;
  125926. }else if( fd->pMethods ){
  125927. rc = sqlite3OsFileControl(fd, op, pArg);
  125928. }else{
  125929. rc = SQLITE_NOTFOUND;
  125930. }
  125931. sqlite3BtreeLeave(pBtree);
  125932. }
  125933. sqlite3_mutex_leave(db->mutex);
  125934. return rc;
  125935. }
  125936. /*
  125937. ** Interface to the testing logic.
  125938. */
  125939. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
  125940. int rc = 0;
  125941. #ifdef SQLITE_OMIT_BUILTIN_TEST
  125942. UNUSED_PARAMETER(op);
  125943. #else
  125944. va_list ap;
  125945. va_start(ap, op);
  125946. switch( op ){
  125947. /*
  125948. ** Save the current state of the PRNG.
  125949. */
  125950. case SQLITE_TESTCTRL_PRNG_SAVE: {
  125951. sqlite3PrngSaveState();
  125952. break;
  125953. }
  125954. /*
  125955. ** Restore the state of the PRNG to the last state saved using
  125956. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  125957. ** this verb acts like PRNG_RESET.
  125958. */
  125959. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  125960. sqlite3PrngRestoreState();
  125961. break;
  125962. }
  125963. /*
  125964. ** Reset the PRNG back to its uninitialized state. The next call
  125965. ** to sqlite3_randomness() will reseed the PRNG using a single call
  125966. ** to the xRandomness method of the default VFS.
  125967. */
  125968. case SQLITE_TESTCTRL_PRNG_RESET: {
  125969. sqlite3_randomness(0,0);
  125970. break;
  125971. }
  125972. /*
  125973. ** sqlite3_test_control(BITVEC_TEST, size, program)
  125974. **
  125975. ** Run a test against a Bitvec object of size. The program argument
  125976. ** is an array of integers that defines the test. Return -1 on a
  125977. ** memory allocation error, 0 on success, or non-zero for an error.
  125978. ** See the sqlite3BitvecBuiltinTest() for additional information.
  125979. */
  125980. case SQLITE_TESTCTRL_BITVEC_TEST: {
  125981. int sz = va_arg(ap, int);
  125982. int *aProg = va_arg(ap, int*);
  125983. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  125984. break;
  125985. }
  125986. /*
  125987. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  125988. **
  125989. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  125990. ** if xCallback is not NULL.
  125991. **
  125992. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  125993. ** is called immediately after installing the new callback and the return
  125994. ** value from sqlite3FaultSim(0) becomes the return from
  125995. ** sqlite3_test_control().
  125996. */
  125997. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  125998. /* MSVC is picky about pulling func ptrs from va lists.
  125999. ** http://support.microsoft.com/kb/47961
  126000. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  126001. */
  126002. typedef int(*TESTCALLBACKFUNC_t)(int);
  126003. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  126004. rc = sqlite3FaultSim(0);
  126005. break;
  126006. }
  126007. /*
  126008. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  126009. **
  126010. ** Register hooks to call to indicate which malloc() failures
  126011. ** are benign.
  126012. */
  126013. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  126014. typedef void (*void_function)(void);
  126015. void_function xBenignBegin;
  126016. void_function xBenignEnd;
  126017. xBenignBegin = va_arg(ap, void_function);
  126018. xBenignEnd = va_arg(ap, void_function);
  126019. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  126020. break;
  126021. }
  126022. /*
  126023. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  126024. **
  126025. ** Set the PENDING byte to the value in the argument, if X>0.
  126026. ** Make no changes if X==0. Return the value of the pending byte
  126027. ** as it existing before this routine was called.
  126028. **
  126029. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  126030. ** an incompatible database file format. Changing the PENDING byte
  126031. ** while any database connection is open results in undefined and
  126032. ** deleterious behavior.
  126033. */
  126034. case SQLITE_TESTCTRL_PENDING_BYTE: {
  126035. rc = PENDING_BYTE;
  126036. #ifndef SQLITE_OMIT_WSD
  126037. {
  126038. unsigned int newVal = va_arg(ap, unsigned int);
  126039. if( newVal ) sqlite3PendingByte = newVal;
  126040. }
  126041. #endif
  126042. break;
  126043. }
  126044. /*
  126045. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  126046. **
  126047. ** This action provides a run-time test to see whether or not
  126048. ** assert() was enabled at compile-time. If X is true and assert()
  126049. ** is enabled, then the return value is true. If X is true and
  126050. ** assert() is disabled, then the return value is zero. If X is
  126051. ** false and assert() is enabled, then the assertion fires and the
  126052. ** process aborts. If X is false and assert() is disabled, then the
  126053. ** return value is zero.
  126054. */
  126055. case SQLITE_TESTCTRL_ASSERT: {
  126056. volatile int x = 0;
  126057. assert( (x = va_arg(ap,int))!=0 );
  126058. rc = x;
  126059. break;
  126060. }
  126061. /*
  126062. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  126063. **
  126064. ** This action provides a run-time test to see how the ALWAYS and
  126065. ** NEVER macros were defined at compile-time.
  126066. **
  126067. ** The return value is ALWAYS(X).
  126068. **
  126069. ** The recommended test is X==2. If the return value is 2, that means
  126070. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  126071. ** default setting. If the return value is 1, then ALWAYS() is either
  126072. ** hard-coded to true or else it asserts if its argument is false.
  126073. ** The first behavior (hard-coded to true) is the case if
  126074. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  126075. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  126076. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  126077. **
  126078. ** The run-time test procedure might look something like this:
  126079. **
  126080. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  126081. ** // ALWAYS() and NEVER() are no-op pass-through macros
  126082. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  126083. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  126084. ** }else{
  126085. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  126086. ** }
  126087. */
  126088. case SQLITE_TESTCTRL_ALWAYS: {
  126089. int x = va_arg(ap,int);
  126090. rc = ALWAYS(x);
  126091. break;
  126092. }
  126093. /*
  126094. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  126095. **
  126096. ** The integer returned reveals the byte-order of the computer on which
  126097. ** SQLite is running:
  126098. **
  126099. ** 1 big-endian, determined at run-time
  126100. ** 10 little-endian, determined at run-time
  126101. ** 432101 big-endian, determined at compile-time
  126102. ** 123410 little-endian, determined at compile-time
  126103. */
  126104. case SQLITE_TESTCTRL_BYTEORDER: {
  126105. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  126106. break;
  126107. }
  126108. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  126109. **
  126110. ** Set the nReserve size to N for the main database on the database
  126111. ** connection db.
  126112. */
  126113. case SQLITE_TESTCTRL_RESERVE: {
  126114. sqlite3 *db = va_arg(ap, sqlite3*);
  126115. int x = va_arg(ap,int);
  126116. sqlite3_mutex_enter(db->mutex);
  126117. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  126118. sqlite3_mutex_leave(db->mutex);
  126119. break;
  126120. }
  126121. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  126122. **
  126123. ** Enable or disable various optimizations for testing purposes. The
  126124. ** argument N is a bitmask of optimizations to be disabled. For normal
  126125. ** operation N should be 0. The idea is that a test program (like the
  126126. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  126127. ** with various optimizations disabled to verify that the same answer
  126128. ** is obtained in every case.
  126129. */
  126130. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  126131. sqlite3 *db = va_arg(ap, sqlite3*);
  126132. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  126133. break;
  126134. }
  126135. #ifdef SQLITE_N_KEYWORD
  126136. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  126137. **
  126138. ** If zWord is a keyword recognized by the parser, then return the
  126139. ** number of keywords. Or if zWord is not a keyword, return 0.
  126140. **
  126141. ** This test feature is only available in the amalgamation since
  126142. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  126143. ** is built using separate source files.
  126144. */
  126145. case SQLITE_TESTCTRL_ISKEYWORD: {
  126146. const char *zWord = va_arg(ap, const char*);
  126147. int n = sqlite3Strlen30(zWord);
  126148. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  126149. break;
  126150. }
  126151. #endif
  126152. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  126153. **
  126154. ** Pass pFree into sqlite3ScratchFree().
  126155. ** If sz>0 then allocate a scratch buffer into pNew.
  126156. */
  126157. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  126158. void *pFree, **ppNew;
  126159. int sz;
  126160. sz = va_arg(ap, int);
  126161. ppNew = va_arg(ap, void**);
  126162. pFree = va_arg(ap, void*);
  126163. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  126164. sqlite3ScratchFree(pFree);
  126165. break;
  126166. }
  126167. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  126168. **
  126169. ** If parameter onoff is non-zero, configure the wrappers so that all
  126170. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  126171. ** undo this setting.
  126172. */
  126173. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  126174. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  126175. break;
  126176. }
  126177. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  126178. **
  126179. ** Set or clear a flag that indicates that the database file is always well-
  126180. ** formed and never corrupt. This flag is clear by default, indicating that
  126181. ** database files might have arbitrary corruption. Setting the flag during
  126182. ** testing causes certain assert() statements in the code to be activated
  126183. ** that demonstrat invariants on well-formed database files.
  126184. */
  126185. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  126186. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  126187. break;
  126188. }
  126189. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  126190. **
  126191. ** Set the VDBE coverage callback function to xCallback with context
  126192. ** pointer ptr.
  126193. */
  126194. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  126195. #ifdef SQLITE_VDBE_COVERAGE
  126196. typedef void (*branch_callback)(void*,int,u8,u8);
  126197. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  126198. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  126199. #endif
  126200. break;
  126201. }
  126202. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  126203. case SQLITE_TESTCTRL_SORTER_MMAP: {
  126204. sqlite3 *db = va_arg(ap, sqlite3*);
  126205. db->nMaxSorterMmap = va_arg(ap, int);
  126206. break;
  126207. }
  126208. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  126209. **
  126210. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  126211. ** not.
  126212. */
  126213. case SQLITE_TESTCTRL_ISINIT: {
  126214. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  126215. break;
  126216. }
  126217. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  126218. **
  126219. ** This test control is used to create imposter tables. "db" is a pointer
  126220. ** to the database connection. dbName is the database name (ex: "main" or
  126221. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  126222. ** or off. "tnum" is the root page of the b-tree to which the imposter
  126223. ** table should connect.
  126224. **
  126225. ** Enable imposter mode only when the schema has already been parsed. Then
  126226. ** run a single CREATE TABLE statement to construct the imposter table in
  126227. ** the parsed schema. Then turn imposter mode back off again.
  126228. **
  126229. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  126230. ** the schema to be reparsed the next time it is needed. This has the
  126231. ** effect of erasing all imposter tables.
  126232. */
  126233. case SQLITE_TESTCTRL_IMPOSTER: {
  126234. sqlite3 *db = va_arg(ap, sqlite3*);
  126235. sqlite3_mutex_enter(db->mutex);
  126236. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  126237. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  126238. db->init.newTnum = va_arg(ap,int);
  126239. if( db->init.busy==0 && db->init.newTnum>0 ){
  126240. sqlite3ResetAllSchemasOfConnection(db);
  126241. }
  126242. sqlite3_mutex_leave(db->mutex);
  126243. break;
  126244. }
  126245. }
  126246. va_end(ap);
  126247. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  126248. return rc;
  126249. }
  126250. /*
  126251. ** This is a utility routine, useful to VFS implementations, that checks
  126252. ** to see if a database file was a URI that contained a specific query
  126253. ** parameter, and if so obtains the value of the query parameter.
  126254. **
  126255. ** The zFilename argument is the filename pointer passed into the xOpen()
  126256. ** method of a VFS implementation. The zParam argument is the name of the
  126257. ** query parameter we seek. This routine returns the value of the zParam
  126258. ** parameter if it exists. If the parameter does not exist, this routine
  126259. ** returns a NULL pointer.
  126260. */
  126261. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  126262. if( zFilename==0 || zParam==0 ) return 0;
  126263. zFilename += sqlite3Strlen30(zFilename) + 1;
  126264. while( zFilename[0] ){
  126265. int x = strcmp(zFilename, zParam);
  126266. zFilename += sqlite3Strlen30(zFilename) + 1;
  126267. if( x==0 ) return zFilename;
  126268. zFilename += sqlite3Strlen30(zFilename) + 1;
  126269. }
  126270. return 0;
  126271. }
  126272. /*
  126273. ** Return a boolean value for a query parameter.
  126274. */
  126275. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  126276. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  126277. bDflt = bDflt!=0;
  126278. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  126279. }
  126280. /*
  126281. ** Return a 64-bit integer value for a query parameter.
  126282. */
  126283. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
  126284. const char *zFilename, /* Filename as passed to xOpen */
  126285. const char *zParam, /* URI parameter sought */
  126286. sqlite3_int64 bDflt /* return if parameter is missing */
  126287. ){
  126288. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  126289. sqlite3_int64 v;
  126290. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  126291. bDflt = v;
  126292. }
  126293. return bDflt;
  126294. }
  126295. /*
  126296. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  126297. */
  126298. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  126299. int i;
  126300. for(i=0; i<db->nDb; i++){
  126301. if( db->aDb[i].pBt
  126302. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  126303. ){
  126304. return db->aDb[i].pBt;
  126305. }
  126306. }
  126307. return 0;
  126308. }
  126309. /*
  126310. ** Return the filename of the database associated with a database
  126311. ** connection.
  126312. */
  126313. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  126314. Btree *pBt;
  126315. #ifdef SQLITE_ENABLE_API_ARMOR
  126316. if( !sqlite3SafetyCheckOk(db) ){
  126317. (void)SQLITE_MISUSE_BKPT;
  126318. return 0;
  126319. }
  126320. #endif
  126321. pBt = sqlite3DbNameToBtree(db, zDbName);
  126322. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  126323. }
  126324. /*
  126325. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  126326. ** no such database exists.
  126327. */
  126328. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  126329. Btree *pBt;
  126330. #ifdef SQLITE_ENABLE_API_ARMOR
  126331. if( !sqlite3SafetyCheckOk(db) ){
  126332. (void)SQLITE_MISUSE_BKPT;
  126333. return -1;
  126334. }
  126335. #endif
  126336. pBt = sqlite3DbNameToBtree(db, zDbName);
  126337. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  126338. }
  126339. /************** End of main.c ************************************************/
  126340. /************** Begin file notify.c ******************************************/
  126341. /*
  126342. ** 2009 March 3
  126343. **
  126344. ** The author disclaims copyright to this source code. In place of
  126345. ** a legal notice, here is a blessing:
  126346. **
  126347. ** May you do good and not evil.
  126348. ** May you find forgiveness for yourself and forgive others.
  126349. ** May you share freely, never taking more than you give.
  126350. **
  126351. *************************************************************************
  126352. **
  126353. ** This file contains the implementation of the sqlite3_unlock_notify()
  126354. ** API method and its associated functionality.
  126355. */
  126356. /* #include "sqliteInt.h" */
  126357. /* #include "btreeInt.h" */
  126358. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  126359. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  126360. /*
  126361. ** Public interfaces:
  126362. **
  126363. ** sqlite3ConnectionBlocked()
  126364. ** sqlite3ConnectionUnlocked()
  126365. ** sqlite3ConnectionClosed()
  126366. ** sqlite3_unlock_notify()
  126367. */
  126368. #define assertMutexHeld() \
  126369. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  126370. /*
  126371. ** Head of a linked list of all sqlite3 objects created by this process
  126372. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  126373. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  126374. ** mutex is held.
  126375. */
  126376. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  126377. #ifndef NDEBUG
  126378. /*
  126379. ** This function is a complex assert() that verifies the following
  126380. ** properties of the blocked connections list:
  126381. **
  126382. ** 1) Each entry in the list has a non-NULL value for either
  126383. ** pUnlockConnection or pBlockingConnection, or both.
  126384. **
  126385. ** 2) All entries in the list that share a common value for
  126386. ** xUnlockNotify are grouped together.
  126387. **
  126388. ** 3) If the argument db is not NULL, then none of the entries in the
  126389. ** blocked connections list have pUnlockConnection or pBlockingConnection
  126390. ** set to db. This is used when closing connection db.
  126391. */
  126392. static void checkListProperties(sqlite3 *db){
  126393. sqlite3 *p;
  126394. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  126395. int seen = 0;
  126396. sqlite3 *p2;
  126397. /* Verify property (1) */
  126398. assert( p->pUnlockConnection || p->pBlockingConnection );
  126399. /* Verify property (2) */
  126400. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  126401. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  126402. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  126403. assert( db==0 || p->pUnlockConnection!=db );
  126404. assert( db==0 || p->pBlockingConnection!=db );
  126405. }
  126406. }
  126407. }
  126408. #else
  126409. # define checkListProperties(x)
  126410. #endif
  126411. /*
  126412. ** Remove connection db from the blocked connections list. If connection
  126413. ** db is not currently a part of the list, this function is a no-op.
  126414. */
  126415. static void removeFromBlockedList(sqlite3 *db){
  126416. sqlite3 **pp;
  126417. assertMutexHeld();
  126418. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  126419. if( *pp==db ){
  126420. *pp = (*pp)->pNextBlocked;
  126421. break;
  126422. }
  126423. }
  126424. }
  126425. /*
  126426. ** Add connection db to the blocked connections list. It is assumed
  126427. ** that it is not already a part of the list.
  126428. */
  126429. static void addToBlockedList(sqlite3 *db){
  126430. sqlite3 **pp;
  126431. assertMutexHeld();
  126432. for(
  126433. pp=&sqlite3BlockedList;
  126434. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  126435. pp=&(*pp)->pNextBlocked
  126436. );
  126437. db->pNextBlocked = *pp;
  126438. *pp = db;
  126439. }
  126440. /*
  126441. ** Obtain the STATIC_MASTER mutex.
  126442. */
  126443. static void enterMutex(void){
  126444. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  126445. checkListProperties(0);
  126446. }
  126447. /*
  126448. ** Release the STATIC_MASTER mutex.
  126449. */
  126450. static void leaveMutex(void){
  126451. assertMutexHeld();
  126452. checkListProperties(0);
  126453. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  126454. }
  126455. /*
  126456. ** Register an unlock-notify callback.
  126457. **
  126458. ** This is called after connection "db" has attempted some operation
  126459. ** but has received an SQLITE_LOCKED error because another connection
  126460. ** (call it pOther) in the same process was busy using the same shared
  126461. ** cache. pOther is found by looking at db->pBlockingConnection.
  126462. **
  126463. ** If there is no blocking connection, the callback is invoked immediately,
  126464. ** before this routine returns.
  126465. **
  126466. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  126467. ** a deadlock.
  126468. **
  126469. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  126470. ** its locks.
  126471. **
  126472. ** Each call to this routine overrides any prior callbacks registered
  126473. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  126474. ** cancelled.
  126475. */
  126476. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  126477. sqlite3 *db,
  126478. void (*xNotify)(void **, int),
  126479. void *pArg
  126480. ){
  126481. int rc = SQLITE_OK;
  126482. sqlite3_mutex_enter(db->mutex);
  126483. enterMutex();
  126484. if( xNotify==0 ){
  126485. removeFromBlockedList(db);
  126486. db->pBlockingConnection = 0;
  126487. db->pUnlockConnection = 0;
  126488. db->xUnlockNotify = 0;
  126489. db->pUnlockArg = 0;
  126490. }else if( 0==db->pBlockingConnection ){
  126491. /* The blocking transaction has been concluded. Or there never was a
  126492. ** blocking transaction. In either case, invoke the notify callback
  126493. ** immediately.
  126494. */
  126495. xNotify(&pArg, 1);
  126496. }else{
  126497. sqlite3 *p;
  126498. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  126499. if( p ){
  126500. rc = SQLITE_LOCKED; /* Deadlock detected. */
  126501. }else{
  126502. db->pUnlockConnection = db->pBlockingConnection;
  126503. db->xUnlockNotify = xNotify;
  126504. db->pUnlockArg = pArg;
  126505. removeFromBlockedList(db);
  126506. addToBlockedList(db);
  126507. }
  126508. }
  126509. leaveMutex();
  126510. assert( !db->mallocFailed );
  126511. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  126512. sqlite3_mutex_leave(db->mutex);
  126513. return rc;
  126514. }
  126515. /*
  126516. ** This function is called while stepping or preparing a statement
  126517. ** associated with connection db. The operation will return SQLITE_LOCKED
  126518. ** to the user because it requires a lock that will not be available
  126519. ** until connection pBlocker concludes its current transaction.
  126520. */
  126521. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  126522. enterMutex();
  126523. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  126524. addToBlockedList(db);
  126525. }
  126526. db->pBlockingConnection = pBlocker;
  126527. leaveMutex();
  126528. }
  126529. /*
  126530. ** This function is called when
  126531. ** the transaction opened by database db has just finished. Locks held
  126532. ** by database connection db have been released.
  126533. **
  126534. ** This function loops through each entry in the blocked connections
  126535. ** list and does the following:
  126536. **
  126537. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  126538. ** set to db, then set pBlockingConnection=0.
  126539. **
  126540. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  126541. ** set to db, then invoke the configured unlock-notify callback and
  126542. ** set pUnlockConnection=0.
  126543. **
  126544. ** 3) If the two steps above mean that pBlockingConnection==0 and
  126545. ** pUnlockConnection==0, remove the entry from the blocked connections
  126546. ** list.
  126547. */
  126548. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  126549. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  126550. int nArg = 0; /* Number of entries in aArg[] */
  126551. sqlite3 **pp; /* Iterator variable */
  126552. void **aArg; /* Arguments to the unlock callback */
  126553. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  126554. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  126555. aArg = aStatic;
  126556. enterMutex(); /* Enter STATIC_MASTER mutex */
  126557. /* This loop runs once for each entry in the blocked-connections list. */
  126558. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  126559. sqlite3 *p = *pp;
  126560. /* Step 1. */
  126561. if( p->pBlockingConnection==db ){
  126562. p->pBlockingConnection = 0;
  126563. }
  126564. /* Step 2. */
  126565. if( p->pUnlockConnection==db ){
  126566. assert( p->xUnlockNotify );
  126567. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  126568. xUnlockNotify(aArg, nArg);
  126569. nArg = 0;
  126570. }
  126571. sqlite3BeginBenignMalloc();
  126572. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  126573. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  126574. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  126575. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  126576. ){
  126577. /* The aArg[] array needs to grow. */
  126578. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  126579. if( pNew ){
  126580. memcpy(pNew, aArg, nArg*sizeof(void *));
  126581. sqlite3_free(aDyn);
  126582. aDyn = aArg = pNew;
  126583. }else{
  126584. /* This occurs when the array of context pointers that need to
  126585. ** be passed to the unlock-notify callback is larger than the
  126586. ** aStatic[] array allocated on the stack and the attempt to
  126587. ** allocate a larger array from the heap has failed.
  126588. **
  126589. ** This is a difficult situation to handle. Returning an error
  126590. ** code to the caller is insufficient, as even if an error code
  126591. ** is returned the transaction on connection db will still be
  126592. ** closed and the unlock-notify callbacks on blocked connections
  126593. ** will go unissued. This might cause the application to wait
  126594. ** indefinitely for an unlock-notify callback that will never
  126595. ** arrive.
  126596. **
  126597. ** Instead, invoke the unlock-notify callback with the context
  126598. ** array already accumulated. We can then clear the array and
  126599. ** begin accumulating any further context pointers without
  126600. ** requiring any dynamic allocation. This is sub-optimal because
  126601. ** it means that instead of one callback with a large array of
  126602. ** context pointers the application will receive two or more
  126603. ** callbacks with smaller arrays of context pointers, which will
  126604. ** reduce the applications ability to prioritize multiple
  126605. ** connections. But it is the best that can be done under the
  126606. ** circumstances.
  126607. */
  126608. xUnlockNotify(aArg, nArg);
  126609. nArg = 0;
  126610. }
  126611. }
  126612. sqlite3EndBenignMalloc();
  126613. aArg[nArg++] = p->pUnlockArg;
  126614. xUnlockNotify = p->xUnlockNotify;
  126615. p->pUnlockConnection = 0;
  126616. p->xUnlockNotify = 0;
  126617. p->pUnlockArg = 0;
  126618. }
  126619. /* Step 3. */
  126620. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  126621. /* Remove connection p from the blocked connections list. */
  126622. *pp = p->pNextBlocked;
  126623. p->pNextBlocked = 0;
  126624. }else{
  126625. pp = &p->pNextBlocked;
  126626. }
  126627. }
  126628. if( nArg!=0 ){
  126629. xUnlockNotify(aArg, nArg);
  126630. }
  126631. sqlite3_free(aDyn);
  126632. leaveMutex(); /* Leave STATIC_MASTER mutex */
  126633. }
  126634. /*
  126635. ** This is called when the database connection passed as an argument is
  126636. ** being closed. The connection is removed from the blocked list.
  126637. */
  126638. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  126639. sqlite3ConnectionUnlocked(db);
  126640. enterMutex();
  126641. removeFromBlockedList(db);
  126642. checkListProperties(db);
  126643. leaveMutex();
  126644. }
  126645. #endif
  126646. /************** End of notify.c **********************************************/
  126647. /************** Begin file fts3.c ********************************************/
  126648. /*
  126649. ** 2006 Oct 10
  126650. **
  126651. ** The author disclaims copyright to this source code. In place of
  126652. ** a legal notice, here is a blessing:
  126653. **
  126654. ** May you do good and not evil.
  126655. ** May you find forgiveness for yourself and forgive others.
  126656. ** May you share freely, never taking more than you give.
  126657. **
  126658. ******************************************************************************
  126659. **
  126660. ** This is an SQLite module implementing full-text search.
  126661. */
  126662. /*
  126663. ** The code in this file is only compiled if:
  126664. **
  126665. ** * The FTS3 module is being built as an extension
  126666. ** (in which case SQLITE_CORE is not defined), or
  126667. **
  126668. ** * The FTS3 module is being built into the core of
  126669. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  126670. */
  126671. /* The full-text index is stored in a series of b+tree (-like)
  126672. ** structures called segments which map terms to doclists. The
  126673. ** structures are like b+trees in layout, but are constructed from the
  126674. ** bottom up in optimal fashion and are not updatable. Since trees
  126675. ** are built from the bottom up, things will be described from the
  126676. ** bottom up.
  126677. **
  126678. **
  126679. **** Varints ****
  126680. ** The basic unit of encoding is a variable-length integer called a
  126681. ** varint. We encode variable-length integers in little-endian order
  126682. ** using seven bits * per byte as follows:
  126683. **
  126684. ** KEY:
  126685. ** A = 0xxxxxxx 7 bits of data and one flag bit
  126686. ** B = 1xxxxxxx 7 bits of data and one flag bit
  126687. **
  126688. ** 7 bits - A
  126689. ** 14 bits - BA
  126690. ** 21 bits - BBA
  126691. ** and so on.
  126692. **
  126693. ** This is similar in concept to how sqlite encodes "varints" but
  126694. ** the encoding is not the same. SQLite varints are big-endian
  126695. ** are are limited to 9 bytes in length whereas FTS3 varints are
  126696. ** little-endian and can be up to 10 bytes in length (in theory).
  126697. **
  126698. ** Example encodings:
  126699. **
  126700. ** 1: 0x01
  126701. ** 127: 0x7f
  126702. ** 128: 0x81 0x00
  126703. **
  126704. **
  126705. **** Document lists ****
  126706. ** A doclist (document list) holds a docid-sorted list of hits for a
  126707. ** given term. Doclists hold docids and associated token positions.
  126708. ** A docid is the unique integer identifier for a single document.
  126709. ** A position is the index of a word within the document. The first
  126710. ** word of the document has a position of 0.
  126711. **
  126712. ** FTS3 used to optionally store character offsets using a compile-time
  126713. ** option. But that functionality is no longer supported.
  126714. **
  126715. ** A doclist is stored like this:
  126716. **
  126717. ** array {
  126718. ** varint docid; (delta from previous doclist)
  126719. ** array { (position list for column 0)
  126720. ** varint position; (2 more than the delta from previous position)
  126721. ** }
  126722. ** array {
  126723. ** varint POS_COLUMN; (marks start of position list for new column)
  126724. ** varint column; (index of new column)
  126725. ** array {
  126726. ** varint position; (2 more than the delta from previous position)
  126727. ** }
  126728. ** }
  126729. ** varint POS_END; (marks end of positions for this document.
  126730. ** }
  126731. **
  126732. ** Here, array { X } means zero or more occurrences of X, adjacent in
  126733. ** memory. A "position" is an index of a token in the token stream
  126734. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  126735. ** in the same logical place as the position element, and act as sentinals
  126736. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  126737. ** The positions numbers are not stored literally but rather as two more
  126738. ** than the difference from the prior position, or the just the position plus
  126739. ** 2 for the first position. Example:
  126740. **
  126741. ** label: A B C D E F G H I J K
  126742. ** value: 123 5 9 1 1 14 35 0 234 72 0
  126743. **
  126744. ** The 123 value is the first docid. For column zero in this document
  126745. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  126746. ** at D signals the start of a new column; the 1 at E indicates that the
  126747. ** new column is column number 1. There are two positions at 12 and 45
  126748. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  126749. ** 234 at I is the delta to next docid (357). It has one position 70
  126750. ** (72-2) and then terminates with the 0 at K.
  126751. **
  126752. ** A "position-list" is the list of positions for multiple columns for
  126753. ** a single docid. A "column-list" is the set of positions for a single
  126754. ** column. Hence, a position-list consists of one or more column-lists,
  126755. ** a document record consists of a docid followed by a position-list and
  126756. ** a doclist consists of one or more document records.
  126757. **
  126758. ** A bare doclist omits the position information, becoming an
  126759. ** array of varint-encoded docids.
  126760. **
  126761. **** Segment leaf nodes ****
  126762. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  126763. ** nodes are written using LeafWriter, and read using LeafReader (to
  126764. ** iterate through a single leaf node's data) and LeavesReader (to
  126765. ** iterate through a segment's entire leaf layer). Leaf nodes have
  126766. ** the format:
  126767. **
  126768. ** varint iHeight; (height from leaf level, always 0)
  126769. ** varint nTerm; (length of first term)
  126770. ** char pTerm[nTerm]; (content of first term)
  126771. ** varint nDoclist; (length of term's associated doclist)
  126772. ** char pDoclist[nDoclist]; (content of doclist)
  126773. ** array {
  126774. ** (further terms are delta-encoded)
  126775. ** varint nPrefix; (length of prefix shared with previous term)
  126776. ** varint nSuffix; (length of unshared suffix)
  126777. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  126778. ** varint nDoclist; (length of term's associated doclist)
  126779. ** char pDoclist[nDoclist]; (content of doclist)
  126780. ** }
  126781. **
  126782. ** Here, array { X } means zero or more occurrences of X, adjacent in
  126783. ** memory.
  126784. **
  126785. ** Leaf nodes are broken into blocks which are stored contiguously in
  126786. ** the %_segments table in sorted order. This means that when the end
  126787. ** of a node is reached, the next term is in the node with the next
  126788. ** greater node id.
  126789. **
  126790. ** New data is spilled to a new leaf node when the current node
  126791. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  126792. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  126793. ** node (a leaf node with a single term and doclist). The goal of
  126794. ** these settings is to pack together groups of small doclists while
  126795. ** making it efficient to directly access large doclists. The
  126796. ** assumption is that large doclists represent terms which are more
  126797. ** likely to be query targets.
  126798. **
  126799. ** TODO(shess) It may be useful for blocking decisions to be more
  126800. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  126801. ** node rather than splitting into 2k and .5k nodes. My intuition is
  126802. ** that this might extend through 2x or 4x the pagesize.
  126803. **
  126804. **
  126805. **** Segment interior nodes ****
  126806. ** Segment interior nodes store blockids for subtree nodes and terms
  126807. ** to describe what data is stored by the each subtree. Interior
  126808. ** nodes are written using InteriorWriter, and read using
  126809. ** InteriorReader. InteriorWriters are created as needed when
  126810. ** SegmentWriter creates new leaf nodes, or when an interior node
  126811. ** itself grows too big and must be split. The format of interior
  126812. ** nodes:
  126813. **
  126814. ** varint iHeight; (height from leaf level, always >0)
  126815. ** varint iBlockid; (block id of node's leftmost subtree)
  126816. ** optional {
  126817. ** varint nTerm; (length of first term)
  126818. ** char pTerm[nTerm]; (content of first term)
  126819. ** array {
  126820. ** (further terms are delta-encoded)
  126821. ** varint nPrefix; (length of shared prefix with previous term)
  126822. ** varint nSuffix; (length of unshared suffix)
  126823. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  126824. ** }
  126825. ** }
  126826. **
  126827. ** Here, optional { X } means an optional element, while array { X }
  126828. ** means zero or more occurrences of X, adjacent in memory.
  126829. **
  126830. ** An interior node encodes n terms separating n+1 subtrees. The
  126831. ** subtree blocks are contiguous, so only the first subtree's blockid
  126832. ** is encoded. The subtree at iBlockid will contain all terms less
  126833. ** than the first term encoded (or all terms if no term is encoded).
  126834. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  126835. ** than pTerm[i+1], the subtree for that term will be rooted at
  126836. ** iBlockid+i. Interior nodes only store enough term data to
  126837. ** distinguish adjacent children (if the rightmost term of the left
  126838. ** child is "something", and the leftmost term of the right child is
  126839. ** "wicked", only "w" is stored).
  126840. **
  126841. ** New data is spilled to a new interior node at the same height when
  126842. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  126843. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  126844. ** interior nodes and making the tree too skinny. The interior nodes
  126845. ** at a given height are naturally tracked by interior nodes at
  126846. ** height+1, and so on.
  126847. **
  126848. **
  126849. **** Segment directory ****
  126850. ** The segment directory in table %_segdir stores meta-information for
  126851. ** merging and deleting segments, and also the root node of the
  126852. ** segment's tree.
  126853. **
  126854. ** The root node is the top node of the segment's tree after encoding
  126855. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  126856. ** This could be either a leaf node or an interior node. If the top
  126857. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  126858. ** and a new root interior node is generated (which should always fit
  126859. ** within ROOT_MAX because it only needs space for 2 varints, the
  126860. ** height and the blockid of the previous root).
  126861. **
  126862. ** The meta-information in the segment directory is:
  126863. ** level - segment level (see below)
  126864. ** idx - index within level
  126865. ** - (level,idx uniquely identify a segment)
  126866. ** start_block - first leaf node
  126867. ** leaves_end_block - last leaf node
  126868. ** end_block - last block (including interior nodes)
  126869. ** root - contents of root node
  126870. **
  126871. ** If the root node is a leaf node, then start_block,
  126872. ** leaves_end_block, and end_block are all 0.
  126873. **
  126874. **
  126875. **** Segment merging ****
  126876. ** To amortize update costs, segments are grouped into levels and
  126877. ** merged in batches. Each increase in level represents exponentially
  126878. ** more documents.
  126879. **
  126880. ** New documents (actually, document updates) are tokenized and
  126881. ** written individually (using LeafWriter) to a level 0 segment, with
  126882. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  126883. ** level 0 segments are merged into a single level 1 segment. Level 1
  126884. ** is populated like level 0, and eventually MERGE_COUNT level 1
  126885. ** segments are merged to a single level 2 segment (representing
  126886. ** MERGE_COUNT^2 updates), and so on.
  126887. **
  126888. ** A segment merge traverses all segments at a given level in
  126889. ** parallel, performing a straightforward sorted merge. Since segment
  126890. ** leaf nodes are written in to the %_segments table in order, this
  126891. ** merge traverses the underlying sqlite disk structures efficiently.
  126892. ** After the merge, all segment blocks from the merged level are
  126893. ** deleted.
  126894. **
  126895. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  126896. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  126897. ** very similar performance numbers to 16 on insertion, though they're
  126898. ** a tiny bit slower (perhaps due to more overhead in merge-time
  126899. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  126900. ** 16, 2 about 66% slower than 16.
  126901. **
  126902. ** At query time, high MERGE_COUNT increases the number of segments
  126903. ** which need to be scanned and merged. For instance, with 100k docs
  126904. ** inserted:
  126905. **
  126906. ** MERGE_COUNT segments
  126907. ** 16 25
  126908. ** 8 12
  126909. ** 4 10
  126910. ** 2 6
  126911. **
  126912. ** This appears to have only a moderate impact on queries for very
  126913. ** frequent terms (which are somewhat dominated by segment merge
  126914. ** costs), and infrequent and non-existent terms still seem to be fast
  126915. ** even with many segments.
  126916. **
  126917. ** TODO(shess) That said, it would be nice to have a better query-side
  126918. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  126919. ** optimizations to things like doclist merging will swing the sweet
  126920. ** spot around.
  126921. **
  126922. **
  126923. **
  126924. **** Handling of deletions and updates ****
  126925. ** Since we're using a segmented structure, with no docid-oriented
  126926. ** index into the term index, we clearly cannot simply update the term
  126927. ** index when a document is deleted or updated. For deletions, we
  126928. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  126929. ** we simply write the new doclist. Segment merges overwrite older
  126930. ** data for a particular docid with newer data, so deletes or updates
  126931. ** will eventually overtake the earlier data and knock it out. The
  126932. ** query logic likewise merges doclists so that newer data knocks out
  126933. ** older data.
  126934. */
  126935. /************** Include fts3Int.h in the middle of fts3.c ********************/
  126936. /************** Begin file fts3Int.h *****************************************/
  126937. /*
  126938. ** 2009 Nov 12
  126939. **
  126940. ** The author disclaims copyright to this source code. In place of
  126941. ** a legal notice, here is a blessing:
  126942. **
  126943. ** May you do good and not evil.
  126944. ** May you find forgiveness for yourself and forgive others.
  126945. ** May you share freely, never taking more than you give.
  126946. **
  126947. ******************************************************************************
  126948. **
  126949. */
  126950. #ifndef _FTSINT_H
  126951. #define _FTSINT_H
  126952. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  126953. # define NDEBUG 1
  126954. #endif
  126955. /*
  126956. ** FTS4 is really an extension for FTS3. It is enabled using the
  126957. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  126958. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  126959. */
  126960. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  126961. # define SQLITE_ENABLE_FTS3
  126962. #endif
  126963. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126964. /* If not building as part of the core, include sqlite3ext.h. */
  126965. #ifndef SQLITE_CORE
  126966. /* # include "sqlite3ext.h" */
  126967. SQLITE_EXTENSION_INIT3
  126968. #endif
  126969. /* #include "sqlite3.h" */
  126970. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  126971. /************** Begin file fts3_tokenizer.h **********************************/
  126972. /*
  126973. ** 2006 July 10
  126974. **
  126975. ** The author disclaims copyright to this source code.
  126976. **
  126977. *************************************************************************
  126978. ** Defines the interface to tokenizers used by fulltext-search. There
  126979. ** are three basic components:
  126980. **
  126981. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  126982. ** interface functions. This is essentially the class structure for
  126983. ** tokenizers.
  126984. **
  126985. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  126986. ** including customization information defined at creation time.
  126987. **
  126988. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  126989. ** tokens from a particular input.
  126990. */
  126991. #ifndef _FTS3_TOKENIZER_H_
  126992. #define _FTS3_TOKENIZER_H_
  126993. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  126994. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  126995. ** we will need a way to register the API consistently.
  126996. */
  126997. /* #include "sqlite3.h" */
  126998. /*
  126999. ** Structures used by the tokenizer interface. When a new tokenizer
  127000. ** implementation is registered, the caller provides a pointer to
  127001. ** an sqlite3_tokenizer_module containing pointers to the callback
  127002. ** functions that make up an implementation.
  127003. **
  127004. ** When an fts3 table is created, it passes any arguments passed to
  127005. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  127006. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  127007. ** implementation. The xCreate() function in turn returns an
  127008. ** sqlite3_tokenizer structure representing the specific tokenizer to
  127009. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  127010. **
  127011. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  127012. ** method is called. It returns an sqlite3_tokenizer_cursor object
  127013. ** that may be used to tokenize a specific input buffer based on
  127014. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  127015. ** object.
  127016. */
  127017. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  127018. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  127019. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  127020. struct sqlite3_tokenizer_module {
  127021. /*
  127022. ** Structure version. Should always be set to 0 or 1.
  127023. */
  127024. int iVersion;
  127025. /*
  127026. ** Create a new tokenizer. The values in the argv[] array are the
  127027. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  127028. ** TABLE statement that created the fts3 table. For example, if
  127029. ** the following SQL is executed:
  127030. **
  127031. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  127032. **
  127033. ** then argc is set to 2, and the argv[] array contains pointers
  127034. ** to the strings "arg1" and "arg2".
  127035. **
  127036. ** This method should return either SQLITE_OK (0), or an SQLite error
  127037. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  127038. ** to point at the newly created tokenizer structure. The generic
  127039. ** sqlite3_tokenizer.pModule variable should not be initialized by
  127040. ** this callback. The caller will do so.
  127041. */
  127042. int (*xCreate)(
  127043. int argc, /* Size of argv array */
  127044. const char *const*argv, /* Tokenizer argument strings */
  127045. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  127046. );
  127047. /*
  127048. ** Destroy an existing tokenizer. The fts3 module calls this method
  127049. ** exactly once for each successful call to xCreate().
  127050. */
  127051. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  127052. /*
  127053. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  127054. ** is responsible for ensuring that the input buffer remains valid
  127055. ** until the cursor is closed (using the xClose() method).
  127056. */
  127057. int (*xOpen)(
  127058. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  127059. const char *pInput, int nBytes, /* Input buffer */
  127060. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  127061. );
  127062. /*
  127063. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  127064. ** method exactly once for each successful call to xOpen().
  127065. */
  127066. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  127067. /*
  127068. ** Retrieve the next token from the tokenizer cursor pCursor. This
  127069. ** method should either return SQLITE_OK and set the values of the
  127070. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  127071. ** the end of the buffer has been reached, or an SQLite error code.
  127072. **
  127073. ** *ppToken should be set to point at a buffer containing the
  127074. ** normalized version of the token (i.e. after any case-folding and/or
  127075. ** stemming has been performed). *pnBytes should be set to the length
  127076. ** of this buffer in bytes. The input text that generated the token is
  127077. ** identified by the byte offsets returned in *piStartOffset and
  127078. ** *piEndOffset. *piStartOffset should be set to the index of the first
  127079. ** byte of the token in the input buffer. *piEndOffset should be set
  127080. ** to the index of the first byte just past the end of the token in
  127081. ** the input buffer.
  127082. **
  127083. ** The buffer *ppToken is set to point at is managed by the tokenizer
  127084. ** implementation. It is only required to be valid until the next call
  127085. ** to xNext() or xClose().
  127086. */
  127087. /* TODO(shess) current implementation requires pInput to be
  127088. ** nul-terminated. This should either be fixed, or pInput/nBytes
  127089. ** should be converted to zInput.
  127090. */
  127091. int (*xNext)(
  127092. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  127093. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  127094. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  127095. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  127096. int *piPosition /* OUT: Number of tokens returned before this one */
  127097. );
  127098. /***********************************************************************
  127099. ** Methods below this point are only available if iVersion>=1.
  127100. */
  127101. /*
  127102. ** Configure the language id of a tokenizer cursor.
  127103. */
  127104. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  127105. };
  127106. struct sqlite3_tokenizer {
  127107. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  127108. /* Tokenizer implementations will typically add additional fields */
  127109. };
  127110. struct sqlite3_tokenizer_cursor {
  127111. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  127112. /* Tokenizer implementations will typically add additional fields */
  127113. };
  127114. int fts3_global_term_cnt(int iTerm, int iCol);
  127115. int fts3_term_cnt(int iTerm, int iCol);
  127116. #endif /* _FTS3_TOKENIZER_H_ */
  127117. /************** End of fts3_tokenizer.h **************************************/
  127118. /************** Continuing where we left off in fts3Int.h ********************/
  127119. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  127120. /************** Begin file fts3_hash.h ***************************************/
  127121. /*
  127122. ** 2001 September 22
  127123. **
  127124. ** The author disclaims copyright to this source code. In place of
  127125. ** a legal notice, here is a blessing:
  127126. **
  127127. ** May you do good and not evil.
  127128. ** May you find forgiveness for yourself and forgive others.
  127129. ** May you share freely, never taking more than you give.
  127130. **
  127131. *************************************************************************
  127132. ** This is the header file for the generic hash-table implementation
  127133. ** used in SQLite. We've modified it slightly to serve as a standalone
  127134. ** hash table implementation for the full-text indexing module.
  127135. **
  127136. */
  127137. #ifndef _FTS3_HASH_H_
  127138. #define _FTS3_HASH_H_
  127139. /* Forward declarations of structures. */
  127140. typedef struct Fts3Hash Fts3Hash;
  127141. typedef struct Fts3HashElem Fts3HashElem;
  127142. /* A complete hash table is an instance of the following structure.
  127143. ** The internals of this structure are intended to be opaque -- client
  127144. ** code should not attempt to access or modify the fields of this structure
  127145. ** directly. Change this structure only by using the routines below.
  127146. ** However, many of the "procedures" and "functions" for modifying and
  127147. ** accessing this structure are really macros, so we can't really make
  127148. ** this structure opaque.
  127149. */
  127150. struct Fts3Hash {
  127151. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  127152. char copyKey; /* True if copy of key made on insert */
  127153. int count; /* Number of entries in this table */
  127154. Fts3HashElem *first; /* The first element of the array */
  127155. int htsize; /* Number of buckets in the hash table */
  127156. struct _fts3ht { /* the hash table */
  127157. int count; /* Number of entries with this hash */
  127158. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  127159. } *ht;
  127160. };
  127161. /* Each element in the hash table is an instance of the following
  127162. ** structure. All elements are stored on a single doubly-linked list.
  127163. **
  127164. ** Again, this structure is intended to be opaque, but it can't really
  127165. ** be opaque because it is used by macros.
  127166. */
  127167. struct Fts3HashElem {
  127168. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  127169. void *data; /* Data associated with this element */
  127170. void *pKey; int nKey; /* Key associated with this element */
  127171. };
  127172. /*
  127173. ** There are 2 different modes of operation for a hash table:
  127174. **
  127175. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  127176. ** (including the null-terminator, if any). Case
  127177. ** is respected in comparisons.
  127178. **
  127179. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  127180. ** memcmp() is used to compare keys.
  127181. **
  127182. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  127183. */
  127184. #define FTS3_HASH_STRING 1
  127185. #define FTS3_HASH_BINARY 2
  127186. /*
  127187. ** Access routines. To delete, insert a NULL pointer.
  127188. */
  127189. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  127190. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  127191. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  127192. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  127193. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  127194. /*
  127195. ** Shorthand for the functions above
  127196. */
  127197. #define fts3HashInit sqlite3Fts3HashInit
  127198. #define fts3HashInsert sqlite3Fts3HashInsert
  127199. #define fts3HashFind sqlite3Fts3HashFind
  127200. #define fts3HashClear sqlite3Fts3HashClear
  127201. #define fts3HashFindElem sqlite3Fts3HashFindElem
  127202. /*
  127203. ** Macros for looping over all elements of a hash table. The idiom is
  127204. ** like this:
  127205. **
  127206. ** Fts3Hash h;
  127207. ** Fts3HashElem *p;
  127208. ** ...
  127209. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  127210. ** SomeStructure *pData = fts3HashData(p);
  127211. ** // do something with pData
  127212. ** }
  127213. */
  127214. #define fts3HashFirst(H) ((H)->first)
  127215. #define fts3HashNext(E) ((E)->next)
  127216. #define fts3HashData(E) ((E)->data)
  127217. #define fts3HashKey(E) ((E)->pKey)
  127218. #define fts3HashKeysize(E) ((E)->nKey)
  127219. /*
  127220. ** Number of entries in a hash table
  127221. */
  127222. #define fts3HashCount(H) ((H)->count)
  127223. #endif /* _FTS3_HASH_H_ */
  127224. /************** End of fts3_hash.h *******************************************/
  127225. /************** Continuing where we left off in fts3Int.h ********************/
  127226. /*
  127227. ** This constant determines the maximum depth of an FTS expression tree
  127228. ** that the library will create and use. FTS uses recursion to perform
  127229. ** various operations on the query tree, so the disadvantage of a large
  127230. ** limit is that it may allow very large queries to use large amounts
  127231. ** of stack space (perhaps causing a stack overflow).
  127232. */
  127233. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  127234. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  127235. #endif
  127236. /*
  127237. ** This constant controls how often segments are merged. Once there are
  127238. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  127239. ** segment of level N+1.
  127240. */
  127241. #define FTS3_MERGE_COUNT 16
  127242. /*
  127243. ** This is the maximum amount of data (in bytes) to store in the
  127244. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  127245. ** populated as documents are inserted/updated/deleted in a transaction
  127246. ** and used to create a new segment when the transaction is committed.
  127247. ** However if this limit is reached midway through a transaction, a new
  127248. ** segment is created and the hash table cleared immediately.
  127249. */
  127250. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  127251. /*
  127252. ** Macro to return the number of elements in an array. SQLite has a
  127253. ** similar macro called ArraySize(). Use a different name to avoid
  127254. ** a collision when building an amalgamation with built-in FTS3.
  127255. */
  127256. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  127257. #ifndef MIN
  127258. # define MIN(x,y) ((x)<(y)?(x):(y))
  127259. #endif
  127260. #ifndef MAX
  127261. # define MAX(x,y) ((x)>(y)?(x):(y))
  127262. #endif
  127263. /*
  127264. ** Maximum length of a varint encoded integer. The varint format is different
  127265. ** from that used by SQLite, so the maximum length is 10, not 9.
  127266. */
  127267. #define FTS3_VARINT_MAX 10
  127268. /*
  127269. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  127270. ** in the document set and zero or more prefix indexes. All indexes are stored
  127271. ** as one or more b+-trees in the %_segments and %_segdir tables.
  127272. **
  127273. ** It is possible to determine which index a b+-tree belongs to based on the
  127274. ** value stored in the "%_segdir.level" column. Given this value L, the index
  127275. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  127276. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  127277. ** between 1024 and 2047 to index 1, and so on.
  127278. **
  127279. ** It is considered impossible for an index to use more than 1024 levels. In
  127280. ** theory though this may happen, but only after at least
  127281. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  127282. */
  127283. #define FTS3_SEGDIR_MAXLEVEL 1024
  127284. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  127285. /*
  127286. ** The testcase() macro is only used by the amalgamation. If undefined,
  127287. ** make it a no-op.
  127288. */
  127289. #ifndef testcase
  127290. # define testcase(X)
  127291. #endif
  127292. /*
  127293. ** Terminator values for position-lists and column-lists.
  127294. */
  127295. #define POS_COLUMN (1) /* Column-list terminator */
  127296. #define POS_END (0) /* Position-list terminator */
  127297. /*
  127298. ** This section provides definitions to allow the
  127299. ** FTS3 extension to be compiled outside of the
  127300. ** amalgamation.
  127301. */
  127302. #ifndef SQLITE_AMALGAMATION
  127303. /*
  127304. ** Macros indicating that conditional expressions are always true or
  127305. ** false.
  127306. */
  127307. #ifdef SQLITE_COVERAGE_TEST
  127308. # define ALWAYS(x) (1)
  127309. # define NEVER(X) (0)
  127310. #elif defined(SQLITE_DEBUG)
  127311. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  127312. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  127313. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  127314. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  127315. #else
  127316. # define ALWAYS(x) (x)
  127317. # define NEVER(x) (x)
  127318. #endif
  127319. /*
  127320. ** Internal types used by SQLite.
  127321. */
  127322. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  127323. typedef short int i16; /* 2-byte (or larger) signed integer */
  127324. typedef unsigned int u32; /* 4-byte unsigned integer */
  127325. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  127326. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  127327. /*
  127328. ** Macro used to suppress compiler warnings for unused parameters.
  127329. */
  127330. #define UNUSED_PARAMETER(x) (void)(x)
  127331. /*
  127332. ** Activate assert() only if SQLITE_TEST is enabled.
  127333. */
  127334. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  127335. # define NDEBUG 1
  127336. #endif
  127337. /*
  127338. ** The TESTONLY macro is used to enclose variable declarations or
  127339. ** other bits of code that are needed to support the arguments
  127340. ** within testcase() and assert() macros.
  127341. */
  127342. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  127343. # define TESTONLY(X) X
  127344. #else
  127345. # define TESTONLY(X)
  127346. #endif
  127347. #endif /* SQLITE_AMALGAMATION */
  127348. #ifdef SQLITE_DEBUG
  127349. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  127350. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  127351. #else
  127352. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  127353. #endif
  127354. typedef struct Fts3Table Fts3Table;
  127355. typedef struct Fts3Cursor Fts3Cursor;
  127356. typedef struct Fts3Expr Fts3Expr;
  127357. typedef struct Fts3Phrase Fts3Phrase;
  127358. typedef struct Fts3PhraseToken Fts3PhraseToken;
  127359. typedef struct Fts3Doclist Fts3Doclist;
  127360. typedef struct Fts3SegFilter Fts3SegFilter;
  127361. typedef struct Fts3DeferredToken Fts3DeferredToken;
  127362. typedef struct Fts3SegReader Fts3SegReader;
  127363. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  127364. typedef struct MatchinfoBuffer MatchinfoBuffer;
  127365. /*
  127366. ** A connection to a fulltext index is an instance of the following
  127367. ** structure. The xCreate and xConnect methods create an instance
  127368. ** of this structure and xDestroy and xDisconnect free that instance.
  127369. ** All other methods receive a pointer to the structure as one of their
  127370. ** arguments.
  127371. */
  127372. struct Fts3Table {
  127373. sqlite3_vtab base; /* Base class used by SQLite core */
  127374. sqlite3 *db; /* The database connection */
  127375. const char *zDb; /* logical database name */
  127376. const char *zName; /* virtual table name */
  127377. int nColumn; /* number of named columns in virtual table */
  127378. char **azColumn; /* column names. malloced */
  127379. u8 *abNotindexed; /* True for 'notindexed' columns */
  127380. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  127381. char *zContentTbl; /* content=xxx option, or NULL */
  127382. char *zLanguageid; /* languageid=xxx option, or NULL */
  127383. int nAutoincrmerge; /* Value configured by 'automerge' */
  127384. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  127385. /* Precompiled statements used by the implementation. Each of these
  127386. ** statements is run and reset within a single virtual table API call.
  127387. */
  127388. sqlite3_stmt *aStmt[40];
  127389. char *zReadExprlist;
  127390. char *zWriteExprlist;
  127391. int nNodeSize; /* Soft limit for node size */
  127392. u8 bFts4; /* True for FTS4, false for FTS3 */
  127393. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  127394. u8 bHasDocsize; /* True if %_docsize table exists */
  127395. u8 bDescIdx; /* True if doclists are in reverse order */
  127396. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  127397. int nPgsz; /* Page size for host database */
  127398. char *zSegmentsTbl; /* Name of %_segments table */
  127399. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  127400. /*
  127401. ** The following array of hash tables is used to buffer pending index
  127402. ** updates during transactions. All pending updates buffered at any one
  127403. ** time must share a common language-id (see the FTS4 langid= feature).
  127404. ** The current language id is stored in variable iPrevLangid.
  127405. **
  127406. ** A single FTS4 table may have multiple full-text indexes. For each index
  127407. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  127408. ** terms that appear in the document set. Each subsequent index in aIndex[]
  127409. ** is an index of prefixes of a specific length.
  127410. **
  127411. ** Variable nPendingData contains an estimate the memory consumed by the
  127412. ** pending data structures, including hash table overhead, but not including
  127413. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  127414. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  127415. ** recently inserted record.
  127416. */
  127417. int nIndex; /* Size of aIndex[] */
  127418. struct Fts3Index {
  127419. int nPrefix; /* Prefix length (0 for main terms index) */
  127420. Fts3Hash hPending; /* Pending terms table for this index */
  127421. } *aIndex;
  127422. int nMaxPendingData; /* Max pending data before flush to disk */
  127423. int nPendingData; /* Current bytes of pending data */
  127424. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  127425. int iPrevLangid; /* Langid of recently inserted document */
  127426. int bPrevDelete; /* True if last operation was a delete */
  127427. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  127428. /* State variables used for validating that the transaction control
  127429. ** methods of the virtual table are called at appropriate times. These
  127430. ** values do not contribute to FTS functionality; they are used for
  127431. ** verifying the operation of the SQLite core.
  127432. */
  127433. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  127434. int mxSavepoint; /* Largest valid xSavepoint integer */
  127435. #endif
  127436. #ifdef SQLITE_TEST
  127437. /* True to disable the incremental doclist optimization. This is controled
  127438. ** by special insert command 'test-no-incr-doclist'. */
  127439. int bNoIncrDoclist;
  127440. #endif
  127441. };
  127442. /*
  127443. ** When the core wants to read from the virtual table, it creates a
  127444. ** virtual table cursor (an instance of the following structure) using
  127445. ** the xOpen method. Cursors are destroyed using the xClose method.
  127446. */
  127447. struct Fts3Cursor {
  127448. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  127449. i16 eSearch; /* Search strategy (see below) */
  127450. u8 isEof; /* True if at End Of Results */
  127451. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  127452. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  127453. Fts3Expr *pExpr; /* Parsed MATCH query string */
  127454. int iLangid; /* Language being queried for */
  127455. int nPhrase; /* Number of matchable phrases in query */
  127456. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  127457. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  127458. char *pNextId; /* Pointer into the body of aDoclist */
  127459. char *aDoclist; /* List of docids for full-text queries */
  127460. int nDoclist; /* Size of buffer at aDoclist */
  127461. u8 bDesc; /* True to sort in descending order */
  127462. int eEvalmode; /* An FTS3_EVAL_XX constant */
  127463. int nRowAvg; /* Average size of database rows, in pages */
  127464. sqlite3_int64 nDoc; /* Documents in table */
  127465. i64 iMinDocid; /* Minimum docid to return */
  127466. i64 iMaxDocid; /* Maximum docid to return */
  127467. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  127468. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  127469. };
  127470. #define FTS3_EVAL_FILTER 0
  127471. #define FTS3_EVAL_NEXT 1
  127472. #define FTS3_EVAL_MATCHINFO 2
  127473. /*
  127474. ** The Fts3Cursor.eSearch member is always set to one of the following.
  127475. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  127476. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  127477. ** of the column to be searched. For example, in
  127478. **
  127479. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  127480. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  127481. **
  127482. ** Because the LHS of the MATCH operator is 2nd column "b",
  127483. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  127484. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  127485. ** indicating that all columns should be searched,
  127486. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  127487. */
  127488. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  127489. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  127490. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  127491. /*
  127492. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  127493. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  127494. ** above. The upper 16-bits contain a combination of the following
  127495. ** bits, used to describe extra constraints on full-text searches.
  127496. */
  127497. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  127498. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  127499. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  127500. struct Fts3Doclist {
  127501. char *aAll; /* Array containing doclist (or NULL) */
  127502. int nAll; /* Size of a[] in bytes */
  127503. char *pNextDocid; /* Pointer to next docid */
  127504. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  127505. int bFreeList; /* True if pList should be sqlite3_free()d */
  127506. char *pList; /* Pointer to position list following iDocid */
  127507. int nList; /* Length of position list */
  127508. };
  127509. /*
  127510. ** A "phrase" is a sequence of one or more tokens that must match in
  127511. ** sequence. A single token is the base case and the most common case.
  127512. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  127513. ** nToken will be the number of tokens in the string.
  127514. */
  127515. struct Fts3PhraseToken {
  127516. char *z; /* Text of the token */
  127517. int n; /* Number of bytes in buffer z */
  127518. int isPrefix; /* True if token ends with a "*" character */
  127519. int bFirst; /* True if token must appear at position 0 */
  127520. /* Variables above this point are populated when the expression is
  127521. ** parsed (by code in fts3_expr.c). Below this point the variables are
  127522. ** used when evaluating the expression. */
  127523. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  127524. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  127525. };
  127526. struct Fts3Phrase {
  127527. /* Cache of doclist for this phrase. */
  127528. Fts3Doclist doclist;
  127529. int bIncr; /* True if doclist is loaded incrementally */
  127530. int iDoclistToken;
  127531. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  127532. ** OR condition. */
  127533. char *pOrPoslist;
  127534. i64 iOrDocid;
  127535. /* Variables below this point are populated by fts3_expr.c when parsing
  127536. ** a MATCH expression. Everything above is part of the evaluation phase.
  127537. */
  127538. int nToken; /* Number of tokens in the phrase */
  127539. int iColumn; /* Index of column this phrase must match */
  127540. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  127541. };
  127542. /*
  127543. ** A tree of these objects forms the RHS of a MATCH operator.
  127544. **
  127545. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  127546. ** points to a malloced buffer, size nDoclist bytes, containing the results
  127547. ** of this phrase query in FTS3 doclist format. As usual, the initial
  127548. ** "Length" field found in doclists stored on disk is omitted from this
  127549. ** buffer.
  127550. **
  127551. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  127552. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  127553. ** where nCol is the number of columns in the queried FTS table. The array
  127554. ** is populated as follows:
  127555. **
  127556. ** aMI[iCol*3 + 0] = Undefined
  127557. ** aMI[iCol*3 + 1] = Number of occurrences
  127558. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  127559. **
  127560. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  127561. ** when the expression node is.
  127562. */
  127563. struct Fts3Expr {
  127564. int eType; /* One of the FTSQUERY_XXX values defined below */
  127565. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  127566. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  127567. Fts3Expr *pLeft; /* Left operand */
  127568. Fts3Expr *pRight; /* Right operand */
  127569. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  127570. /* The following are used by the fts3_eval.c module. */
  127571. sqlite3_int64 iDocid; /* Current docid */
  127572. u8 bEof; /* True this expression is at EOF already */
  127573. u8 bStart; /* True if iDocid is valid */
  127574. u8 bDeferred; /* True if this expression is entirely deferred */
  127575. /* The following are used by the fts3_snippet.c module. */
  127576. int iPhrase; /* Index of this phrase in matchinfo() results */
  127577. u32 *aMI; /* See above */
  127578. };
  127579. /*
  127580. ** Candidate values for Fts3Query.eType. Note that the order of the first
  127581. ** four values is in order of precedence when parsing expressions. For
  127582. ** example, the following:
  127583. **
  127584. ** "a OR b AND c NOT d NEAR e"
  127585. **
  127586. ** is equivalent to:
  127587. **
  127588. ** "a OR (b AND (c NOT (d NEAR e)))"
  127589. */
  127590. #define FTSQUERY_NEAR 1
  127591. #define FTSQUERY_NOT 2
  127592. #define FTSQUERY_AND 3
  127593. #define FTSQUERY_OR 4
  127594. #define FTSQUERY_PHRASE 5
  127595. /* fts3_write.c */
  127596. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  127597. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  127598. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  127599. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  127600. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  127601. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  127602. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  127603. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  127604. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  127605. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  127606. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  127607. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  127608. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  127609. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  127610. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  127611. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  127612. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  127613. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  127614. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  127615. #else
  127616. # define sqlite3Fts3FreeDeferredTokens(x)
  127617. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  127618. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  127619. # define sqlite3Fts3FreeDeferredDoclists(x)
  127620. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  127621. #endif
  127622. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  127623. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  127624. /* Special values interpreted by sqlite3SegReaderCursor() */
  127625. #define FTS3_SEGCURSOR_PENDING -1
  127626. #define FTS3_SEGCURSOR_ALL -2
  127627. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  127628. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  127629. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  127630. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  127631. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  127632. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  127633. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  127634. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  127635. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  127636. #define FTS3_SEGMENT_PREFIX 0x00000008
  127637. #define FTS3_SEGMENT_SCAN 0x00000010
  127638. #define FTS3_SEGMENT_FIRST 0x00000020
  127639. /* Type passed as 4th argument to SegmentReaderIterate() */
  127640. struct Fts3SegFilter {
  127641. const char *zTerm;
  127642. int nTerm;
  127643. int iCol;
  127644. int flags;
  127645. };
  127646. struct Fts3MultiSegReader {
  127647. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  127648. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  127649. int nSegment; /* Size of apSegment array */
  127650. int nAdvance; /* How many seg-readers to advance */
  127651. Fts3SegFilter *pFilter; /* Pointer to filter object */
  127652. char *aBuffer; /* Buffer to merge doclists in */
  127653. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  127654. int iColFilter; /* If >=0, filter for this column */
  127655. int bRestart;
  127656. /* Used by fts3.c only. */
  127657. int nCost; /* Cost of running iterator */
  127658. int bLookup; /* True if a lookup of a single entry. */
  127659. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  127660. char *zTerm; /* Pointer to term buffer */
  127661. int nTerm; /* Size of zTerm in bytes */
  127662. char *aDoclist; /* Pointer to doclist buffer */
  127663. int nDoclist; /* Size of aDoclist[] in bytes */
  127664. };
  127665. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  127666. #define fts3GetVarint32(p, piVal) ( \
  127667. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  127668. )
  127669. /* fts3.c */
  127670. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  127671. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  127672. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  127673. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  127674. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  127675. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  127676. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  127677. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  127678. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  127679. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  127680. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  127681. /* fts3_tokenizer.c */
  127682. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  127683. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  127684. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  127685. sqlite3_tokenizer **, char **
  127686. );
  127687. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  127688. /* fts3_snippet.c */
  127689. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  127690. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  127691. const char *, const char *, int, int
  127692. );
  127693. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  127694. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  127695. /* fts3_expr.c */
  127696. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  127697. char **, int, int, int, const char *, int, Fts3Expr **, char **
  127698. );
  127699. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  127700. #ifdef SQLITE_TEST
  127701. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  127702. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  127703. #endif
  127704. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  127705. sqlite3_tokenizer_cursor **
  127706. );
  127707. /* fts3_aux.c */
  127708. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  127709. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  127710. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  127711. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  127712. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  127713. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  127714. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  127715. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  127716. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  127717. /* fts3_tokenize_vtab.c */
  127718. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  127719. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  127720. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  127721. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  127722. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  127723. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  127724. #endif
  127725. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  127726. #endif /* _FTSINT_H */
  127727. /************** End of fts3Int.h *********************************************/
  127728. /************** Continuing where we left off in fts3.c ***********************/
  127729. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  127730. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  127731. # define SQLITE_CORE 1
  127732. #endif
  127733. /* #include <assert.h> */
  127734. /* #include <stdlib.h> */
  127735. /* #include <stddef.h> */
  127736. /* #include <stdio.h> */
  127737. /* #include <string.h> */
  127738. /* #include <stdarg.h> */
  127739. /* #include "fts3.h" */
  127740. #ifndef SQLITE_CORE
  127741. /* # include "sqlite3ext.h" */
  127742. SQLITE_EXTENSION_INIT1
  127743. #endif
  127744. static int fts3EvalNext(Fts3Cursor *pCsr);
  127745. static int fts3EvalStart(Fts3Cursor *pCsr);
  127746. static int fts3TermSegReaderCursor(
  127747. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  127748. #ifndef SQLITE_AMALGAMATION
  127749. # if defined(SQLITE_DEBUG)
  127750. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  127751. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  127752. # endif
  127753. #endif
  127754. /*
  127755. ** Write a 64-bit variable-length integer to memory starting at p[0].
  127756. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  127757. ** The number of bytes written is returned.
  127758. */
  127759. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  127760. unsigned char *q = (unsigned char *) p;
  127761. sqlite_uint64 vu = v;
  127762. do{
  127763. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  127764. vu >>= 7;
  127765. }while( vu!=0 );
  127766. q[-1] &= 0x7f; /* turn off high bit in final byte */
  127767. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  127768. return (int) (q - (unsigned char *)p);
  127769. }
  127770. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  127771. v = (v & mask1) | ( (*ptr++) << shift ); \
  127772. if( (v & mask2)==0 ){ var = v; return ret; }
  127773. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  127774. v = (*ptr++); \
  127775. if( (v & mask2)==0 ){ var = v; return ret; }
  127776. /*
  127777. ** Read a 64-bit variable-length integer from memory starting at p[0].
  127778. ** Return the number of bytes read, or 0 on error.
  127779. ** The value is stored in *v.
  127780. */
  127781. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  127782. const char *pStart = p;
  127783. u32 a;
  127784. u64 b;
  127785. int shift;
  127786. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  127787. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  127788. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  127789. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  127790. b = (a & 0x0FFFFFFF );
  127791. for(shift=28; shift<=63; shift+=7){
  127792. u64 c = *p++;
  127793. b += (c&0x7F) << shift;
  127794. if( (c & 0x80)==0 ) break;
  127795. }
  127796. *v = b;
  127797. return (int)(p - pStart);
  127798. }
  127799. /*
  127800. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  127801. ** 32-bit integer before it is returned.
  127802. */
  127803. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  127804. u32 a;
  127805. #ifndef fts3GetVarint32
  127806. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  127807. #else
  127808. a = (*p++);
  127809. assert( a & 0x80 );
  127810. #endif
  127811. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  127812. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  127813. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  127814. a = (a & 0x0FFFFFFF );
  127815. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  127816. return 5;
  127817. }
  127818. /*
  127819. ** Return the number of bytes required to encode v as a varint
  127820. */
  127821. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  127822. int i = 0;
  127823. do{
  127824. i++;
  127825. v >>= 7;
  127826. }while( v!=0 );
  127827. return i;
  127828. }
  127829. /*
  127830. ** Convert an SQL-style quoted string into a normal string by removing
  127831. ** the quote characters. The conversion is done in-place. If the
  127832. ** input does not begin with a quote character, then this routine
  127833. ** is a no-op.
  127834. **
  127835. ** Examples:
  127836. **
  127837. ** "abc" becomes abc
  127838. ** 'xyz' becomes xyz
  127839. ** [pqr] becomes pqr
  127840. ** `mno` becomes mno
  127841. **
  127842. */
  127843. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  127844. char quote; /* Quote character (if any ) */
  127845. quote = z[0];
  127846. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  127847. int iIn = 1; /* Index of next byte to read from input */
  127848. int iOut = 0; /* Index of next byte to write to output */
  127849. /* If the first byte was a '[', then the close-quote character is a ']' */
  127850. if( quote=='[' ) quote = ']';
  127851. while( z[iIn] ){
  127852. if( z[iIn]==quote ){
  127853. if( z[iIn+1]!=quote ) break;
  127854. z[iOut++] = quote;
  127855. iIn += 2;
  127856. }else{
  127857. z[iOut++] = z[iIn++];
  127858. }
  127859. }
  127860. z[iOut] = '\0';
  127861. }
  127862. }
  127863. /*
  127864. ** Read a single varint from the doclist at *pp and advance *pp to point
  127865. ** to the first byte past the end of the varint. Add the value of the varint
  127866. ** to *pVal.
  127867. */
  127868. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  127869. sqlite3_int64 iVal;
  127870. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  127871. *pVal += iVal;
  127872. }
  127873. /*
  127874. ** When this function is called, *pp points to the first byte following a
  127875. ** varint that is part of a doclist (or position-list, or any other list
  127876. ** of varints). This function moves *pp to point to the start of that varint,
  127877. ** and sets *pVal by the varint value.
  127878. **
  127879. ** Argument pStart points to the first byte of the doclist that the
  127880. ** varint is part of.
  127881. */
  127882. static void fts3GetReverseVarint(
  127883. char **pp,
  127884. char *pStart,
  127885. sqlite3_int64 *pVal
  127886. ){
  127887. sqlite3_int64 iVal;
  127888. char *p;
  127889. /* Pointer p now points at the first byte past the varint we are
  127890. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  127891. ** clear on character p[-1]. */
  127892. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  127893. p++;
  127894. *pp = p;
  127895. sqlite3Fts3GetVarint(p, &iVal);
  127896. *pVal = iVal;
  127897. }
  127898. /*
  127899. ** The xDisconnect() virtual table method.
  127900. */
  127901. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  127902. Fts3Table *p = (Fts3Table *)pVtab;
  127903. int i;
  127904. assert( p->nPendingData==0 );
  127905. assert( p->pSegments==0 );
  127906. /* Free any prepared statements held */
  127907. for(i=0; i<SizeofArray(p->aStmt); i++){
  127908. sqlite3_finalize(p->aStmt[i]);
  127909. }
  127910. sqlite3_free(p->zSegmentsTbl);
  127911. sqlite3_free(p->zReadExprlist);
  127912. sqlite3_free(p->zWriteExprlist);
  127913. sqlite3_free(p->zContentTbl);
  127914. sqlite3_free(p->zLanguageid);
  127915. /* Invoke the tokenizer destructor to free the tokenizer. */
  127916. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  127917. sqlite3_free(p);
  127918. return SQLITE_OK;
  127919. }
  127920. /*
  127921. ** Write an error message into *pzErr
  127922. */
  127923. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  127924. va_list ap;
  127925. sqlite3_free(*pzErr);
  127926. va_start(ap, zFormat);
  127927. *pzErr = sqlite3_vmprintf(zFormat, ap);
  127928. va_end(ap);
  127929. }
  127930. /*
  127931. ** Construct one or more SQL statements from the format string given
  127932. ** and then evaluate those statements. The success code is written
  127933. ** into *pRc.
  127934. **
  127935. ** If *pRc is initially non-zero then this routine is a no-op.
  127936. */
  127937. static void fts3DbExec(
  127938. int *pRc, /* Success code */
  127939. sqlite3 *db, /* Database in which to run SQL */
  127940. const char *zFormat, /* Format string for SQL */
  127941. ... /* Arguments to the format string */
  127942. ){
  127943. va_list ap;
  127944. char *zSql;
  127945. if( *pRc ) return;
  127946. va_start(ap, zFormat);
  127947. zSql = sqlite3_vmprintf(zFormat, ap);
  127948. va_end(ap);
  127949. if( zSql==0 ){
  127950. *pRc = SQLITE_NOMEM;
  127951. }else{
  127952. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  127953. sqlite3_free(zSql);
  127954. }
  127955. }
  127956. /*
  127957. ** The xDestroy() virtual table method.
  127958. */
  127959. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  127960. Fts3Table *p = (Fts3Table *)pVtab;
  127961. int rc = SQLITE_OK; /* Return code */
  127962. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  127963. sqlite3 *db = p->db; /* Database handle */
  127964. /* Drop the shadow tables */
  127965. if( p->zContentTbl==0 ){
  127966. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  127967. }
  127968. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  127969. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  127970. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  127971. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  127972. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  127973. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  127974. ** Otherwise, return an SQLite error code.
  127975. */
  127976. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  127977. }
  127978. /*
  127979. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  127980. ** passed as the first argument. This is done as part of the xConnect()
  127981. ** and xCreate() methods.
  127982. **
  127983. ** If *pRc is non-zero when this function is called, it is a no-op.
  127984. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  127985. ** before returning.
  127986. */
  127987. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  127988. if( *pRc==SQLITE_OK ){
  127989. int i; /* Iterator variable */
  127990. int rc; /* Return code */
  127991. char *zSql; /* SQL statement passed to declare_vtab() */
  127992. char *zCols; /* List of user defined columns */
  127993. const char *zLanguageid;
  127994. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  127995. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  127996. /* Create a list of user columns for the virtual table */
  127997. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  127998. for(i=1; zCols && i<p->nColumn; i++){
  127999. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  128000. }
  128001. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  128002. zSql = sqlite3_mprintf(
  128003. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  128004. zCols, p->zName, zLanguageid
  128005. );
  128006. if( !zCols || !zSql ){
  128007. rc = SQLITE_NOMEM;
  128008. }else{
  128009. rc = sqlite3_declare_vtab(p->db, zSql);
  128010. }
  128011. sqlite3_free(zSql);
  128012. sqlite3_free(zCols);
  128013. *pRc = rc;
  128014. }
  128015. }
  128016. /*
  128017. ** Create the %_stat table if it does not already exist.
  128018. */
  128019. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  128020. fts3DbExec(pRc, p->db,
  128021. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  128022. "(id INTEGER PRIMARY KEY, value BLOB);",
  128023. p->zDb, p->zName
  128024. );
  128025. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  128026. }
  128027. /*
  128028. ** Create the backing store tables (%_content, %_segments and %_segdir)
  128029. ** required by the FTS3 table passed as the only argument. This is done
  128030. ** as part of the vtab xCreate() method.
  128031. **
  128032. ** If the p->bHasDocsize boolean is true (indicating that this is an
  128033. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  128034. ** %_stat tables required by FTS4.
  128035. */
  128036. static int fts3CreateTables(Fts3Table *p){
  128037. int rc = SQLITE_OK; /* Return code */
  128038. int i; /* Iterator variable */
  128039. sqlite3 *db = p->db; /* The database connection */
  128040. if( p->zContentTbl==0 ){
  128041. const char *zLanguageid = p->zLanguageid;
  128042. char *zContentCols; /* Columns of %_content table */
  128043. /* Create a list of user columns for the content table */
  128044. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  128045. for(i=0; zContentCols && i<p->nColumn; i++){
  128046. char *z = p->azColumn[i];
  128047. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  128048. }
  128049. if( zLanguageid && zContentCols ){
  128050. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  128051. }
  128052. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  128053. /* Create the content table */
  128054. fts3DbExec(&rc, db,
  128055. "CREATE TABLE %Q.'%q_content'(%s)",
  128056. p->zDb, p->zName, zContentCols
  128057. );
  128058. sqlite3_free(zContentCols);
  128059. }
  128060. /* Create other tables */
  128061. fts3DbExec(&rc, db,
  128062. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  128063. p->zDb, p->zName
  128064. );
  128065. fts3DbExec(&rc, db,
  128066. "CREATE TABLE %Q.'%q_segdir'("
  128067. "level INTEGER,"
  128068. "idx INTEGER,"
  128069. "start_block INTEGER,"
  128070. "leaves_end_block INTEGER,"
  128071. "end_block INTEGER,"
  128072. "root BLOB,"
  128073. "PRIMARY KEY(level, idx)"
  128074. ");",
  128075. p->zDb, p->zName
  128076. );
  128077. if( p->bHasDocsize ){
  128078. fts3DbExec(&rc, db,
  128079. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  128080. p->zDb, p->zName
  128081. );
  128082. }
  128083. assert( p->bHasStat==p->bFts4 );
  128084. if( p->bHasStat ){
  128085. sqlite3Fts3CreateStatTable(&rc, p);
  128086. }
  128087. return rc;
  128088. }
  128089. /*
  128090. ** Store the current database page-size in bytes in p->nPgsz.
  128091. **
  128092. ** If *pRc is non-zero when this function is called, it is a no-op.
  128093. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  128094. ** before returning.
  128095. */
  128096. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  128097. if( *pRc==SQLITE_OK ){
  128098. int rc; /* Return code */
  128099. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  128100. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  128101. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  128102. if( !zSql ){
  128103. rc = SQLITE_NOMEM;
  128104. }else{
  128105. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  128106. if( rc==SQLITE_OK ){
  128107. sqlite3_step(pStmt);
  128108. p->nPgsz = sqlite3_column_int(pStmt, 0);
  128109. rc = sqlite3_finalize(pStmt);
  128110. }else if( rc==SQLITE_AUTH ){
  128111. p->nPgsz = 1024;
  128112. rc = SQLITE_OK;
  128113. }
  128114. }
  128115. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  128116. sqlite3_free(zSql);
  128117. *pRc = rc;
  128118. }
  128119. }
  128120. /*
  128121. ** "Special" FTS4 arguments are column specifications of the following form:
  128122. **
  128123. ** <key> = <value>
  128124. **
  128125. ** There may not be whitespace surrounding the "=" character. The <value>
  128126. ** term may be quoted, but the <key> may not.
  128127. */
  128128. static int fts3IsSpecialColumn(
  128129. const char *z,
  128130. int *pnKey,
  128131. char **pzValue
  128132. ){
  128133. char *zValue;
  128134. const char *zCsr = z;
  128135. while( *zCsr!='=' ){
  128136. if( *zCsr=='\0' ) return 0;
  128137. zCsr++;
  128138. }
  128139. *pnKey = (int)(zCsr-z);
  128140. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  128141. if( zValue ){
  128142. sqlite3Fts3Dequote(zValue);
  128143. }
  128144. *pzValue = zValue;
  128145. return 1;
  128146. }
  128147. /*
  128148. ** Append the output of a printf() style formatting to an existing string.
  128149. */
  128150. static void fts3Appendf(
  128151. int *pRc, /* IN/OUT: Error code */
  128152. char **pz, /* IN/OUT: Pointer to string buffer */
  128153. const char *zFormat, /* Printf format string to append */
  128154. ... /* Arguments for printf format string */
  128155. ){
  128156. if( *pRc==SQLITE_OK ){
  128157. va_list ap;
  128158. char *z;
  128159. va_start(ap, zFormat);
  128160. z = sqlite3_vmprintf(zFormat, ap);
  128161. va_end(ap);
  128162. if( z && *pz ){
  128163. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  128164. sqlite3_free(z);
  128165. z = z2;
  128166. }
  128167. if( z==0 ) *pRc = SQLITE_NOMEM;
  128168. sqlite3_free(*pz);
  128169. *pz = z;
  128170. }
  128171. }
  128172. /*
  128173. ** Return a copy of input string zInput enclosed in double-quotes (") and
  128174. ** with all double quote characters escaped. For example:
  128175. **
  128176. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  128177. **
  128178. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  128179. ** is the callers responsibility to call sqlite3_free() to release this
  128180. ** memory.
  128181. */
  128182. static char *fts3QuoteId(char const *zInput){
  128183. int nRet;
  128184. char *zRet;
  128185. nRet = 2 + (int)strlen(zInput)*2 + 1;
  128186. zRet = sqlite3_malloc(nRet);
  128187. if( zRet ){
  128188. int i;
  128189. char *z = zRet;
  128190. *(z++) = '"';
  128191. for(i=0; zInput[i]; i++){
  128192. if( zInput[i]=='"' ) *(z++) = '"';
  128193. *(z++) = zInput[i];
  128194. }
  128195. *(z++) = '"';
  128196. *(z++) = '\0';
  128197. }
  128198. return zRet;
  128199. }
  128200. /*
  128201. ** Return a list of comma separated SQL expressions and a FROM clause that
  128202. ** could be used in a SELECT statement such as the following:
  128203. **
  128204. ** SELECT <list of expressions> FROM %_content AS x ...
  128205. **
  128206. ** to return the docid, followed by each column of text data in order
  128207. ** from left to write. If parameter zFunc is not NULL, then instead of
  128208. ** being returned directly each column of text data is passed to an SQL
  128209. ** function named zFunc first. For example, if zFunc is "unzip" and the
  128210. ** table has the three user-defined columns "a", "b", and "c", the following
  128211. ** string is returned:
  128212. **
  128213. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  128214. **
  128215. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  128216. ** is the responsibility of the caller to eventually free it.
  128217. **
  128218. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  128219. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  128220. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  128221. ** no error occurs, *pRc is left unmodified.
  128222. */
  128223. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  128224. char *zRet = 0;
  128225. char *zFree = 0;
  128226. char *zFunction;
  128227. int i;
  128228. if( p->zContentTbl==0 ){
  128229. if( !zFunc ){
  128230. zFunction = "";
  128231. }else{
  128232. zFree = zFunction = fts3QuoteId(zFunc);
  128233. }
  128234. fts3Appendf(pRc, &zRet, "docid");
  128235. for(i=0; i<p->nColumn; i++){
  128236. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  128237. }
  128238. if( p->zLanguageid ){
  128239. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  128240. }
  128241. sqlite3_free(zFree);
  128242. }else{
  128243. fts3Appendf(pRc, &zRet, "rowid");
  128244. for(i=0; i<p->nColumn; i++){
  128245. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  128246. }
  128247. if( p->zLanguageid ){
  128248. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  128249. }
  128250. }
  128251. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  128252. p->zDb,
  128253. (p->zContentTbl ? p->zContentTbl : p->zName),
  128254. (p->zContentTbl ? "" : "_content")
  128255. );
  128256. return zRet;
  128257. }
  128258. /*
  128259. ** Return a list of N comma separated question marks, where N is the number
  128260. ** of columns in the %_content table (one for the docid plus one for each
  128261. ** user-defined text column).
  128262. **
  128263. ** If argument zFunc is not NULL, then all but the first question mark
  128264. ** is preceded by zFunc and an open bracket, and followed by a closed
  128265. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  128266. ** user-defined text columns, the following string is returned:
  128267. **
  128268. ** "?, zip(?), zip(?), zip(?)"
  128269. **
  128270. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  128271. ** is the responsibility of the caller to eventually free it.
  128272. **
  128273. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  128274. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  128275. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  128276. ** no error occurs, *pRc is left unmodified.
  128277. */
  128278. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  128279. char *zRet = 0;
  128280. char *zFree = 0;
  128281. char *zFunction;
  128282. int i;
  128283. if( !zFunc ){
  128284. zFunction = "";
  128285. }else{
  128286. zFree = zFunction = fts3QuoteId(zFunc);
  128287. }
  128288. fts3Appendf(pRc, &zRet, "?");
  128289. for(i=0; i<p->nColumn; i++){
  128290. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  128291. }
  128292. if( p->zLanguageid ){
  128293. fts3Appendf(pRc, &zRet, ", ?");
  128294. }
  128295. sqlite3_free(zFree);
  128296. return zRet;
  128297. }
  128298. /*
  128299. ** This function interprets the string at (*pp) as a non-negative integer
  128300. ** value. It reads the integer and sets *pnOut to the value read, then
  128301. ** sets *pp to point to the byte immediately following the last byte of
  128302. ** the integer value.
  128303. **
  128304. ** Only decimal digits ('0'..'9') may be part of an integer value.
  128305. **
  128306. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  128307. ** the output value undefined. Otherwise SQLITE_OK is returned.
  128308. **
  128309. ** This function is used when parsing the "prefix=" FTS4 parameter.
  128310. */
  128311. static int fts3GobbleInt(const char **pp, int *pnOut){
  128312. const int MAX_NPREFIX = 10000000;
  128313. const char *p; /* Iterator pointer */
  128314. int nInt = 0; /* Output value */
  128315. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  128316. nInt = nInt * 10 + (p[0] - '0');
  128317. if( nInt>MAX_NPREFIX ){
  128318. nInt = 0;
  128319. break;
  128320. }
  128321. }
  128322. if( p==*pp ) return SQLITE_ERROR;
  128323. *pnOut = nInt;
  128324. *pp = p;
  128325. return SQLITE_OK;
  128326. }
  128327. /*
  128328. ** This function is called to allocate an array of Fts3Index structures
  128329. ** representing the indexes maintained by the current FTS table. FTS tables
  128330. ** always maintain the main "terms" index, but may also maintain one or
  128331. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  128332. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  128333. **
  128334. ** Argument zParam is passed the value of the "prefix=" option if one was
  128335. ** specified, or NULL otherwise.
  128336. **
  128337. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  128338. ** the allocated array. *pnIndex is set to the number of elements in the
  128339. ** array. If an error does occur, an SQLite error code is returned.
  128340. **
  128341. ** Regardless of whether or not an error is returned, it is the responsibility
  128342. ** of the caller to call sqlite3_free() on the output array to free it.
  128343. */
  128344. static int fts3PrefixParameter(
  128345. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  128346. int *pnIndex, /* OUT: size of *apIndex[] array */
  128347. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  128348. ){
  128349. struct Fts3Index *aIndex; /* Allocated array */
  128350. int nIndex = 1; /* Number of entries in array */
  128351. if( zParam && zParam[0] ){
  128352. const char *p;
  128353. nIndex++;
  128354. for(p=zParam; *p; p++){
  128355. if( *p==',' ) nIndex++;
  128356. }
  128357. }
  128358. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  128359. *apIndex = aIndex;
  128360. if( !aIndex ){
  128361. return SQLITE_NOMEM;
  128362. }
  128363. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  128364. if( zParam ){
  128365. const char *p = zParam;
  128366. int i;
  128367. for(i=1; i<nIndex; i++){
  128368. int nPrefix = 0;
  128369. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  128370. assert( nPrefix>=0 );
  128371. if( nPrefix==0 ){
  128372. nIndex--;
  128373. i--;
  128374. }else{
  128375. aIndex[i].nPrefix = nPrefix;
  128376. }
  128377. p++;
  128378. }
  128379. }
  128380. *pnIndex = nIndex;
  128381. return SQLITE_OK;
  128382. }
  128383. /*
  128384. ** This function is called when initializing an FTS4 table that uses the
  128385. ** content=xxx option. It determines the number of and names of the columns
  128386. ** of the new FTS4 table.
  128387. **
  128388. ** The third argument passed to this function is the value passed to the
  128389. ** config=xxx option (i.e. "xxx"). This function queries the database for
  128390. ** a table of that name. If found, the output variables are populated
  128391. ** as follows:
  128392. **
  128393. ** *pnCol: Set to the number of columns table xxx has,
  128394. **
  128395. ** *pnStr: Set to the total amount of space required to store a copy
  128396. ** of each columns name, including the nul-terminator.
  128397. **
  128398. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  128399. ** the name of the corresponding column in table xxx. The array
  128400. ** and its contents are allocated using a single allocation. It
  128401. ** is the responsibility of the caller to free this allocation
  128402. ** by eventually passing the *pazCol value to sqlite3_free().
  128403. **
  128404. ** If the table cannot be found, an error code is returned and the output
  128405. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  128406. ** returned (and the output variables are undefined).
  128407. */
  128408. static int fts3ContentColumns(
  128409. sqlite3 *db, /* Database handle */
  128410. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  128411. const char *zTbl, /* Name of content table */
  128412. const char ***pazCol, /* OUT: Malloc'd array of column names */
  128413. int *pnCol, /* OUT: Size of array *pazCol */
  128414. int *pnStr, /* OUT: Bytes of string content */
  128415. char **pzErr /* OUT: error message */
  128416. ){
  128417. int rc = SQLITE_OK; /* Return code */
  128418. char *zSql; /* "SELECT *" statement on zTbl */
  128419. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  128420. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  128421. if( !zSql ){
  128422. rc = SQLITE_NOMEM;
  128423. }else{
  128424. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  128425. if( rc!=SQLITE_OK ){
  128426. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  128427. }
  128428. }
  128429. sqlite3_free(zSql);
  128430. if( rc==SQLITE_OK ){
  128431. const char **azCol; /* Output array */
  128432. int nStr = 0; /* Size of all column names (incl. 0x00) */
  128433. int nCol; /* Number of table columns */
  128434. int i; /* Used to iterate through columns */
  128435. /* Loop through the returned columns. Set nStr to the number of bytes of
  128436. ** space required to store a copy of each column name, including the
  128437. ** nul-terminator byte. */
  128438. nCol = sqlite3_column_count(pStmt);
  128439. for(i=0; i<nCol; i++){
  128440. const char *zCol = sqlite3_column_name(pStmt, i);
  128441. nStr += (int)strlen(zCol) + 1;
  128442. }
  128443. /* Allocate and populate the array to return. */
  128444. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  128445. if( azCol==0 ){
  128446. rc = SQLITE_NOMEM;
  128447. }else{
  128448. char *p = (char *)&azCol[nCol];
  128449. for(i=0; i<nCol; i++){
  128450. const char *zCol = sqlite3_column_name(pStmt, i);
  128451. int n = (int)strlen(zCol)+1;
  128452. memcpy(p, zCol, n);
  128453. azCol[i] = p;
  128454. p += n;
  128455. }
  128456. }
  128457. sqlite3_finalize(pStmt);
  128458. /* Set the output variables. */
  128459. *pnCol = nCol;
  128460. *pnStr = nStr;
  128461. *pazCol = azCol;
  128462. }
  128463. return rc;
  128464. }
  128465. /*
  128466. ** This function is the implementation of both the xConnect and xCreate
  128467. ** methods of the FTS3 virtual table.
  128468. **
  128469. ** The argv[] array contains the following:
  128470. **
  128471. ** argv[0] -> module name ("fts3" or "fts4")
  128472. ** argv[1] -> database name
  128473. ** argv[2] -> table name
  128474. ** argv[...] -> "column name" and other module argument fields.
  128475. */
  128476. static int fts3InitVtab(
  128477. int isCreate, /* True for xCreate, false for xConnect */
  128478. sqlite3 *db, /* The SQLite database connection */
  128479. void *pAux, /* Hash table containing tokenizers */
  128480. int argc, /* Number of elements in argv array */
  128481. const char * const *argv, /* xCreate/xConnect argument array */
  128482. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  128483. char **pzErr /* Write any error message here */
  128484. ){
  128485. Fts3Hash *pHash = (Fts3Hash *)pAux;
  128486. Fts3Table *p = 0; /* Pointer to allocated vtab */
  128487. int rc = SQLITE_OK; /* Return code */
  128488. int i; /* Iterator variable */
  128489. int nByte; /* Size of allocation used for *p */
  128490. int iCol; /* Column index */
  128491. int nString = 0; /* Bytes required to hold all column names */
  128492. int nCol = 0; /* Number of columns in the FTS table */
  128493. char *zCsr; /* Space for holding column names */
  128494. int nDb; /* Bytes required to hold database name */
  128495. int nName; /* Bytes required to hold table name */
  128496. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  128497. const char **aCol; /* Array of column names */
  128498. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  128499. int nIndex = 0; /* Size of aIndex[] array */
  128500. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  128501. /* The results of parsing supported FTS4 key=value options: */
  128502. int bNoDocsize = 0; /* True to omit %_docsize table */
  128503. int bDescIdx = 0; /* True to store descending indexes */
  128504. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  128505. char *zCompress = 0; /* compress=? parameter (or NULL) */
  128506. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  128507. char *zContent = 0; /* content=? parameter (or NULL) */
  128508. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  128509. char **azNotindexed = 0; /* The set of notindexed= columns */
  128510. int nNotindexed = 0; /* Size of azNotindexed[] array */
  128511. assert( strlen(argv[0])==4 );
  128512. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  128513. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  128514. );
  128515. nDb = (int)strlen(argv[1]) + 1;
  128516. nName = (int)strlen(argv[2]) + 1;
  128517. nByte = sizeof(const char *) * (argc-2);
  128518. aCol = (const char **)sqlite3_malloc(nByte);
  128519. if( aCol ){
  128520. memset((void*)aCol, 0, nByte);
  128521. azNotindexed = (char **)sqlite3_malloc(nByte);
  128522. }
  128523. if( azNotindexed ){
  128524. memset(azNotindexed, 0, nByte);
  128525. }
  128526. if( !aCol || !azNotindexed ){
  128527. rc = SQLITE_NOMEM;
  128528. goto fts3_init_out;
  128529. }
  128530. /* Loop through all of the arguments passed by the user to the FTS3/4
  128531. ** module (i.e. all the column names and special arguments). This loop
  128532. ** does the following:
  128533. **
  128534. ** + Figures out the number of columns the FTSX table will have, and
  128535. ** the number of bytes of space that must be allocated to store copies
  128536. ** of the column names.
  128537. **
  128538. ** + If there is a tokenizer specification included in the arguments,
  128539. ** initializes the tokenizer pTokenizer.
  128540. */
  128541. for(i=3; rc==SQLITE_OK && i<argc; i++){
  128542. char const *z = argv[i];
  128543. int nKey;
  128544. char *zVal;
  128545. /* Check if this is a tokenizer specification */
  128546. if( !pTokenizer
  128547. && strlen(z)>8
  128548. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  128549. && 0==sqlite3Fts3IsIdChar(z[8])
  128550. ){
  128551. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  128552. }
  128553. /* Check if it is an FTS4 special argument. */
  128554. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  128555. struct Fts4Option {
  128556. const char *zOpt;
  128557. int nOpt;
  128558. } aFts4Opt[] = {
  128559. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  128560. { "prefix", 6 }, /* 1 -> PREFIX */
  128561. { "compress", 8 }, /* 2 -> COMPRESS */
  128562. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  128563. { "order", 5 }, /* 4 -> ORDER */
  128564. { "content", 7 }, /* 5 -> CONTENT */
  128565. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  128566. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  128567. };
  128568. int iOpt;
  128569. if( !zVal ){
  128570. rc = SQLITE_NOMEM;
  128571. }else{
  128572. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  128573. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  128574. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  128575. break;
  128576. }
  128577. }
  128578. if( iOpt==SizeofArray(aFts4Opt) ){
  128579. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  128580. rc = SQLITE_ERROR;
  128581. }else{
  128582. switch( iOpt ){
  128583. case 0: /* MATCHINFO */
  128584. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  128585. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  128586. rc = SQLITE_ERROR;
  128587. }
  128588. bNoDocsize = 1;
  128589. break;
  128590. case 1: /* PREFIX */
  128591. sqlite3_free(zPrefix);
  128592. zPrefix = zVal;
  128593. zVal = 0;
  128594. break;
  128595. case 2: /* COMPRESS */
  128596. sqlite3_free(zCompress);
  128597. zCompress = zVal;
  128598. zVal = 0;
  128599. break;
  128600. case 3: /* UNCOMPRESS */
  128601. sqlite3_free(zUncompress);
  128602. zUncompress = zVal;
  128603. zVal = 0;
  128604. break;
  128605. case 4: /* ORDER */
  128606. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  128607. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  128608. ){
  128609. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  128610. rc = SQLITE_ERROR;
  128611. }
  128612. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  128613. break;
  128614. case 5: /* CONTENT */
  128615. sqlite3_free(zContent);
  128616. zContent = zVal;
  128617. zVal = 0;
  128618. break;
  128619. case 6: /* LANGUAGEID */
  128620. assert( iOpt==6 );
  128621. sqlite3_free(zLanguageid);
  128622. zLanguageid = zVal;
  128623. zVal = 0;
  128624. break;
  128625. case 7: /* NOTINDEXED */
  128626. azNotindexed[nNotindexed++] = zVal;
  128627. zVal = 0;
  128628. break;
  128629. }
  128630. }
  128631. sqlite3_free(zVal);
  128632. }
  128633. }
  128634. /* Otherwise, the argument is a column name. */
  128635. else {
  128636. nString += (int)(strlen(z) + 1);
  128637. aCol[nCol++] = z;
  128638. }
  128639. }
  128640. /* If a content=xxx option was specified, the following:
  128641. **
  128642. ** 1. Ignore any compress= and uncompress= options.
  128643. **
  128644. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  128645. ** TABLE statement, use all columns from the content table.
  128646. */
  128647. if( rc==SQLITE_OK && zContent ){
  128648. sqlite3_free(zCompress);
  128649. sqlite3_free(zUncompress);
  128650. zCompress = 0;
  128651. zUncompress = 0;
  128652. if( nCol==0 ){
  128653. sqlite3_free((void*)aCol);
  128654. aCol = 0;
  128655. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  128656. /* If a languageid= option was specified, remove the language id
  128657. ** column from the aCol[] array. */
  128658. if( rc==SQLITE_OK && zLanguageid ){
  128659. int j;
  128660. for(j=0; j<nCol; j++){
  128661. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  128662. int k;
  128663. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  128664. nCol--;
  128665. break;
  128666. }
  128667. }
  128668. }
  128669. }
  128670. }
  128671. if( rc!=SQLITE_OK ) goto fts3_init_out;
  128672. if( nCol==0 ){
  128673. assert( nString==0 );
  128674. aCol[0] = "content";
  128675. nString = 8;
  128676. nCol = 1;
  128677. }
  128678. if( pTokenizer==0 ){
  128679. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  128680. if( rc!=SQLITE_OK ) goto fts3_init_out;
  128681. }
  128682. assert( pTokenizer );
  128683. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  128684. if( rc==SQLITE_ERROR ){
  128685. assert( zPrefix );
  128686. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  128687. }
  128688. if( rc!=SQLITE_OK ) goto fts3_init_out;
  128689. /* Allocate and populate the Fts3Table structure. */
  128690. nByte = sizeof(Fts3Table) + /* Fts3Table */
  128691. nCol * sizeof(char *) + /* azColumn */
  128692. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  128693. nCol * sizeof(u8) + /* abNotindexed */
  128694. nName + /* zName */
  128695. nDb + /* zDb */
  128696. nString; /* Space for azColumn strings */
  128697. p = (Fts3Table*)sqlite3_malloc(nByte);
  128698. if( p==0 ){
  128699. rc = SQLITE_NOMEM;
  128700. goto fts3_init_out;
  128701. }
  128702. memset(p, 0, nByte);
  128703. p->db = db;
  128704. p->nColumn = nCol;
  128705. p->nPendingData = 0;
  128706. p->azColumn = (char **)&p[1];
  128707. p->pTokenizer = pTokenizer;
  128708. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  128709. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  128710. p->bHasStat = isFts4;
  128711. p->bFts4 = isFts4;
  128712. p->bDescIdx = bDescIdx;
  128713. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  128714. p->zContentTbl = zContent;
  128715. p->zLanguageid = zLanguageid;
  128716. zContent = 0;
  128717. zLanguageid = 0;
  128718. TESTONLY( p->inTransaction = -1 );
  128719. TESTONLY( p->mxSavepoint = -1 );
  128720. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  128721. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  128722. p->nIndex = nIndex;
  128723. for(i=0; i<nIndex; i++){
  128724. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  128725. }
  128726. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  128727. /* Fill in the zName and zDb fields of the vtab structure. */
  128728. zCsr = (char *)&p->abNotindexed[nCol];
  128729. p->zName = zCsr;
  128730. memcpy(zCsr, argv[2], nName);
  128731. zCsr += nName;
  128732. p->zDb = zCsr;
  128733. memcpy(zCsr, argv[1], nDb);
  128734. zCsr += nDb;
  128735. /* Fill in the azColumn array */
  128736. for(iCol=0; iCol<nCol; iCol++){
  128737. char *z;
  128738. int n = 0;
  128739. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  128740. memcpy(zCsr, z, n);
  128741. zCsr[n] = '\0';
  128742. sqlite3Fts3Dequote(zCsr);
  128743. p->azColumn[iCol] = zCsr;
  128744. zCsr += n+1;
  128745. assert( zCsr <= &((char *)p)[nByte] );
  128746. }
  128747. /* Fill in the abNotindexed array */
  128748. for(iCol=0; iCol<nCol; iCol++){
  128749. int n = (int)strlen(p->azColumn[iCol]);
  128750. for(i=0; i<nNotindexed; i++){
  128751. char *zNot = azNotindexed[i];
  128752. if( zNot && n==(int)strlen(zNot)
  128753. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  128754. ){
  128755. p->abNotindexed[iCol] = 1;
  128756. sqlite3_free(zNot);
  128757. azNotindexed[i] = 0;
  128758. }
  128759. }
  128760. }
  128761. for(i=0; i<nNotindexed; i++){
  128762. if( azNotindexed[i] ){
  128763. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  128764. rc = SQLITE_ERROR;
  128765. }
  128766. }
  128767. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  128768. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  128769. rc = SQLITE_ERROR;
  128770. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  128771. }
  128772. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  128773. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  128774. if( rc!=SQLITE_OK ) goto fts3_init_out;
  128775. /* If this is an xCreate call, create the underlying tables in the
  128776. ** database. TODO: For xConnect(), it could verify that said tables exist.
  128777. */
  128778. if( isCreate ){
  128779. rc = fts3CreateTables(p);
  128780. }
  128781. /* Check to see if a legacy fts3 table has been "upgraded" by the
  128782. ** addition of a %_stat table so that it can use incremental merge.
  128783. */
  128784. if( !isFts4 && !isCreate ){
  128785. p->bHasStat = 2;
  128786. }
  128787. /* Figure out the page-size for the database. This is required in order to
  128788. ** estimate the cost of loading large doclists from the database. */
  128789. fts3DatabasePageSize(&rc, p);
  128790. p->nNodeSize = p->nPgsz-35;
  128791. /* Declare the table schema to SQLite. */
  128792. fts3DeclareVtab(&rc, p);
  128793. fts3_init_out:
  128794. sqlite3_free(zPrefix);
  128795. sqlite3_free(aIndex);
  128796. sqlite3_free(zCompress);
  128797. sqlite3_free(zUncompress);
  128798. sqlite3_free(zContent);
  128799. sqlite3_free(zLanguageid);
  128800. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  128801. sqlite3_free((void *)aCol);
  128802. sqlite3_free((void *)azNotindexed);
  128803. if( rc!=SQLITE_OK ){
  128804. if( p ){
  128805. fts3DisconnectMethod((sqlite3_vtab *)p);
  128806. }else if( pTokenizer ){
  128807. pTokenizer->pModule->xDestroy(pTokenizer);
  128808. }
  128809. }else{
  128810. assert( p->pSegments==0 );
  128811. *ppVTab = &p->base;
  128812. }
  128813. return rc;
  128814. }
  128815. /*
  128816. ** The xConnect() and xCreate() methods for the virtual table. All the
  128817. ** work is done in function fts3InitVtab().
  128818. */
  128819. static int fts3ConnectMethod(
  128820. sqlite3 *db, /* Database connection */
  128821. void *pAux, /* Pointer to tokenizer hash table */
  128822. int argc, /* Number of elements in argv array */
  128823. const char * const *argv, /* xCreate/xConnect argument array */
  128824. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  128825. char **pzErr /* OUT: sqlite3_malloc'd error message */
  128826. ){
  128827. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  128828. }
  128829. static int fts3CreateMethod(
  128830. sqlite3 *db, /* Database connection */
  128831. void *pAux, /* Pointer to tokenizer hash table */
  128832. int argc, /* Number of elements in argv array */
  128833. const char * const *argv, /* xCreate/xConnect argument array */
  128834. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  128835. char **pzErr /* OUT: sqlite3_malloc'd error message */
  128836. ){
  128837. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  128838. }
  128839. /*
  128840. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  128841. ** extension is currently being used by a version of SQLite too old to
  128842. ** support estimatedRows. In that case this function is a no-op.
  128843. */
  128844. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  128845. #if SQLITE_VERSION_NUMBER>=3008002
  128846. if( sqlite3_libversion_number()>=3008002 ){
  128847. pIdxInfo->estimatedRows = nRow;
  128848. }
  128849. #endif
  128850. }
  128851. /*
  128852. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  128853. ** extension is currently being used by a version of SQLite too old to
  128854. ** support index-info flags. In that case this function is a no-op.
  128855. */
  128856. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  128857. #if SQLITE_VERSION_NUMBER>=3008012
  128858. if( sqlite3_libversion_number()>=3008012 ){
  128859. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  128860. }
  128861. #endif
  128862. }
  128863. /*
  128864. ** Implementation of the xBestIndex method for FTS3 tables. There
  128865. ** are three possible strategies, in order of preference:
  128866. **
  128867. ** 1. Direct lookup by rowid or docid.
  128868. ** 2. Full-text search using a MATCH operator on a non-docid column.
  128869. ** 3. Linear scan of %_content table.
  128870. */
  128871. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  128872. Fts3Table *p = (Fts3Table *)pVTab;
  128873. int i; /* Iterator variable */
  128874. int iCons = -1; /* Index of constraint to use */
  128875. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  128876. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  128877. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  128878. int iIdx;
  128879. /* By default use a full table scan. This is an expensive option,
  128880. ** so search through the constraints to see if a more efficient
  128881. ** strategy is possible.
  128882. */
  128883. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  128884. pInfo->estimatedCost = 5000000;
  128885. for(i=0; i<pInfo->nConstraint; i++){
  128886. int bDocid; /* True if this constraint is on docid */
  128887. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  128888. if( pCons->usable==0 ){
  128889. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  128890. /* There exists an unusable MATCH constraint. This means that if
  128891. ** the planner does elect to use the results of this call as part
  128892. ** of the overall query plan the user will see an "unable to use
  128893. ** function MATCH in the requested context" error. To discourage
  128894. ** this, return a very high cost here. */
  128895. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  128896. pInfo->estimatedCost = 1e50;
  128897. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  128898. return SQLITE_OK;
  128899. }
  128900. continue;
  128901. }
  128902. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  128903. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  128904. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  128905. pInfo->idxNum = FTS3_DOCID_SEARCH;
  128906. pInfo->estimatedCost = 1.0;
  128907. iCons = i;
  128908. }
  128909. /* A MATCH constraint. Use a full-text search.
  128910. **
  128911. ** If there is more than one MATCH constraint available, use the first
  128912. ** one encountered. If there is both a MATCH constraint and a direct
  128913. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  128914. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  128915. ** it would lead to an "unable to use function MATCH in the requested
  128916. ** context" error.
  128917. */
  128918. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  128919. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  128920. ){
  128921. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  128922. pInfo->estimatedCost = 2.0;
  128923. iCons = i;
  128924. }
  128925. /* Equality constraint on the langid column */
  128926. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  128927. && pCons->iColumn==p->nColumn + 2
  128928. ){
  128929. iLangidCons = i;
  128930. }
  128931. if( bDocid ){
  128932. switch( pCons->op ){
  128933. case SQLITE_INDEX_CONSTRAINT_GE:
  128934. case SQLITE_INDEX_CONSTRAINT_GT:
  128935. iDocidGe = i;
  128936. break;
  128937. case SQLITE_INDEX_CONSTRAINT_LE:
  128938. case SQLITE_INDEX_CONSTRAINT_LT:
  128939. iDocidLe = i;
  128940. break;
  128941. }
  128942. }
  128943. }
  128944. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  128945. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  128946. iIdx = 1;
  128947. if( iCons>=0 ){
  128948. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  128949. pInfo->aConstraintUsage[iCons].omit = 1;
  128950. }
  128951. if( iLangidCons>=0 ){
  128952. pInfo->idxNum |= FTS3_HAVE_LANGID;
  128953. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  128954. }
  128955. if( iDocidGe>=0 ){
  128956. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  128957. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  128958. }
  128959. if( iDocidLe>=0 ){
  128960. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  128961. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  128962. }
  128963. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  128964. ** docid) order. Both ascending and descending are possible.
  128965. */
  128966. if( pInfo->nOrderBy==1 ){
  128967. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  128968. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  128969. if( pOrder->desc ){
  128970. pInfo->idxStr = "DESC";
  128971. }else{
  128972. pInfo->idxStr = "ASC";
  128973. }
  128974. pInfo->orderByConsumed = 1;
  128975. }
  128976. }
  128977. assert( p->pSegments==0 );
  128978. return SQLITE_OK;
  128979. }
  128980. /*
  128981. ** Implementation of xOpen method.
  128982. */
  128983. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  128984. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  128985. UNUSED_PARAMETER(pVTab);
  128986. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  128987. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  128988. ** if the allocation fails, return SQLITE_NOMEM.
  128989. */
  128990. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  128991. if( !pCsr ){
  128992. return SQLITE_NOMEM;
  128993. }
  128994. memset(pCsr, 0, sizeof(Fts3Cursor));
  128995. return SQLITE_OK;
  128996. }
  128997. /*
  128998. ** Close the cursor. For additional information see the documentation
  128999. ** on the xClose method of the virtual table interface.
  129000. */
  129001. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  129002. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  129003. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  129004. sqlite3_finalize(pCsr->pStmt);
  129005. sqlite3Fts3ExprFree(pCsr->pExpr);
  129006. sqlite3Fts3FreeDeferredTokens(pCsr);
  129007. sqlite3_free(pCsr->aDoclist);
  129008. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  129009. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  129010. sqlite3_free(pCsr);
  129011. return SQLITE_OK;
  129012. }
  129013. /*
  129014. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  129015. ** compose and prepare an SQL statement of the form:
  129016. **
  129017. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  129018. **
  129019. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  129020. ** it. If an error occurs, return an SQLite error code.
  129021. **
  129022. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  129023. */
  129024. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  129025. int rc = SQLITE_OK;
  129026. if( pCsr->pStmt==0 ){
  129027. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  129028. char *zSql;
  129029. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  129030. if( !zSql ) return SQLITE_NOMEM;
  129031. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  129032. sqlite3_free(zSql);
  129033. }
  129034. *ppStmt = pCsr->pStmt;
  129035. return rc;
  129036. }
  129037. /*
  129038. ** Position the pCsr->pStmt statement so that it is on the row
  129039. ** of the %_content table that contains the last match. Return
  129040. ** SQLITE_OK on success.
  129041. */
  129042. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  129043. int rc = SQLITE_OK;
  129044. if( pCsr->isRequireSeek ){
  129045. sqlite3_stmt *pStmt = 0;
  129046. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  129047. if( rc==SQLITE_OK ){
  129048. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  129049. pCsr->isRequireSeek = 0;
  129050. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  129051. return SQLITE_OK;
  129052. }else{
  129053. rc = sqlite3_reset(pCsr->pStmt);
  129054. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  129055. /* If no row was found and no error has occurred, then the %_content
  129056. ** table is missing a row that is present in the full-text index.
  129057. ** The data structures are corrupt. */
  129058. rc = FTS_CORRUPT_VTAB;
  129059. pCsr->isEof = 1;
  129060. }
  129061. }
  129062. }
  129063. }
  129064. if( rc!=SQLITE_OK && pContext ){
  129065. sqlite3_result_error_code(pContext, rc);
  129066. }
  129067. return rc;
  129068. }
  129069. /*
  129070. ** This function is used to process a single interior node when searching
  129071. ** a b-tree for a term or term prefix. The node data is passed to this
  129072. ** function via the zNode/nNode parameters. The term to search for is
  129073. ** passed in zTerm/nTerm.
  129074. **
  129075. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  129076. ** of the child node that heads the sub-tree that may contain the term.
  129077. **
  129078. ** If piLast is not NULL, then *piLast is set to the right-most child node
  129079. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  129080. ** a prefix.
  129081. **
  129082. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  129083. */
  129084. static int fts3ScanInteriorNode(
  129085. const char *zTerm, /* Term to select leaves for */
  129086. int nTerm, /* Size of term zTerm in bytes */
  129087. const char *zNode, /* Buffer containing segment interior node */
  129088. int nNode, /* Size of buffer at zNode */
  129089. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  129090. sqlite3_int64 *piLast /* OUT: Selected child node */
  129091. ){
  129092. int rc = SQLITE_OK; /* Return code */
  129093. const char *zCsr = zNode; /* Cursor to iterate through node */
  129094. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  129095. char *zBuffer = 0; /* Buffer to load terms into */
  129096. int nAlloc = 0; /* Size of allocated buffer */
  129097. int isFirstTerm = 1; /* True when processing first term on page */
  129098. sqlite3_int64 iChild; /* Block id of child node to descend to */
  129099. /* Skip over the 'height' varint that occurs at the start of every
  129100. ** interior node. Then load the blockid of the left-child of the b-tree
  129101. ** node into variable iChild.
  129102. **
  129103. ** Even if the data structure on disk is corrupted, this (reading two
  129104. ** varints from the buffer) does not risk an overread. If zNode is a
  129105. ** root node, then the buffer comes from a SELECT statement. SQLite does
  129106. ** not make this guarantee explicitly, but in practice there are always
  129107. ** either more than 20 bytes of allocated space following the nNode bytes of
  129108. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  129109. ** table, then there are always 20 bytes of zeroed padding following the
  129110. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  129111. */
  129112. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  129113. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  129114. if( zCsr>zEnd ){
  129115. return FTS_CORRUPT_VTAB;
  129116. }
  129117. while( zCsr<zEnd && (piFirst || piLast) ){
  129118. int cmp; /* memcmp() result */
  129119. int nSuffix; /* Size of term suffix */
  129120. int nPrefix = 0; /* Size of term prefix */
  129121. int nBuffer; /* Total term size */
  129122. /* Load the next term on the node into zBuffer. Use realloc() to expand
  129123. ** the size of zBuffer if required. */
  129124. if( !isFirstTerm ){
  129125. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  129126. }
  129127. isFirstTerm = 0;
  129128. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  129129. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  129130. rc = FTS_CORRUPT_VTAB;
  129131. goto finish_scan;
  129132. }
  129133. if( nPrefix+nSuffix>nAlloc ){
  129134. char *zNew;
  129135. nAlloc = (nPrefix+nSuffix) * 2;
  129136. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  129137. if( !zNew ){
  129138. rc = SQLITE_NOMEM;
  129139. goto finish_scan;
  129140. }
  129141. zBuffer = zNew;
  129142. }
  129143. assert( zBuffer );
  129144. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  129145. nBuffer = nPrefix + nSuffix;
  129146. zCsr += nSuffix;
  129147. /* Compare the term we are searching for with the term just loaded from
  129148. ** the interior node. If the specified term is greater than or equal
  129149. ** to the term from the interior node, then all terms on the sub-tree
  129150. ** headed by node iChild are smaller than zTerm. No need to search
  129151. ** iChild.
  129152. **
  129153. ** If the interior node term is larger than the specified term, then
  129154. ** the tree headed by iChild may contain the specified term.
  129155. */
  129156. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  129157. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  129158. *piFirst = iChild;
  129159. piFirst = 0;
  129160. }
  129161. if( piLast && cmp<0 ){
  129162. *piLast = iChild;
  129163. piLast = 0;
  129164. }
  129165. iChild++;
  129166. };
  129167. if( piFirst ) *piFirst = iChild;
  129168. if( piLast ) *piLast = iChild;
  129169. finish_scan:
  129170. sqlite3_free(zBuffer);
  129171. return rc;
  129172. }
  129173. /*
  129174. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  129175. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  129176. ** contains a term. This function searches the sub-tree headed by the zNode
  129177. ** node for the range of leaf nodes that may contain the specified term
  129178. ** or terms for which the specified term is a prefix.
  129179. **
  129180. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  129181. ** left-most leaf node in the tree that may contain the specified term.
  129182. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  129183. ** right-most leaf node that may contain a term for which the specified
  129184. ** term is a prefix.
  129185. **
  129186. ** It is possible that the range of returned leaf nodes does not contain
  129187. ** the specified term or any terms for which it is a prefix. However, if the
  129188. ** segment does contain any such terms, they are stored within the identified
  129189. ** range. Because this function only inspects interior segment nodes (and
  129190. ** never loads leaf nodes into memory), it is not possible to be sure.
  129191. **
  129192. ** If an error occurs, an error code other than SQLITE_OK is returned.
  129193. */
  129194. static int fts3SelectLeaf(
  129195. Fts3Table *p, /* Virtual table handle */
  129196. const char *zTerm, /* Term to select leaves for */
  129197. int nTerm, /* Size of term zTerm in bytes */
  129198. const char *zNode, /* Buffer containing segment interior node */
  129199. int nNode, /* Size of buffer at zNode */
  129200. sqlite3_int64 *piLeaf, /* Selected leaf node */
  129201. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  129202. ){
  129203. int rc = SQLITE_OK; /* Return code */
  129204. int iHeight; /* Height of this node in tree */
  129205. assert( piLeaf || piLeaf2 );
  129206. fts3GetVarint32(zNode, &iHeight);
  129207. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  129208. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  129209. if( rc==SQLITE_OK && iHeight>1 ){
  129210. char *zBlob = 0; /* Blob read from %_segments table */
  129211. int nBlob = 0; /* Size of zBlob in bytes */
  129212. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  129213. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  129214. if( rc==SQLITE_OK ){
  129215. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  129216. }
  129217. sqlite3_free(zBlob);
  129218. piLeaf = 0;
  129219. zBlob = 0;
  129220. }
  129221. if( rc==SQLITE_OK ){
  129222. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  129223. }
  129224. if( rc==SQLITE_OK ){
  129225. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  129226. }
  129227. sqlite3_free(zBlob);
  129228. }
  129229. return rc;
  129230. }
  129231. /*
  129232. ** This function is used to create delta-encoded serialized lists of FTS3
  129233. ** varints. Each call to this function appends a single varint to a list.
  129234. */
  129235. static void fts3PutDeltaVarint(
  129236. char **pp, /* IN/OUT: Output pointer */
  129237. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  129238. sqlite3_int64 iVal /* Write this value to the list */
  129239. ){
  129240. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  129241. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  129242. *piPrev = iVal;
  129243. }
  129244. /*
  129245. ** When this function is called, *ppPoslist is assumed to point to the
  129246. ** start of a position-list. After it returns, *ppPoslist points to the
  129247. ** first byte after the position-list.
  129248. **
  129249. ** A position list is list of positions (delta encoded) and columns for
  129250. ** a single document record of a doclist. So, in other words, this
  129251. ** routine advances *ppPoslist so that it points to the next docid in
  129252. ** the doclist, or to the first byte past the end of the doclist.
  129253. **
  129254. ** If pp is not NULL, then the contents of the position list are copied
  129255. ** to *pp. *pp is set to point to the first byte past the last byte copied
  129256. ** before this function returns.
  129257. */
  129258. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  129259. char *pEnd = *ppPoslist;
  129260. char c = 0;
  129261. /* The end of a position list is marked by a zero encoded as an FTS3
  129262. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  129263. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  129264. ** of some other, multi-byte, value.
  129265. **
  129266. ** The following while-loop moves pEnd to point to the first byte that is not
  129267. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  129268. ** pEnd once more so that it points to the byte immediately following the
  129269. ** last byte in the position-list.
  129270. */
  129271. while( *pEnd | c ){
  129272. c = *pEnd++ & 0x80;
  129273. testcase( c!=0 && (*pEnd)==0 );
  129274. }
  129275. pEnd++; /* Advance past the POS_END terminator byte */
  129276. if( pp ){
  129277. int n = (int)(pEnd - *ppPoslist);
  129278. char *p = *pp;
  129279. memcpy(p, *ppPoslist, n);
  129280. p += n;
  129281. *pp = p;
  129282. }
  129283. *ppPoslist = pEnd;
  129284. }
  129285. /*
  129286. ** When this function is called, *ppPoslist is assumed to point to the
  129287. ** start of a column-list. After it returns, *ppPoslist points to the
  129288. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  129289. **
  129290. ** A column-list is list of delta-encoded positions for a single column
  129291. ** within a single document within a doclist.
  129292. **
  129293. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  129294. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  129295. ** the POS_COLUMN or POS_END that terminates the column-list.
  129296. **
  129297. ** If pp is not NULL, then the contents of the column-list are copied
  129298. ** to *pp. *pp is set to point to the first byte past the last byte copied
  129299. ** before this function returns. The POS_COLUMN or POS_END terminator
  129300. ** is not copied into *pp.
  129301. */
  129302. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  129303. char *pEnd = *ppPoslist;
  129304. char c = 0;
  129305. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  129306. ** not part of a multi-byte varint.
  129307. */
  129308. while( 0xFE & (*pEnd | c) ){
  129309. c = *pEnd++ & 0x80;
  129310. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  129311. }
  129312. if( pp ){
  129313. int n = (int)(pEnd - *ppPoslist);
  129314. char *p = *pp;
  129315. memcpy(p, *ppPoslist, n);
  129316. p += n;
  129317. *pp = p;
  129318. }
  129319. *ppPoslist = pEnd;
  129320. }
  129321. /*
  129322. ** Value used to signify the end of an position-list. This is safe because
  129323. ** it is not possible to have a document with 2^31 terms.
  129324. */
  129325. #define POSITION_LIST_END 0x7fffffff
  129326. /*
  129327. ** This function is used to help parse position-lists. When this function is
  129328. ** called, *pp may point to the start of the next varint in the position-list
  129329. ** being parsed, or it may point to 1 byte past the end of the position-list
  129330. ** (in which case **pp will be a terminator bytes POS_END (0) or
  129331. ** (1)).
  129332. **
  129333. ** If *pp points past the end of the current position-list, set *pi to
  129334. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  129335. ** increment the current value of *pi by the value read, and set *pp to
  129336. ** point to the next value before returning.
  129337. **
  129338. ** Before calling this routine *pi must be initialized to the value of
  129339. ** the previous position, or zero if we are reading the first position
  129340. ** in the position-list. Because positions are delta-encoded, the value
  129341. ** of the previous position is needed in order to compute the value of
  129342. ** the next position.
  129343. */
  129344. static void fts3ReadNextPos(
  129345. char **pp, /* IN/OUT: Pointer into position-list buffer */
  129346. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  129347. ){
  129348. if( (**pp)&0xFE ){
  129349. fts3GetDeltaVarint(pp, pi);
  129350. *pi -= 2;
  129351. }else{
  129352. *pi = POSITION_LIST_END;
  129353. }
  129354. }
  129355. /*
  129356. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  129357. ** the value of iCol encoded as a varint to *pp. This will start a new
  129358. ** column list.
  129359. **
  129360. ** Set *pp to point to the byte just after the last byte written before
  129361. ** returning (do not modify it if iCol==0). Return the total number of bytes
  129362. ** written (0 if iCol==0).
  129363. */
  129364. static int fts3PutColNumber(char **pp, int iCol){
  129365. int n = 0; /* Number of bytes written */
  129366. if( iCol ){
  129367. char *p = *pp; /* Output pointer */
  129368. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  129369. *p = 0x01;
  129370. *pp = &p[n];
  129371. }
  129372. return n;
  129373. }
  129374. /*
  129375. ** Compute the union of two position lists. The output written
  129376. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  129377. ** order and with any duplicates removed. All pointers are
  129378. ** updated appropriately. The caller is responsible for insuring
  129379. ** that there is enough space in *pp to hold the complete output.
  129380. */
  129381. static void fts3PoslistMerge(
  129382. char **pp, /* Output buffer */
  129383. char **pp1, /* Left input list */
  129384. char **pp2 /* Right input list */
  129385. ){
  129386. char *p = *pp;
  129387. char *p1 = *pp1;
  129388. char *p2 = *pp2;
  129389. while( *p1 || *p2 ){
  129390. int iCol1; /* The current column index in pp1 */
  129391. int iCol2; /* The current column index in pp2 */
  129392. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  129393. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  129394. else iCol1 = 0;
  129395. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  129396. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  129397. else iCol2 = 0;
  129398. if( iCol1==iCol2 ){
  129399. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  129400. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  129401. sqlite3_int64 iPrev = 0;
  129402. int n = fts3PutColNumber(&p, iCol1);
  129403. p1 += n;
  129404. p2 += n;
  129405. /* At this point, both p1 and p2 point to the start of column-lists
  129406. ** for the same column (the column with index iCol1 and iCol2).
  129407. ** A column-list is a list of non-negative delta-encoded varints, each
  129408. ** incremented by 2 before being stored. Each list is terminated by a
  129409. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  129410. ** and writes the results to buffer p. p is left pointing to the byte
  129411. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  129412. ** written to the output.
  129413. */
  129414. fts3GetDeltaVarint(&p1, &i1);
  129415. fts3GetDeltaVarint(&p2, &i2);
  129416. do {
  129417. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  129418. iPrev -= 2;
  129419. if( i1==i2 ){
  129420. fts3ReadNextPos(&p1, &i1);
  129421. fts3ReadNextPos(&p2, &i2);
  129422. }else if( i1<i2 ){
  129423. fts3ReadNextPos(&p1, &i1);
  129424. }else{
  129425. fts3ReadNextPos(&p2, &i2);
  129426. }
  129427. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  129428. }else if( iCol1<iCol2 ){
  129429. p1 += fts3PutColNumber(&p, iCol1);
  129430. fts3ColumnlistCopy(&p, &p1);
  129431. }else{
  129432. p2 += fts3PutColNumber(&p, iCol2);
  129433. fts3ColumnlistCopy(&p, &p2);
  129434. }
  129435. }
  129436. *p++ = POS_END;
  129437. *pp = p;
  129438. *pp1 = p1 + 1;
  129439. *pp2 = p2 + 1;
  129440. }
  129441. /*
  129442. ** This function is used to merge two position lists into one. When it is
  129443. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  129444. ** the part of a doclist that follows each document id. For example, if a row
  129445. ** contains:
  129446. **
  129447. ** 'a b c'|'x y z'|'a b b a'
  129448. **
  129449. ** Then the position list for this row for token 'b' would consist of:
  129450. **
  129451. ** 0x02 0x01 0x02 0x03 0x03 0x00
  129452. **
  129453. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  129454. ** byte following the 0x00 terminator of their respective position lists.
  129455. **
  129456. ** If isSaveLeft is 0, an entry is added to the output position list for
  129457. ** each position in *pp2 for which there exists one or more positions in
  129458. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  129459. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  129460. ** slots before it.
  129461. **
  129462. ** e.g. nToken==1 searches for adjacent positions.
  129463. */
  129464. static int fts3PoslistPhraseMerge(
  129465. char **pp, /* IN/OUT: Preallocated output buffer */
  129466. int nToken, /* Maximum difference in token positions */
  129467. int isSaveLeft, /* Save the left position */
  129468. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  129469. char **pp1, /* IN/OUT: Left input list */
  129470. char **pp2 /* IN/OUT: Right input list */
  129471. ){
  129472. char *p = *pp;
  129473. char *p1 = *pp1;
  129474. char *p2 = *pp2;
  129475. int iCol1 = 0;
  129476. int iCol2 = 0;
  129477. /* Never set both isSaveLeft and isExact for the same invocation. */
  129478. assert( isSaveLeft==0 || isExact==0 );
  129479. assert( p!=0 && *p1!=0 && *p2!=0 );
  129480. if( *p1==POS_COLUMN ){
  129481. p1++;
  129482. p1 += fts3GetVarint32(p1, &iCol1);
  129483. }
  129484. if( *p2==POS_COLUMN ){
  129485. p2++;
  129486. p2 += fts3GetVarint32(p2, &iCol2);
  129487. }
  129488. while( 1 ){
  129489. if( iCol1==iCol2 ){
  129490. char *pSave = p;
  129491. sqlite3_int64 iPrev = 0;
  129492. sqlite3_int64 iPos1 = 0;
  129493. sqlite3_int64 iPos2 = 0;
  129494. if( iCol1 ){
  129495. *p++ = POS_COLUMN;
  129496. p += sqlite3Fts3PutVarint(p, iCol1);
  129497. }
  129498. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  129499. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  129500. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  129501. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  129502. while( 1 ){
  129503. if( iPos2==iPos1+nToken
  129504. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  129505. ){
  129506. sqlite3_int64 iSave;
  129507. iSave = isSaveLeft ? iPos1 : iPos2;
  129508. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  129509. pSave = 0;
  129510. assert( p );
  129511. }
  129512. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  129513. if( (*p2&0xFE)==0 ) break;
  129514. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  129515. }else{
  129516. if( (*p1&0xFE)==0 ) break;
  129517. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  129518. }
  129519. }
  129520. if( pSave ){
  129521. assert( pp && p );
  129522. p = pSave;
  129523. }
  129524. fts3ColumnlistCopy(0, &p1);
  129525. fts3ColumnlistCopy(0, &p2);
  129526. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  129527. if( 0==*p1 || 0==*p2 ) break;
  129528. p1++;
  129529. p1 += fts3GetVarint32(p1, &iCol1);
  129530. p2++;
  129531. p2 += fts3GetVarint32(p2, &iCol2);
  129532. }
  129533. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  129534. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  129535. ** end of the position list, or the 0x01 that precedes the next
  129536. ** column-number in the position list.
  129537. */
  129538. else if( iCol1<iCol2 ){
  129539. fts3ColumnlistCopy(0, &p1);
  129540. if( 0==*p1 ) break;
  129541. p1++;
  129542. p1 += fts3GetVarint32(p1, &iCol1);
  129543. }else{
  129544. fts3ColumnlistCopy(0, &p2);
  129545. if( 0==*p2 ) break;
  129546. p2++;
  129547. p2 += fts3GetVarint32(p2, &iCol2);
  129548. }
  129549. }
  129550. fts3PoslistCopy(0, &p2);
  129551. fts3PoslistCopy(0, &p1);
  129552. *pp1 = p1;
  129553. *pp2 = p2;
  129554. if( *pp==p ){
  129555. return 0;
  129556. }
  129557. *p++ = 0x00;
  129558. *pp = p;
  129559. return 1;
  129560. }
  129561. /*
  129562. ** Merge two position-lists as required by the NEAR operator. The argument
  129563. ** position lists correspond to the left and right phrases of an expression
  129564. ** like:
  129565. **
  129566. ** "phrase 1" NEAR "phrase number 2"
  129567. **
  129568. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  129569. ** expression and *pp2 to the right. As usual, the indexes in the position
  129570. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  129571. ** in the example above).
  129572. **
  129573. ** The output position list - written to *pp - is a copy of *pp2 with those
  129574. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  129575. */
  129576. static int fts3PoslistNearMerge(
  129577. char **pp, /* Output buffer */
  129578. char *aTmp, /* Temporary buffer space */
  129579. int nRight, /* Maximum difference in token positions */
  129580. int nLeft, /* Maximum difference in token positions */
  129581. char **pp1, /* IN/OUT: Left input list */
  129582. char **pp2 /* IN/OUT: Right input list */
  129583. ){
  129584. char *p1 = *pp1;
  129585. char *p2 = *pp2;
  129586. char *pTmp1 = aTmp;
  129587. char *pTmp2;
  129588. char *aTmp2;
  129589. int res = 1;
  129590. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  129591. aTmp2 = pTmp2 = pTmp1;
  129592. *pp1 = p1;
  129593. *pp2 = p2;
  129594. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  129595. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  129596. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  129597. }else if( pTmp1!=aTmp ){
  129598. fts3PoslistCopy(pp, &aTmp);
  129599. }else if( pTmp2!=aTmp2 ){
  129600. fts3PoslistCopy(pp, &aTmp2);
  129601. }else{
  129602. res = 0;
  129603. }
  129604. return res;
  129605. }
  129606. /*
  129607. ** An instance of this function is used to merge together the (potentially
  129608. ** large number of) doclists for each term that matches a prefix query.
  129609. ** See function fts3TermSelectMerge() for details.
  129610. */
  129611. typedef struct TermSelect TermSelect;
  129612. struct TermSelect {
  129613. char *aaOutput[16]; /* Malloc'd output buffers */
  129614. int anOutput[16]; /* Size each output buffer in bytes */
  129615. };
  129616. /*
  129617. ** This function is used to read a single varint from a buffer. Parameter
  129618. ** pEnd points 1 byte past the end of the buffer. When this function is
  129619. ** called, if *pp points to pEnd or greater, then the end of the buffer
  129620. ** has been reached. In this case *pp is set to 0 and the function returns.
  129621. **
  129622. ** If *pp does not point to or past pEnd, then a single varint is read
  129623. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  129624. **
  129625. ** If bDescIdx is false, the value read is added to *pVal before returning.
  129626. ** If it is true, the value read is subtracted from *pVal before this
  129627. ** function returns.
  129628. */
  129629. static void fts3GetDeltaVarint3(
  129630. char **pp, /* IN/OUT: Point to read varint from */
  129631. char *pEnd, /* End of buffer */
  129632. int bDescIdx, /* True if docids are descending */
  129633. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  129634. ){
  129635. if( *pp>=pEnd ){
  129636. *pp = 0;
  129637. }else{
  129638. sqlite3_int64 iVal;
  129639. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  129640. if( bDescIdx ){
  129641. *pVal -= iVal;
  129642. }else{
  129643. *pVal += iVal;
  129644. }
  129645. }
  129646. }
  129647. /*
  129648. ** This function is used to write a single varint to a buffer. The varint
  129649. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  129650. ** end of the value written.
  129651. **
  129652. ** If *pbFirst is zero when this function is called, the value written to
  129653. ** the buffer is that of parameter iVal.
  129654. **
  129655. ** If *pbFirst is non-zero when this function is called, then the value
  129656. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  129657. ** (if bDescIdx is non-zero).
  129658. **
  129659. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  129660. ** to the value of parameter iVal.
  129661. */
  129662. static void fts3PutDeltaVarint3(
  129663. char **pp, /* IN/OUT: Output pointer */
  129664. int bDescIdx, /* True for descending docids */
  129665. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  129666. int *pbFirst, /* IN/OUT: True after first int written */
  129667. sqlite3_int64 iVal /* Write this value to the list */
  129668. ){
  129669. sqlite3_int64 iWrite;
  129670. if( bDescIdx==0 || *pbFirst==0 ){
  129671. iWrite = iVal - *piPrev;
  129672. }else{
  129673. iWrite = *piPrev - iVal;
  129674. }
  129675. assert( *pbFirst || *piPrev==0 );
  129676. assert( *pbFirst==0 || iWrite>0 );
  129677. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  129678. *piPrev = iVal;
  129679. *pbFirst = 1;
  129680. }
  129681. /*
  129682. ** This macro is used by various functions that merge doclists. The two
  129683. ** arguments are 64-bit docid values. If the value of the stack variable
  129684. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  129685. ** Otherwise, (i2-i1).
  129686. **
  129687. ** Using this makes it easier to write code that can merge doclists that are
  129688. ** sorted in either ascending or descending order.
  129689. */
  129690. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  129691. /*
  129692. ** This function does an "OR" merge of two doclists (output contains all
  129693. ** positions contained in either argument doclist). If the docids in the
  129694. ** input doclists are sorted in ascending order, parameter bDescDoclist
  129695. ** should be false. If they are sorted in ascending order, it should be
  129696. ** passed a non-zero value.
  129697. **
  129698. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  129699. ** containing the output doclist and SQLITE_OK is returned. In this case
  129700. ** *pnOut is set to the number of bytes in the output doclist.
  129701. **
  129702. ** If an error occurs, an SQLite error code is returned. The output values
  129703. ** are undefined in this case.
  129704. */
  129705. static int fts3DoclistOrMerge(
  129706. int bDescDoclist, /* True if arguments are desc */
  129707. char *a1, int n1, /* First doclist */
  129708. char *a2, int n2, /* Second doclist */
  129709. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  129710. ){
  129711. sqlite3_int64 i1 = 0;
  129712. sqlite3_int64 i2 = 0;
  129713. sqlite3_int64 iPrev = 0;
  129714. char *pEnd1 = &a1[n1];
  129715. char *pEnd2 = &a2[n2];
  129716. char *p1 = a1;
  129717. char *p2 = a2;
  129718. char *p;
  129719. char *aOut;
  129720. int bFirstOut = 0;
  129721. *paOut = 0;
  129722. *pnOut = 0;
  129723. /* Allocate space for the output. Both the input and output doclists
  129724. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  129725. ** then the first docid in each list is simply encoded as a varint. For
  129726. ** each subsequent docid, the varint stored is the difference between the
  129727. ** current and previous docid (a positive number - since the list is in
  129728. ** ascending order).
  129729. **
  129730. ** The first docid written to the output is therefore encoded using the
  129731. ** same number of bytes as it is in whichever of the input lists it is
  129732. ** read from. And each subsequent docid read from the same input list
  129733. ** consumes either the same or less bytes as it did in the input (since
  129734. ** the difference between it and the previous value in the output must
  129735. ** be a positive value less than or equal to the delta value read from
  129736. ** the input list). The same argument applies to all but the first docid
  129737. ** read from the 'other' list. And to the contents of all position lists
  129738. ** that will be copied and merged from the input to the output.
  129739. **
  129740. ** However, if the first docid copied to the output is a negative number,
  129741. ** then the encoding of the first docid from the 'other' input list may
  129742. ** be larger in the output than it was in the input (since the delta value
  129743. ** may be a larger positive integer than the actual docid).
  129744. **
  129745. ** The space required to store the output is therefore the sum of the
  129746. ** sizes of the two inputs, plus enough space for exactly one of the input
  129747. ** docids to grow.
  129748. **
  129749. ** A symetric argument may be made if the doclists are in descending
  129750. ** order.
  129751. */
  129752. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  129753. if( !aOut ) return SQLITE_NOMEM;
  129754. p = aOut;
  129755. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  129756. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  129757. while( p1 || p2 ){
  129758. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  129759. if( p2 && p1 && iDiff==0 ){
  129760. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  129761. fts3PoslistMerge(&p, &p1, &p2);
  129762. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  129763. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  129764. }else if( !p2 || (p1 && iDiff<0) ){
  129765. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  129766. fts3PoslistCopy(&p, &p1);
  129767. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  129768. }else{
  129769. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  129770. fts3PoslistCopy(&p, &p2);
  129771. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  129772. }
  129773. }
  129774. *paOut = aOut;
  129775. *pnOut = (int)(p-aOut);
  129776. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  129777. return SQLITE_OK;
  129778. }
  129779. /*
  129780. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  129781. ** the output contains a copy of each position from the right-hand input
  129782. ** doclist for which there is a position in the left-hand input doclist
  129783. ** exactly nDist tokens before it.
  129784. **
  129785. ** If the docids in the input doclists are sorted in ascending order,
  129786. ** parameter bDescDoclist should be false. If they are sorted in ascending
  129787. ** order, it should be passed a non-zero value.
  129788. **
  129789. ** The right-hand input doclist is overwritten by this function.
  129790. */
  129791. static int fts3DoclistPhraseMerge(
  129792. int bDescDoclist, /* True if arguments are desc */
  129793. int nDist, /* Distance from left to right (1=adjacent) */
  129794. char *aLeft, int nLeft, /* Left doclist */
  129795. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  129796. ){
  129797. sqlite3_int64 i1 = 0;
  129798. sqlite3_int64 i2 = 0;
  129799. sqlite3_int64 iPrev = 0;
  129800. char *aRight = *paRight;
  129801. char *pEnd1 = &aLeft[nLeft];
  129802. char *pEnd2 = &aRight[*pnRight];
  129803. char *p1 = aLeft;
  129804. char *p2 = aRight;
  129805. char *p;
  129806. int bFirstOut = 0;
  129807. char *aOut;
  129808. assert( nDist>0 );
  129809. if( bDescDoclist ){
  129810. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  129811. if( aOut==0 ) return SQLITE_NOMEM;
  129812. }else{
  129813. aOut = aRight;
  129814. }
  129815. p = aOut;
  129816. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  129817. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  129818. while( p1 && p2 ){
  129819. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  129820. if( iDiff==0 ){
  129821. char *pSave = p;
  129822. sqlite3_int64 iPrevSave = iPrev;
  129823. int bFirstOutSave = bFirstOut;
  129824. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  129825. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  129826. p = pSave;
  129827. iPrev = iPrevSave;
  129828. bFirstOut = bFirstOutSave;
  129829. }
  129830. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  129831. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  129832. }else if( iDiff<0 ){
  129833. fts3PoslistCopy(0, &p1);
  129834. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  129835. }else{
  129836. fts3PoslistCopy(0, &p2);
  129837. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  129838. }
  129839. }
  129840. *pnRight = (int)(p - aOut);
  129841. if( bDescDoclist ){
  129842. sqlite3_free(aRight);
  129843. *paRight = aOut;
  129844. }
  129845. return SQLITE_OK;
  129846. }
  129847. /*
  129848. ** Argument pList points to a position list nList bytes in size. This
  129849. ** function checks to see if the position list contains any entries for
  129850. ** a token in position 0 (of any column). If so, it writes argument iDelta
  129851. ** to the output buffer pOut, followed by a position list consisting only
  129852. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  129853. ** The value returned is the number of bytes written to pOut (if any).
  129854. */
  129855. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  129856. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  129857. char *pList, /* Position list (no 0x00 term) */
  129858. int nList, /* Size of pList in bytes */
  129859. char *pOut /* Write output here */
  129860. ){
  129861. int nOut = 0;
  129862. int bWritten = 0; /* True once iDelta has been written */
  129863. char *p = pList;
  129864. char *pEnd = &pList[nList];
  129865. if( *p!=0x01 ){
  129866. if( *p==0x02 ){
  129867. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  129868. pOut[nOut++] = 0x02;
  129869. bWritten = 1;
  129870. }
  129871. fts3ColumnlistCopy(0, &p);
  129872. }
  129873. while( p<pEnd && *p==0x01 ){
  129874. sqlite3_int64 iCol;
  129875. p++;
  129876. p += sqlite3Fts3GetVarint(p, &iCol);
  129877. if( *p==0x02 ){
  129878. if( bWritten==0 ){
  129879. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  129880. bWritten = 1;
  129881. }
  129882. pOut[nOut++] = 0x01;
  129883. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  129884. pOut[nOut++] = 0x02;
  129885. }
  129886. fts3ColumnlistCopy(0, &p);
  129887. }
  129888. if( bWritten ){
  129889. pOut[nOut++] = 0x00;
  129890. }
  129891. return nOut;
  129892. }
  129893. /*
  129894. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  129895. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  129896. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  129897. **
  129898. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  129899. ** the responsibility of the caller to free any doclists left in the
  129900. ** TermSelect.aaOutput[] array.
  129901. */
  129902. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  129903. char *aOut = 0;
  129904. int nOut = 0;
  129905. int i;
  129906. /* Loop through the doclists in the aaOutput[] array. Merge them all
  129907. ** into a single doclist.
  129908. */
  129909. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  129910. if( pTS->aaOutput[i] ){
  129911. if( !aOut ){
  129912. aOut = pTS->aaOutput[i];
  129913. nOut = pTS->anOutput[i];
  129914. pTS->aaOutput[i] = 0;
  129915. }else{
  129916. int nNew;
  129917. char *aNew;
  129918. int rc = fts3DoclistOrMerge(p->bDescIdx,
  129919. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  129920. );
  129921. if( rc!=SQLITE_OK ){
  129922. sqlite3_free(aOut);
  129923. return rc;
  129924. }
  129925. sqlite3_free(pTS->aaOutput[i]);
  129926. sqlite3_free(aOut);
  129927. pTS->aaOutput[i] = 0;
  129928. aOut = aNew;
  129929. nOut = nNew;
  129930. }
  129931. }
  129932. }
  129933. pTS->aaOutput[0] = aOut;
  129934. pTS->anOutput[0] = nOut;
  129935. return SQLITE_OK;
  129936. }
  129937. /*
  129938. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  129939. ** as the first argument. The merge is an "OR" merge (see function
  129940. ** fts3DoclistOrMerge() for details).
  129941. **
  129942. ** This function is called with the doclist for each term that matches
  129943. ** a queried prefix. It merges all these doclists into one, the doclist
  129944. ** for the specified prefix. Since there can be a very large number of
  129945. ** doclists to merge, the merging is done pair-wise using the TermSelect
  129946. ** object.
  129947. **
  129948. ** This function returns SQLITE_OK if the merge is successful, or an
  129949. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  129950. */
  129951. static int fts3TermSelectMerge(
  129952. Fts3Table *p, /* FTS table handle */
  129953. TermSelect *pTS, /* TermSelect object to merge into */
  129954. char *aDoclist, /* Pointer to doclist */
  129955. int nDoclist /* Size of aDoclist in bytes */
  129956. ){
  129957. if( pTS->aaOutput[0]==0 ){
  129958. /* If this is the first term selected, copy the doclist to the output
  129959. ** buffer using memcpy().
  129960. **
  129961. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  129962. ** allocation. This is so as to ensure that the buffer is big enough
  129963. ** to hold the current doclist AND'd with any other doclist. If the
  129964. ** doclists are stored in order=ASC order, this padding would not be
  129965. ** required (since the size of [doclistA AND doclistB] is always less
  129966. ** than or equal to the size of [doclistA] in that case). But this is
  129967. ** not true for order=DESC. For example, a doclist containing (1, -1)
  129968. ** may be smaller than (-1), as in the first example the -1 may be stored
  129969. ** as a single-byte delta, whereas in the second it must be stored as a
  129970. ** FTS3_VARINT_MAX byte varint.
  129971. **
  129972. ** Similar padding is added in the fts3DoclistOrMerge() function.
  129973. */
  129974. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  129975. pTS->anOutput[0] = nDoclist;
  129976. if( pTS->aaOutput[0] ){
  129977. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  129978. }else{
  129979. return SQLITE_NOMEM;
  129980. }
  129981. }else{
  129982. char *aMerge = aDoclist;
  129983. int nMerge = nDoclist;
  129984. int iOut;
  129985. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  129986. if( pTS->aaOutput[iOut]==0 ){
  129987. assert( iOut>0 );
  129988. pTS->aaOutput[iOut] = aMerge;
  129989. pTS->anOutput[iOut] = nMerge;
  129990. break;
  129991. }else{
  129992. char *aNew;
  129993. int nNew;
  129994. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  129995. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  129996. );
  129997. if( rc!=SQLITE_OK ){
  129998. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  129999. return rc;
  130000. }
  130001. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  130002. sqlite3_free(pTS->aaOutput[iOut]);
  130003. pTS->aaOutput[iOut] = 0;
  130004. aMerge = aNew;
  130005. nMerge = nNew;
  130006. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  130007. pTS->aaOutput[iOut] = aMerge;
  130008. pTS->anOutput[iOut] = nMerge;
  130009. }
  130010. }
  130011. }
  130012. }
  130013. return SQLITE_OK;
  130014. }
  130015. /*
  130016. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  130017. */
  130018. static int fts3SegReaderCursorAppend(
  130019. Fts3MultiSegReader *pCsr,
  130020. Fts3SegReader *pNew
  130021. ){
  130022. if( (pCsr->nSegment%16)==0 ){
  130023. Fts3SegReader **apNew;
  130024. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  130025. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  130026. if( !apNew ){
  130027. sqlite3Fts3SegReaderFree(pNew);
  130028. return SQLITE_NOMEM;
  130029. }
  130030. pCsr->apSegment = apNew;
  130031. }
  130032. pCsr->apSegment[pCsr->nSegment++] = pNew;
  130033. return SQLITE_OK;
  130034. }
  130035. /*
  130036. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  130037. ** 8th argument.
  130038. **
  130039. ** This function returns SQLITE_OK if successful, or an SQLite error code
  130040. ** otherwise.
  130041. */
  130042. static int fts3SegReaderCursor(
  130043. Fts3Table *p, /* FTS3 table handle */
  130044. int iLangid, /* Language id */
  130045. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  130046. int iLevel, /* Level of segments to scan */
  130047. const char *zTerm, /* Term to query for */
  130048. int nTerm, /* Size of zTerm in bytes */
  130049. int isPrefix, /* True for a prefix search */
  130050. int isScan, /* True to scan from zTerm to EOF */
  130051. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  130052. ){
  130053. int rc = SQLITE_OK; /* Error code */
  130054. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  130055. int rc2; /* Result of sqlite3_reset() */
  130056. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  130057. ** for the pending-terms. If this is a scan, then this call must be being
  130058. ** made by an fts4aux module, not an FTS table. In this case calling
  130059. ** Fts3SegReaderPending might segfault, as the data structures used by
  130060. ** fts4aux are not completely populated. So it's easiest to filter these
  130061. ** calls out here. */
  130062. if( iLevel<0 && p->aIndex ){
  130063. Fts3SegReader *pSeg = 0;
  130064. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  130065. if( rc==SQLITE_OK && pSeg ){
  130066. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  130067. }
  130068. }
  130069. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  130070. if( rc==SQLITE_OK ){
  130071. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  130072. }
  130073. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  130074. Fts3SegReader *pSeg = 0;
  130075. /* Read the values returned by the SELECT into local variables. */
  130076. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  130077. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  130078. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  130079. int nRoot = sqlite3_column_bytes(pStmt, 4);
  130080. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  130081. /* If zTerm is not NULL, and this segment is not stored entirely on its
  130082. ** root node, the range of leaves scanned can be reduced. Do this. */
  130083. if( iStartBlock && zTerm ){
  130084. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  130085. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  130086. if( rc!=SQLITE_OK ) goto finished;
  130087. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  130088. }
  130089. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  130090. (isPrefix==0 && isScan==0),
  130091. iStartBlock, iLeavesEndBlock,
  130092. iEndBlock, zRoot, nRoot, &pSeg
  130093. );
  130094. if( rc!=SQLITE_OK ) goto finished;
  130095. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  130096. }
  130097. }
  130098. finished:
  130099. rc2 = sqlite3_reset(pStmt);
  130100. if( rc==SQLITE_DONE ) rc = rc2;
  130101. return rc;
  130102. }
  130103. /*
  130104. ** Set up a cursor object for iterating through a full-text index or a
  130105. ** single level therein.
  130106. */
  130107. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  130108. Fts3Table *p, /* FTS3 table handle */
  130109. int iLangid, /* Language-id to search */
  130110. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  130111. int iLevel, /* Level of segments to scan */
  130112. const char *zTerm, /* Term to query for */
  130113. int nTerm, /* Size of zTerm in bytes */
  130114. int isPrefix, /* True for a prefix search */
  130115. int isScan, /* True to scan from zTerm to EOF */
  130116. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  130117. ){
  130118. assert( iIndex>=0 && iIndex<p->nIndex );
  130119. assert( iLevel==FTS3_SEGCURSOR_ALL
  130120. || iLevel==FTS3_SEGCURSOR_PENDING
  130121. || iLevel>=0
  130122. );
  130123. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  130124. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  130125. assert( isPrefix==0 || isScan==0 );
  130126. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  130127. return fts3SegReaderCursor(
  130128. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  130129. );
  130130. }
  130131. /*
  130132. ** In addition to its current configuration, have the Fts3MultiSegReader
  130133. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  130134. **
  130135. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  130136. */
  130137. static int fts3SegReaderCursorAddZero(
  130138. Fts3Table *p, /* FTS virtual table handle */
  130139. int iLangid,
  130140. const char *zTerm, /* Term to scan doclist of */
  130141. int nTerm, /* Number of bytes in zTerm */
  130142. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  130143. ){
  130144. return fts3SegReaderCursor(p,
  130145. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  130146. );
  130147. }
  130148. /*
  130149. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  130150. ** if isPrefix is true, to scan the doclist for all terms for which
  130151. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  130152. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  130153. ** an SQLite error code.
  130154. **
  130155. ** It is the responsibility of the caller to free this object by eventually
  130156. ** passing it to fts3SegReaderCursorFree()
  130157. **
  130158. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  130159. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  130160. */
  130161. static int fts3TermSegReaderCursor(
  130162. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  130163. const char *zTerm, /* Term to query for */
  130164. int nTerm, /* Size of zTerm in bytes */
  130165. int isPrefix, /* True for a prefix search */
  130166. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  130167. ){
  130168. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  130169. int rc = SQLITE_NOMEM; /* Return code */
  130170. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  130171. if( pSegcsr ){
  130172. int i;
  130173. int bFound = 0; /* True once an index has been found */
  130174. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  130175. if( isPrefix ){
  130176. for(i=1; bFound==0 && i<p->nIndex; i++){
  130177. if( p->aIndex[i].nPrefix==nTerm ){
  130178. bFound = 1;
  130179. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  130180. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  130181. );
  130182. pSegcsr->bLookup = 1;
  130183. }
  130184. }
  130185. for(i=1; bFound==0 && i<p->nIndex; i++){
  130186. if( p->aIndex[i].nPrefix==nTerm+1 ){
  130187. bFound = 1;
  130188. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  130189. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  130190. );
  130191. if( rc==SQLITE_OK ){
  130192. rc = fts3SegReaderCursorAddZero(
  130193. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  130194. );
  130195. }
  130196. }
  130197. }
  130198. }
  130199. if( bFound==0 ){
  130200. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  130201. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  130202. );
  130203. pSegcsr->bLookup = !isPrefix;
  130204. }
  130205. }
  130206. *ppSegcsr = pSegcsr;
  130207. return rc;
  130208. }
  130209. /*
  130210. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  130211. */
  130212. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  130213. sqlite3Fts3SegReaderFinish(pSegcsr);
  130214. sqlite3_free(pSegcsr);
  130215. }
  130216. /*
  130217. ** This function retrieves the doclist for the specified term (or term
  130218. ** prefix) from the database.
  130219. */
  130220. static int fts3TermSelect(
  130221. Fts3Table *p, /* Virtual table handle */
  130222. Fts3PhraseToken *pTok, /* Token to query for */
  130223. int iColumn, /* Column to query (or -ve for all columns) */
  130224. int *pnOut, /* OUT: Size of buffer at *ppOut */
  130225. char **ppOut /* OUT: Malloced result buffer */
  130226. ){
  130227. int rc; /* Return code */
  130228. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  130229. TermSelect tsc; /* Object for pair-wise doclist merging */
  130230. Fts3SegFilter filter; /* Segment term filter configuration */
  130231. pSegcsr = pTok->pSegcsr;
  130232. memset(&tsc, 0, sizeof(TermSelect));
  130233. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  130234. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  130235. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  130236. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  130237. filter.iCol = iColumn;
  130238. filter.zTerm = pTok->z;
  130239. filter.nTerm = pTok->n;
  130240. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  130241. while( SQLITE_OK==rc
  130242. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  130243. ){
  130244. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  130245. }
  130246. if( rc==SQLITE_OK ){
  130247. rc = fts3TermSelectFinishMerge(p, &tsc);
  130248. }
  130249. if( rc==SQLITE_OK ){
  130250. *ppOut = tsc.aaOutput[0];
  130251. *pnOut = tsc.anOutput[0];
  130252. }else{
  130253. int i;
  130254. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  130255. sqlite3_free(tsc.aaOutput[i]);
  130256. }
  130257. }
  130258. fts3SegReaderCursorFree(pSegcsr);
  130259. pTok->pSegcsr = 0;
  130260. return rc;
  130261. }
  130262. /*
  130263. ** This function counts the total number of docids in the doclist stored
  130264. ** in buffer aList[], size nList bytes.
  130265. **
  130266. ** If the isPoslist argument is true, then it is assumed that the doclist
  130267. ** contains a position-list following each docid. Otherwise, it is assumed
  130268. ** that the doclist is simply a list of docids stored as delta encoded
  130269. ** varints.
  130270. */
  130271. static int fts3DoclistCountDocids(char *aList, int nList){
  130272. int nDoc = 0; /* Return value */
  130273. if( aList ){
  130274. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  130275. char *p = aList; /* Cursor */
  130276. while( p<aEnd ){
  130277. nDoc++;
  130278. while( (*p++)&0x80 ); /* Skip docid varint */
  130279. fts3PoslistCopy(0, &p); /* Skip over position list */
  130280. }
  130281. }
  130282. return nDoc;
  130283. }
  130284. /*
  130285. ** Advance the cursor to the next row in the %_content table that
  130286. ** matches the search criteria. For a MATCH search, this will be
  130287. ** the next row that matches. For a full-table scan, this will be
  130288. ** simply the next row in the %_content table. For a docid lookup,
  130289. ** this routine simply sets the EOF flag.
  130290. **
  130291. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  130292. ** even if we reach end-of-file. The fts3EofMethod() will be called
  130293. ** subsequently to determine whether or not an EOF was hit.
  130294. */
  130295. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  130296. int rc;
  130297. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  130298. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  130299. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  130300. pCsr->isEof = 1;
  130301. rc = sqlite3_reset(pCsr->pStmt);
  130302. }else{
  130303. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  130304. rc = SQLITE_OK;
  130305. }
  130306. }else{
  130307. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  130308. }
  130309. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  130310. return rc;
  130311. }
  130312. /*
  130313. ** The following are copied from sqliteInt.h.
  130314. **
  130315. ** Constants for the largest and smallest possible 64-bit signed integers.
  130316. ** These macros are designed to work correctly on both 32-bit and 64-bit
  130317. ** compilers.
  130318. */
  130319. #ifndef SQLITE_AMALGAMATION
  130320. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  130321. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  130322. #endif
  130323. /*
  130324. ** If the numeric type of argument pVal is "integer", then return it
  130325. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  130326. ** the second parameter, iDefault.
  130327. */
  130328. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  130329. if( pVal ){
  130330. int eType = sqlite3_value_numeric_type(pVal);
  130331. if( eType==SQLITE_INTEGER ){
  130332. return sqlite3_value_int64(pVal);
  130333. }
  130334. }
  130335. return iDefault;
  130336. }
  130337. /*
  130338. ** This is the xFilter interface for the virtual table. See
  130339. ** the virtual table xFilter method documentation for additional
  130340. ** information.
  130341. **
  130342. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  130343. ** the %_content table.
  130344. **
  130345. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  130346. ** in the %_content table.
  130347. **
  130348. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  130349. ** column on the left-hand side of the MATCH operator is column
  130350. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  130351. ** side of the MATCH operator.
  130352. */
  130353. static int fts3FilterMethod(
  130354. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  130355. int idxNum, /* Strategy index */
  130356. const char *idxStr, /* Unused */
  130357. int nVal, /* Number of elements in apVal */
  130358. sqlite3_value **apVal /* Arguments for the indexing scheme */
  130359. ){
  130360. int rc = SQLITE_OK;
  130361. char *zSql; /* SQL statement used to access %_content */
  130362. int eSearch;
  130363. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  130364. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  130365. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  130366. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  130367. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  130368. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  130369. int iIdx;
  130370. UNUSED_PARAMETER(idxStr);
  130371. UNUSED_PARAMETER(nVal);
  130372. eSearch = (idxNum & 0x0000FFFF);
  130373. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  130374. assert( p->pSegments==0 );
  130375. /* Collect arguments into local variables */
  130376. iIdx = 0;
  130377. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  130378. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  130379. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  130380. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  130381. assert( iIdx==nVal );
  130382. /* In case the cursor has been used before, clear it now. */
  130383. sqlite3_finalize(pCsr->pStmt);
  130384. sqlite3_free(pCsr->aDoclist);
  130385. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  130386. sqlite3Fts3ExprFree(pCsr->pExpr);
  130387. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  130388. /* Set the lower and upper bounds on docids to return */
  130389. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  130390. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  130391. if( idxStr ){
  130392. pCsr->bDesc = (idxStr[0]=='D');
  130393. }else{
  130394. pCsr->bDesc = p->bDescIdx;
  130395. }
  130396. pCsr->eSearch = (i16)eSearch;
  130397. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  130398. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  130399. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  130400. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  130401. return SQLITE_NOMEM;
  130402. }
  130403. pCsr->iLangid = 0;
  130404. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  130405. assert( p->base.zErrMsg==0 );
  130406. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  130407. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  130408. &p->base.zErrMsg
  130409. );
  130410. if( rc!=SQLITE_OK ){
  130411. return rc;
  130412. }
  130413. rc = fts3EvalStart(pCsr);
  130414. sqlite3Fts3SegmentsClose(p);
  130415. if( rc!=SQLITE_OK ) return rc;
  130416. pCsr->pNextId = pCsr->aDoclist;
  130417. pCsr->iPrevId = 0;
  130418. }
  130419. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  130420. ** statement loops through all rows of the %_content table. For a
  130421. ** full-text query or docid lookup, the statement retrieves a single
  130422. ** row by docid.
  130423. */
  130424. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  130425. if( pDocidGe || pDocidLe ){
  130426. zSql = sqlite3_mprintf(
  130427. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  130428. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  130429. (pCsr->bDesc ? "DESC" : "ASC")
  130430. );
  130431. }else{
  130432. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  130433. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  130434. );
  130435. }
  130436. if( zSql ){
  130437. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  130438. sqlite3_free(zSql);
  130439. }else{
  130440. rc = SQLITE_NOMEM;
  130441. }
  130442. }else if( eSearch==FTS3_DOCID_SEARCH ){
  130443. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  130444. if( rc==SQLITE_OK ){
  130445. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  130446. }
  130447. }
  130448. if( rc!=SQLITE_OK ) return rc;
  130449. return fts3NextMethod(pCursor);
  130450. }
  130451. /*
  130452. ** This is the xEof method of the virtual table. SQLite calls this
  130453. ** routine to find out if it has reached the end of a result set.
  130454. */
  130455. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  130456. return ((Fts3Cursor *)pCursor)->isEof;
  130457. }
  130458. /*
  130459. ** This is the xRowid method. The SQLite core calls this routine to
  130460. ** retrieve the rowid for the current row of the result set. fts3
  130461. ** exposes %_content.docid as the rowid for the virtual table. The
  130462. ** rowid should be written to *pRowid.
  130463. */
  130464. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  130465. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  130466. *pRowid = pCsr->iPrevId;
  130467. return SQLITE_OK;
  130468. }
  130469. /*
  130470. ** This is the xColumn method, called by SQLite to request a value from
  130471. ** the row that the supplied cursor currently points to.
  130472. **
  130473. ** If:
  130474. **
  130475. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  130476. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  130477. ** (iCol == p->nColumn+1) -> Docid column
  130478. ** (iCol == p->nColumn+2) -> Langid column
  130479. */
  130480. static int fts3ColumnMethod(
  130481. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130482. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  130483. int iCol /* Index of column to read value from */
  130484. ){
  130485. int rc = SQLITE_OK; /* Return Code */
  130486. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  130487. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  130488. /* The column value supplied by SQLite must be in range. */
  130489. assert( iCol>=0 && iCol<=p->nColumn+2 );
  130490. if( iCol==p->nColumn+1 ){
  130491. /* This call is a request for the "docid" column. Since "docid" is an
  130492. ** alias for "rowid", use the xRowid() method to obtain the value.
  130493. */
  130494. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  130495. }else if( iCol==p->nColumn ){
  130496. /* The extra column whose name is the same as the table.
  130497. ** Return a blob which is a pointer to the cursor. */
  130498. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  130499. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  130500. sqlite3_result_int64(pCtx, pCsr->iLangid);
  130501. }else{
  130502. /* The requested column is either a user column (one that contains
  130503. ** indexed data), or the language-id column. */
  130504. rc = fts3CursorSeek(0, pCsr);
  130505. if( rc==SQLITE_OK ){
  130506. if( iCol==p->nColumn+2 ){
  130507. int iLangid = 0;
  130508. if( p->zLanguageid ){
  130509. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  130510. }
  130511. sqlite3_result_int(pCtx, iLangid);
  130512. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  130513. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  130514. }
  130515. }
  130516. }
  130517. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  130518. return rc;
  130519. }
  130520. /*
  130521. ** This function is the implementation of the xUpdate callback used by
  130522. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  130523. ** inserted, updated or deleted.
  130524. */
  130525. static int fts3UpdateMethod(
  130526. sqlite3_vtab *pVtab, /* Virtual table handle */
  130527. int nArg, /* Size of argument array */
  130528. sqlite3_value **apVal, /* Array of arguments */
  130529. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  130530. ){
  130531. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  130532. }
  130533. /*
  130534. ** Implementation of xSync() method. Flush the contents of the pending-terms
  130535. ** hash-table to the database.
  130536. */
  130537. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  130538. /* Following an incremental-merge operation, assuming that the input
  130539. ** segments are not completely consumed (the usual case), they are updated
  130540. ** in place to remove the entries that have already been merged. This
  130541. ** involves updating the leaf block that contains the smallest unmerged
  130542. ** entry and each block (if any) between the leaf and the root node. So
  130543. ** if the height of the input segment b-trees is N, and input segments
  130544. ** are merged eight at a time, updating the input segments at the end
  130545. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  130546. ** small - often between 0 and 2. So the overhead of the incremental
  130547. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  130548. ** dwarfing the actual productive work accomplished, the incremental merge
  130549. ** is only attempted if it will write at least 64 leaf blocks. Hence
  130550. ** nMinMerge.
  130551. **
  130552. ** Of course, updating the input segments also involves deleting a bunch
  130553. ** of blocks from the segments table. But this is not considered overhead
  130554. ** as it would also be required by a crisis-merge that used the same input
  130555. ** segments.
  130556. */
  130557. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  130558. Fts3Table *p = (Fts3Table*)pVtab;
  130559. int rc = sqlite3Fts3PendingTermsFlush(p);
  130560. if( rc==SQLITE_OK
  130561. && p->nLeafAdd>(nMinMerge/16)
  130562. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  130563. ){
  130564. int mxLevel = 0; /* Maximum relative level value in db */
  130565. int A; /* Incr-merge parameter A */
  130566. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  130567. assert( rc==SQLITE_OK || mxLevel==0 );
  130568. A = p->nLeafAdd * mxLevel;
  130569. A += (A/2);
  130570. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  130571. }
  130572. sqlite3Fts3SegmentsClose(p);
  130573. return rc;
  130574. }
  130575. /*
  130576. ** If it is currently unknown whether or not the FTS table has an %_stat
  130577. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  130578. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  130579. ** if an error occurs.
  130580. */
  130581. static int fts3SetHasStat(Fts3Table *p){
  130582. int rc = SQLITE_OK;
  130583. if( p->bHasStat==2 ){
  130584. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  130585. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  130586. if( zSql ){
  130587. sqlite3_stmt *pStmt = 0;
  130588. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  130589. if( rc==SQLITE_OK ){
  130590. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  130591. rc = sqlite3_finalize(pStmt);
  130592. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  130593. }
  130594. sqlite3_free(zSql);
  130595. }else{
  130596. rc = SQLITE_NOMEM;
  130597. }
  130598. }
  130599. return rc;
  130600. }
  130601. /*
  130602. ** Implementation of xBegin() method.
  130603. */
  130604. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  130605. Fts3Table *p = (Fts3Table*)pVtab;
  130606. UNUSED_PARAMETER(pVtab);
  130607. assert( p->pSegments==0 );
  130608. assert( p->nPendingData==0 );
  130609. assert( p->inTransaction!=1 );
  130610. TESTONLY( p->inTransaction = 1 );
  130611. TESTONLY( p->mxSavepoint = -1; );
  130612. p->nLeafAdd = 0;
  130613. return fts3SetHasStat(p);
  130614. }
  130615. /*
  130616. ** Implementation of xCommit() method. This is a no-op. The contents of
  130617. ** the pending-terms hash-table have already been flushed into the database
  130618. ** by fts3SyncMethod().
  130619. */
  130620. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  130621. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  130622. UNUSED_PARAMETER(pVtab);
  130623. assert( p->nPendingData==0 );
  130624. assert( p->inTransaction!=0 );
  130625. assert( p->pSegments==0 );
  130626. TESTONLY( p->inTransaction = 0 );
  130627. TESTONLY( p->mxSavepoint = -1; );
  130628. return SQLITE_OK;
  130629. }
  130630. /*
  130631. ** Implementation of xRollback(). Discard the contents of the pending-terms
  130632. ** hash-table. Any changes made to the database are reverted by SQLite.
  130633. */
  130634. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  130635. Fts3Table *p = (Fts3Table*)pVtab;
  130636. sqlite3Fts3PendingTermsClear(p);
  130637. assert( p->inTransaction!=0 );
  130638. TESTONLY( p->inTransaction = 0 );
  130639. TESTONLY( p->mxSavepoint = -1; );
  130640. return SQLITE_OK;
  130641. }
  130642. /*
  130643. ** When called, *ppPoslist must point to the byte immediately following the
  130644. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  130645. ** moves *ppPoslist so that it instead points to the first byte of the
  130646. ** same position list.
  130647. */
  130648. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  130649. char *p = &(*ppPoslist)[-2];
  130650. char c = 0;
  130651. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  130652. while( p>pStart && (c=*p--)==0 );
  130653. /* Search backwards for a varint with value zero (the end of the previous
  130654. ** poslist). This is an 0x00 byte preceded by some byte that does not
  130655. ** have the 0x80 bit set. */
  130656. while( p>pStart && (*p & 0x80) | c ){
  130657. c = *p--;
  130658. }
  130659. assert( p==pStart || c==0 );
  130660. /* At this point p points to that preceding byte without the 0x80 bit
  130661. ** set. So to find the start of the poslist, skip forward 2 bytes then
  130662. ** over a varint.
  130663. **
  130664. ** Normally. The other case is that p==pStart and the poslist to return
  130665. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  130666. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  130667. ** is required for cases where the first byte of a doclist and the
  130668. ** doclist is empty. For example, if the first docid is 10, a doclist
  130669. ** that begins with:
  130670. **
  130671. ** 0x0A 0x00 <next docid delta varint>
  130672. */
  130673. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  130674. while( *p++&0x80 );
  130675. *ppPoslist = p;
  130676. }
  130677. /*
  130678. ** Helper function used by the implementation of the overloaded snippet(),
  130679. ** offsets() and optimize() SQL functions.
  130680. **
  130681. ** If the value passed as the third argument is a blob of size
  130682. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  130683. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  130684. ** message is written to context pContext and SQLITE_ERROR returned. The
  130685. ** string passed via zFunc is used as part of the error message.
  130686. */
  130687. static int fts3FunctionArg(
  130688. sqlite3_context *pContext, /* SQL function call context */
  130689. const char *zFunc, /* Function name */
  130690. sqlite3_value *pVal, /* argv[0] passed to function */
  130691. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  130692. ){
  130693. Fts3Cursor *pRet;
  130694. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  130695. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  130696. ){
  130697. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  130698. sqlite3_result_error(pContext, zErr, -1);
  130699. sqlite3_free(zErr);
  130700. return SQLITE_ERROR;
  130701. }
  130702. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  130703. *ppCsr = pRet;
  130704. return SQLITE_OK;
  130705. }
  130706. /*
  130707. ** Implementation of the snippet() function for FTS3
  130708. */
  130709. static void fts3SnippetFunc(
  130710. sqlite3_context *pContext, /* SQLite function call context */
  130711. int nVal, /* Size of apVal[] array */
  130712. sqlite3_value **apVal /* Array of arguments */
  130713. ){
  130714. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  130715. const char *zStart = "<b>";
  130716. const char *zEnd = "</b>";
  130717. const char *zEllipsis = "<b>...</b>";
  130718. int iCol = -1;
  130719. int nToken = 15; /* Default number of tokens in snippet */
  130720. /* There must be at least one argument passed to this function (otherwise
  130721. ** the non-overloaded version would have been called instead of this one).
  130722. */
  130723. assert( nVal>=1 );
  130724. if( nVal>6 ){
  130725. sqlite3_result_error(pContext,
  130726. "wrong number of arguments to function snippet()", -1);
  130727. return;
  130728. }
  130729. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  130730. switch( nVal ){
  130731. case 6: nToken = sqlite3_value_int(apVal[5]);
  130732. case 5: iCol = sqlite3_value_int(apVal[4]);
  130733. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  130734. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  130735. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  130736. }
  130737. if( !zEllipsis || !zEnd || !zStart ){
  130738. sqlite3_result_error_nomem(pContext);
  130739. }else if( nToken==0 ){
  130740. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  130741. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  130742. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  130743. }
  130744. }
  130745. /*
  130746. ** Implementation of the offsets() function for FTS3
  130747. */
  130748. static void fts3OffsetsFunc(
  130749. sqlite3_context *pContext, /* SQLite function call context */
  130750. int nVal, /* Size of argument array */
  130751. sqlite3_value **apVal /* Array of arguments */
  130752. ){
  130753. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  130754. UNUSED_PARAMETER(nVal);
  130755. assert( nVal==1 );
  130756. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  130757. assert( pCsr );
  130758. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  130759. sqlite3Fts3Offsets(pContext, pCsr);
  130760. }
  130761. }
  130762. /*
  130763. ** Implementation of the special optimize() function for FTS3. This
  130764. ** function merges all segments in the database to a single segment.
  130765. ** Example usage is:
  130766. **
  130767. ** SELECT optimize(t) FROM t LIMIT 1;
  130768. **
  130769. ** where 't' is the name of an FTS3 table.
  130770. */
  130771. static void fts3OptimizeFunc(
  130772. sqlite3_context *pContext, /* SQLite function call context */
  130773. int nVal, /* Size of argument array */
  130774. sqlite3_value **apVal /* Array of arguments */
  130775. ){
  130776. int rc; /* Return code */
  130777. Fts3Table *p; /* Virtual table handle */
  130778. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  130779. UNUSED_PARAMETER(nVal);
  130780. assert( nVal==1 );
  130781. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  130782. p = (Fts3Table *)pCursor->base.pVtab;
  130783. assert( p );
  130784. rc = sqlite3Fts3Optimize(p);
  130785. switch( rc ){
  130786. case SQLITE_OK:
  130787. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  130788. break;
  130789. case SQLITE_DONE:
  130790. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  130791. break;
  130792. default:
  130793. sqlite3_result_error_code(pContext, rc);
  130794. break;
  130795. }
  130796. }
  130797. /*
  130798. ** Implementation of the matchinfo() function for FTS3
  130799. */
  130800. static void fts3MatchinfoFunc(
  130801. sqlite3_context *pContext, /* SQLite function call context */
  130802. int nVal, /* Size of argument array */
  130803. sqlite3_value **apVal /* Array of arguments */
  130804. ){
  130805. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  130806. assert( nVal==1 || nVal==2 );
  130807. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  130808. const char *zArg = 0;
  130809. if( nVal>1 ){
  130810. zArg = (const char *)sqlite3_value_text(apVal[1]);
  130811. }
  130812. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  130813. }
  130814. }
  130815. /*
  130816. ** This routine implements the xFindFunction method for the FTS3
  130817. ** virtual table.
  130818. */
  130819. static int fts3FindFunctionMethod(
  130820. sqlite3_vtab *pVtab, /* Virtual table handle */
  130821. int nArg, /* Number of SQL function arguments */
  130822. const char *zName, /* Name of SQL function */
  130823. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  130824. void **ppArg /* Unused */
  130825. ){
  130826. struct Overloaded {
  130827. const char *zName;
  130828. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  130829. } aOverload[] = {
  130830. { "snippet", fts3SnippetFunc },
  130831. { "offsets", fts3OffsetsFunc },
  130832. { "optimize", fts3OptimizeFunc },
  130833. { "matchinfo", fts3MatchinfoFunc },
  130834. };
  130835. int i; /* Iterator variable */
  130836. UNUSED_PARAMETER(pVtab);
  130837. UNUSED_PARAMETER(nArg);
  130838. UNUSED_PARAMETER(ppArg);
  130839. for(i=0; i<SizeofArray(aOverload); i++){
  130840. if( strcmp(zName, aOverload[i].zName)==0 ){
  130841. *pxFunc = aOverload[i].xFunc;
  130842. return 1;
  130843. }
  130844. }
  130845. /* No function of the specified name was found. Return 0. */
  130846. return 0;
  130847. }
  130848. /*
  130849. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  130850. */
  130851. static int fts3RenameMethod(
  130852. sqlite3_vtab *pVtab, /* Virtual table handle */
  130853. const char *zName /* New name of table */
  130854. ){
  130855. Fts3Table *p = (Fts3Table *)pVtab;
  130856. sqlite3 *db = p->db; /* Database connection */
  130857. int rc; /* Return Code */
  130858. /* At this point it must be known if the %_stat table exists or not.
  130859. ** So bHasStat may not be 2. */
  130860. rc = fts3SetHasStat(p);
  130861. /* As it happens, the pending terms table is always empty here. This is
  130862. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  130863. ** always opens a savepoint transaction. And the xSavepoint() method
  130864. ** flushes the pending terms table. But leave the (no-op) call to
  130865. ** PendingTermsFlush() in in case that changes.
  130866. */
  130867. assert( p->nPendingData==0 );
  130868. if( rc==SQLITE_OK ){
  130869. rc = sqlite3Fts3PendingTermsFlush(p);
  130870. }
  130871. if( p->zContentTbl==0 ){
  130872. fts3DbExec(&rc, db,
  130873. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  130874. p->zDb, p->zName, zName
  130875. );
  130876. }
  130877. if( p->bHasDocsize ){
  130878. fts3DbExec(&rc, db,
  130879. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  130880. p->zDb, p->zName, zName
  130881. );
  130882. }
  130883. if( p->bHasStat ){
  130884. fts3DbExec(&rc, db,
  130885. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  130886. p->zDb, p->zName, zName
  130887. );
  130888. }
  130889. fts3DbExec(&rc, db,
  130890. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  130891. p->zDb, p->zName, zName
  130892. );
  130893. fts3DbExec(&rc, db,
  130894. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  130895. p->zDb, p->zName, zName
  130896. );
  130897. return rc;
  130898. }
  130899. /*
  130900. ** The xSavepoint() method.
  130901. **
  130902. ** Flush the contents of the pending-terms table to disk.
  130903. */
  130904. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  130905. int rc = SQLITE_OK;
  130906. UNUSED_PARAMETER(iSavepoint);
  130907. assert( ((Fts3Table *)pVtab)->inTransaction );
  130908. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  130909. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  130910. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  130911. rc = fts3SyncMethod(pVtab);
  130912. }
  130913. return rc;
  130914. }
  130915. /*
  130916. ** The xRelease() method.
  130917. **
  130918. ** This is a no-op.
  130919. */
  130920. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  130921. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  130922. UNUSED_PARAMETER(iSavepoint);
  130923. UNUSED_PARAMETER(pVtab);
  130924. assert( p->inTransaction );
  130925. assert( p->mxSavepoint >= iSavepoint );
  130926. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  130927. return SQLITE_OK;
  130928. }
  130929. /*
  130930. ** The xRollbackTo() method.
  130931. **
  130932. ** Discard the contents of the pending terms table.
  130933. */
  130934. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  130935. Fts3Table *p = (Fts3Table*)pVtab;
  130936. UNUSED_PARAMETER(iSavepoint);
  130937. assert( p->inTransaction );
  130938. assert( p->mxSavepoint >= iSavepoint );
  130939. TESTONLY( p->mxSavepoint = iSavepoint );
  130940. sqlite3Fts3PendingTermsClear(p);
  130941. return SQLITE_OK;
  130942. }
  130943. static const sqlite3_module fts3Module = {
  130944. /* iVersion */ 2,
  130945. /* xCreate */ fts3CreateMethod,
  130946. /* xConnect */ fts3ConnectMethod,
  130947. /* xBestIndex */ fts3BestIndexMethod,
  130948. /* xDisconnect */ fts3DisconnectMethod,
  130949. /* xDestroy */ fts3DestroyMethod,
  130950. /* xOpen */ fts3OpenMethod,
  130951. /* xClose */ fts3CloseMethod,
  130952. /* xFilter */ fts3FilterMethod,
  130953. /* xNext */ fts3NextMethod,
  130954. /* xEof */ fts3EofMethod,
  130955. /* xColumn */ fts3ColumnMethod,
  130956. /* xRowid */ fts3RowidMethod,
  130957. /* xUpdate */ fts3UpdateMethod,
  130958. /* xBegin */ fts3BeginMethod,
  130959. /* xSync */ fts3SyncMethod,
  130960. /* xCommit */ fts3CommitMethod,
  130961. /* xRollback */ fts3RollbackMethod,
  130962. /* xFindFunction */ fts3FindFunctionMethod,
  130963. /* xRename */ fts3RenameMethod,
  130964. /* xSavepoint */ fts3SavepointMethod,
  130965. /* xRelease */ fts3ReleaseMethod,
  130966. /* xRollbackTo */ fts3RollbackToMethod,
  130967. };
  130968. /*
  130969. ** This function is registered as the module destructor (called when an
  130970. ** FTS3 enabled database connection is closed). It frees the memory
  130971. ** allocated for the tokenizer hash table.
  130972. */
  130973. static void hashDestroy(void *p){
  130974. Fts3Hash *pHash = (Fts3Hash *)p;
  130975. sqlite3Fts3HashClear(pHash);
  130976. sqlite3_free(pHash);
  130977. }
  130978. /*
  130979. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  130980. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  130981. ** respectively. The following three forward declarations are for functions
  130982. ** declared in these files used to retrieve the respective implementations.
  130983. **
  130984. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  130985. ** to by the argument to point to the "simple" tokenizer implementation.
  130986. ** And so on.
  130987. */
  130988. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  130989. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  130990. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  130991. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  130992. #endif
  130993. #ifdef SQLITE_ENABLE_ICU
  130994. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  130995. #endif
  130996. /*
  130997. ** Initialize the fts3 extension. If this extension is built as part
  130998. ** of the sqlite library, then this function is called directly by
  130999. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  131000. ** function is called by the sqlite3_extension_init() entry point.
  131001. */
  131002. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  131003. int rc = SQLITE_OK;
  131004. Fts3Hash *pHash = 0;
  131005. const sqlite3_tokenizer_module *pSimple = 0;
  131006. const sqlite3_tokenizer_module *pPorter = 0;
  131007. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  131008. const sqlite3_tokenizer_module *pUnicode = 0;
  131009. #endif
  131010. #ifdef SQLITE_ENABLE_ICU
  131011. const sqlite3_tokenizer_module *pIcu = 0;
  131012. sqlite3Fts3IcuTokenizerModule(&pIcu);
  131013. #endif
  131014. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  131015. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  131016. #endif
  131017. #ifdef SQLITE_TEST
  131018. rc = sqlite3Fts3InitTerm(db);
  131019. if( rc!=SQLITE_OK ) return rc;
  131020. #endif
  131021. rc = sqlite3Fts3InitAux(db);
  131022. if( rc!=SQLITE_OK ) return rc;
  131023. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  131024. sqlite3Fts3PorterTokenizerModule(&pPorter);
  131025. /* Allocate and initialize the hash-table used to store tokenizers. */
  131026. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  131027. if( !pHash ){
  131028. rc = SQLITE_NOMEM;
  131029. }else{
  131030. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  131031. }
  131032. /* Load the built-in tokenizers into the hash table */
  131033. if( rc==SQLITE_OK ){
  131034. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  131035. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  131036. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  131037. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  131038. #endif
  131039. #ifdef SQLITE_ENABLE_ICU
  131040. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  131041. #endif
  131042. ){
  131043. rc = SQLITE_NOMEM;
  131044. }
  131045. }
  131046. #ifdef SQLITE_TEST
  131047. if( rc==SQLITE_OK ){
  131048. rc = sqlite3Fts3ExprInitTestInterface(db);
  131049. }
  131050. #endif
  131051. /* Create the virtual table wrapper around the hash-table and overload
  131052. ** the two scalar functions. If this is successful, register the
  131053. ** module with sqlite.
  131054. */
  131055. if( SQLITE_OK==rc
  131056. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  131057. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  131058. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  131059. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  131060. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  131061. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  131062. ){
  131063. rc = sqlite3_create_module_v2(
  131064. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  131065. );
  131066. if( rc==SQLITE_OK ){
  131067. rc = sqlite3_create_module_v2(
  131068. db, "fts4", &fts3Module, (void *)pHash, 0
  131069. );
  131070. }
  131071. if( rc==SQLITE_OK ){
  131072. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  131073. }
  131074. return rc;
  131075. }
  131076. /* An error has occurred. Delete the hash table and return the error code. */
  131077. assert( rc!=SQLITE_OK );
  131078. if( pHash ){
  131079. sqlite3Fts3HashClear(pHash);
  131080. sqlite3_free(pHash);
  131081. }
  131082. return rc;
  131083. }
  131084. /*
  131085. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  131086. ** by pExpr.
  131087. **
  131088. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  131089. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  131090. ** Fts3SegReader objects internally to provide an interface to seek or scan
  131091. ** within the union of all segments of a b-tree. Hence the name.
  131092. **
  131093. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  131094. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  131095. ** there exists prefix b-tree of the right length) then it may be traversed
  131096. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  131097. ** doclist and then traversed.
  131098. */
  131099. static void fts3EvalAllocateReaders(
  131100. Fts3Cursor *pCsr, /* FTS cursor handle */
  131101. Fts3Expr *pExpr, /* Allocate readers for this expression */
  131102. int *pnToken, /* OUT: Total number of tokens in phrase. */
  131103. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  131104. int *pRc /* IN/OUT: Error code */
  131105. ){
  131106. if( pExpr && SQLITE_OK==*pRc ){
  131107. if( pExpr->eType==FTSQUERY_PHRASE ){
  131108. int i;
  131109. int nToken = pExpr->pPhrase->nToken;
  131110. *pnToken += nToken;
  131111. for(i=0; i<nToken; i++){
  131112. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  131113. int rc = fts3TermSegReaderCursor(pCsr,
  131114. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  131115. );
  131116. if( rc!=SQLITE_OK ){
  131117. *pRc = rc;
  131118. return;
  131119. }
  131120. }
  131121. assert( pExpr->pPhrase->iDoclistToken==0 );
  131122. pExpr->pPhrase->iDoclistToken = -1;
  131123. }else{
  131124. *pnOr += (pExpr->eType==FTSQUERY_OR);
  131125. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  131126. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  131127. }
  131128. }
  131129. }
  131130. /*
  131131. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  131132. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  131133. **
  131134. ** This function assumes that pList points to a buffer allocated using
  131135. ** sqlite3_malloc(). This function takes responsibility for eventually
  131136. ** freeing the buffer.
  131137. **
  131138. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  131139. */
  131140. static int fts3EvalPhraseMergeToken(
  131141. Fts3Table *pTab, /* FTS Table pointer */
  131142. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  131143. int iToken, /* Token pList/nList corresponds to */
  131144. char *pList, /* Pointer to doclist */
  131145. int nList /* Number of bytes in pList */
  131146. ){
  131147. int rc = SQLITE_OK;
  131148. assert( iToken!=p->iDoclistToken );
  131149. if( pList==0 ){
  131150. sqlite3_free(p->doclist.aAll);
  131151. p->doclist.aAll = 0;
  131152. p->doclist.nAll = 0;
  131153. }
  131154. else if( p->iDoclistToken<0 ){
  131155. p->doclist.aAll = pList;
  131156. p->doclist.nAll = nList;
  131157. }
  131158. else if( p->doclist.aAll==0 ){
  131159. sqlite3_free(pList);
  131160. }
  131161. else {
  131162. char *pLeft;
  131163. char *pRight;
  131164. int nLeft;
  131165. int nRight;
  131166. int nDiff;
  131167. if( p->iDoclistToken<iToken ){
  131168. pLeft = p->doclist.aAll;
  131169. nLeft = p->doclist.nAll;
  131170. pRight = pList;
  131171. nRight = nList;
  131172. nDiff = iToken - p->iDoclistToken;
  131173. }else{
  131174. pRight = p->doclist.aAll;
  131175. nRight = p->doclist.nAll;
  131176. pLeft = pList;
  131177. nLeft = nList;
  131178. nDiff = p->iDoclistToken - iToken;
  131179. }
  131180. rc = fts3DoclistPhraseMerge(
  131181. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  131182. );
  131183. sqlite3_free(pLeft);
  131184. p->doclist.aAll = pRight;
  131185. p->doclist.nAll = nRight;
  131186. }
  131187. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  131188. return rc;
  131189. }
  131190. /*
  131191. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  131192. ** does not take deferred tokens into account.
  131193. **
  131194. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  131195. */
  131196. static int fts3EvalPhraseLoad(
  131197. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131198. Fts3Phrase *p /* Phrase object */
  131199. ){
  131200. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131201. int iToken;
  131202. int rc = SQLITE_OK;
  131203. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  131204. Fts3PhraseToken *pToken = &p->aToken[iToken];
  131205. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  131206. if( pToken->pSegcsr ){
  131207. int nThis = 0;
  131208. char *pThis = 0;
  131209. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  131210. if( rc==SQLITE_OK ){
  131211. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  131212. }
  131213. }
  131214. assert( pToken->pSegcsr==0 );
  131215. }
  131216. return rc;
  131217. }
  131218. /*
  131219. ** This function is called on each phrase after the position lists for
  131220. ** any deferred tokens have been loaded into memory. It updates the phrases
  131221. ** current position list to include only those positions that are really
  131222. ** instances of the phrase (after considering deferred tokens). If this
  131223. ** means that the phrase does not appear in the current row, doclist.pList
  131224. ** and doclist.nList are both zeroed.
  131225. **
  131226. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  131227. */
  131228. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  131229. int iToken; /* Used to iterate through phrase tokens */
  131230. char *aPoslist = 0; /* Position list for deferred tokens */
  131231. int nPoslist = 0; /* Number of bytes in aPoslist */
  131232. int iPrev = -1; /* Token number of previous deferred token */
  131233. assert( pPhrase->doclist.bFreeList==0 );
  131234. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  131235. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  131236. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  131237. if( pDeferred ){
  131238. char *pList;
  131239. int nList;
  131240. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  131241. if( rc!=SQLITE_OK ) return rc;
  131242. if( pList==0 ){
  131243. sqlite3_free(aPoslist);
  131244. pPhrase->doclist.pList = 0;
  131245. pPhrase->doclist.nList = 0;
  131246. return SQLITE_OK;
  131247. }else if( aPoslist==0 ){
  131248. aPoslist = pList;
  131249. nPoslist = nList;
  131250. }else{
  131251. char *aOut = pList;
  131252. char *p1 = aPoslist;
  131253. char *p2 = aOut;
  131254. assert( iPrev>=0 );
  131255. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  131256. sqlite3_free(aPoslist);
  131257. aPoslist = pList;
  131258. nPoslist = (int)(aOut - aPoslist);
  131259. if( nPoslist==0 ){
  131260. sqlite3_free(aPoslist);
  131261. pPhrase->doclist.pList = 0;
  131262. pPhrase->doclist.nList = 0;
  131263. return SQLITE_OK;
  131264. }
  131265. }
  131266. iPrev = iToken;
  131267. }
  131268. }
  131269. if( iPrev>=0 ){
  131270. int nMaxUndeferred = pPhrase->iDoclistToken;
  131271. if( nMaxUndeferred<0 ){
  131272. pPhrase->doclist.pList = aPoslist;
  131273. pPhrase->doclist.nList = nPoslist;
  131274. pPhrase->doclist.iDocid = pCsr->iPrevId;
  131275. pPhrase->doclist.bFreeList = 1;
  131276. }else{
  131277. int nDistance;
  131278. char *p1;
  131279. char *p2;
  131280. char *aOut;
  131281. if( nMaxUndeferred>iPrev ){
  131282. p1 = aPoslist;
  131283. p2 = pPhrase->doclist.pList;
  131284. nDistance = nMaxUndeferred - iPrev;
  131285. }else{
  131286. p1 = pPhrase->doclist.pList;
  131287. p2 = aPoslist;
  131288. nDistance = iPrev - nMaxUndeferred;
  131289. }
  131290. aOut = (char *)sqlite3_malloc(nPoslist+8);
  131291. if( !aOut ){
  131292. sqlite3_free(aPoslist);
  131293. return SQLITE_NOMEM;
  131294. }
  131295. pPhrase->doclist.pList = aOut;
  131296. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  131297. pPhrase->doclist.bFreeList = 1;
  131298. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  131299. }else{
  131300. sqlite3_free(aOut);
  131301. pPhrase->doclist.pList = 0;
  131302. pPhrase->doclist.nList = 0;
  131303. }
  131304. sqlite3_free(aPoslist);
  131305. }
  131306. }
  131307. return SQLITE_OK;
  131308. }
  131309. /*
  131310. ** Maximum number of tokens a phrase may have to be considered for the
  131311. ** incremental doclists strategy.
  131312. */
  131313. #define MAX_INCR_PHRASE_TOKENS 4
  131314. /*
  131315. ** This function is called for each Fts3Phrase in a full-text query
  131316. ** expression to initialize the mechanism for returning rows. Once this
  131317. ** function has been called successfully on an Fts3Phrase, it may be
  131318. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  131319. **
  131320. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  131321. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  131322. ** memory within this call.
  131323. **
  131324. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  131325. */
  131326. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  131327. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131328. int rc = SQLITE_OK; /* Error code */
  131329. int i;
  131330. /* Determine if doclists may be loaded from disk incrementally. This is
  131331. ** possible if the bOptOk argument is true, the FTS doclists will be
  131332. ** scanned in forward order, and the phrase consists of
  131333. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  131334. ** tokens or prefix tokens that cannot use a prefix-index. */
  131335. int bHaveIncr = 0;
  131336. int bIncrOk = (bOptOk
  131337. && pCsr->bDesc==pTab->bDescIdx
  131338. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  131339. #ifdef SQLITE_TEST
  131340. && pTab->bNoIncrDoclist==0
  131341. #endif
  131342. );
  131343. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  131344. Fts3PhraseToken *pToken = &p->aToken[i];
  131345. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  131346. bIncrOk = 0;
  131347. }
  131348. if( pToken->pSegcsr ) bHaveIncr = 1;
  131349. }
  131350. if( bIncrOk && bHaveIncr ){
  131351. /* Use the incremental approach. */
  131352. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  131353. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  131354. Fts3PhraseToken *pToken = &p->aToken[i];
  131355. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  131356. if( pSegcsr ){
  131357. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  131358. }
  131359. }
  131360. p->bIncr = 1;
  131361. }else{
  131362. /* Load the full doclist for the phrase into memory. */
  131363. rc = fts3EvalPhraseLoad(pCsr, p);
  131364. p->bIncr = 0;
  131365. }
  131366. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  131367. return rc;
  131368. }
  131369. /*
  131370. ** This function is used to iterate backwards (from the end to start)
  131371. ** through doclists. It is used by this module to iterate through phrase
  131372. ** doclists in reverse and by the fts3_write.c module to iterate through
  131373. ** pending-terms lists when writing to databases with "order=desc".
  131374. **
  131375. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  131376. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  131377. ** function iterates from the end of the doclist to the beginning.
  131378. */
  131379. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  131380. int bDescIdx, /* True if the doclist is desc */
  131381. char *aDoclist, /* Pointer to entire doclist */
  131382. int nDoclist, /* Length of aDoclist in bytes */
  131383. char **ppIter, /* IN/OUT: Iterator pointer */
  131384. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  131385. int *pnList, /* OUT: List length pointer */
  131386. u8 *pbEof /* OUT: End-of-file flag */
  131387. ){
  131388. char *p = *ppIter;
  131389. assert( nDoclist>0 );
  131390. assert( *pbEof==0 );
  131391. assert( p || *piDocid==0 );
  131392. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  131393. if( p==0 ){
  131394. sqlite3_int64 iDocid = 0;
  131395. char *pNext = 0;
  131396. char *pDocid = aDoclist;
  131397. char *pEnd = &aDoclist[nDoclist];
  131398. int iMul = 1;
  131399. while( pDocid<pEnd ){
  131400. sqlite3_int64 iDelta;
  131401. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  131402. iDocid += (iMul * iDelta);
  131403. pNext = pDocid;
  131404. fts3PoslistCopy(0, &pDocid);
  131405. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  131406. iMul = (bDescIdx ? -1 : 1);
  131407. }
  131408. *pnList = (int)(pEnd - pNext);
  131409. *ppIter = pNext;
  131410. *piDocid = iDocid;
  131411. }else{
  131412. int iMul = (bDescIdx ? -1 : 1);
  131413. sqlite3_int64 iDelta;
  131414. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  131415. *piDocid -= (iMul * iDelta);
  131416. if( p==aDoclist ){
  131417. *pbEof = 1;
  131418. }else{
  131419. char *pSave = p;
  131420. fts3ReversePoslist(aDoclist, &p);
  131421. *pnList = (int)(pSave - p);
  131422. }
  131423. *ppIter = p;
  131424. }
  131425. }
  131426. /*
  131427. ** Iterate forwards through a doclist.
  131428. */
  131429. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  131430. int bDescIdx, /* True if the doclist is desc */
  131431. char *aDoclist, /* Pointer to entire doclist */
  131432. int nDoclist, /* Length of aDoclist in bytes */
  131433. char **ppIter, /* IN/OUT: Iterator pointer */
  131434. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  131435. u8 *pbEof /* OUT: End-of-file flag */
  131436. ){
  131437. char *p = *ppIter;
  131438. assert( nDoclist>0 );
  131439. assert( *pbEof==0 );
  131440. assert( p || *piDocid==0 );
  131441. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  131442. if( p==0 ){
  131443. p = aDoclist;
  131444. p += sqlite3Fts3GetVarint(p, piDocid);
  131445. }else{
  131446. fts3PoslistCopy(0, &p);
  131447. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  131448. if( p>=&aDoclist[nDoclist] ){
  131449. *pbEof = 1;
  131450. }else{
  131451. sqlite3_int64 iVar;
  131452. p += sqlite3Fts3GetVarint(p, &iVar);
  131453. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  131454. }
  131455. }
  131456. *ppIter = p;
  131457. }
  131458. /*
  131459. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  131460. ** to true if EOF is reached.
  131461. */
  131462. static void fts3EvalDlPhraseNext(
  131463. Fts3Table *pTab,
  131464. Fts3Doclist *pDL,
  131465. u8 *pbEof
  131466. ){
  131467. char *pIter; /* Used to iterate through aAll */
  131468. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  131469. if( pDL->pNextDocid ){
  131470. pIter = pDL->pNextDocid;
  131471. }else{
  131472. pIter = pDL->aAll;
  131473. }
  131474. if( pIter>=pEnd ){
  131475. /* We have already reached the end of this doclist. EOF. */
  131476. *pbEof = 1;
  131477. }else{
  131478. sqlite3_int64 iDelta;
  131479. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  131480. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  131481. pDL->iDocid += iDelta;
  131482. }else{
  131483. pDL->iDocid -= iDelta;
  131484. }
  131485. pDL->pList = pIter;
  131486. fts3PoslistCopy(0, &pIter);
  131487. pDL->nList = (int)(pIter - pDL->pList);
  131488. /* pIter now points just past the 0x00 that terminates the position-
  131489. ** list for document pDL->iDocid. However, if this position-list was
  131490. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  131491. ** point to the start of the next docid value. The following line deals
  131492. ** with this case by advancing pIter past the zero-padding added by
  131493. ** fts3EvalNearTrim(). */
  131494. while( pIter<pEnd && *pIter==0 ) pIter++;
  131495. pDL->pNextDocid = pIter;
  131496. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  131497. *pbEof = 0;
  131498. }
  131499. }
  131500. /*
  131501. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  131502. */
  131503. typedef struct TokenDoclist TokenDoclist;
  131504. struct TokenDoclist {
  131505. int bIgnore;
  131506. sqlite3_int64 iDocid;
  131507. char *pList;
  131508. int nList;
  131509. };
  131510. /*
  131511. ** Token pToken is an incrementally loaded token that is part of a
  131512. ** multi-token phrase. Advance it to the next matching document in the
  131513. ** database and populate output variable *p with the details of the new
  131514. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  131515. **
  131516. ** If an error occurs, return an SQLite error code. Otherwise, return
  131517. ** SQLITE_OK.
  131518. */
  131519. static int incrPhraseTokenNext(
  131520. Fts3Table *pTab, /* Virtual table handle */
  131521. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  131522. int iToken, /* Specific token to advance */
  131523. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  131524. u8 *pbEof /* OUT: True if iterator is at EOF */
  131525. ){
  131526. int rc = SQLITE_OK;
  131527. if( pPhrase->iDoclistToken==iToken ){
  131528. assert( p->bIgnore==0 );
  131529. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  131530. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  131531. p->pList = pPhrase->doclist.pList;
  131532. p->nList = pPhrase->doclist.nList;
  131533. p->iDocid = pPhrase->doclist.iDocid;
  131534. }else{
  131535. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  131536. assert( pToken->pDeferred==0 );
  131537. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  131538. if( pToken->pSegcsr ){
  131539. assert( p->bIgnore==0 );
  131540. rc = sqlite3Fts3MsrIncrNext(
  131541. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  131542. );
  131543. if( p->pList==0 ) *pbEof = 1;
  131544. }else{
  131545. p->bIgnore = 1;
  131546. }
  131547. }
  131548. return rc;
  131549. }
  131550. /*
  131551. ** The phrase iterator passed as the second argument:
  131552. **
  131553. ** * features at least one token that uses an incremental doclist, and
  131554. **
  131555. ** * does not contain any deferred tokens.
  131556. **
  131557. ** Advance it to the next matching documnent in the database and populate
  131558. ** the Fts3Doclist.pList and nList fields.
  131559. **
  131560. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  131561. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  131562. ** successfully advanced, *pbEof is set to 0.
  131563. **
  131564. ** If an error occurs, return an SQLite error code. Otherwise, return
  131565. ** SQLITE_OK.
  131566. */
  131567. static int fts3EvalIncrPhraseNext(
  131568. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131569. Fts3Phrase *p, /* Phrase object to advance to next docid */
  131570. u8 *pbEof /* OUT: Set to 1 if EOF */
  131571. ){
  131572. int rc = SQLITE_OK;
  131573. Fts3Doclist *pDL = &p->doclist;
  131574. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131575. u8 bEof = 0;
  131576. /* This is only called if it is guaranteed that the phrase has at least
  131577. ** one incremental token. In which case the bIncr flag is set. */
  131578. assert( p->bIncr==1 );
  131579. if( p->nToken==1 && p->bIncr ){
  131580. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  131581. &pDL->iDocid, &pDL->pList, &pDL->nList
  131582. );
  131583. if( pDL->pList==0 ) bEof = 1;
  131584. }else{
  131585. int bDescDoclist = pCsr->bDesc;
  131586. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  131587. memset(a, 0, sizeof(a));
  131588. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  131589. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  131590. while( bEof==0 ){
  131591. int bMaxSet = 0;
  131592. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  131593. int i; /* Used to iterate through tokens */
  131594. /* Advance the iterator for each token in the phrase once. */
  131595. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  131596. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  131597. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  131598. iMax = a[i].iDocid;
  131599. bMaxSet = 1;
  131600. }
  131601. }
  131602. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  131603. assert( rc!=SQLITE_OK || bMaxSet );
  131604. /* Keep advancing iterators until they all point to the same document */
  131605. for(i=0; i<p->nToken; i++){
  131606. while( rc==SQLITE_OK && bEof==0
  131607. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  131608. ){
  131609. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  131610. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  131611. iMax = a[i].iDocid;
  131612. i = 0;
  131613. }
  131614. }
  131615. }
  131616. /* Check if the current entries really are a phrase match */
  131617. if( bEof==0 ){
  131618. int nList = 0;
  131619. int nByte = a[p->nToken-1].nList;
  131620. char *aDoclist = sqlite3_malloc(nByte+1);
  131621. if( !aDoclist ) return SQLITE_NOMEM;
  131622. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  131623. for(i=0; i<(p->nToken-1); i++){
  131624. if( a[i].bIgnore==0 ){
  131625. char *pL = a[i].pList;
  131626. char *pR = aDoclist;
  131627. char *pOut = aDoclist;
  131628. int nDist = p->nToken-1-i;
  131629. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  131630. if( res==0 ) break;
  131631. nList = (int)(pOut - aDoclist);
  131632. }
  131633. }
  131634. if( i==(p->nToken-1) ){
  131635. pDL->iDocid = iMax;
  131636. pDL->pList = aDoclist;
  131637. pDL->nList = nList;
  131638. pDL->bFreeList = 1;
  131639. break;
  131640. }
  131641. sqlite3_free(aDoclist);
  131642. }
  131643. }
  131644. }
  131645. *pbEof = bEof;
  131646. return rc;
  131647. }
  131648. /*
  131649. ** Attempt to move the phrase iterator to point to the next matching docid.
  131650. ** If an error occurs, return an SQLite error code. Otherwise, return
  131651. ** SQLITE_OK.
  131652. **
  131653. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  131654. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  131655. ** successfully advanced, *pbEof is set to 0.
  131656. */
  131657. static int fts3EvalPhraseNext(
  131658. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131659. Fts3Phrase *p, /* Phrase object to advance to next docid */
  131660. u8 *pbEof /* OUT: Set to 1 if EOF */
  131661. ){
  131662. int rc = SQLITE_OK;
  131663. Fts3Doclist *pDL = &p->doclist;
  131664. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131665. if( p->bIncr ){
  131666. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  131667. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  131668. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  131669. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  131670. );
  131671. pDL->pList = pDL->pNextDocid;
  131672. }else{
  131673. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  131674. }
  131675. return rc;
  131676. }
  131677. /*
  131678. **
  131679. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  131680. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  131681. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  131682. ** expressions for which all descendent tokens are deferred.
  131683. **
  131684. ** If parameter bOptOk is zero, then it is guaranteed that the
  131685. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  131686. ** each phrase in the expression (subject to deferred token processing).
  131687. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  131688. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  131689. **
  131690. ** If an error occurs within this function, *pRc is set to an SQLite error
  131691. ** code before returning.
  131692. */
  131693. static void fts3EvalStartReaders(
  131694. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131695. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  131696. int *pRc /* IN/OUT: Error code */
  131697. ){
  131698. if( pExpr && SQLITE_OK==*pRc ){
  131699. if( pExpr->eType==FTSQUERY_PHRASE ){
  131700. int nToken = pExpr->pPhrase->nToken;
  131701. if( nToken ){
  131702. int i;
  131703. for(i=0; i<nToken; i++){
  131704. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  131705. }
  131706. pExpr->bDeferred = (i==nToken);
  131707. }
  131708. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  131709. }else{
  131710. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  131711. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  131712. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  131713. }
  131714. }
  131715. }
  131716. /*
  131717. ** An array of the following structures is assembled as part of the process
  131718. ** of selecting tokens to defer before the query starts executing (as part
  131719. ** of the xFilter() method). There is one element in the array for each
  131720. ** token in the FTS expression.
  131721. **
  131722. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  131723. ** to phrases that are connected only by AND and NEAR operators (not OR or
  131724. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  131725. ** separately. The root of a tokens AND/NEAR cluster is stored in
  131726. ** Fts3TokenAndCost.pRoot.
  131727. */
  131728. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  131729. struct Fts3TokenAndCost {
  131730. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  131731. int iToken; /* Position of token in phrase */
  131732. Fts3PhraseToken *pToken; /* The token itself */
  131733. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  131734. int nOvfl; /* Number of overflow pages to load doclist */
  131735. int iCol; /* The column the token must match */
  131736. };
  131737. /*
  131738. ** This function is used to populate an allocated Fts3TokenAndCost array.
  131739. **
  131740. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  131741. ** Otherwise, if an error occurs during execution, *pRc is set to an
  131742. ** SQLite error code.
  131743. */
  131744. static void fts3EvalTokenCosts(
  131745. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131746. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  131747. Fts3Expr *pExpr, /* Expression to consider */
  131748. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  131749. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  131750. int *pRc /* IN/OUT: Error code */
  131751. ){
  131752. if( *pRc==SQLITE_OK ){
  131753. if( pExpr->eType==FTSQUERY_PHRASE ){
  131754. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131755. int i;
  131756. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  131757. Fts3TokenAndCost *pTC = (*ppTC)++;
  131758. pTC->pPhrase = pPhrase;
  131759. pTC->iToken = i;
  131760. pTC->pRoot = pRoot;
  131761. pTC->pToken = &pPhrase->aToken[i];
  131762. pTC->iCol = pPhrase->iColumn;
  131763. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  131764. }
  131765. }else if( pExpr->eType!=FTSQUERY_NOT ){
  131766. assert( pExpr->eType==FTSQUERY_OR
  131767. || pExpr->eType==FTSQUERY_AND
  131768. || pExpr->eType==FTSQUERY_NEAR
  131769. );
  131770. assert( pExpr->pLeft && pExpr->pRight );
  131771. if( pExpr->eType==FTSQUERY_OR ){
  131772. pRoot = pExpr->pLeft;
  131773. **ppOr = pRoot;
  131774. (*ppOr)++;
  131775. }
  131776. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  131777. if( pExpr->eType==FTSQUERY_OR ){
  131778. pRoot = pExpr->pRight;
  131779. **ppOr = pRoot;
  131780. (*ppOr)++;
  131781. }
  131782. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  131783. }
  131784. }
  131785. }
  131786. /*
  131787. ** Determine the average document (row) size in pages. If successful,
  131788. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  131789. ** an SQLite error code.
  131790. **
  131791. ** The average document size in pages is calculated by first calculating
  131792. ** determining the average size in bytes, B. If B is less than the amount
  131793. ** of data that will fit on a single leaf page of an intkey table in
  131794. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  131795. ** the number of overflow pages consumed by a record B bytes in size.
  131796. */
  131797. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  131798. if( pCsr->nRowAvg==0 ){
  131799. /* The average document size, which is required to calculate the cost
  131800. ** of each doclist, has not yet been determined. Read the required
  131801. ** data from the %_stat table to calculate it.
  131802. **
  131803. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  131804. ** varints, where nCol is the number of columns in the FTS3 table.
  131805. ** The first varint is the number of documents currently stored in
  131806. ** the table. The following nCol varints contain the total amount of
  131807. ** data stored in all rows of each column of the table, from left
  131808. ** to right.
  131809. */
  131810. int rc;
  131811. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  131812. sqlite3_stmt *pStmt;
  131813. sqlite3_int64 nDoc = 0;
  131814. sqlite3_int64 nByte = 0;
  131815. const char *pEnd;
  131816. const char *a;
  131817. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  131818. if( rc!=SQLITE_OK ) return rc;
  131819. a = sqlite3_column_blob(pStmt, 0);
  131820. assert( a );
  131821. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  131822. a += sqlite3Fts3GetVarint(a, &nDoc);
  131823. while( a<pEnd ){
  131824. a += sqlite3Fts3GetVarint(a, &nByte);
  131825. }
  131826. if( nDoc==0 || nByte==0 ){
  131827. sqlite3_reset(pStmt);
  131828. return FTS_CORRUPT_VTAB;
  131829. }
  131830. pCsr->nDoc = nDoc;
  131831. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  131832. assert( pCsr->nRowAvg>0 );
  131833. rc = sqlite3_reset(pStmt);
  131834. if( rc!=SQLITE_OK ) return rc;
  131835. }
  131836. *pnPage = pCsr->nRowAvg;
  131837. return SQLITE_OK;
  131838. }
  131839. /*
  131840. ** This function is called to select the tokens (if any) that will be
  131841. ** deferred. The array aTC[] has already been populated when this is
  131842. ** called.
  131843. **
  131844. ** This function is called once for each AND/NEAR cluster in the
  131845. ** expression. Each invocation determines which tokens to defer within
  131846. ** the cluster with root node pRoot. See comments above the definition
  131847. ** of struct Fts3TokenAndCost for more details.
  131848. **
  131849. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  131850. ** called on each token to defer. Otherwise, an SQLite error code is
  131851. ** returned.
  131852. */
  131853. static int fts3EvalSelectDeferred(
  131854. Fts3Cursor *pCsr, /* FTS Cursor handle */
  131855. Fts3Expr *pRoot, /* Consider tokens with this root node */
  131856. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  131857. int nTC /* Number of entries in aTC[] */
  131858. ){
  131859. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131860. int nDocSize = 0; /* Number of pages per doc loaded */
  131861. int rc = SQLITE_OK; /* Return code */
  131862. int ii; /* Iterator variable for various purposes */
  131863. int nOvfl = 0; /* Total overflow pages used by doclists */
  131864. int nToken = 0; /* Total number of tokens in cluster */
  131865. int nMinEst = 0; /* The minimum count for any phrase so far. */
  131866. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  131867. /* Tokens are never deferred for FTS tables created using the content=xxx
  131868. ** option. The reason being that it is not guaranteed that the content
  131869. ** table actually contains the same data as the index. To prevent this from
  131870. ** causing any problems, the deferred token optimization is completely
  131871. ** disabled for content=xxx tables. */
  131872. if( pTab->zContentTbl ){
  131873. return SQLITE_OK;
  131874. }
  131875. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  131876. ** associated with the tokens spill onto overflow pages, or if there is
  131877. ** only 1 token, exit early. No tokens to defer in this case. */
  131878. for(ii=0; ii<nTC; ii++){
  131879. if( aTC[ii].pRoot==pRoot ){
  131880. nOvfl += aTC[ii].nOvfl;
  131881. nToken++;
  131882. }
  131883. }
  131884. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  131885. /* Obtain the average docsize (in pages). */
  131886. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  131887. assert( rc!=SQLITE_OK || nDocSize>0 );
  131888. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  131889. ** of the number of overflow pages that will be loaded by the pager layer
  131890. ** to retrieve the entire doclist for the token from the full-text index.
  131891. ** Load the doclists for tokens that are either:
  131892. **
  131893. ** a. The cheapest token in the entire query (i.e. the one visited by the
  131894. ** first iteration of this loop), or
  131895. **
  131896. ** b. Part of a multi-token phrase.
  131897. **
  131898. ** After each token doclist is loaded, merge it with the others from the
  131899. ** same phrase and count the number of documents that the merged doclist
  131900. ** contains. Set variable "nMinEst" to the smallest number of documents in
  131901. ** any phrase doclist for which 1 or more token doclists have been loaded.
  131902. ** Let nOther be the number of other phrases for which it is certain that
  131903. ** one or more tokens will not be deferred.
  131904. **
  131905. ** Then, for each token, defer it if loading the doclist would result in
  131906. ** loading N or more overflow pages into memory, where N is computed as:
  131907. **
  131908. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  131909. */
  131910. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  131911. int iTC; /* Used to iterate through aTC[] array. */
  131912. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  131913. /* Set pTC to point to the cheapest remaining token. */
  131914. for(iTC=0; iTC<nTC; iTC++){
  131915. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  131916. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  131917. ){
  131918. pTC = &aTC[iTC];
  131919. }
  131920. }
  131921. assert( pTC );
  131922. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  131923. /* The number of overflow pages to load for this (and therefore all
  131924. ** subsequent) tokens is greater than the estimated number of pages
  131925. ** that will be loaded if all subsequent tokens are deferred.
  131926. */
  131927. Fts3PhraseToken *pToken = pTC->pToken;
  131928. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  131929. fts3SegReaderCursorFree(pToken->pSegcsr);
  131930. pToken->pSegcsr = 0;
  131931. }else{
  131932. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  131933. ** for-loop. Except, limit the value to 2^24 to prevent it from
  131934. ** overflowing the 32-bit integer it is stored in. */
  131935. if( ii<12 ) nLoad4 = nLoad4*4;
  131936. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  131937. /* Either this is the cheapest token in the entire query, or it is
  131938. ** part of a multi-token phrase. Either way, the entire doclist will
  131939. ** (eventually) be loaded into memory. It may as well be now. */
  131940. Fts3PhraseToken *pToken = pTC->pToken;
  131941. int nList = 0;
  131942. char *pList = 0;
  131943. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  131944. assert( rc==SQLITE_OK || pList==0 );
  131945. if( rc==SQLITE_OK ){
  131946. rc = fts3EvalPhraseMergeToken(
  131947. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  131948. );
  131949. }
  131950. if( rc==SQLITE_OK ){
  131951. int nCount;
  131952. nCount = fts3DoclistCountDocids(
  131953. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  131954. );
  131955. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  131956. }
  131957. }
  131958. }
  131959. pTC->pToken = 0;
  131960. }
  131961. return rc;
  131962. }
  131963. /*
  131964. ** This function is called from within the xFilter method. It initializes
  131965. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  131966. ** the results of a query, the caller does:
  131967. **
  131968. ** fts3EvalStart(pCsr);
  131969. ** while( 1 ){
  131970. ** fts3EvalNext(pCsr);
  131971. ** if( pCsr->bEof ) break;
  131972. ** ... return row pCsr->iPrevId to the caller ...
  131973. ** }
  131974. */
  131975. static int fts3EvalStart(Fts3Cursor *pCsr){
  131976. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131977. int rc = SQLITE_OK;
  131978. int nToken = 0;
  131979. int nOr = 0;
  131980. /* Allocate a MultiSegReader for each token in the expression. */
  131981. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  131982. /* Determine which, if any, tokens in the expression should be deferred. */
  131983. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  131984. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  131985. Fts3TokenAndCost *aTC;
  131986. Fts3Expr **apOr;
  131987. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  131988. sizeof(Fts3TokenAndCost) * nToken
  131989. + sizeof(Fts3Expr *) * nOr * 2
  131990. );
  131991. apOr = (Fts3Expr **)&aTC[nToken];
  131992. if( !aTC ){
  131993. rc = SQLITE_NOMEM;
  131994. }else{
  131995. int ii;
  131996. Fts3TokenAndCost *pTC = aTC;
  131997. Fts3Expr **ppOr = apOr;
  131998. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  131999. nToken = (int)(pTC-aTC);
  132000. nOr = (int)(ppOr-apOr);
  132001. if( rc==SQLITE_OK ){
  132002. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  132003. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  132004. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  132005. }
  132006. }
  132007. sqlite3_free(aTC);
  132008. }
  132009. }
  132010. #endif
  132011. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  132012. return rc;
  132013. }
  132014. /*
  132015. ** Invalidate the current position list for phrase pPhrase.
  132016. */
  132017. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  132018. if( pPhrase->doclist.bFreeList ){
  132019. sqlite3_free(pPhrase->doclist.pList);
  132020. }
  132021. pPhrase->doclist.pList = 0;
  132022. pPhrase->doclist.nList = 0;
  132023. pPhrase->doclist.bFreeList = 0;
  132024. }
  132025. /*
  132026. ** This function is called to edit the position list associated with
  132027. ** the phrase object passed as the fifth argument according to a NEAR
  132028. ** condition. For example:
  132029. **
  132030. ** abc NEAR/5 "def ghi"
  132031. **
  132032. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  132033. ** the example above). When this function is called, *paPoslist points to
  132034. ** the position list, and *pnToken is the number of phrase tokens in, the
  132035. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  132036. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  132037. ** the position list associated with phrase "abc".
  132038. **
  132039. ** All positions in the pPhrase position list that are not sufficiently
  132040. ** close to a position in the *paPoslist position list are removed. If this
  132041. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  132042. **
  132043. ** Before returning, *paPoslist is set to point to the position lsit
  132044. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  132045. ** pPhrase.
  132046. */
  132047. static int fts3EvalNearTrim(
  132048. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  132049. char *aTmp, /* Temporary space to use */
  132050. char **paPoslist, /* IN/OUT: Position list */
  132051. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  132052. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  132053. ){
  132054. int nParam1 = nNear + pPhrase->nToken;
  132055. int nParam2 = nNear + *pnToken;
  132056. int nNew;
  132057. char *p2;
  132058. char *pOut;
  132059. int res;
  132060. assert( pPhrase->doclist.pList );
  132061. p2 = pOut = pPhrase->doclist.pList;
  132062. res = fts3PoslistNearMerge(
  132063. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  132064. );
  132065. if( res ){
  132066. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  132067. assert( pPhrase->doclist.pList[nNew]=='\0' );
  132068. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  132069. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  132070. pPhrase->doclist.nList = nNew;
  132071. *paPoslist = pPhrase->doclist.pList;
  132072. *pnToken = pPhrase->nToken;
  132073. }
  132074. return res;
  132075. }
  132076. /*
  132077. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  132078. ** Otherwise, it advances the expression passed as the second argument to
  132079. ** point to the next matching row in the database. Expressions iterate through
  132080. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  132081. ** or descending if it is non-zero.
  132082. **
  132083. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  132084. ** successful, the following variables in pExpr are set:
  132085. **
  132086. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  132087. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  132088. **
  132089. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  132090. ** at EOF, then the following variables are populated with the position list
  132091. ** for the phrase for the visited row:
  132092. **
  132093. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  132094. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  132095. **
  132096. ** It says above that this function advances the expression to the next
  132097. ** matching row. This is usually true, but there are the following exceptions:
  132098. **
  132099. ** 1. Deferred tokens are not taken into account. If a phrase consists
  132100. ** entirely of deferred tokens, it is assumed to match every row in
  132101. ** the db. In this case the position-list is not populated at all.
  132102. **
  132103. ** Or, if a phrase contains one or more deferred tokens and one or
  132104. ** more non-deferred tokens, then the expression is advanced to the
  132105. ** next possible match, considering only non-deferred tokens. In other
  132106. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  132107. ** is advanced to the next row that contains an instance of "A * C",
  132108. ** where "*" may match any single token. The position list in this case
  132109. ** is populated as for "A * C" before returning.
  132110. **
  132111. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  132112. ** advanced to point to the next row that matches "x AND y".
  132113. **
  132114. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  132115. ** really a match, taking into account deferred tokens and NEAR operators.
  132116. */
  132117. static void fts3EvalNextRow(
  132118. Fts3Cursor *pCsr, /* FTS Cursor handle */
  132119. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  132120. int *pRc /* IN/OUT: Error code */
  132121. ){
  132122. if( *pRc==SQLITE_OK ){
  132123. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  132124. assert( pExpr->bEof==0 );
  132125. pExpr->bStart = 1;
  132126. switch( pExpr->eType ){
  132127. case FTSQUERY_NEAR:
  132128. case FTSQUERY_AND: {
  132129. Fts3Expr *pLeft = pExpr->pLeft;
  132130. Fts3Expr *pRight = pExpr->pRight;
  132131. assert( !pLeft->bDeferred || !pRight->bDeferred );
  132132. if( pLeft->bDeferred ){
  132133. /* LHS is entirely deferred. So we assume it matches every row.
  132134. ** Advance the RHS iterator to find the next row visited. */
  132135. fts3EvalNextRow(pCsr, pRight, pRc);
  132136. pExpr->iDocid = pRight->iDocid;
  132137. pExpr->bEof = pRight->bEof;
  132138. }else if( pRight->bDeferred ){
  132139. /* RHS is entirely deferred. So we assume it matches every row.
  132140. ** Advance the LHS iterator to find the next row visited. */
  132141. fts3EvalNextRow(pCsr, pLeft, pRc);
  132142. pExpr->iDocid = pLeft->iDocid;
  132143. pExpr->bEof = pLeft->bEof;
  132144. }else{
  132145. /* Neither the RHS or LHS are deferred. */
  132146. fts3EvalNextRow(pCsr, pLeft, pRc);
  132147. fts3EvalNextRow(pCsr, pRight, pRc);
  132148. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  132149. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  132150. if( iDiff==0 ) break;
  132151. if( iDiff<0 ){
  132152. fts3EvalNextRow(pCsr, pLeft, pRc);
  132153. }else{
  132154. fts3EvalNextRow(pCsr, pRight, pRc);
  132155. }
  132156. }
  132157. pExpr->iDocid = pLeft->iDocid;
  132158. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  132159. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  132160. if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
  132161. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  132162. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  132163. memset(pDl->pList, 0, pDl->nList);
  132164. fts3EvalNextRow(pCsr, pRight, pRc);
  132165. }
  132166. }
  132167. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  132168. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  132169. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  132170. memset(pDl->pList, 0, pDl->nList);
  132171. fts3EvalNextRow(pCsr, pLeft, pRc);
  132172. }
  132173. }
  132174. }
  132175. }
  132176. break;
  132177. }
  132178. case FTSQUERY_OR: {
  132179. Fts3Expr *pLeft = pExpr->pLeft;
  132180. Fts3Expr *pRight = pExpr->pRight;
  132181. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  132182. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  132183. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  132184. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  132185. fts3EvalNextRow(pCsr, pLeft, pRc);
  132186. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  132187. fts3EvalNextRow(pCsr, pRight, pRc);
  132188. }else{
  132189. fts3EvalNextRow(pCsr, pLeft, pRc);
  132190. fts3EvalNextRow(pCsr, pRight, pRc);
  132191. }
  132192. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  132193. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  132194. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  132195. pExpr->iDocid = pLeft->iDocid;
  132196. }else{
  132197. pExpr->iDocid = pRight->iDocid;
  132198. }
  132199. break;
  132200. }
  132201. case FTSQUERY_NOT: {
  132202. Fts3Expr *pLeft = pExpr->pLeft;
  132203. Fts3Expr *pRight = pExpr->pRight;
  132204. if( pRight->bStart==0 ){
  132205. fts3EvalNextRow(pCsr, pRight, pRc);
  132206. assert( *pRc!=SQLITE_OK || pRight->bStart );
  132207. }
  132208. fts3EvalNextRow(pCsr, pLeft, pRc);
  132209. if( pLeft->bEof==0 ){
  132210. while( !*pRc
  132211. && !pRight->bEof
  132212. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  132213. ){
  132214. fts3EvalNextRow(pCsr, pRight, pRc);
  132215. }
  132216. }
  132217. pExpr->iDocid = pLeft->iDocid;
  132218. pExpr->bEof = pLeft->bEof;
  132219. break;
  132220. }
  132221. default: {
  132222. Fts3Phrase *pPhrase = pExpr->pPhrase;
  132223. fts3EvalInvalidatePoslist(pPhrase);
  132224. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  132225. pExpr->iDocid = pPhrase->doclist.iDocid;
  132226. break;
  132227. }
  132228. }
  132229. }
  132230. }
  132231. /*
  132232. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  132233. ** cluster, then this function returns 1 immediately.
  132234. **
  132235. ** Otherwise, it checks if the current row really does match the NEAR
  132236. ** expression, using the data currently stored in the position lists
  132237. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  132238. **
  132239. ** If the current row is a match, the position list associated with each
  132240. ** phrase in the NEAR expression is edited in place to contain only those
  132241. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  132242. ** constraints. In this case it returns 1. If the NEAR expression does not
  132243. ** match the current row, 0 is returned. The position lists may or may not
  132244. ** be edited if 0 is returned.
  132245. */
  132246. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  132247. int res = 1;
  132248. /* The following block runs if pExpr is the root of a NEAR query.
  132249. ** For example, the query:
  132250. **
  132251. ** "w" NEAR "x" NEAR "y" NEAR "z"
  132252. **
  132253. ** which is represented in tree form as:
  132254. **
  132255. ** |
  132256. ** +--NEAR--+ <-- root of NEAR query
  132257. ** | |
  132258. ** +--NEAR--+ "z"
  132259. ** | |
  132260. ** +--NEAR--+ "y"
  132261. ** | |
  132262. ** "w" "x"
  132263. **
  132264. ** The right-hand child of a NEAR node is always a phrase. The
  132265. ** left-hand child may be either a phrase or a NEAR node. There are
  132266. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  132267. */
  132268. if( *pRc==SQLITE_OK
  132269. && pExpr->eType==FTSQUERY_NEAR
  132270. && pExpr->bEof==0
  132271. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  132272. ){
  132273. Fts3Expr *p;
  132274. int nTmp = 0; /* Bytes of temp space */
  132275. char *aTmp; /* Temp space for PoslistNearMerge() */
  132276. /* Allocate temporary working space. */
  132277. for(p=pExpr; p->pLeft; p=p->pLeft){
  132278. nTmp += p->pRight->pPhrase->doclist.nList;
  132279. }
  132280. nTmp += p->pPhrase->doclist.nList;
  132281. if( nTmp==0 ){
  132282. res = 0;
  132283. }else{
  132284. aTmp = sqlite3_malloc(nTmp*2);
  132285. if( !aTmp ){
  132286. *pRc = SQLITE_NOMEM;
  132287. res = 0;
  132288. }else{
  132289. char *aPoslist = p->pPhrase->doclist.pList;
  132290. int nToken = p->pPhrase->nToken;
  132291. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  132292. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  132293. int nNear = p->nNear;
  132294. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  132295. }
  132296. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  132297. nToken = pExpr->pRight->pPhrase->nToken;
  132298. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  132299. int nNear;
  132300. Fts3Phrase *pPhrase;
  132301. assert( p->pParent && p->pParent->pLeft==p );
  132302. nNear = p->pParent->nNear;
  132303. pPhrase = (
  132304. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  132305. );
  132306. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  132307. }
  132308. }
  132309. sqlite3_free(aTmp);
  132310. }
  132311. }
  132312. return res;
  132313. }
  132314. /*
  132315. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  132316. ** Assuming no error occurs or has occurred, It returns non-zero if the
  132317. ** expression passed as the second argument matches the row that pCsr
  132318. ** currently points to, or zero if it does not.
  132319. **
  132320. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  132321. ** If an error occurs during execution of this function, *pRc is set to
  132322. ** the appropriate SQLite error code. In this case the returned value is
  132323. ** undefined.
  132324. */
  132325. static int fts3EvalTestExpr(
  132326. Fts3Cursor *pCsr, /* FTS cursor handle */
  132327. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  132328. int *pRc /* IN/OUT: Error code */
  132329. ){
  132330. int bHit = 1; /* Return value */
  132331. if( *pRc==SQLITE_OK ){
  132332. switch( pExpr->eType ){
  132333. case FTSQUERY_NEAR:
  132334. case FTSQUERY_AND:
  132335. bHit = (
  132336. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  132337. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  132338. && fts3EvalNearTest(pExpr, pRc)
  132339. );
  132340. /* If the NEAR expression does not match any rows, zero the doclist for
  132341. ** all phrases involved in the NEAR. This is because the snippet(),
  132342. ** offsets() and matchinfo() functions are not supposed to recognize
  132343. ** any instances of phrases that are part of unmatched NEAR queries.
  132344. ** For example if this expression:
  132345. **
  132346. ** ... MATCH 'a OR (b NEAR c)'
  132347. **
  132348. ** is matched against a row containing:
  132349. **
  132350. ** 'a b d e'
  132351. **
  132352. ** then any snippet() should ony highlight the "a" term, not the "b"
  132353. ** (as "b" is part of a non-matching NEAR clause).
  132354. */
  132355. if( bHit==0
  132356. && pExpr->eType==FTSQUERY_NEAR
  132357. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  132358. ){
  132359. Fts3Expr *p;
  132360. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  132361. if( p->pRight->iDocid==pCsr->iPrevId ){
  132362. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  132363. }
  132364. }
  132365. if( p->iDocid==pCsr->iPrevId ){
  132366. fts3EvalInvalidatePoslist(p->pPhrase);
  132367. }
  132368. }
  132369. break;
  132370. case FTSQUERY_OR: {
  132371. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  132372. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  132373. bHit = bHit1 || bHit2;
  132374. break;
  132375. }
  132376. case FTSQUERY_NOT:
  132377. bHit = (
  132378. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  132379. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  132380. );
  132381. break;
  132382. default: {
  132383. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  132384. if( pCsr->pDeferred
  132385. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  132386. ){
  132387. Fts3Phrase *pPhrase = pExpr->pPhrase;
  132388. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  132389. if( pExpr->bDeferred ){
  132390. fts3EvalInvalidatePoslist(pPhrase);
  132391. }
  132392. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  132393. bHit = (pPhrase->doclist.pList!=0);
  132394. pExpr->iDocid = pCsr->iPrevId;
  132395. }else
  132396. #endif
  132397. {
  132398. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  132399. }
  132400. break;
  132401. }
  132402. }
  132403. }
  132404. return bHit;
  132405. }
  132406. /*
  132407. ** This function is called as the second part of each xNext operation when
  132408. ** iterating through the results of a full-text query. At this point the
  132409. ** cursor points to a row that matches the query expression, with the
  132410. ** following caveats:
  132411. **
  132412. ** * Up until this point, "NEAR" operators in the expression have been
  132413. ** treated as "AND".
  132414. **
  132415. ** * Deferred tokens have not yet been considered.
  132416. **
  132417. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  132418. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  132419. ** operators and deferred tokens the current row is still a match for the
  132420. ** expression. It returns 1 if both of the following are true:
  132421. **
  132422. ** 1. *pRc is SQLITE_OK when this function returns, and
  132423. **
  132424. ** 2. After scanning the current FTS table row for the deferred tokens,
  132425. ** it is determined that the row does *not* match the query.
  132426. **
  132427. ** Or, if no error occurs and it seems the current row does match the FTS
  132428. ** query, return 0.
  132429. */
  132430. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  132431. int rc = *pRc;
  132432. int bMiss = 0;
  132433. if( rc==SQLITE_OK ){
  132434. /* If there are one or more deferred tokens, load the current row into
  132435. ** memory and scan it to determine the position list for each deferred
  132436. ** token. Then, see if this row is really a match, considering deferred
  132437. ** tokens and NEAR operators (neither of which were taken into account
  132438. ** earlier, by fts3EvalNextRow()).
  132439. */
  132440. if( pCsr->pDeferred ){
  132441. rc = fts3CursorSeek(0, pCsr);
  132442. if( rc==SQLITE_OK ){
  132443. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  132444. }
  132445. }
  132446. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  132447. /* Free the position-lists accumulated for each deferred token above. */
  132448. sqlite3Fts3FreeDeferredDoclists(pCsr);
  132449. *pRc = rc;
  132450. }
  132451. return (rc==SQLITE_OK && bMiss);
  132452. }
  132453. /*
  132454. ** Advance to the next document that matches the FTS expression in
  132455. ** Fts3Cursor.pExpr.
  132456. */
  132457. static int fts3EvalNext(Fts3Cursor *pCsr){
  132458. int rc = SQLITE_OK; /* Return Code */
  132459. Fts3Expr *pExpr = pCsr->pExpr;
  132460. assert( pCsr->isEof==0 );
  132461. if( pExpr==0 ){
  132462. pCsr->isEof = 1;
  132463. }else{
  132464. do {
  132465. if( pCsr->isRequireSeek==0 ){
  132466. sqlite3_reset(pCsr->pStmt);
  132467. }
  132468. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  132469. fts3EvalNextRow(pCsr, pExpr, &rc);
  132470. pCsr->isEof = pExpr->bEof;
  132471. pCsr->isRequireSeek = 1;
  132472. pCsr->isMatchinfoNeeded = 1;
  132473. pCsr->iPrevId = pExpr->iDocid;
  132474. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  132475. }
  132476. /* Check if the cursor is past the end of the docid range specified
  132477. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  132478. if( rc==SQLITE_OK && (
  132479. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  132480. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  132481. )){
  132482. pCsr->isEof = 1;
  132483. }
  132484. return rc;
  132485. }
  132486. /*
  132487. ** Restart interation for expression pExpr so that the next call to
  132488. ** fts3EvalNext() visits the first row. Do not allow incremental
  132489. ** loading or merging of phrase doclists for this iteration.
  132490. **
  132491. ** If *pRc is other than SQLITE_OK when this function is called, it is
  132492. ** a no-op. If an error occurs within this function, *pRc is set to an
  132493. ** SQLite error code before returning.
  132494. */
  132495. static void fts3EvalRestart(
  132496. Fts3Cursor *pCsr,
  132497. Fts3Expr *pExpr,
  132498. int *pRc
  132499. ){
  132500. if( pExpr && *pRc==SQLITE_OK ){
  132501. Fts3Phrase *pPhrase = pExpr->pPhrase;
  132502. if( pPhrase ){
  132503. fts3EvalInvalidatePoslist(pPhrase);
  132504. if( pPhrase->bIncr ){
  132505. int i;
  132506. for(i=0; i<pPhrase->nToken; i++){
  132507. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  132508. assert( pToken->pDeferred==0 );
  132509. if( pToken->pSegcsr ){
  132510. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  132511. }
  132512. }
  132513. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  132514. }
  132515. pPhrase->doclist.pNextDocid = 0;
  132516. pPhrase->doclist.iDocid = 0;
  132517. pPhrase->pOrPoslist = 0;
  132518. }
  132519. pExpr->iDocid = 0;
  132520. pExpr->bEof = 0;
  132521. pExpr->bStart = 0;
  132522. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  132523. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  132524. }
  132525. }
  132526. /*
  132527. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  132528. ** expression rooted at pExpr, the cursor iterates through all rows matched
  132529. ** by pExpr, calling this function for each row. This function increments
  132530. ** the values in Fts3Expr.aMI[] according to the position-list currently
  132531. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  132532. ** expression nodes.
  132533. */
  132534. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  132535. if( pExpr ){
  132536. Fts3Phrase *pPhrase = pExpr->pPhrase;
  132537. if( pPhrase && pPhrase->doclist.pList ){
  132538. int iCol = 0;
  132539. char *p = pPhrase->doclist.pList;
  132540. assert( *p );
  132541. while( 1 ){
  132542. u8 c = 0;
  132543. int iCnt = 0;
  132544. while( 0xFE & (*p | c) ){
  132545. if( (c&0x80)==0 ) iCnt++;
  132546. c = *p++ & 0x80;
  132547. }
  132548. /* aMI[iCol*3 + 1] = Number of occurrences
  132549. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  132550. */
  132551. pExpr->aMI[iCol*3 + 1] += iCnt;
  132552. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  132553. if( *p==0x00 ) break;
  132554. p++;
  132555. p += fts3GetVarint32(p, &iCol);
  132556. }
  132557. }
  132558. fts3EvalUpdateCounts(pExpr->pLeft);
  132559. fts3EvalUpdateCounts(pExpr->pRight);
  132560. }
  132561. }
  132562. /*
  132563. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  132564. **
  132565. ** If it is not already allocated and populated, this function allocates and
  132566. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  132567. ** of a NEAR expression, then it also allocates and populates the same array
  132568. ** for all other phrases that are part of the NEAR expression.
  132569. **
  132570. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  132571. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  132572. */
  132573. static int fts3EvalGatherStats(
  132574. Fts3Cursor *pCsr, /* Cursor object */
  132575. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  132576. ){
  132577. int rc = SQLITE_OK; /* Return code */
  132578. assert( pExpr->eType==FTSQUERY_PHRASE );
  132579. if( pExpr->aMI==0 ){
  132580. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132581. Fts3Expr *pRoot; /* Root of NEAR expression */
  132582. Fts3Expr *p; /* Iterator used for several purposes */
  132583. sqlite3_int64 iPrevId = pCsr->iPrevId;
  132584. sqlite3_int64 iDocid;
  132585. u8 bEof;
  132586. /* Find the root of the NEAR expression */
  132587. pRoot = pExpr;
  132588. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  132589. pRoot = pRoot->pParent;
  132590. }
  132591. iDocid = pRoot->iDocid;
  132592. bEof = pRoot->bEof;
  132593. assert( pRoot->bStart );
  132594. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  132595. for(p=pRoot; p; p=p->pLeft){
  132596. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  132597. assert( pE->aMI==0 );
  132598. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  132599. if( !pE->aMI ) return SQLITE_NOMEM;
  132600. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  132601. }
  132602. fts3EvalRestart(pCsr, pRoot, &rc);
  132603. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  132604. do {
  132605. /* Ensure the %_content statement is reset. */
  132606. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  132607. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  132608. /* Advance to the next document */
  132609. fts3EvalNextRow(pCsr, pRoot, &rc);
  132610. pCsr->isEof = pRoot->bEof;
  132611. pCsr->isRequireSeek = 1;
  132612. pCsr->isMatchinfoNeeded = 1;
  132613. pCsr->iPrevId = pRoot->iDocid;
  132614. }while( pCsr->isEof==0
  132615. && pRoot->eType==FTSQUERY_NEAR
  132616. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  132617. );
  132618. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  132619. fts3EvalUpdateCounts(pRoot);
  132620. }
  132621. }
  132622. pCsr->isEof = 0;
  132623. pCsr->iPrevId = iPrevId;
  132624. if( bEof ){
  132625. pRoot->bEof = bEof;
  132626. }else{
  132627. /* Caution: pRoot may iterate through docids in ascending or descending
  132628. ** order. For this reason, even though it seems more defensive, the
  132629. ** do loop can not be written:
  132630. **
  132631. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  132632. */
  132633. fts3EvalRestart(pCsr, pRoot, &rc);
  132634. do {
  132635. fts3EvalNextRow(pCsr, pRoot, &rc);
  132636. assert( pRoot->bEof==0 );
  132637. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  132638. }
  132639. }
  132640. return rc;
  132641. }
  132642. /*
  132643. ** This function is used by the matchinfo() module to query a phrase
  132644. ** expression node for the following information:
  132645. **
  132646. ** 1. The total number of occurrences of the phrase in each column of
  132647. ** the FTS table (considering all rows), and
  132648. **
  132649. ** 2. For each column, the number of rows in the table for which the
  132650. ** column contains at least one instance of the phrase.
  132651. **
  132652. ** If no error occurs, SQLITE_OK is returned and the values for each column
  132653. ** written into the array aiOut as follows:
  132654. **
  132655. ** aiOut[iCol*3 + 1] = Number of occurrences
  132656. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  132657. **
  132658. ** Caveats:
  132659. **
  132660. ** * If a phrase consists entirely of deferred tokens, then all output
  132661. ** values are set to the number of documents in the table. In other
  132662. ** words we assume that very common tokens occur exactly once in each
  132663. ** column of each row of the table.
  132664. **
  132665. ** * If a phrase contains some deferred tokens (and some non-deferred
  132666. ** tokens), count the potential occurrence identified by considering
  132667. ** the non-deferred tokens instead of actual phrase occurrences.
  132668. **
  132669. ** * If the phrase is part of a NEAR expression, then only phrase instances
  132670. ** that meet the NEAR constraint are included in the counts.
  132671. */
  132672. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  132673. Fts3Cursor *pCsr, /* FTS cursor handle */
  132674. Fts3Expr *pExpr, /* Phrase expression */
  132675. u32 *aiOut /* Array to write results into (see above) */
  132676. ){
  132677. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132678. int rc = SQLITE_OK;
  132679. int iCol;
  132680. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  132681. assert( pCsr->nDoc>0 );
  132682. for(iCol=0; iCol<pTab->nColumn; iCol++){
  132683. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  132684. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  132685. }
  132686. }else{
  132687. rc = fts3EvalGatherStats(pCsr, pExpr);
  132688. if( rc==SQLITE_OK ){
  132689. assert( pExpr->aMI );
  132690. for(iCol=0; iCol<pTab->nColumn; iCol++){
  132691. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  132692. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  132693. }
  132694. }
  132695. }
  132696. return rc;
  132697. }
  132698. /*
  132699. ** The expression pExpr passed as the second argument to this function
  132700. ** must be of type FTSQUERY_PHRASE.
  132701. **
  132702. ** The returned value is either NULL or a pointer to a buffer containing
  132703. ** a position-list indicating the occurrences of the phrase in column iCol
  132704. ** of the current row.
  132705. **
  132706. ** More specifically, the returned buffer contains 1 varint for each
  132707. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  132708. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  132709. ** if the requested column contains "a b X c d X X" and the position-list
  132710. ** for 'X' is requested, the buffer returned may contain:
  132711. **
  132712. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  132713. **
  132714. ** This function works regardless of whether or not the phrase is deferred,
  132715. ** incremental, or neither.
  132716. */
  132717. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  132718. Fts3Cursor *pCsr, /* FTS3 cursor object */
  132719. Fts3Expr *pExpr, /* Phrase to return doclist for */
  132720. int iCol, /* Column to return position list for */
  132721. char **ppOut /* OUT: Pointer to position list */
  132722. ){
  132723. Fts3Phrase *pPhrase = pExpr->pPhrase;
  132724. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132725. char *pIter;
  132726. int iThis;
  132727. sqlite3_int64 iDocid;
  132728. /* If this phrase is applies specifically to some column other than
  132729. ** column iCol, return a NULL pointer. */
  132730. *ppOut = 0;
  132731. assert( iCol>=0 && iCol<pTab->nColumn );
  132732. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  132733. return SQLITE_OK;
  132734. }
  132735. iDocid = pExpr->iDocid;
  132736. pIter = pPhrase->doclist.pList;
  132737. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  132738. int rc = SQLITE_OK;
  132739. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  132740. int bOr = 0;
  132741. u8 bTreeEof = 0;
  132742. Fts3Expr *p; /* Used to iterate from pExpr to root */
  132743. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  132744. int bMatch;
  132745. /* Check if this phrase descends from an OR expression node. If not,
  132746. ** return NULL. Otherwise, the entry that corresponds to docid
  132747. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  132748. ** tree that the node is part of has been marked as EOF, but the node
  132749. ** itself is not EOF, then it may point to an earlier entry. */
  132750. pNear = pExpr;
  132751. for(p=pExpr->pParent; p; p=p->pParent){
  132752. if( p->eType==FTSQUERY_OR ) bOr = 1;
  132753. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  132754. if( p->bEof ) bTreeEof = 1;
  132755. }
  132756. if( bOr==0 ) return SQLITE_OK;
  132757. /* This is the descendent of an OR node. In this case we cannot use
  132758. ** an incremental phrase. Load the entire doclist for the phrase
  132759. ** into memory in this case. */
  132760. if( pPhrase->bIncr ){
  132761. int bEofSave = pNear->bEof;
  132762. fts3EvalRestart(pCsr, pNear, &rc);
  132763. while( rc==SQLITE_OK && !pNear->bEof ){
  132764. fts3EvalNextRow(pCsr, pNear, &rc);
  132765. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  132766. }
  132767. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  132768. }
  132769. if( bTreeEof ){
  132770. while( rc==SQLITE_OK && !pNear->bEof ){
  132771. fts3EvalNextRow(pCsr, pNear, &rc);
  132772. }
  132773. }
  132774. if( rc!=SQLITE_OK ) return rc;
  132775. bMatch = 1;
  132776. for(p=pNear; p; p=p->pLeft){
  132777. u8 bEof = 0;
  132778. Fts3Expr *pTest = p;
  132779. Fts3Phrase *pPh;
  132780. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  132781. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  132782. assert( pTest->eType==FTSQUERY_PHRASE );
  132783. pPh = pTest->pPhrase;
  132784. pIter = pPh->pOrPoslist;
  132785. iDocid = pPh->iOrDocid;
  132786. if( pCsr->bDesc==bDescDoclist ){
  132787. bEof = !pPh->doclist.nAll ||
  132788. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  132789. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  132790. sqlite3Fts3DoclistNext(
  132791. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  132792. &pIter, &iDocid, &bEof
  132793. );
  132794. }
  132795. }else{
  132796. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  132797. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  132798. int dummy;
  132799. sqlite3Fts3DoclistPrev(
  132800. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  132801. &pIter, &iDocid, &dummy, &bEof
  132802. );
  132803. }
  132804. }
  132805. pPh->pOrPoslist = pIter;
  132806. pPh->iOrDocid = iDocid;
  132807. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  132808. }
  132809. if( bMatch ){
  132810. pIter = pPhrase->pOrPoslist;
  132811. }else{
  132812. pIter = 0;
  132813. }
  132814. }
  132815. if( pIter==0 ) return SQLITE_OK;
  132816. if( *pIter==0x01 ){
  132817. pIter++;
  132818. pIter += fts3GetVarint32(pIter, &iThis);
  132819. }else{
  132820. iThis = 0;
  132821. }
  132822. while( iThis<iCol ){
  132823. fts3ColumnlistCopy(0, &pIter);
  132824. if( *pIter==0x00 ) return SQLITE_OK;
  132825. pIter++;
  132826. pIter += fts3GetVarint32(pIter, &iThis);
  132827. }
  132828. if( *pIter==0x00 ){
  132829. pIter = 0;
  132830. }
  132831. *ppOut = ((iCol==iThis)?pIter:0);
  132832. return SQLITE_OK;
  132833. }
  132834. /*
  132835. ** Free all components of the Fts3Phrase structure that were allocated by
  132836. ** the eval module. Specifically, this means to free:
  132837. **
  132838. ** * the contents of pPhrase->doclist, and
  132839. ** * any Fts3MultiSegReader objects held by phrase tokens.
  132840. */
  132841. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  132842. if( pPhrase ){
  132843. int i;
  132844. sqlite3_free(pPhrase->doclist.aAll);
  132845. fts3EvalInvalidatePoslist(pPhrase);
  132846. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  132847. for(i=0; i<pPhrase->nToken; i++){
  132848. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  132849. pPhrase->aToken[i].pSegcsr = 0;
  132850. }
  132851. }
  132852. }
  132853. /*
  132854. ** Return SQLITE_CORRUPT_VTAB.
  132855. */
  132856. #ifdef SQLITE_DEBUG
  132857. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  132858. return SQLITE_CORRUPT_VTAB;
  132859. }
  132860. #endif
  132861. #if !SQLITE_CORE
  132862. /*
  132863. ** Initialize API pointer table, if required.
  132864. */
  132865. #ifdef _WIN32
  132866. __declspec(dllexport)
  132867. #endif
  132868. SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
  132869. sqlite3 *db,
  132870. char **pzErrMsg,
  132871. const sqlite3_api_routines *pApi
  132872. ){
  132873. SQLITE_EXTENSION_INIT2(pApi)
  132874. return sqlite3Fts3Init(db);
  132875. }
  132876. #endif
  132877. #endif
  132878. /************** End of fts3.c ************************************************/
  132879. /************** Begin file fts3_aux.c ****************************************/
  132880. /*
  132881. ** 2011 Jan 27
  132882. **
  132883. ** The author disclaims copyright to this source code. In place of
  132884. ** a legal notice, here is a blessing:
  132885. **
  132886. ** May you do good and not evil.
  132887. ** May you find forgiveness for yourself and forgive others.
  132888. ** May you share freely, never taking more than you give.
  132889. **
  132890. ******************************************************************************
  132891. **
  132892. */
  132893. /* #include "fts3Int.h" */
  132894. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132895. /* #include <string.h> */
  132896. /* #include <assert.h> */
  132897. typedef struct Fts3auxTable Fts3auxTable;
  132898. typedef struct Fts3auxCursor Fts3auxCursor;
  132899. struct Fts3auxTable {
  132900. sqlite3_vtab base; /* Base class used by SQLite core */
  132901. Fts3Table *pFts3Tab;
  132902. };
  132903. struct Fts3auxCursor {
  132904. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  132905. Fts3MultiSegReader csr; /* Must be right after "base" */
  132906. Fts3SegFilter filter;
  132907. char *zStop;
  132908. int nStop; /* Byte-length of string zStop */
  132909. int iLangid; /* Language id to query */
  132910. int isEof; /* True if cursor is at EOF */
  132911. sqlite3_int64 iRowid; /* Current rowid */
  132912. int iCol; /* Current value of 'col' column */
  132913. int nStat; /* Size of aStat[] array */
  132914. struct Fts3auxColstats {
  132915. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  132916. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  132917. } *aStat;
  132918. };
  132919. /*
  132920. ** Schema of the terms table.
  132921. */
  132922. #define FTS3_AUX_SCHEMA \
  132923. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  132924. /*
  132925. ** This function does all the work for both the xConnect and xCreate methods.
  132926. ** These tables have no persistent representation of their own, so xConnect
  132927. ** and xCreate are identical operations.
  132928. */
  132929. static int fts3auxConnectMethod(
  132930. sqlite3 *db, /* Database connection */
  132931. void *pUnused, /* Unused */
  132932. int argc, /* Number of elements in argv array */
  132933. const char * const *argv, /* xCreate/xConnect argument array */
  132934. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  132935. char **pzErr /* OUT: sqlite3_malloc'd error message */
  132936. ){
  132937. char const *zDb; /* Name of database (e.g. "main") */
  132938. char const *zFts3; /* Name of fts3 table */
  132939. int nDb; /* Result of strlen(zDb) */
  132940. int nFts3; /* Result of strlen(zFts3) */
  132941. int nByte; /* Bytes of space to allocate here */
  132942. int rc; /* value returned by declare_vtab() */
  132943. Fts3auxTable *p; /* Virtual table object to return */
  132944. UNUSED_PARAMETER(pUnused);
  132945. /* The user should invoke this in one of two forms:
  132946. **
  132947. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  132948. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  132949. */
  132950. if( argc!=4 && argc!=5 ) goto bad_args;
  132951. zDb = argv[1];
  132952. nDb = (int)strlen(zDb);
  132953. if( argc==5 ){
  132954. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  132955. zDb = argv[3];
  132956. nDb = (int)strlen(zDb);
  132957. zFts3 = argv[4];
  132958. }else{
  132959. goto bad_args;
  132960. }
  132961. }else{
  132962. zFts3 = argv[3];
  132963. }
  132964. nFts3 = (int)strlen(zFts3);
  132965. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  132966. if( rc!=SQLITE_OK ) return rc;
  132967. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  132968. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  132969. if( !p ) return SQLITE_NOMEM;
  132970. memset(p, 0, nByte);
  132971. p->pFts3Tab = (Fts3Table *)&p[1];
  132972. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  132973. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  132974. p->pFts3Tab->db = db;
  132975. p->pFts3Tab->nIndex = 1;
  132976. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  132977. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  132978. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  132979. *ppVtab = (sqlite3_vtab *)p;
  132980. return SQLITE_OK;
  132981. bad_args:
  132982. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  132983. return SQLITE_ERROR;
  132984. }
  132985. /*
  132986. ** This function does the work for both the xDisconnect and xDestroy methods.
  132987. ** These tables have no persistent representation of their own, so xDisconnect
  132988. ** and xDestroy are identical operations.
  132989. */
  132990. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  132991. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  132992. Fts3Table *pFts3 = p->pFts3Tab;
  132993. int i;
  132994. /* Free any prepared statements held */
  132995. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  132996. sqlite3_finalize(pFts3->aStmt[i]);
  132997. }
  132998. sqlite3_free(pFts3->zSegmentsTbl);
  132999. sqlite3_free(p);
  133000. return SQLITE_OK;
  133001. }
  133002. #define FTS4AUX_EQ_CONSTRAINT 1
  133003. #define FTS4AUX_GE_CONSTRAINT 2
  133004. #define FTS4AUX_LE_CONSTRAINT 4
  133005. /*
  133006. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  133007. */
  133008. static int fts3auxBestIndexMethod(
  133009. sqlite3_vtab *pVTab,
  133010. sqlite3_index_info *pInfo
  133011. ){
  133012. int i;
  133013. int iEq = -1;
  133014. int iGe = -1;
  133015. int iLe = -1;
  133016. int iLangid = -1;
  133017. int iNext = 1; /* Next free argvIndex value */
  133018. UNUSED_PARAMETER(pVTab);
  133019. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  133020. if( pInfo->nOrderBy==1
  133021. && pInfo->aOrderBy[0].iColumn==0
  133022. && pInfo->aOrderBy[0].desc==0
  133023. ){
  133024. pInfo->orderByConsumed = 1;
  133025. }
  133026. /* Search for equality and range constraints on the "term" column.
  133027. ** And equality constraints on the hidden "languageid" column. */
  133028. for(i=0; i<pInfo->nConstraint; i++){
  133029. if( pInfo->aConstraint[i].usable ){
  133030. int op = pInfo->aConstraint[i].op;
  133031. int iCol = pInfo->aConstraint[i].iColumn;
  133032. if( iCol==0 ){
  133033. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  133034. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  133035. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  133036. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  133037. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  133038. }
  133039. if( iCol==4 ){
  133040. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  133041. }
  133042. }
  133043. }
  133044. if( iEq>=0 ){
  133045. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  133046. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  133047. pInfo->estimatedCost = 5;
  133048. }else{
  133049. pInfo->idxNum = 0;
  133050. pInfo->estimatedCost = 20000;
  133051. if( iGe>=0 ){
  133052. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  133053. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  133054. pInfo->estimatedCost /= 2;
  133055. }
  133056. if( iLe>=0 ){
  133057. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  133058. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  133059. pInfo->estimatedCost /= 2;
  133060. }
  133061. }
  133062. if( iLangid>=0 ){
  133063. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  133064. pInfo->estimatedCost--;
  133065. }
  133066. return SQLITE_OK;
  133067. }
  133068. /*
  133069. ** xOpen - Open a cursor.
  133070. */
  133071. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  133072. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  133073. UNUSED_PARAMETER(pVTab);
  133074. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  133075. if( !pCsr ) return SQLITE_NOMEM;
  133076. memset(pCsr, 0, sizeof(Fts3auxCursor));
  133077. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  133078. return SQLITE_OK;
  133079. }
  133080. /*
  133081. ** xClose - Close a cursor.
  133082. */
  133083. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  133084. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  133085. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  133086. sqlite3Fts3SegmentsClose(pFts3);
  133087. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  133088. sqlite3_free((void *)pCsr->filter.zTerm);
  133089. sqlite3_free(pCsr->zStop);
  133090. sqlite3_free(pCsr->aStat);
  133091. sqlite3_free(pCsr);
  133092. return SQLITE_OK;
  133093. }
  133094. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  133095. if( nSize>pCsr->nStat ){
  133096. struct Fts3auxColstats *aNew;
  133097. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  133098. sizeof(struct Fts3auxColstats) * nSize
  133099. );
  133100. if( aNew==0 ) return SQLITE_NOMEM;
  133101. memset(&aNew[pCsr->nStat], 0,
  133102. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  133103. );
  133104. pCsr->aStat = aNew;
  133105. pCsr->nStat = nSize;
  133106. }
  133107. return SQLITE_OK;
  133108. }
  133109. /*
  133110. ** xNext - Advance the cursor to the next row, if any.
  133111. */
  133112. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  133113. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  133114. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  133115. int rc;
  133116. /* Increment our pretend rowid value. */
  133117. pCsr->iRowid++;
  133118. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  133119. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  133120. }
  133121. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  133122. if( rc==SQLITE_ROW ){
  133123. int i = 0;
  133124. int nDoclist = pCsr->csr.nDoclist;
  133125. char *aDoclist = pCsr->csr.aDoclist;
  133126. int iCol;
  133127. int eState = 0;
  133128. if( pCsr->zStop ){
  133129. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  133130. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  133131. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  133132. pCsr->isEof = 1;
  133133. return SQLITE_OK;
  133134. }
  133135. }
  133136. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  133137. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  133138. iCol = 0;
  133139. while( i<nDoclist ){
  133140. sqlite3_int64 v = 0;
  133141. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  133142. switch( eState ){
  133143. /* State 0. In this state the integer just read was a docid. */
  133144. case 0:
  133145. pCsr->aStat[0].nDoc++;
  133146. eState = 1;
  133147. iCol = 0;
  133148. break;
  133149. /* State 1. In this state we are expecting either a 1, indicating
  133150. ** that the following integer will be a column number, or the
  133151. ** start of a position list for column 0.
  133152. **
  133153. ** The only difference between state 1 and state 2 is that if the
  133154. ** integer encountered in state 1 is not 0 or 1, then we need to
  133155. ** increment the column 0 "nDoc" count for this term.
  133156. */
  133157. case 1:
  133158. assert( iCol==0 );
  133159. if( v>1 ){
  133160. pCsr->aStat[1].nDoc++;
  133161. }
  133162. eState = 2;
  133163. /* fall through */
  133164. case 2:
  133165. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  133166. eState = 0;
  133167. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  133168. eState = 3;
  133169. }else{ /* 2 or greater. A position. */
  133170. pCsr->aStat[iCol+1].nOcc++;
  133171. pCsr->aStat[0].nOcc++;
  133172. }
  133173. break;
  133174. /* State 3. The integer just read is a column number. */
  133175. default: assert( eState==3 );
  133176. iCol = (int)v;
  133177. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  133178. pCsr->aStat[iCol+1].nDoc++;
  133179. eState = 2;
  133180. break;
  133181. }
  133182. }
  133183. pCsr->iCol = 0;
  133184. rc = SQLITE_OK;
  133185. }else{
  133186. pCsr->isEof = 1;
  133187. }
  133188. return rc;
  133189. }
  133190. /*
  133191. ** xFilter - Initialize a cursor to point at the start of its data.
  133192. */
  133193. static int fts3auxFilterMethod(
  133194. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  133195. int idxNum, /* Strategy index */
  133196. const char *idxStr, /* Unused */
  133197. int nVal, /* Number of elements in apVal */
  133198. sqlite3_value **apVal /* Arguments for the indexing scheme */
  133199. ){
  133200. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  133201. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  133202. int rc;
  133203. int isScan = 0;
  133204. int iLangVal = 0; /* Language id to query */
  133205. int iEq = -1; /* Index of term=? value in apVal */
  133206. int iGe = -1; /* Index of term>=? value in apVal */
  133207. int iLe = -1; /* Index of term<=? value in apVal */
  133208. int iLangid = -1; /* Index of languageid=? value in apVal */
  133209. int iNext = 0;
  133210. UNUSED_PARAMETER(nVal);
  133211. UNUSED_PARAMETER(idxStr);
  133212. assert( idxStr==0 );
  133213. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  133214. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  133215. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  133216. );
  133217. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  133218. iEq = iNext++;
  133219. }else{
  133220. isScan = 1;
  133221. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  133222. iGe = iNext++;
  133223. }
  133224. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  133225. iLe = iNext++;
  133226. }
  133227. }
  133228. if( iNext<nVal ){
  133229. iLangid = iNext++;
  133230. }
  133231. /* In case this cursor is being reused, close and zero it. */
  133232. testcase(pCsr->filter.zTerm);
  133233. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  133234. sqlite3_free((void *)pCsr->filter.zTerm);
  133235. sqlite3_free(pCsr->aStat);
  133236. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  133237. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  133238. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  133239. if( iEq>=0 || iGe>=0 ){
  133240. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  133241. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  133242. if( zStr ){
  133243. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  133244. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  133245. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  133246. }
  133247. }
  133248. if( iLe>=0 ){
  133249. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  133250. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  133251. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  133252. }
  133253. if( iLangid>=0 ){
  133254. iLangVal = sqlite3_value_int(apVal[iLangid]);
  133255. /* If the user specified a negative value for the languageid, use zero
  133256. ** instead. This works, as the "languageid=?" constraint will also
  133257. ** be tested by the VDBE layer. The test will always be false (since
  133258. ** this module will not return a row with a negative languageid), and
  133259. ** so the overall query will return zero rows. */
  133260. if( iLangVal<0 ) iLangVal = 0;
  133261. }
  133262. pCsr->iLangid = iLangVal;
  133263. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  133264. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  133265. );
  133266. if( rc==SQLITE_OK ){
  133267. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  133268. }
  133269. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  133270. return rc;
  133271. }
  133272. /*
  133273. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  133274. */
  133275. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  133276. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  133277. return pCsr->isEof;
  133278. }
  133279. /*
  133280. ** xColumn - Return a column value.
  133281. */
  133282. static int fts3auxColumnMethod(
  133283. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  133284. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  133285. int iCol /* Index of column to read value from */
  133286. ){
  133287. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  133288. assert( p->isEof==0 );
  133289. switch( iCol ){
  133290. case 0: /* term */
  133291. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  133292. break;
  133293. case 1: /* col */
  133294. if( p->iCol ){
  133295. sqlite3_result_int(pCtx, p->iCol-1);
  133296. }else{
  133297. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  133298. }
  133299. break;
  133300. case 2: /* documents */
  133301. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  133302. break;
  133303. case 3: /* occurrences */
  133304. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  133305. break;
  133306. default: /* languageid */
  133307. assert( iCol==4 );
  133308. sqlite3_result_int(pCtx, p->iLangid);
  133309. break;
  133310. }
  133311. return SQLITE_OK;
  133312. }
  133313. /*
  133314. ** xRowid - Return the current rowid for the cursor.
  133315. */
  133316. static int fts3auxRowidMethod(
  133317. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  133318. sqlite_int64 *pRowid /* OUT: Rowid value */
  133319. ){
  133320. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  133321. *pRowid = pCsr->iRowid;
  133322. return SQLITE_OK;
  133323. }
  133324. /*
  133325. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  133326. ** if successful or an error code if sqlite3_create_module() fails.
  133327. */
  133328. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  133329. static const sqlite3_module fts3aux_module = {
  133330. 0, /* iVersion */
  133331. fts3auxConnectMethod, /* xCreate */
  133332. fts3auxConnectMethod, /* xConnect */
  133333. fts3auxBestIndexMethod, /* xBestIndex */
  133334. fts3auxDisconnectMethod, /* xDisconnect */
  133335. fts3auxDisconnectMethod, /* xDestroy */
  133336. fts3auxOpenMethod, /* xOpen */
  133337. fts3auxCloseMethod, /* xClose */
  133338. fts3auxFilterMethod, /* xFilter */
  133339. fts3auxNextMethod, /* xNext */
  133340. fts3auxEofMethod, /* xEof */
  133341. fts3auxColumnMethod, /* xColumn */
  133342. fts3auxRowidMethod, /* xRowid */
  133343. 0, /* xUpdate */
  133344. 0, /* xBegin */
  133345. 0, /* xSync */
  133346. 0, /* xCommit */
  133347. 0, /* xRollback */
  133348. 0, /* xFindFunction */
  133349. 0, /* xRename */
  133350. 0, /* xSavepoint */
  133351. 0, /* xRelease */
  133352. 0 /* xRollbackTo */
  133353. };
  133354. int rc; /* Return code */
  133355. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  133356. return rc;
  133357. }
  133358. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133359. /************** End of fts3_aux.c ********************************************/
  133360. /************** Begin file fts3_expr.c ***************************************/
  133361. /*
  133362. ** 2008 Nov 28
  133363. **
  133364. ** The author disclaims copyright to this source code. In place of
  133365. ** a legal notice, here is a blessing:
  133366. **
  133367. ** May you do good and not evil.
  133368. ** May you find forgiveness for yourself and forgive others.
  133369. ** May you share freely, never taking more than you give.
  133370. **
  133371. ******************************************************************************
  133372. **
  133373. ** This module contains code that implements a parser for fts3 query strings
  133374. ** (the right-hand argument to the MATCH operator). Because the supported
  133375. ** syntax is relatively simple, the whole tokenizer/parser system is
  133376. ** hand-coded.
  133377. */
  133378. /* #include "fts3Int.h" */
  133379. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133380. /*
  133381. ** By default, this module parses the legacy syntax that has been
  133382. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  133383. ** is defined, then it uses the new syntax. The differences between
  133384. ** the new and the old syntaxes are:
  133385. **
  133386. ** a) The new syntax supports parenthesis. The old does not.
  133387. **
  133388. ** b) The new syntax supports the AND and NOT operators. The old does not.
  133389. **
  133390. ** c) The old syntax supports the "-" token qualifier. This is not
  133391. ** supported by the new syntax (it is replaced by the NOT operator).
  133392. **
  133393. ** d) When using the old syntax, the OR operator has a greater precedence
  133394. ** than an implicit AND. When using the new, both implicity and explicit
  133395. ** AND operators have a higher precedence than OR.
  133396. **
  133397. ** If compiled with SQLITE_TEST defined, then this module exports the
  133398. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  133399. ** to zero causes the module to use the old syntax. If it is set to
  133400. ** non-zero the new syntax is activated. This is so both syntaxes can
  133401. ** be tested using a single build of testfixture.
  133402. **
  133403. ** The following describes the syntax supported by the fts3 MATCH
  133404. ** operator in a similar format to that used by the lemon parser
  133405. ** generator. This module does not use actually lemon, it uses a
  133406. ** custom parser.
  133407. **
  133408. ** query ::= andexpr (OR andexpr)*.
  133409. **
  133410. ** andexpr ::= notexpr (AND? notexpr)*.
  133411. **
  133412. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  133413. ** notexpr ::= LP query RP.
  133414. **
  133415. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  133416. **
  133417. ** distance_opt ::= .
  133418. ** distance_opt ::= / INTEGER.
  133419. **
  133420. ** phrase ::= TOKEN.
  133421. ** phrase ::= COLUMN:TOKEN.
  133422. ** phrase ::= "TOKEN TOKEN TOKEN...".
  133423. */
  133424. #ifdef SQLITE_TEST
  133425. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  133426. #else
  133427. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  133428. # define sqlite3_fts3_enable_parentheses 1
  133429. # else
  133430. # define sqlite3_fts3_enable_parentheses 0
  133431. # endif
  133432. #endif
  133433. /*
  133434. ** Default span for NEAR operators.
  133435. */
  133436. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  133437. /* #include <string.h> */
  133438. /* #include <assert.h> */
  133439. /*
  133440. ** isNot:
  133441. ** This variable is used by function getNextNode(). When getNextNode() is
  133442. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  133443. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  133444. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  133445. ** zero.
  133446. */
  133447. typedef struct ParseContext ParseContext;
  133448. struct ParseContext {
  133449. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  133450. int iLangid; /* Language id used with tokenizer */
  133451. const char **azCol; /* Array of column names for fts3 table */
  133452. int bFts4; /* True to allow FTS4-only syntax */
  133453. int nCol; /* Number of entries in azCol[] */
  133454. int iDefaultCol; /* Default column to query */
  133455. int isNot; /* True if getNextNode() sees a unary - */
  133456. sqlite3_context *pCtx; /* Write error message here */
  133457. int nNest; /* Number of nested brackets */
  133458. };
  133459. /*
  133460. ** This function is equivalent to the standard isspace() function.
  133461. **
  133462. ** The standard isspace() can be awkward to use safely, because although it
  133463. ** is defined to accept an argument of type int, its behavior when passed
  133464. ** an integer that falls outside of the range of the unsigned char type
  133465. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  133466. ** is defined to accept an argument of type char, and always returns 0 for
  133467. ** any values that fall outside of the range of the unsigned char type (i.e.
  133468. ** negative values).
  133469. */
  133470. static int fts3isspace(char c){
  133471. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  133472. }
  133473. /*
  133474. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  133475. ** zero the memory before returning a pointer to it. If unsuccessful,
  133476. ** return NULL.
  133477. */
  133478. static void *fts3MallocZero(int nByte){
  133479. void *pRet = sqlite3_malloc(nByte);
  133480. if( pRet ) memset(pRet, 0, nByte);
  133481. return pRet;
  133482. }
  133483. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  133484. sqlite3_tokenizer *pTokenizer,
  133485. int iLangid,
  133486. const char *z,
  133487. int n,
  133488. sqlite3_tokenizer_cursor **ppCsr
  133489. ){
  133490. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  133491. sqlite3_tokenizer_cursor *pCsr = 0;
  133492. int rc;
  133493. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  133494. assert( rc==SQLITE_OK || pCsr==0 );
  133495. if( rc==SQLITE_OK ){
  133496. pCsr->pTokenizer = pTokenizer;
  133497. if( pModule->iVersion>=1 ){
  133498. rc = pModule->xLanguageid(pCsr, iLangid);
  133499. if( rc!=SQLITE_OK ){
  133500. pModule->xClose(pCsr);
  133501. pCsr = 0;
  133502. }
  133503. }
  133504. }
  133505. *ppCsr = pCsr;
  133506. return rc;
  133507. }
  133508. /*
  133509. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  133510. ** call fts3ExprParse(). So this forward declaration is required.
  133511. */
  133512. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  133513. /*
  133514. ** Extract the next token from buffer z (length n) using the tokenizer
  133515. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  133516. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  133517. ** single token and set *ppExpr to point to it. If the end of the buffer is
  133518. ** reached before a token is found, set *ppExpr to zero. It is the
  133519. ** responsibility of the caller to eventually deallocate the allocated
  133520. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  133521. **
  133522. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  133523. ** fails.
  133524. */
  133525. static int getNextToken(
  133526. ParseContext *pParse, /* fts3 query parse context */
  133527. int iCol, /* Value for Fts3Phrase.iColumn */
  133528. const char *z, int n, /* Input string */
  133529. Fts3Expr **ppExpr, /* OUT: expression */
  133530. int *pnConsumed /* OUT: Number of bytes consumed */
  133531. ){
  133532. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  133533. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  133534. int rc;
  133535. sqlite3_tokenizer_cursor *pCursor;
  133536. Fts3Expr *pRet = 0;
  133537. int i = 0;
  133538. /* Set variable i to the maximum number of bytes of input to tokenize. */
  133539. for(i=0; i<n; i++){
  133540. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  133541. if( z[i]=='"' ) break;
  133542. }
  133543. *pnConsumed = i;
  133544. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  133545. if( rc==SQLITE_OK ){
  133546. const char *zToken;
  133547. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  133548. int nByte; /* total space to allocate */
  133549. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  133550. if( rc==SQLITE_OK ){
  133551. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  133552. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  133553. if( !pRet ){
  133554. rc = SQLITE_NOMEM;
  133555. }else{
  133556. pRet->eType = FTSQUERY_PHRASE;
  133557. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  133558. pRet->pPhrase->nToken = 1;
  133559. pRet->pPhrase->iColumn = iCol;
  133560. pRet->pPhrase->aToken[0].n = nToken;
  133561. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  133562. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  133563. if( iEnd<n && z[iEnd]=='*' ){
  133564. pRet->pPhrase->aToken[0].isPrefix = 1;
  133565. iEnd++;
  133566. }
  133567. while( 1 ){
  133568. if( !sqlite3_fts3_enable_parentheses
  133569. && iStart>0 && z[iStart-1]=='-'
  133570. ){
  133571. pParse->isNot = 1;
  133572. iStart--;
  133573. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  133574. pRet->pPhrase->aToken[0].bFirst = 1;
  133575. iStart--;
  133576. }else{
  133577. break;
  133578. }
  133579. }
  133580. }
  133581. *pnConsumed = iEnd;
  133582. }else if( i && rc==SQLITE_DONE ){
  133583. rc = SQLITE_OK;
  133584. }
  133585. pModule->xClose(pCursor);
  133586. }
  133587. *ppExpr = pRet;
  133588. return rc;
  133589. }
  133590. /*
  133591. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  133592. ** then free the old allocation.
  133593. */
  133594. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  133595. void *pRet = sqlite3_realloc(pOrig, nNew);
  133596. if( !pRet ){
  133597. sqlite3_free(pOrig);
  133598. }
  133599. return pRet;
  133600. }
  133601. /*
  133602. ** Buffer zInput, length nInput, contains the contents of a quoted string
  133603. ** that appeared as part of an fts3 query expression. Neither quote character
  133604. ** is included in the buffer. This function attempts to tokenize the entire
  133605. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  133606. ** containing the results.
  133607. **
  133608. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  133609. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  133610. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  133611. ** to 0.
  133612. */
  133613. static int getNextString(
  133614. ParseContext *pParse, /* fts3 query parse context */
  133615. const char *zInput, int nInput, /* Input string */
  133616. Fts3Expr **ppExpr /* OUT: expression */
  133617. ){
  133618. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  133619. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  133620. int rc;
  133621. Fts3Expr *p = 0;
  133622. sqlite3_tokenizer_cursor *pCursor = 0;
  133623. char *zTemp = 0;
  133624. int nTemp = 0;
  133625. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  133626. int nToken = 0;
  133627. /* The final Fts3Expr data structure, including the Fts3Phrase,
  133628. ** Fts3PhraseToken structures token buffers are all stored as a single
  133629. ** allocation so that the expression can be freed with a single call to
  133630. ** sqlite3_free(). Setting this up requires a two pass approach.
  133631. **
  133632. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  133633. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  133634. ** to assemble data in two dynamic buffers:
  133635. **
  133636. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  133637. ** structure, followed by the array of Fts3PhraseToken
  133638. ** structures. This pass only populates the Fts3PhraseToken array.
  133639. **
  133640. ** Buffer zTemp: Contains copies of all tokens.
  133641. **
  133642. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  133643. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  133644. ** structures.
  133645. */
  133646. rc = sqlite3Fts3OpenTokenizer(
  133647. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  133648. if( rc==SQLITE_OK ){
  133649. int ii;
  133650. for(ii=0; rc==SQLITE_OK; ii++){
  133651. const char *zByte;
  133652. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  133653. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  133654. if( rc==SQLITE_OK ){
  133655. Fts3PhraseToken *pToken;
  133656. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  133657. if( !p ) goto no_mem;
  133658. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  133659. if( !zTemp ) goto no_mem;
  133660. assert( nToken==ii );
  133661. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  133662. memset(pToken, 0, sizeof(Fts3PhraseToken));
  133663. memcpy(&zTemp[nTemp], zByte, nByte);
  133664. nTemp += nByte;
  133665. pToken->n = nByte;
  133666. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  133667. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  133668. nToken = ii+1;
  133669. }
  133670. }
  133671. pModule->xClose(pCursor);
  133672. pCursor = 0;
  133673. }
  133674. if( rc==SQLITE_DONE ){
  133675. int jj;
  133676. char *zBuf = 0;
  133677. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  133678. if( !p ) goto no_mem;
  133679. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  133680. p->eType = FTSQUERY_PHRASE;
  133681. p->pPhrase = (Fts3Phrase *)&p[1];
  133682. p->pPhrase->iColumn = pParse->iDefaultCol;
  133683. p->pPhrase->nToken = nToken;
  133684. zBuf = (char *)&p->pPhrase->aToken[nToken];
  133685. if( zTemp ){
  133686. memcpy(zBuf, zTemp, nTemp);
  133687. sqlite3_free(zTemp);
  133688. }else{
  133689. assert( nTemp==0 );
  133690. }
  133691. for(jj=0; jj<p->pPhrase->nToken; jj++){
  133692. p->pPhrase->aToken[jj].z = zBuf;
  133693. zBuf += p->pPhrase->aToken[jj].n;
  133694. }
  133695. rc = SQLITE_OK;
  133696. }
  133697. *ppExpr = p;
  133698. return rc;
  133699. no_mem:
  133700. if( pCursor ){
  133701. pModule->xClose(pCursor);
  133702. }
  133703. sqlite3_free(zTemp);
  133704. sqlite3_free(p);
  133705. *ppExpr = 0;
  133706. return SQLITE_NOMEM;
  133707. }
  133708. /*
  133709. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  133710. ** structure, or set to 0 if the end of the input buffer is reached.
  133711. **
  133712. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  133713. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  133714. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  133715. */
  133716. static int getNextNode(
  133717. ParseContext *pParse, /* fts3 query parse context */
  133718. const char *z, int n, /* Input string */
  133719. Fts3Expr **ppExpr, /* OUT: expression */
  133720. int *pnConsumed /* OUT: Number of bytes consumed */
  133721. ){
  133722. static const struct Fts3Keyword {
  133723. char *z; /* Keyword text */
  133724. unsigned char n; /* Length of the keyword */
  133725. unsigned char parenOnly; /* Only valid in paren mode */
  133726. unsigned char eType; /* Keyword code */
  133727. } aKeyword[] = {
  133728. { "OR" , 2, 0, FTSQUERY_OR },
  133729. { "AND", 3, 1, FTSQUERY_AND },
  133730. { "NOT", 3, 1, FTSQUERY_NOT },
  133731. { "NEAR", 4, 0, FTSQUERY_NEAR }
  133732. };
  133733. int ii;
  133734. int iCol;
  133735. int iColLen;
  133736. int rc;
  133737. Fts3Expr *pRet = 0;
  133738. const char *zInput = z;
  133739. int nInput = n;
  133740. pParse->isNot = 0;
  133741. /* Skip over any whitespace before checking for a keyword, an open or
  133742. ** close bracket, or a quoted string.
  133743. */
  133744. while( nInput>0 && fts3isspace(*zInput) ){
  133745. nInput--;
  133746. zInput++;
  133747. }
  133748. if( nInput==0 ){
  133749. return SQLITE_DONE;
  133750. }
  133751. /* See if we are dealing with a keyword. */
  133752. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  133753. const struct Fts3Keyword *pKey = &aKeyword[ii];
  133754. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  133755. continue;
  133756. }
  133757. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  133758. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  133759. int nKey = pKey->n;
  133760. char cNext;
  133761. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  133762. if( pKey->eType==FTSQUERY_NEAR ){
  133763. assert( nKey==4 );
  133764. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  133765. nNear = 0;
  133766. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  133767. nNear = nNear * 10 + (zInput[nKey] - '0');
  133768. }
  133769. }
  133770. }
  133771. /* At this point this is probably a keyword. But for that to be true,
  133772. ** the next byte must contain either whitespace, an open or close
  133773. ** parenthesis, a quote character, or EOF.
  133774. */
  133775. cNext = zInput[nKey];
  133776. if( fts3isspace(cNext)
  133777. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  133778. ){
  133779. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  133780. if( !pRet ){
  133781. return SQLITE_NOMEM;
  133782. }
  133783. pRet->eType = pKey->eType;
  133784. pRet->nNear = nNear;
  133785. *ppExpr = pRet;
  133786. *pnConsumed = (int)((zInput - z) + nKey);
  133787. return SQLITE_OK;
  133788. }
  133789. /* Turns out that wasn't a keyword after all. This happens if the
  133790. ** user has supplied a token such as "ORacle". Continue.
  133791. */
  133792. }
  133793. }
  133794. /* See if we are dealing with a quoted phrase. If this is the case, then
  133795. ** search for the closing quote and pass the whole string to getNextString()
  133796. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  133797. ** a quote character embedded in a string.
  133798. */
  133799. if( *zInput=='"' ){
  133800. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  133801. *pnConsumed = (int)((zInput - z) + ii + 1);
  133802. if( ii==nInput ){
  133803. return SQLITE_ERROR;
  133804. }
  133805. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  133806. }
  133807. if( sqlite3_fts3_enable_parentheses ){
  133808. if( *zInput=='(' ){
  133809. int nConsumed = 0;
  133810. pParse->nNest++;
  133811. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  133812. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  133813. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  133814. return rc;
  133815. }else if( *zInput==')' ){
  133816. pParse->nNest--;
  133817. *pnConsumed = (int)((zInput - z) + 1);
  133818. *ppExpr = 0;
  133819. return SQLITE_DONE;
  133820. }
  133821. }
  133822. /* If control flows to this point, this must be a regular token, or
  133823. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  133824. ** interface. Before doing so, figure out if there is an explicit
  133825. ** column specifier for the token.
  133826. **
  133827. ** TODO: Strangely, it is not possible to associate a column specifier
  133828. ** with a quoted phrase, only with a single token. Not sure if this was
  133829. ** an implementation artifact or an intentional decision when fts3 was
  133830. ** first implemented. Whichever it was, this module duplicates the
  133831. ** limitation.
  133832. */
  133833. iCol = pParse->iDefaultCol;
  133834. iColLen = 0;
  133835. for(ii=0; ii<pParse->nCol; ii++){
  133836. const char *zStr = pParse->azCol[ii];
  133837. int nStr = (int)strlen(zStr);
  133838. if( nInput>nStr && zInput[nStr]==':'
  133839. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  133840. ){
  133841. iCol = ii;
  133842. iColLen = (int)((zInput - z) + nStr + 1);
  133843. break;
  133844. }
  133845. }
  133846. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  133847. *pnConsumed += iColLen;
  133848. return rc;
  133849. }
  133850. /*
  133851. ** The argument is an Fts3Expr structure for a binary operator (any type
  133852. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  133853. ** precedence of the operator. Lower values have a higher precedence (i.e.
  133854. ** group more tightly). For example, in the C language, the == operator
  133855. ** groups more tightly than ||, and would therefore have a higher precedence.
  133856. **
  133857. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  133858. ** is defined), the order of the operators in precedence from highest to
  133859. ** lowest is:
  133860. **
  133861. ** NEAR
  133862. ** NOT
  133863. ** AND (including implicit ANDs)
  133864. ** OR
  133865. **
  133866. ** Note that when using the old query syntax, the OR operator has a higher
  133867. ** precedence than the AND operator.
  133868. */
  133869. static int opPrecedence(Fts3Expr *p){
  133870. assert( p->eType!=FTSQUERY_PHRASE );
  133871. if( sqlite3_fts3_enable_parentheses ){
  133872. return p->eType;
  133873. }else if( p->eType==FTSQUERY_NEAR ){
  133874. return 1;
  133875. }else if( p->eType==FTSQUERY_OR ){
  133876. return 2;
  133877. }
  133878. assert( p->eType==FTSQUERY_AND );
  133879. return 3;
  133880. }
  133881. /*
  133882. ** Argument ppHead contains a pointer to the current head of a query
  133883. ** expression tree being parsed. pPrev is the expression node most recently
  133884. ** inserted into the tree. This function adds pNew, which is always a binary
  133885. ** operator node, into the expression tree based on the relative precedence
  133886. ** of pNew and the existing nodes of the tree. This may result in the head
  133887. ** of the tree changing, in which case *ppHead is set to the new root node.
  133888. */
  133889. static void insertBinaryOperator(
  133890. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  133891. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  133892. Fts3Expr *pNew /* New binary node to insert into expression tree */
  133893. ){
  133894. Fts3Expr *pSplit = pPrev;
  133895. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  133896. pSplit = pSplit->pParent;
  133897. }
  133898. if( pSplit->pParent ){
  133899. assert( pSplit->pParent->pRight==pSplit );
  133900. pSplit->pParent->pRight = pNew;
  133901. pNew->pParent = pSplit->pParent;
  133902. }else{
  133903. *ppHead = pNew;
  133904. }
  133905. pNew->pLeft = pSplit;
  133906. pSplit->pParent = pNew;
  133907. }
  133908. /*
  133909. ** Parse the fts3 query expression found in buffer z, length n. This function
  133910. ** returns either when the end of the buffer is reached or an unmatched
  133911. ** closing bracket - ')' - is encountered.
  133912. **
  133913. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  133914. ** parsed form of the expression and *pnConsumed is set to the number of
  133915. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  133916. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  133917. */
  133918. static int fts3ExprParse(
  133919. ParseContext *pParse, /* fts3 query parse context */
  133920. const char *z, int n, /* Text of MATCH query */
  133921. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  133922. int *pnConsumed /* OUT: Number of bytes consumed */
  133923. ){
  133924. Fts3Expr *pRet = 0;
  133925. Fts3Expr *pPrev = 0;
  133926. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  133927. int nIn = n;
  133928. const char *zIn = z;
  133929. int rc = SQLITE_OK;
  133930. int isRequirePhrase = 1;
  133931. while( rc==SQLITE_OK ){
  133932. Fts3Expr *p = 0;
  133933. int nByte = 0;
  133934. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  133935. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  133936. if( rc==SQLITE_OK ){
  133937. if( p ){
  133938. int isPhrase;
  133939. if( !sqlite3_fts3_enable_parentheses
  133940. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  133941. ){
  133942. /* Create an implicit NOT operator. */
  133943. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  133944. if( !pNot ){
  133945. sqlite3Fts3ExprFree(p);
  133946. rc = SQLITE_NOMEM;
  133947. goto exprparse_out;
  133948. }
  133949. pNot->eType = FTSQUERY_NOT;
  133950. pNot->pRight = p;
  133951. p->pParent = pNot;
  133952. if( pNotBranch ){
  133953. pNot->pLeft = pNotBranch;
  133954. pNotBranch->pParent = pNot;
  133955. }
  133956. pNotBranch = pNot;
  133957. p = pPrev;
  133958. }else{
  133959. int eType = p->eType;
  133960. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  133961. /* The isRequirePhrase variable is set to true if a phrase or
  133962. ** an expression contained in parenthesis is required. If a
  133963. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  133964. ** isRequirePhrase is set, this is a syntax error.
  133965. */
  133966. if( !isPhrase && isRequirePhrase ){
  133967. sqlite3Fts3ExprFree(p);
  133968. rc = SQLITE_ERROR;
  133969. goto exprparse_out;
  133970. }
  133971. if( isPhrase && !isRequirePhrase ){
  133972. /* Insert an implicit AND operator. */
  133973. Fts3Expr *pAnd;
  133974. assert( pRet && pPrev );
  133975. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  133976. if( !pAnd ){
  133977. sqlite3Fts3ExprFree(p);
  133978. rc = SQLITE_NOMEM;
  133979. goto exprparse_out;
  133980. }
  133981. pAnd->eType = FTSQUERY_AND;
  133982. insertBinaryOperator(&pRet, pPrev, pAnd);
  133983. pPrev = pAnd;
  133984. }
  133985. /* This test catches attempts to make either operand of a NEAR
  133986. ** operator something other than a phrase. For example, either of
  133987. ** the following:
  133988. **
  133989. ** (bracketed expression) NEAR phrase
  133990. ** phrase NEAR (bracketed expression)
  133991. **
  133992. ** Return an error in either case.
  133993. */
  133994. if( pPrev && (
  133995. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  133996. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  133997. )){
  133998. sqlite3Fts3ExprFree(p);
  133999. rc = SQLITE_ERROR;
  134000. goto exprparse_out;
  134001. }
  134002. if( isPhrase ){
  134003. if( pRet ){
  134004. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  134005. pPrev->pRight = p;
  134006. p->pParent = pPrev;
  134007. }else{
  134008. pRet = p;
  134009. }
  134010. }else{
  134011. insertBinaryOperator(&pRet, pPrev, p);
  134012. }
  134013. isRequirePhrase = !isPhrase;
  134014. }
  134015. pPrev = p;
  134016. }
  134017. assert( nByte>0 );
  134018. }
  134019. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  134020. nIn -= nByte;
  134021. zIn += nByte;
  134022. }
  134023. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  134024. rc = SQLITE_ERROR;
  134025. }
  134026. if( rc==SQLITE_DONE ){
  134027. rc = SQLITE_OK;
  134028. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  134029. if( !pRet ){
  134030. rc = SQLITE_ERROR;
  134031. }else{
  134032. Fts3Expr *pIter = pNotBranch;
  134033. while( pIter->pLeft ){
  134034. pIter = pIter->pLeft;
  134035. }
  134036. pIter->pLeft = pRet;
  134037. pRet->pParent = pIter;
  134038. pRet = pNotBranch;
  134039. }
  134040. }
  134041. }
  134042. *pnConsumed = n - nIn;
  134043. exprparse_out:
  134044. if( rc!=SQLITE_OK ){
  134045. sqlite3Fts3ExprFree(pRet);
  134046. sqlite3Fts3ExprFree(pNotBranch);
  134047. pRet = 0;
  134048. }
  134049. *ppExpr = pRet;
  134050. return rc;
  134051. }
  134052. /*
  134053. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  134054. ** as the only argument is more than nMaxDepth.
  134055. */
  134056. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  134057. int rc = SQLITE_OK;
  134058. if( p ){
  134059. if( nMaxDepth<0 ){
  134060. rc = SQLITE_TOOBIG;
  134061. }else{
  134062. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  134063. if( rc==SQLITE_OK ){
  134064. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  134065. }
  134066. }
  134067. }
  134068. return rc;
  134069. }
  134070. /*
  134071. ** This function attempts to transform the expression tree at (*pp) to
  134072. ** an equivalent but more balanced form. The tree is modified in place.
  134073. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  134074. ** new root expression node.
  134075. **
  134076. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  134077. **
  134078. ** Otherwise, if an error occurs, an SQLite error code is returned and
  134079. ** expression (*pp) freed.
  134080. */
  134081. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  134082. int rc = SQLITE_OK; /* Return code */
  134083. Fts3Expr *pRoot = *pp; /* Initial root node */
  134084. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  134085. int eType = pRoot->eType; /* Type of node in this tree */
  134086. if( nMaxDepth==0 ){
  134087. rc = SQLITE_ERROR;
  134088. }
  134089. if( rc==SQLITE_OK ){
  134090. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  134091. Fts3Expr **apLeaf;
  134092. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  134093. if( 0==apLeaf ){
  134094. rc = SQLITE_NOMEM;
  134095. }else{
  134096. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  134097. }
  134098. if( rc==SQLITE_OK ){
  134099. int i;
  134100. Fts3Expr *p;
  134101. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  134102. for(p=pRoot; p->eType==eType; p=p->pLeft){
  134103. assert( p->pParent==0 || p->pParent->pLeft==p );
  134104. assert( p->pLeft && p->pRight );
  134105. }
  134106. /* This loop runs once for each leaf in the tree of eType nodes. */
  134107. while( 1 ){
  134108. int iLvl;
  134109. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  134110. assert( pParent==0 || pParent->pLeft==p );
  134111. p->pParent = 0;
  134112. if( pParent ){
  134113. pParent->pLeft = 0;
  134114. }else{
  134115. pRoot = 0;
  134116. }
  134117. rc = fts3ExprBalance(&p, nMaxDepth-1);
  134118. if( rc!=SQLITE_OK ) break;
  134119. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  134120. if( apLeaf[iLvl]==0 ){
  134121. apLeaf[iLvl] = p;
  134122. p = 0;
  134123. }else{
  134124. assert( pFree );
  134125. pFree->pLeft = apLeaf[iLvl];
  134126. pFree->pRight = p;
  134127. pFree->pLeft->pParent = pFree;
  134128. pFree->pRight->pParent = pFree;
  134129. p = pFree;
  134130. pFree = pFree->pParent;
  134131. p->pParent = 0;
  134132. apLeaf[iLvl] = 0;
  134133. }
  134134. }
  134135. if( p ){
  134136. sqlite3Fts3ExprFree(p);
  134137. rc = SQLITE_TOOBIG;
  134138. break;
  134139. }
  134140. /* If that was the last leaf node, break out of the loop */
  134141. if( pParent==0 ) break;
  134142. /* Set $p to point to the next leaf in the tree of eType nodes */
  134143. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  134144. /* Remove pParent from the original tree. */
  134145. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  134146. pParent->pRight->pParent = pParent->pParent;
  134147. if( pParent->pParent ){
  134148. pParent->pParent->pLeft = pParent->pRight;
  134149. }else{
  134150. assert( pParent==pRoot );
  134151. pRoot = pParent->pRight;
  134152. }
  134153. /* Link pParent into the free node list. It will be used as an
  134154. ** internal node of the new tree. */
  134155. pParent->pParent = pFree;
  134156. pFree = pParent;
  134157. }
  134158. if( rc==SQLITE_OK ){
  134159. p = 0;
  134160. for(i=0; i<nMaxDepth; i++){
  134161. if( apLeaf[i] ){
  134162. if( p==0 ){
  134163. p = apLeaf[i];
  134164. p->pParent = 0;
  134165. }else{
  134166. assert( pFree!=0 );
  134167. pFree->pRight = p;
  134168. pFree->pLeft = apLeaf[i];
  134169. pFree->pLeft->pParent = pFree;
  134170. pFree->pRight->pParent = pFree;
  134171. p = pFree;
  134172. pFree = pFree->pParent;
  134173. p->pParent = 0;
  134174. }
  134175. }
  134176. }
  134177. pRoot = p;
  134178. }else{
  134179. /* An error occurred. Delete the contents of the apLeaf[] array
  134180. ** and pFree list. Everything else is cleaned up by the call to
  134181. ** sqlite3Fts3ExprFree(pRoot) below. */
  134182. Fts3Expr *pDel;
  134183. for(i=0; i<nMaxDepth; i++){
  134184. sqlite3Fts3ExprFree(apLeaf[i]);
  134185. }
  134186. while( (pDel=pFree)!=0 ){
  134187. pFree = pDel->pParent;
  134188. sqlite3_free(pDel);
  134189. }
  134190. }
  134191. assert( pFree==0 );
  134192. sqlite3_free( apLeaf );
  134193. }
  134194. }else if( eType==FTSQUERY_NOT ){
  134195. Fts3Expr *pLeft = pRoot->pLeft;
  134196. Fts3Expr *pRight = pRoot->pRight;
  134197. pRoot->pLeft = 0;
  134198. pRoot->pRight = 0;
  134199. pLeft->pParent = 0;
  134200. pRight->pParent = 0;
  134201. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  134202. if( rc==SQLITE_OK ){
  134203. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  134204. }
  134205. if( rc!=SQLITE_OK ){
  134206. sqlite3Fts3ExprFree(pRight);
  134207. sqlite3Fts3ExprFree(pLeft);
  134208. }else{
  134209. assert( pLeft && pRight );
  134210. pRoot->pLeft = pLeft;
  134211. pLeft->pParent = pRoot;
  134212. pRoot->pRight = pRight;
  134213. pRight->pParent = pRoot;
  134214. }
  134215. }
  134216. }
  134217. if( rc!=SQLITE_OK ){
  134218. sqlite3Fts3ExprFree(pRoot);
  134219. pRoot = 0;
  134220. }
  134221. *pp = pRoot;
  134222. return rc;
  134223. }
  134224. /*
  134225. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  134226. ** differences:
  134227. **
  134228. ** 1. It does not do expression rebalancing.
  134229. ** 2. It does not check that the expression does not exceed the
  134230. ** maximum allowable depth.
  134231. ** 3. Even if it fails, *ppExpr may still be set to point to an
  134232. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  134233. ** in this case.
  134234. */
  134235. static int fts3ExprParseUnbalanced(
  134236. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  134237. int iLangid, /* Language id for tokenizer */
  134238. char **azCol, /* Array of column names for fts3 table */
  134239. int bFts4, /* True to allow FTS4-only syntax */
  134240. int nCol, /* Number of entries in azCol[] */
  134241. int iDefaultCol, /* Default column to query */
  134242. const char *z, int n, /* Text of MATCH query */
  134243. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  134244. ){
  134245. int nParsed;
  134246. int rc;
  134247. ParseContext sParse;
  134248. memset(&sParse, 0, sizeof(ParseContext));
  134249. sParse.pTokenizer = pTokenizer;
  134250. sParse.iLangid = iLangid;
  134251. sParse.azCol = (const char **)azCol;
  134252. sParse.nCol = nCol;
  134253. sParse.iDefaultCol = iDefaultCol;
  134254. sParse.bFts4 = bFts4;
  134255. if( z==0 ){
  134256. *ppExpr = 0;
  134257. return SQLITE_OK;
  134258. }
  134259. if( n<0 ){
  134260. n = (int)strlen(z);
  134261. }
  134262. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  134263. assert( rc==SQLITE_OK || *ppExpr==0 );
  134264. /* Check for mismatched parenthesis */
  134265. if( rc==SQLITE_OK && sParse.nNest ){
  134266. rc = SQLITE_ERROR;
  134267. }
  134268. return rc;
  134269. }
  134270. /*
  134271. ** Parameters z and n contain a pointer to and length of a buffer containing
  134272. ** an fts3 query expression, respectively. This function attempts to parse the
  134273. ** query expression and create a tree of Fts3Expr structures representing the
  134274. ** parsed expression. If successful, *ppExpr is set to point to the head
  134275. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  134276. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  134277. ** error) is returned and *ppExpr is set to 0.
  134278. **
  134279. ** If parameter n is a negative number, then z is assumed to point to a
  134280. ** nul-terminated string and the length is determined using strlen().
  134281. **
  134282. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  134283. ** use to normalize query tokens while parsing the expression. The azCol[]
  134284. ** array, which is assumed to contain nCol entries, should contain the names
  134285. ** of each column in the target fts3 table, in order from left to right.
  134286. ** Column names must be nul-terminated strings.
  134287. **
  134288. ** The iDefaultCol parameter should be passed the index of the table column
  134289. ** that appears on the left-hand-side of the MATCH operator (the default
  134290. ** column to match against for tokens for which a column name is not explicitly
  134291. ** specified as part of the query string), or -1 if tokens may by default
  134292. ** match any table column.
  134293. */
  134294. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  134295. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  134296. int iLangid, /* Language id for tokenizer */
  134297. char **azCol, /* Array of column names for fts3 table */
  134298. int bFts4, /* True to allow FTS4-only syntax */
  134299. int nCol, /* Number of entries in azCol[] */
  134300. int iDefaultCol, /* Default column to query */
  134301. const char *z, int n, /* Text of MATCH query */
  134302. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  134303. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  134304. ){
  134305. int rc = fts3ExprParseUnbalanced(
  134306. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  134307. );
  134308. /* Rebalance the expression. And check that its depth does not exceed
  134309. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  134310. if( rc==SQLITE_OK && *ppExpr ){
  134311. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  134312. if( rc==SQLITE_OK ){
  134313. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  134314. }
  134315. }
  134316. if( rc!=SQLITE_OK ){
  134317. sqlite3Fts3ExprFree(*ppExpr);
  134318. *ppExpr = 0;
  134319. if( rc==SQLITE_TOOBIG ){
  134320. sqlite3Fts3ErrMsg(pzErr,
  134321. "FTS expression tree is too large (maximum depth %d)",
  134322. SQLITE_FTS3_MAX_EXPR_DEPTH
  134323. );
  134324. rc = SQLITE_ERROR;
  134325. }else if( rc==SQLITE_ERROR ){
  134326. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  134327. }
  134328. }
  134329. return rc;
  134330. }
  134331. /*
  134332. ** Free a single node of an expression tree.
  134333. */
  134334. static void fts3FreeExprNode(Fts3Expr *p){
  134335. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  134336. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  134337. sqlite3_free(p->aMI);
  134338. sqlite3_free(p);
  134339. }
  134340. /*
  134341. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  134342. **
  134343. ** This function would be simpler if it recursively called itself. But
  134344. ** that would mean passing a sufficiently large expression to ExprParse()
  134345. ** could cause a stack overflow.
  134346. */
  134347. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  134348. Fts3Expr *p;
  134349. assert( pDel==0 || pDel->pParent==0 );
  134350. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  134351. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  134352. }
  134353. while( p ){
  134354. Fts3Expr *pParent = p->pParent;
  134355. fts3FreeExprNode(p);
  134356. if( pParent && p==pParent->pLeft && pParent->pRight ){
  134357. p = pParent->pRight;
  134358. while( p && (p->pLeft || p->pRight) ){
  134359. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  134360. p = (p->pLeft ? p->pLeft : p->pRight);
  134361. }
  134362. }else{
  134363. p = pParent;
  134364. }
  134365. }
  134366. }
  134367. /****************************************************************************
  134368. *****************************************************************************
  134369. ** Everything after this point is just test code.
  134370. */
  134371. #ifdef SQLITE_TEST
  134372. /* #include <stdio.h> */
  134373. /*
  134374. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  134375. */
  134376. static int queryTestTokenizer(
  134377. sqlite3 *db,
  134378. const char *zName,
  134379. const sqlite3_tokenizer_module **pp
  134380. ){
  134381. int rc;
  134382. sqlite3_stmt *pStmt;
  134383. const char zSql[] = "SELECT fts3_tokenizer(?)";
  134384. *pp = 0;
  134385. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  134386. if( rc!=SQLITE_OK ){
  134387. return rc;
  134388. }
  134389. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  134390. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  134391. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  134392. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  134393. }
  134394. }
  134395. return sqlite3_finalize(pStmt);
  134396. }
  134397. /*
  134398. ** Return a pointer to a buffer containing a text representation of the
  134399. ** expression passed as the first argument. The buffer is obtained from
  134400. ** sqlite3_malloc(). It is the responsibility of the caller to use
  134401. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  134402. ** NULL is returned.
  134403. **
  134404. ** If the second argument is not NULL, then its contents are prepended to
  134405. ** the returned expression text and then freed using sqlite3_free().
  134406. */
  134407. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  134408. if( pExpr==0 ){
  134409. return sqlite3_mprintf("");
  134410. }
  134411. switch( pExpr->eType ){
  134412. case FTSQUERY_PHRASE: {
  134413. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134414. int i;
  134415. zBuf = sqlite3_mprintf(
  134416. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  134417. for(i=0; zBuf && i<pPhrase->nToken; i++){
  134418. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  134419. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  134420. (pPhrase->aToken[i].isPrefix?"+":"")
  134421. );
  134422. }
  134423. return zBuf;
  134424. }
  134425. case FTSQUERY_NEAR:
  134426. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  134427. break;
  134428. case FTSQUERY_NOT:
  134429. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  134430. break;
  134431. case FTSQUERY_AND:
  134432. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  134433. break;
  134434. case FTSQUERY_OR:
  134435. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  134436. break;
  134437. }
  134438. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  134439. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  134440. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  134441. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  134442. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  134443. return zBuf;
  134444. }
  134445. /*
  134446. ** This is the implementation of a scalar SQL function used to test the
  134447. ** expression parser. It should be called as follows:
  134448. **
  134449. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  134450. **
  134451. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  134452. ** to parse the query expression (see README.tokenizers). The second argument
  134453. ** is the query expression to parse. Each subsequent argument is the name
  134454. ** of a column of the fts3 table that the query expression may refer to.
  134455. ** For example:
  134456. **
  134457. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  134458. */
  134459. static void fts3ExprTest(
  134460. sqlite3_context *context,
  134461. int argc,
  134462. sqlite3_value **argv
  134463. ){
  134464. sqlite3_tokenizer_module const *pModule = 0;
  134465. sqlite3_tokenizer *pTokenizer = 0;
  134466. int rc;
  134467. char **azCol = 0;
  134468. const char *zExpr;
  134469. int nExpr;
  134470. int nCol;
  134471. int ii;
  134472. Fts3Expr *pExpr;
  134473. char *zBuf = 0;
  134474. sqlite3 *db = sqlite3_context_db_handle(context);
  134475. if( argc<3 ){
  134476. sqlite3_result_error(context,
  134477. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  134478. );
  134479. return;
  134480. }
  134481. rc = queryTestTokenizer(db,
  134482. (const char *)sqlite3_value_text(argv[0]), &pModule);
  134483. if( rc==SQLITE_NOMEM ){
  134484. sqlite3_result_error_nomem(context);
  134485. goto exprtest_out;
  134486. }else if( !pModule ){
  134487. sqlite3_result_error(context, "No such tokenizer module", -1);
  134488. goto exprtest_out;
  134489. }
  134490. rc = pModule->xCreate(0, 0, &pTokenizer);
  134491. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  134492. if( rc==SQLITE_NOMEM ){
  134493. sqlite3_result_error_nomem(context);
  134494. goto exprtest_out;
  134495. }
  134496. pTokenizer->pModule = pModule;
  134497. zExpr = (const char *)sqlite3_value_text(argv[1]);
  134498. nExpr = sqlite3_value_bytes(argv[1]);
  134499. nCol = argc-2;
  134500. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  134501. if( !azCol ){
  134502. sqlite3_result_error_nomem(context);
  134503. goto exprtest_out;
  134504. }
  134505. for(ii=0; ii<nCol; ii++){
  134506. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  134507. }
  134508. if( sqlite3_user_data(context) ){
  134509. char *zDummy = 0;
  134510. rc = sqlite3Fts3ExprParse(
  134511. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  134512. );
  134513. assert( rc==SQLITE_OK || pExpr==0 );
  134514. sqlite3_free(zDummy);
  134515. }else{
  134516. rc = fts3ExprParseUnbalanced(
  134517. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  134518. );
  134519. }
  134520. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  134521. sqlite3Fts3ExprFree(pExpr);
  134522. sqlite3_result_error(context, "Error parsing expression", -1);
  134523. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  134524. sqlite3_result_error_nomem(context);
  134525. }else{
  134526. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  134527. sqlite3_free(zBuf);
  134528. }
  134529. sqlite3Fts3ExprFree(pExpr);
  134530. exprtest_out:
  134531. if( pModule && pTokenizer ){
  134532. rc = pModule->xDestroy(pTokenizer);
  134533. }
  134534. sqlite3_free(azCol);
  134535. }
  134536. /*
  134537. ** Register the query expression parser test function fts3_exprtest()
  134538. ** with database connection db.
  134539. */
  134540. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  134541. int rc = sqlite3_create_function(
  134542. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  134543. );
  134544. if( rc==SQLITE_OK ){
  134545. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  134546. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  134547. );
  134548. }
  134549. return rc;
  134550. }
  134551. #endif
  134552. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134553. /************** End of fts3_expr.c *******************************************/
  134554. /************** Begin file fts3_hash.c ***************************************/
  134555. /*
  134556. ** 2001 September 22
  134557. **
  134558. ** The author disclaims copyright to this source code. In place of
  134559. ** a legal notice, here is a blessing:
  134560. **
  134561. ** May you do good and not evil.
  134562. ** May you find forgiveness for yourself and forgive others.
  134563. ** May you share freely, never taking more than you give.
  134564. **
  134565. *************************************************************************
  134566. ** This is the implementation of generic hash-tables used in SQLite.
  134567. ** We've modified it slightly to serve as a standalone hash table
  134568. ** implementation for the full-text indexing module.
  134569. */
  134570. /*
  134571. ** The code in this file is only compiled if:
  134572. **
  134573. ** * The FTS3 module is being built as an extension
  134574. ** (in which case SQLITE_CORE is not defined), or
  134575. **
  134576. ** * The FTS3 module is being built into the core of
  134577. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  134578. */
  134579. /* #include "fts3Int.h" */
  134580. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134581. /* #include <assert.h> */
  134582. /* #include <stdlib.h> */
  134583. /* #include <string.h> */
  134584. /* #include "fts3_hash.h" */
  134585. /*
  134586. ** Malloc and Free functions
  134587. */
  134588. static void *fts3HashMalloc(int n){
  134589. void *p = sqlite3_malloc(n);
  134590. if( p ){
  134591. memset(p, 0, n);
  134592. }
  134593. return p;
  134594. }
  134595. static void fts3HashFree(void *p){
  134596. sqlite3_free(p);
  134597. }
  134598. /* Turn bulk memory into a hash table object by initializing the
  134599. ** fields of the Hash structure.
  134600. **
  134601. ** "pNew" is a pointer to the hash table that is to be initialized.
  134602. ** keyClass is one of the constants
  134603. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  134604. ** determines what kind of key the hash table will use. "copyKey" is
  134605. ** true if the hash table should make its own private copy of keys and
  134606. ** false if it should just use the supplied pointer.
  134607. */
  134608. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  134609. assert( pNew!=0 );
  134610. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  134611. pNew->keyClass = keyClass;
  134612. pNew->copyKey = copyKey;
  134613. pNew->first = 0;
  134614. pNew->count = 0;
  134615. pNew->htsize = 0;
  134616. pNew->ht = 0;
  134617. }
  134618. /* Remove all entries from a hash table. Reclaim all memory.
  134619. ** Call this routine to delete a hash table or to reset a hash table
  134620. ** to the empty state.
  134621. */
  134622. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  134623. Fts3HashElem *elem; /* For looping over all elements of the table */
  134624. assert( pH!=0 );
  134625. elem = pH->first;
  134626. pH->first = 0;
  134627. fts3HashFree(pH->ht);
  134628. pH->ht = 0;
  134629. pH->htsize = 0;
  134630. while( elem ){
  134631. Fts3HashElem *next_elem = elem->next;
  134632. if( pH->copyKey && elem->pKey ){
  134633. fts3HashFree(elem->pKey);
  134634. }
  134635. fts3HashFree(elem);
  134636. elem = next_elem;
  134637. }
  134638. pH->count = 0;
  134639. }
  134640. /*
  134641. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  134642. */
  134643. static int fts3StrHash(const void *pKey, int nKey){
  134644. const char *z = (const char *)pKey;
  134645. unsigned h = 0;
  134646. if( nKey<=0 ) nKey = (int) strlen(z);
  134647. while( nKey > 0 ){
  134648. h = (h<<3) ^ h ^ *z++;
  134649. nKey--;
  134650. }
  134651. return (int)(h & 0x7fffffff);
  134652. }
  134653. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  134654. if( n1!=n2 ) return 1;
  134655. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  134656. }
  134657. /*
  134658. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  134659. */
  134660. static int fts3BinHash(const void *pKey, int nKey){
  134661. int h = 0;
  134662. const char *z = (const char *)pKey;
  134663. while( nKey-- > 0 ){
  134664. h = (h<<3) ^ h ^ *(z++);
  134665. }
  134666. return h & 0x7fffffff;
  134667. }
  134668. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  134669. if( n1!=n2 ) return 1;
  134670. return memcmp(pKey1,pKey2,n1);
  134671. }
  134672. /*
  134673. ** Return a pointer to the appropriate hash function given the key class.
  134674. **
  134675. ** The C syntax in this function definition may be unfamilar to some
  134676. ** programmers, so we provide the following additional explanation:
  134677. **
  134678. ** The name of the function is "ftsHashFunction". The function takes a
  134679. ** single parameter "keyClass". The return value of ftsHashFunction()
  134680. ** is a pointer to another function. Specifically, the return value
  134681. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  134682. ** with types "const void*" and "int" and returns an "int".
  134683. */
  134684. static int (*ftsHashFunction(int keyClass))(const void*,int){
  134685. if( keyClass==FTS3_HASH_STRING ){
  134686. return &fts3StrHash;
  134687. }else{
  134688. assert( keyClass==FTS3_HASH_BINARY );
  134689. return &fts3BinHash;
  134690. }
  134691. }
  134692. /*
  134693. ** Return a pointer to the appropriate hash function given the key class.
  134694. **
  134695. ** For help in interpreted the obscure C code in the function definition,
  134696. ** see the header comment on the previous function.
  134697. */
  134698. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  134699. if( keyClass==FTS3_HASH_STRING ){
  134700. return &fts3StrCompare;
  134701. }else{
  134702. assert( keyClass==FTS3_HASH_BINARY );
  134703. return &fts3BinCompare;
  134704. }
  134705. }
  134706. /* Link an element into the hash table
  134707. */
  134708. static void fts3HashInsertElement(
  134709. Fts3Hash *pH, /* The complete hash table */
  134710. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  134711. Fts3HashElem *pNew /* The element to be inserted */
  134712. ){
  134713. Fts3HashElem *pHead; /* First element already in pEntry */
  134714. pHead = pEntry->chain;
  134715. if( pHead ){
  134716. pNew->next = pHead;
  134717. pNew->prev = pHead->prev;
  134718. if( pHead->prev ){ pHead->prev->next = pNew; }
  134719. else { pH->first = pNew; }
  134720. pHead->prev = pNew;
  134721. }else{
  134722. pNew->next = pH->first;
  134723. if( pH->first ){ pH->first->prev = pNew; }
  134724. pNew->prev = 0;
  134725. pH->first = pNew;
  134726. }
  134727. pEntry->count++;
  134728. pEntry->chain = pNew;
  134729. }
  134730. /* Resize the hash table so that it cantains "new_size" buckets.
  134731. ** "new_size" must be a power of 2. The hash table might fail
  134732. ** to resize if sqliteMalloc() fails.
  134733. **
  134734. ** Return non-zero if a memory allocation error occurs.
  134735. */
  134736. static int fts3Rehash(Fts3Hash *pH, int new_size){
  134737. struct _fts3ht *new_ht; /* The new hash table */
  134738. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  134739. int (*xHash)(const void*,int); /* The hash function */
  134740. assert( (new_size & (new_size-1))==0 );
  134741. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  134742. if( new_ht==0 ) return 1;
  134743. fts3HashFree(pH->ht);
  134744. pH->ht = new_ht;
  134745. pH->htsize = new_size;
  134746. xHash = ftsHashFunction(pH->keyClass);
  134747. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  134748. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  134749. next_elem = elem->next;
  134750. fts3HashInsertElement(pH, &new_ht[h], elem);
  134751. }
  134752. return 0;
  134753. }
  134754. /* This function (for internal use only) locates an element in an
  134755. ** hash table that matches the given key. The hash for this key has
  134756. ** already been computed and is passed as the 4th parameter.
  134757. */
  134758. static Fts3HashElem *fts3FindElementByHash(
  134759. const Fts3Hash *pH, /* The pH to be searched */
  134760. const void *pKey, /* The key we are searching for */
  134761. int nKey,
  134762. int h /* The hash for this key. */
  134763. ){
  134764. Fts3HashElem *elem; /* Used to loop thru the element list */
  134765. int count; /* Number of elements left to test */
  134766. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  134767. if( pH->ht ){
  134768. struct _fts3ht *pEntry = &pH->ht[h];
  134769. elem = pEntry->chain;
  134770. count = pEntry->count;
  134771. xCompare = ftsCompareFunction(pH->keyClass);
  134772. while( count-- && elem ){
  134773. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  134774. return elem;
  134775. }
  134776. elem = elem->next;
  134777. }
  134778. }
  134779. return 0;
  134780. }
  134781. /* Remove a single entry from the hash table given a pointer to that
  134782. ** element and a hash on the element's key.
  134783. */
  134784. static void fts3RemoveElementByHash(
  134785. Fts3Hash *pH, /* The pH containing "elem" */
  134786. Fts3HashElem* elem, /* The element to be removed from the pH */
  134787. int h /* Hash value for the element */
  134788. ){
  134789. struct _fts3ht *pEntry;
  134790. if( elem->prev ){
  134791. elem->prev->next = elem->next;
  134792. }else{
  134793. pH->first = elem->next;
  134794. }
  134795. if( elem->next ){
  134796. elem->next->prev = elem->prev;
  134797. }
  134798. pEntry = &pH->ht[h];
  134799. if( pEntry->chain==elem ){
  134800. pEntry->chain = elem->next;
  134801. }
  134802. pEntry->count--;
  134803. if( pEntry->count<=0 ){
  134804. pEntry->chain = 0;
  134805. }
  134806. if( pH->copyKey && elem->pKey ){
  134807. fts3HashFree(elem->pKey);
  134808. }
  134809. fts3HashFree( elem );
  134810. pH->count--;
  134811. if( pH->count<=0 ){
  134812. assert( pH->first==0 );
  134813. assert( pH->count==0 );
  134814. fts3HashClear(pH);
  134815. }
  134816. }
  134817. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  134818. const Fts3Hash *pH,
  134819. const void *pKey,
  134820. int nKey
  134821. ){
  134822. int h; /* A hash on key */
  134823. int (*xHash)(const void*,int); /* The hash function */
  134824. if( pH==0 || pH->ht==0 ) return 0;
  134825. xHash = ftsHashFunction(pH->keyClass);
  134826. assert( xHash!=0 );
  134827. h = (*xHash)(pKey,nKey);
  134828. assert( (pH->htsize & (pH->htsize-1))==0 );
  134829. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  134830. }
  134831. /*
  134832. ** Attempt to locate an element of the hash table pH with a key
  134833. ** that matches pKey,nKey. Return the data for this element if it is
  134834. ** found, or NULL if there is no match.
  134835. */
  134836. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  134837. Fts3HashElem *pElem; /* The element that matches key (if any) */
  134838. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  134839. return pElem ? pElem->data : 0;
  134840. }
  134841. /* Insert an element into the hash table pH. The key is pKey,nKey
  134842. ** and the data is "data".
  134843. **
  134844. ** If no element exists with a matching key, then a new
  134845. ** element is created. A copy of the key is made if the copyKey
  134846. ** flag is set. NULL is returned.
  134847. **
  134848. ** If another element already exists with the same key, then the
  134849. ** new data replaces the old data and the old data is returned.
  134850. ** The key is not copied in this instance. If a malloc fails, then
  134851. ** the new data is returned and the hash table is unchanged.
  134852. **
  134853. ** If the "data" parameter to this function is NULL, then the
  134854. ** element corresponding to "key" is removed from the hash table.
  134855. */
  134856. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  134857. Fts3Hash *pH, /* The hash table to insert into */
  134858. const void *pKey, /* The key */
  134859. int nKey, /* Number of bytes in the key */
  134860. void *data /* The data */
  134861. ){
  134862. int hraw; /* Raw hash value of the key */
  134863. int h; /* the hash of the key modulo hash table size */
  134864. Fts3HashElem *elem; /* Used to loop thru the element list */
  134865. Fts3HashElem *new_elem; /* New element added to the pH */
  134866. int (*xHash)(const void*,int); /* The hash function */
  134867. assert( pH!=0 );
  134868. xHash = ftsHashFunction(pH->keyClass);
  134869. assert( xHash!=0 );
  134870. hraw = (*xHash)(pKey, nKey);
  134871. assert( (pH->htsize & (pH->htsize-1))==0 );
  134872. h = hraw & (pH->htsize-1);
  134873. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  134874. if( elem ){
  134875. void *old_data = elem->data;
  134876. if( data==0 ){
  134877. fts3RemoveElementByHash(pH,elem,h);
  134878. }else{
  134879. elem->data = data;
  134880. }
  134881. return old_data;
  134882. }
  134883. if( data==0 ) return 0;
  134884. if( (pH->htsize==0 && fts3Rehash(pH,8))
  134885. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  134886. ){
  134887. pH->count = 0;
  134888. return data;
  134889. }
  134890. assert( pH->htsize>0 );
  134891. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  134892. if( new_elem==0 ) return data;
  134893. if( pH->copyKey && pKey!=0 ){
  134894. new_elem->pKey = fts3HashMalloc( nKey );
  134895. if( new_elem->pKey==0 ){
  134896. fts3HashFree(new_elem);
  134897. return data;
  134898. }
  134899. memcpy((void*)new_elem->pKey, pKey, nKey);
  134900. }else{
  134901. new_elem->pKey = (void*)pKey;
  134902. }
  134903. new_elem->nKey = nKey;
  134904. pH->count++;
  134905. assert( pH->htsize>0 );
  134906. assert( (pH->htsize & (pH->htsize-1))==0 );
  134907. h = hraw & (pH->htsize-1);
  134908. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  134909. new_elem->data = data;
  134910. return 0;
  134911. }
  134912. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134913. /************** End of fts3_hash.c *******************************************/
  134914. /************** Begin file fts3_porter.c *************************************/
  134915. /*
  134916. ** 2006 September 30
  134917. **
  134918. ** The author disclaims copyright to this source code. In place of
  134919. ** a legal notice, here is a blessing:
  134920. **
  134921. ** May you do good and not evil.
  134922. ** May you find forgiveness for yourself and forgive others.
  134923. ** May you share freely, never taking more than you give.
  134924. **
  134925. *************************************************************************
  134926. ** Implementation of the full-text-search tokenizer that implements
  134927. ** a Porter stemmer.
  134928. */
  134929. /*
  134930. ** The code in this file is only compiled if:
  134931. **
  134932. ** * The FTS3 module is being built as an extension
  134933. ** (in which case SQLITE_CORE is not defined), or
  134934. **
  134935. ** * The FTS3 module is being built into the core of
  134936. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  134937. */
  134938. /* #include "fts3Int.h" */
  134939. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134940. /* #include <assert.h> */
  134941. /* #include <stdlib.h> */
  134942. /* #include <stdio.h> */
  134943. /* #include <string.h> */
  134944. /* #include "fts3_tokenizer.h" */
  134945. /*
  134946. ** Class derived from sqlite3_tokenizer
  134947. */
  134948. typedef struct porter_tokenizer {
  134949. sqlite3_tokenizer base; /* Base class */
  134950. } porter_tokenizer;
  134951. /*
  134952. ** Class derived from sqlite3_tokenizer_cursor
  134953. */
  134954. typedef struct porter_tokenizer_cursor {
  134955. sqlite3_tokenizer_cursor base;
  134956. const char *zInput; /* input we are tokenizing */
  134957. int nInput; /* size of the input */
  134958. int iOffset; /* current position in zInput */
  134959. int iToken; /* index of next token to be returned */
  134960. char *zToken; /* storage for current token */
  134961. int nAllocated; /* space allocated to zToken buffer */
  134962. } porter_tokenizer_cursor;
  134963. /*
  134964. ** Create a new tokenizer instance.
  134965. */
  134966. static int porterCreate(
  134967. int argc, const char * const *argv,
  134968. sqlite3_tokenizer **ppTokenizer
  134969. ){
  134970. porter_tokenizer *t;
  134971. UNUSED_PARAMETER(argc);
  134972. UNUSED_PARAMETER(argv);
  134973. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  134974. if( t==NULL ) return SQLITE_NOMEM;
  134975. memset(t, 0, sizeof(*t));
  134976. *ppTokenizer = &t->base;
  134977. return SQLITE_OK;
  134978. }
  134979. /*
  134980. ** Destroy a tokenizer
  134981. */
  134982. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  134983. sqlite3_free(pTokenizer);
  134984. return SQLITE_OK;
  134985. }
  134986. /*
  134987. ** Prepare to begin tokenizing a particular string. The input
  134988. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  134989. ** used to incrementally tokenize this string is returned in
  134990. ** *ppCursor.
  134991. */
  134992. static int porterOpen(
  134993. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  134994. const char *zInput, int nInput, /* String to be tokenized */
  134995. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  134996. ){
  134997. porter_tokenizer_cursor *c;
  134998. UNUSED_PARAMETER(pTokenizer);
  134999. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  135000. if( c==NULL ) return SQLITE_NOMEM;
  135001. c->zInput = zInput;
  135002. if( zInput==0 ){
  135003. c->nInput = 0;
  135004. }else if( nInput<0 ){
  135005. c->nInput = (int)strlen(zInput);
  135006. }else{
  135007. c->nInput = nInput;
  135008. }
  135009. c->iOffset = 0; /* start tokenizing at the beginning */
  135010. c->iToken = 0;
  135011. c->zToken = NULL; /* no space allocated, yet. */
  135012. c->nAllocated = 0;
  135013. *ppCursor = &c->base;
  135014. return SQLITE_OK;
  135015. }
  135016. /*
  135017. ** Close a tokenization cursor previously opened by a call to
  135018. ** porterOpen() above.
  135019. */
  135020. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  135021. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  135022. sqlite3_free(c->zToken);
  135023. sqlite3_free(c);
  135024. return SQLITE_OK;
  135025. }
  135026. /*
  135027. ** Vowel or consonant
  135028. */
  135029. static const char cType[] = {
  135030. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  135031. 1, 1, 1, 2, 1
  135032. };
  135033. /*
  135034. ** isConsonant() and isVowel() determine if their first character in
  135035. ** the string they point to is a consonant or a vowel, according
  135036. ** to Porter ruls.
  135037. **
  135038. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  135039. ** 'Y' is a consonant unless it follows another consonant,
  135040. ** in which case it is a vowel.
  135041. **
  135042. ** In these routine, the letters are in reverse order. So the 'y' rule
  135043. ** is that 'y' is a consonant unless it is followed by another
  135044. ** consonent.
  135045. */
  135046. static int isVowel(const char*);
  135047. static int isConsonant(const char *z){
  135048. int j;
  135049. char x = *z;
  135050. if( x==0 ) return 0;
  135051. assert( x>='a' && x<='z' );
  135052. j = cType[x-'a'];
  135053. if( j<2 ) return j;
  135054. return z[1]==0 || isVowel(z + 1);
  135055. }
  135056. static int isVowel(const char *z){
  135057. int j;
  135058. char x = *z;
  135059. if( x==0 ) return 0;
  135060. assert( x>='a' && x<='z' );
  135061. j = cType[x-'a'];
  135062. if( j<2 ) return 1-j;
  135063. return isConsonant(z + 1);
  135064. }
  135065. /*
  135066. ** Let any sequence of one or more vowels be represented by V and let
  135067. ** C be sequence of one or more consonants. Then every word can be
  135068. ** represented as:
  135069. **
  135070. ** [C] (VC){m} [V]
  135071. **
  135072. ** In prose: A word is an optional consonant followed by zero or
  135073. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  135074. ** number of vowel consonant pairs. This routine computes the value
  135075. ** of m for the first i bytes of a word.
  135076. **
  135077. ** Return true if the m-value for z is 1 or more. In other words,
  135078. ** return true if z contains at least one vowel that is followed
  135079. ** by a consonant.
  135080. **
  135081. ** In this routine z[] is in reverse order. So we are really looking
  135082. ** for an instance of a consonant followed by a vowel.
  135083. */
  135084. static int m_gt_0(const char *z){
  135085. while( isVowel(z) ){ z++; }
  135086. if( *z==0 ) return 0;
  135087. while( isConsonant(z) ){ z++; }
  135088. return *z!=0;
  135089. }
  135090. /* Like mgt0 above except we are looking for a value of m which is
  135091. ** exactly 1
  135092. */
  135093. static int m_eq_1(const char *z){
  135094. while( isVowel(z) ){ z++; }
  135095. if( *z==0 ) return 0;
  135096. while( isConsonant(z) ){ z++; }
  135097. if( *z==0 ) return 0;
  135098. while( isVowel(z) ){ z++; }
  135099. if( *z==0 ) return 1;
  135100. while( isConsonant(z) ){ z++; }
  135101. return *z==0;
  135102. }
  135103. /* Like mgt0 above except we are looking for a value of m>1 instead
  135104. ** or m>0
  135105. */
  135106. static int m_gt_1(const char *z){
  135107. while( isVowel(z) ){ z++; }
  135108. if( *z==0 ) return 0;
  135109. while( isConsonant(z) ){ z++; }
  135110. if( *z==0 ) return 0;
  135111. while( isVowel(z) ){ z++; }
  135112. if( *z==0 ) return 0;
  135113. while( isConsonant(z) ){ z++; }
  135114. return *z!=0;
  135115. }
  135116. /*
  135117. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  135118. */
  135119. static int hasVowel(const char *z){
  135120. while( isConsonant(z) ){ z++; }
  135121. return *z!=0;
  135122. }
  135123. /*
  135124. ** Return TRUE if the word ends in a double consonant.
  135125. **
  135126. ** The text is reversed here. So we are really looking at
  135127. ** the first two characters of z[].
  135128. */
  135129. static int doubleConsonant(const char *z){
  135130. return isConsonant(z) && z[0]==z[1];
  135131. }
  135132. /*
  135133. ** Return TRUE if the word ends with three letters which
  135134. ** are consonant-vowel-consonent and where the final consonant
  135135. ** is not 'w', 'x', or 'y'.
  135136. **
  135137. ** The word is reversed here. So we are really checking the
  135138. ** first three letters and the first one cannot be in [wxy].
  135139. */
  135140. static int star_oh(const char *z){
  135141. return
  135142. isConsonant(z) &&
  135143. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  135144. isVowel(z+1) &&
  135145. isConsonant(z+2);
  135146. }
  135147. /*
  135148. ** If the word ends with zFrom and xCond() is true for the stem
  135149. ** of the word that preceeds the zFrom ending, then change the
  135150. ** ending to zTo.
  135151. **
  135152. ** The input word *pz and zFrom are both in reverse order. zTo
  135153. ** is in normal order.
  135154. **
  135155. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  135156. ** match. Not that TRUE is returned even if xCond() fails and
  135157. ** no substitution occurs.
  135158. */
  135159. static int stem(
  135160. char **pz, /* The word being stemmed (Reversed) */
  135161. const char *zFrom, /* If the ending matches this... (Reversed) */
  135162. const char *zTo, /* ... change the ending to this (not reversed) */
  135163. int (*xCond)(const char*) /* Condition that must be true */
  135164. ){
  135165. char *z = *pz;
  135166. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  135167. if( *zFrom!=0 ) return 0;
  135168. if( xCond && !xCond(z) ) return 1;
  135169. while( *zTo ){
  135170. *(--z) = *(zTo++);
  135171. }
  135172. *pz = z;
  135173. return 1;
  135174. }
  135175. /*
  135176. ** This is the fallback stemmer used when the porter stemmer is
  135177. ** inappropriate. The input word is copied into the output with
  135178. ** US-ASCII case folding. If the input word is too long (more
  135179. ** than 20 bytes if it contains no digits or more than 6 bytes if
  135180. ** it contains digits) then word is truncated to 20 or 6 bytes
  135181. ** by taking 10 or 3 bytes from the beginning and end.
  135182. */
  135183. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  135184. int i, mx, j;
  135185. int hasDigit = 0;
  135186. for(i=0; i<nIn; i++){
  135187. char c = zIn[i];
  135188. if( c>='A' && c<='Z' ){
  135189. zOut[i] = c - 'A' + 'a';
  135190. }else{
  135191. if( c>='0' && c<='9' ) hasDigit = 1;
  135192. zOut[i] = c;
  135193. }
  135194. }
  135195. mx = hasDigit ? 3 : 10;
  135196. if( nIn>mx*2 ){
  135197. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  135198. zOut[j] = zOut[i];
  135199. }
  135200. i = j;
  135201. }
  135202. zOut[i] = 0;
  135203. *pnOut = i;
  135204. }
  135205. /*
  135206. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  135207. ** zOut is at least big enough to hold nIn bytes. Write the actual
  135208. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  135209. **
  135210. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  135211. ** are converted to lower case. Upper-case UTF characters are
  135212. ** unchanged.
  135213. **
  135214. ** Words that are longer than about 20 bytes are stemmed by retaining
  135215. ** a few bytes from the beginning and the end of the word. If the
  135216. ** word contains digits, 3 bytes are taken from the beginning and
  135217. ** 3 bytes from the end. For long words without digits, 10 bytes
  135218. ** are taken from each end. US-ASCII case folding still applies.
  135219. **
  135220. ** If the input word contains not digits but does characters not
  135221. ** in [a-zA-Z] then no stemming is attempted and this routine just
  135222. ** copies the input into the input into the output with US-ASCII
  135223. ** case folding.
  135224. **
  135225. ** Stemming never increases the length of the word. So there is
  135226. ** no chance of overflowing the zOut buffer.
  135227. */
  135228. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  135229. int i, j;
  135230. char zReverse[28];
  135231. char *z, *z2;
  135232. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  135233. /* The word is too big or too small for the porter stemmer.
  135234. ** Fallback to the copy stemmer */
  135235. copy_stemmer(zIn, nIn, zOut, pnOut);
  135236. return;
  135237. }
  135238. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  135239. char c = zIn[i];
  135240. if( c>='A' && c<='Z' ){
  135241. zReverse[j] = c + 'a' - 'A';
  135242. }else if( c>='a' && c<='z' ){
  135243. zReverse[j] = c;
  135244. }else{
  135245. /* The use of a character not in [a-zA-Z] means that we fallback
  135246. ** to the copy stemmer */
  135247. copy_stemmer(zIn, nIn, zOut, pnOut);
  135248. return;
  135249. }
  135250. }
  135251. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  135252. z = &zReverse[j+1];
  135253. /* Step 1a */
  135254. if( z[0]=='s' ){
  135255. if(
  135256. !stem(&z, "sess", "ss", 0) &&
  135257. !stem(&z, "sei", "i", 0) &&
  135258. !stem(&z, "ss", "ss", 0)
  135259. ){
  135260. z++;
  135261. }
  135262. }
  135263. /* Step 1b */
  135264. z2 = z;
  135265. if( stem(&z, "dee", "ee", m_gt_0) ){
  135266. /* Do nothing. The work was all in the test */
  135267. }else if(
  135268. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  135269. && z!=z2
  135270. ){
  135271. if( stem(&z, "ta", "ate", 0) ||
  135272. stem(&z, "lb", "ble", 0) ||
  135273. stem(&z, "zi", "ize", 0) ){
  135274. /* Do nothing. The work was all in the test */
  135275. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  135276. z++;
  135277. }else if( m_eq_1(z) && star_oh(z) ){
  135278. *(--z) = 'e';
  135279. }
  135280. }
  135281. /* Step 1c */
  135282. if( z[0]=='y' && hasVowel(z+1) ){
  135283. z[0] = 'i';
  135284. }
  135285. /* Step 2 */
  135286. switch( z[1] ){
  135287. case 'a':
  135288. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  135289. stem(&z, "lanoit", "tion", m_gt_0);
  135290. }
  135291. break;
  135292. case 'c':
  135293. if( !stem(&z, "icne", "ence", m_gt_0) ){
  135294. stem(&z, "icna", "ance", m_gt_0);
  135295. }
  135296. break;
  135297. case 'e':
  135298. stem(&z, "rezi", "ize", m_gt_0);
  135299. break;
  135300. case 'g':
  135301. stem(&z, "igol", "log", m_gt_0);
  135302. break;
  135303. case 'l':
  135304. if( !stem(&z, "ilb", "ble", m_gt_0)
  135305. && !stem(&z, "illa", "al", m_gt_0)
  135306. && !stem(&z, "iltne", "ent", m_gt_0)
  135307. && !stem(&z, "ile", "e", m_gt_0)
  135308. ){
  135309. stem(&z, "ilsuo", "ous", m_gt_0);
  135310. }
  135311. break;
  135312. case 'o':
  135313. if( !stem(&z, "noitazi", "ize", m_gt_0)
  135314. && !stem(&z, "noita", "ate", m_gt_0)
  135315. ){
  135316. stem(&z, "rota", "ate", m_gt_0);
  135317. }
  135318. break;
  135319. case 's':
  135320. if( !stem(&z, "msila", "al", m_gt_0)
  135321. && !stem(&z, "ssenevi", "ive", m_gt_0)
  135322. && !stem(&z, "ssenluf", "ful", m_gt_0)
  135323. ){
  135324. stem(&z, "ssensuo", "ous", m_gt_0);
  135325. }
  135326. break;
  135327. case 't':
  135328. if( !stem(&z, "itila", "al", m_gt_0)
  135329. && !stem(&z, "itivi", "ive", m_gt_0)
  135330. ){
  135331. stem(&z, "itilib", "ble", m_gt_0);
  135332. }
  135333. break;
  135334. }
  135335. /* Step 3 */
  135336. switch( z[0] ){
  135337. case 'e':
  135338. if( !stem(&z, "etaci", "ic", m_gt_0)
  135339. && !stem(&z, "evita", "", m_gt_0)
  135340. ){
  135341. stem(&z, "ezila", "al", m_gt_0);
  135342. }
  135343. break;
  135344. case 'i':
  135345. stem(&z, "itici", "ic", m_gt_0);
  135346. break;
  135347. case 'l':
  135348. if( !stem(&z, "laci", "ic", m_gt_0) ){
  135349. stem(&z, "luf", "", m_gt_0);
  135350. }
  135351. break;
  135352. case 's':
  135353. stem(&z, "ssen", "", m_gt_0);
  135354. break;
  135355. }
  135356. /* Step 4 */
  135357. switch( z[1] ){
  135358. case 'a':
  135359. if( z[0]=='l' && m_gt_1(z+2) ){
  135360. z += 2;
  135361. }
  135362. break;
  135363. case 'c':
  135364. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  135365. z += 4;
  135366. }
  135367. break;
  135368. case 'e':
  135369. if( z[0]=='r' && m_gt_1(z+2) ){
  135370. z += 2;
  135371. }
  135372. break;
  135373. case 'i':
  135374. if( z[0]=='c' && m_gt_1(z+2) ){
  135375. z += 2;
  135376. }
  135377. break;
  135378. case 'l':
  135379. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  135380. z += 4;
  135381. }
  135382. break;
  135383. case 'n':
  135384. if( z[0]=='t' ){
  135385. if( z[2]=='a' ){
  135386. if( m_gt_1(z+3) ){
  135387. z += 3;
  135388. }
  135389. }else if( z[2]=='e' ){
  135390. if( !stem(&z, "tneme", "", m_gt_1)
  135391. && !stem(&z, "tnem", "", m_gt_1)
  135392. ){
  135393. stem(&z, "tne", "", m_gt_1);
  135394. }
  135395. }
  135396. }
  135397. break;
  135398. case 'o':
  135399. if( z[0]=='u' ){
  135400. if( m_gt_1(z+2) ){
  135401. z += 2;
  135402. }
  135403. }else if( z[3]=='s' || z[3]=='t' ){
  135404. stem(&z, "noi", "", m_gt_1);
  135405. }
  135406. break;
  135407. case 's':
  135408. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  135409. z += 3;
  135410. }
  135411. break;
  135412. case 't':
  135413. if( !stem(&z, "eta", "", m_gt_1) ){
  135414. stem(&z, "iti", "", m_gt_1);
  135415. }
  135416. break;
  135417. case 'u':
  135418. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  135419. z += 3;
  135420. }
  135421. break;
  135422. case 'v':
  135423. case 'z':
  135424. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  135425. z += 3;
  135426. }
  135427. break;
  135428. }
  135429. /* Step 5a */
  135430. if( z[0]=='e' ){
  135431. if( m_gt_1(z+1) ){
  135432. z++;
  135433. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  135434. z++;
  135435. }
  135436. }
  135437. /* Step 5b */
  135438. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  135439. z++;
  135440. }
  135441. /* z[] is now the stemmed word in reverse order. Flip it back
  135442. ** around into forward order and return.
  135443. */
  135444. *pnOut = i = (int)strlen(z);
  135445. zOut[i] = 0;
  135446. while( *z ){
  135447. zOut[--i] = *(z++);
  135448. }
  135449. }
  135450. /*
  135451. ** Characters that can be part of a token. We assume any character
  135452. ** whose value is greater than 0x80 (any UTF character) can be
  135453. ** part of a token. In other words, delimiters all must have
  135454. ** values of 0x7f or lower.
  135455. */
  135456. static const char porterIdChar[] = {
  135457. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  135458. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  135459. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  135460. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  135461. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  135462. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  135463. };
  135464. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  135465. /*
  135466. ** Extract the next token from a tokenization cursor. The cursor must
  135467. ** have been opened by a prior call to porterOpen().
  135468. */
  135469. static int porterNext(
  135470. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  135471. const char **pzToken, /* OUT: *pzToken is the token text */
  135472. int *pnBytes, /* OUT: Number of bytes in token */
  135473. int *piStartOffset, /* OUT: Starting offset of token */
  135474. int *piEndOffset, /* OUT: Ending offset of token */
  135475. int *piPosition /* OUT: Position integer of token */
  135476. ){
  135477. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  135478. const char *z = c->zInput;
  135479. while( c->iOffset<c->nInput ){
  135480. int iStartOffset, ch;
  135481. /* Scan past delimiter characters */
  135482. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  135483. c->iOffset++;
  135484. }
  135485. /* Count non-delimiter characters. */
  135486. iStartOffset = c->iOffset;
  135487. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  135488. c->iOffset++;
  135489. }
  135490. if( c->iOffset>iStartOffset ){
  135491. int n = c->iOffset-iStartOffset;
  135492. if( n>c->nAllocated ){
  135493. char *pNew;
  135494. c->nAllocated = n+20;
  135495. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  135496. if( !pNew ) return SQLITE_NOMEM;
  135497. c->zToken = pNew;
  135498. }
  135499. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  135500. *pzToken = c->zToken;
  135501. *piStartOffset = iStartOffset;
  135502. *piEndOffset = c->iOffset;
  135503. *piPosition = c->iToken++;
  135504. return SQLITE_OK;
  135505. }
  135506. }
  135507. return SQLITE_DONE;
  135508. }
  135509. /*
  135510. ** The set of routines that implement the porter-stemmer tokenizer
  135511. */
  135512. static const sqlite3_tokenizer_module porterTokenizerModule = {
  135513. 0,
  135514. porterCreate,
  135515. porterDestroy,
  135516. porterOpen,
  135517. porterClose,
  135518. porterNext,
  135519. 0
  135520. };
  135521. /*
  135522. ** Allocate a new porter tokenizer. Return a pointer to the new
  135523. ** tokenizer in *ppModule
  135524. */
  135525. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  135526. sqlite3_tokenizer_module const**ppModule
  135527. ){
  135528. *ppModule = &porterTokenizerModule;
  135529. }
  135530. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  135531. /************** End of fts3_porter.c *****************************************/
  135532. /************** Begin file fts3_tokenizer.c **********************************/
  135533. /*
  135534. ** 2007 June 22
  135535. **
  135536. ** The author disclaims copyright to this source code. In place of
  135537. ** a legal notice, here is a blessing:
  135538. **
  135539. ** May you do good and not evil.
  135540. ** May you find forgiveness for yourself and forgive others.
  135541. ** May you share freely, never taking more than you give.
  135542. **
  135543. ******************************************************************************
  135544. **
  135545. ** This is part of an SQLite module implementing full-text search.
  135546. ** This particular file implements the generic tokenizer interface.
  135547. */
  135548. /*
  135549. ** The code in this file is only compiled if:
  135550. **
  135551. ** * The FTS3 module is being built as an extension
  135552. ** (in which case SQLITE_CORE is not defined), or
  135553. **
  135554. ** * The FTS3 module is being built into the core of
  135555. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  135556. */
  135557. /* #include "fts3Int.h" */
  135558. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135559. /* #include <assert.h> */
  135560. /* #include <string.h> */
  135561. /*
  135562. ** Implementation of the SQL scalar function for accessing the underlying
  135563. ** hash table. This function may be called as follows:
  135564. **
  135565. ** SELECT <function-name>(<key-name>);
  135566. ** SELECT <function-name>(<key-name>, <pointer>);
  135567. **
  135568. ** where <function-name> is the name passed as the second argument
  135569. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  135570. **
  135571. ** If the <pointer> argument is specified, it must be a blob value
  135572. ** containing a pointer to be stored as the hash data corresponding
  135573. ** to the string <key-name>. If <pointer> is not specified, then
  135574. ** the string <key-name> must already exist in the has table. Otherwise,
  135575. ** an error is returned.
  135576. **
  135577. ** Whether or not the <pointer> argument is specified, the value returned
  135578. ** is a blob containing the pointer stored as the hash data corresponding
  135579. ** to string <key-name> (after the hash-table is updated, if applicable).
  135580. */
  135581. static void scalarFunc(
  135582. sqlite3_context *context,
  135583. int argc,
  135584. sqlite3_value **argv
  135585. ){
  135586. Fts3Hash *pHash;
  135587. void *pPtr = 0;
  135588. const unsigned char *zName;
  135589. int nName;
  135590. assert( argc==1 || argc==2 );
  135591. pHash = (Fts3Hash *)sqlite3_user_data(context);
  135592. zName = sqlite3_value_text(argv[0]);
  135593. nName = sqlite3_value_bytes(argv[0])+1;
  135594. if( argc==2 ){
  135595. void *pOld;
  135596. int n = sqlite3_value_bytes(argv[1]);
  135597. if( zName==0 || n!=sizeof(pPtr) ){
  135598. sqlite3_result_error(context, "argument type mismatch", -1);
  135599. return;
  135600. }
  135601. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  135602. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  135603. if( pOld==pPtr ){
  135604. sqlite3_result_error(context, "out of memory", -1);
  135605. return;
  135606. }
  135607. }else{
  135608. if( zName ){
  135609. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  135610. }
  135611. if( !pPtr ){
  135612. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  135613. sqlite3_result_error(context, zErr, -1);
  135614. sqlite3_free(zErr);
  135615. return;
  135616. }
  135617. }
  135618. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  135619. }
  135620. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  135621. static const char isFtsIdChar[] = {
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  135624. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  135625. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  135626. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  135627. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  135628. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  135629. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  135630. };
  135631. return (c&0x80 || isFtsIdChar[(int)(c)]);
  135632. }
  135633. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  135634. const char *z1;
  135635. const char *z2 = 0;
  135636. /* Find the start of the next token. */
  135637. z1 = zStr;
  135638. while( z2==0 ){
  135639. char c = *z1;
  135640. switch( c ){
  135641. case '\0': return 0; /* No more tokens here */
  135642. case '\'':
  135643. case '"':
  135644. case '`': {
  135645. z2 = z1;
  135646. while( *++z2 && (*z2!=c || *++z2==c) );
  135647. break;
  135648. }
  135649. case '[':
  135650. z2 = &z1[1];
  135651. while( *z2 && z2[0]!=']' ) z2++;
  135652. if( *z2 ) z2++;
  135653. break;
  135654. default:
  135655. if( sqlite3Fts3IsIdChar(*z1) ){
  135656. z2 = &z1[1];
  135657. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  135658. }else{
  135659. z1++;
  135660. }
  135661. }
  135662. }
  135663. *pn = (int)(z2-z1);
  135664. return z1;
  135665. }
  135666. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  135667. Fts3Hash *pHash, /* Tokenizer hash table */
  135668. const char *zArg, /* Tokenizer name */
  135669. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  135670. char **pzErr /* OUT: Set to malloced error message */
  135671. ){
  135672. int rc;
  135673. char *z = (char *)zArg;
  135674. int n = 0;
  135675. char *zCopy;
  135676. char *zEnd; /* Pointer to nul-term of zCopy */
  135677. sqlite3_tokenizer_module *m;
  135678. zCopy = sqlite3_mprintf("%s", zArg);
  135679. if( !zCopy ) return SQLITE_NOMEM;
  135680. zEnd = &zCopy[strlen(zCopy)];
  135681. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  135682. if( z==0 ){
  135683. assert( n==0 );
  135684. z = zCopy;
  135685. }
  135686. z[n] = '\0';
  135687. sqlite3Fts3Dequote(z);
  135688. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  135689. if( !m ){
  135690. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  135691. rc = SQLITE_ERROR;
  135692. }else{
  135693. char const **aArg = 0;
  135694. int iArg = 0;
  135695. z = &z[n+1];
  135696. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  135697. int nNew = sizeof(char *)*(iArg+1);
  135698. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  135699. if( !aNew ){
  135700. sqlite3_free(zCopy);
  135701. sqlite3_free((void *)aArg);
  135702. return SQLITE_NOMEM;
  135703. }
  135704. aArg = aNew;
  135705. aArg[iArg++] = z;
  135706. z[n] = '\0';
  135707. sqlite3Fts3Dequote(z);
  135708. z = &z[n+1];
  135709. }
  135710. rc = m->xCreate(iArg, aArg, ppTok);
  135711. assert( rc!=SQLITE_OK || *ppTok );
  135712. if( rc!=SQLITE_OK ){
  135713. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  135714. }else{
  135715. (*ppTok)->pModule = m;
  135716. }
  135717. sqlite3_free((void *)aArg);
  135718. }
  135719. sqlite3_free(zCopy);
  135720. return rc;
  135721. }
  135722. #ifdef SQLITE_TEST
  135723. #include <tcl.h>
  135724. /* #include <string.h> */
  135725. /*
  135726. ** Implementation of a special SQL scalar function for testing tokenizers
  135727. ** designed to be used in concert with the Tcl testing framework. This
  135728. ** function must be called with two or more arguments:
  135729. **
  135730. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  135731. **
  135732. ** where <function-name> is the name passed as the second argument
  135733. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  135734. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  135735. **
  135736. ** The return value is a string that may be interpreted as a Tcl
  135737. ** list. For each token in the <input-string>, three elements are
  135738. ** added to the returned list. The first is the token position, the
  135739. ** second is the token text (folded, stemmed, etc.) and the third is the
  135740. ** substring of <input-string> associated with the token. For example,
  135741. ** using the built-in "simple" tokenizer:
  135742. **
  135743. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  135744. **
  135745. ** will return the string:
  135746. **
  135747. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  135748. **
  135749. */
  135750. static void testFunc(
  135751. sqlite3_context *context,
  135752. int argc,
  135753. sqlite3_value **argv
  135754. ){
  135755. Fts3Hash *pHash;
  135756. sqlite3_tokenizer_module *p;
  135757. sqlite3_tokenizer *pTokenizer = 0;
  135758. sqlite3_tokenizer_cursor *pCsr = 0;
  135759. const char *zErr = 0;
  135760. const char *zName;
  135761. int nName;
  135762. const char *zInput;
  135763. int nInput;
  135764. const char *azArg[64];
  135765. const char *zToken;
  135766. int nToken = 0;
  135767. int iStart = 0;
  135768. int iEnd = 0;
  135769. int iPos = 0;
  135770. int i;
  135771. Tcl_Obj *pRet;
  135772. if( argc<2 ){
  135773. sqlite3_result_error(context, "insufficient arguments", -1);
  135774. return;
  135775. }
  135776. nName = sqlite3_value_bytes(argv[0]);
  135777. zName = (const char *)sqlite3_value_text(argv[0]);
  135778. nInput = sqlite3_value_bytes(argv[argc-1]);
  135779. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  135780. pHash = (Fts3Hash *)sqlite3_user_data(context);
  135781. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  135782. if( !p ){
  135783. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  135784. sqlite3_result_error(context, zErr2, -1);
  135785. sqlite3_free(zErr2);
  135786. return;
  135787. }
  135788. pRet = Tcl_NewObj();
  135789. Tcl_IncrRefCount(pRet);
  135790. for(i=1; i<argc-1; i++){
  135791. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  135792. }
  135793. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  135794. zErr = "error in xCreate()";
  135795. goto finish;
  135796. }
  135797. pTokenizer->pModule = p;
  135798. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  135799. zErr = "error in xOpen()";
  135800. goto finish;
  135801. }
  135802. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  135803. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  135804. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  135805. zToken = &zInput[iStart];
  135806. nToken = iEnd-iStart;
  135807. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  135808. }
  135809. if( SQLITE_OK!=p->xClose(pCsr) ){
  135810. zErr = "error in xClose()";
  135811. goto finish;
  135812. }
  135813. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  135814. zErr = "error in xDestroy()";
  135815. goto finish;
  135816. }
  135817. finish:
  135818. if( zErr ){
  135819. sqlite3_result_error(context, zErr, -1);
  135820. }else{
  135821. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  135822. }
  135823. Tcl_DecrRefCount(pRet);
  135824. }
  135825. static
  135826. int registerTokenizer(
  135827. sqlite3 *db,
  135828. char *zName,
  135829. const sqlite3_tokenizer_module *p
  135830. ){
  135831. int rc;
  135832. sqlite3_stmt *pStmt;
  135833. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  135834. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  135835. if( rc!=SQLITE_OK ){
  135836. return rc;
  135837. }
  135838. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  135839. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  135840. sqlite3_step(pStmt);
  135841. return sqlite3_finalize(pStmt);
  135842. }
  135843. static
  135844. int queryTokenizer(
  135845. sqlite3 *db,
  135846. char *zName,
  135847. const sqlite3_tokenizer_module **pp
  135848. ){
  135849. int rc;
  135850. sqlite3_stmt *pStmt;
  135851. const char zSql[] = "SELECT fts3_tokenizer(?)";
  135852. *pp = 0;
  135853. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  135854. if( rc!=SQLITE_OK ){
  135855. return rc;
  135856. }
  135857. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  135858. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135859. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  135860. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  135861. }
  135862. }
  135863. return sqlite3_finalize(pStmt);
  135864. }
  135865. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  135866. /*
  135867. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  135868. ** This function is used for testing only, it is not included in the
  135869. ** build unless SQLITE_TEST is defined.
  135870. **
  135871. ** The purpose of this is to test that the fts3_tokenizer() function
  135872. ** can be used as designed by the C-code in the queryTokenizer and
  135873. ** registerTokenizer() functions above. These two functions are repeated
  135874. ** in the README.tokenizer file as an example, so it is important to
  135875. ** test them.
  135876. **
  135877. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  135878. ** function with no arguments. An assert() will fail if a problem is
  135879. ** detected. i.e.:
  135880. **
  135881. ** SELECT fts3_tokenizer_internal_test();
  135882. **
  135883. */
  135884. static void intTestFunc(
  135885. sqlite3_context *context,
  135886. int argc,
  135887. sqlite3_value **argv
  135888. ){
  135889. int rc;
  135890. const sqlite3_tokenizer_module *p1;
  135891. const sqlite3_tokenizer_module *p2;
  135892. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  135893. UNUSED_PARAMETER(argc);
  135894. UNUSED_PARAMETER(argv);
  135895. /* Test the query function */
  135896. sqlite3Fts3SimpleTokenizerModule(&p1);
  135897. rc = queryTokenizer(db, "simple", &p2);
  135898. assert( rc==SQLITE_OK );
  135899. assert( p1==p2 );
  135900. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  135901. assert( rc==SQLITE_ERROR );
  135902. assert( p2==0 );
  135903. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  135904. /* Test the storage function */
  135905. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  135906. assert( rc==SQLITE_OK );
  135907. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  135908. assert( rc==SQLITE_OK );
  135909. assert( p2==p1 );
  135910. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  135911. }
  135912. #endif
  135913. /*
  135914. ** Set up SQL objects in database db used to access the contents of
  135915. ** the hash table pointed to by argument pHash. The hash table must
  135916. ** been initialized to use string keys, and to take a private copy
  135917. ** of the key when a value is inserted. i.e. by a call similar to:
  135918. **
  135919. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  135920. **
  135921. ** This function adds a scalar function (see header comment above
  135922. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  135923. ** defined at compilation time, a temporary virtual table (see header
  135924. ** comment above struct HashTableVtab) to the database schema. Both
  135925. ** provide read/write access to the contents of *pHash.
  135926. **
  135927. ** The third argument to this function, zName, is used as the name
  135928. ** of both the scalar and, if created, the virtual table.
  135929. */
  135930. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  135931. sqlite3 *db,
  135932. Fts3Hash *pHash,
  135933. const char *zName
  135934. ){
  135935. int rc = SQLITE_OK;
  135936. void *p = (void *)pHash;
  135937. const int any = SQLITE_ANY;
  135938. #ifdef SQLITE_TEST
  135939. char *zTest = 0;
  135940. char *zTest2 = 0;
  135941. void *pdb = (void *)db;
  135942. zTest = sqlite3_mprintf("%s_test", zName);
  135943. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  135944. if( !zTest || !zTest2 ){
  135945. rc = SQLITE_NOMEM;
  135946. }
  135947. #endif
  135948. if( SQLITE_OK==rc ){
  135949. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  135950. }
  135951. if( SQLITE_OK==rc ){
  135952. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  135953. }
  135954. #ifdef SQLITE_TEST
  135955. if( SQLITE_OK==rc ){
  135956. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  135957. }
  135958. if( SQLITE_OK==rc ){
  135959. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  135960. }
  135961. #endif
  135962. #ifdef SQLITE_TEST
  135963. sqlite3_free(zTest);
  135964. sqlite3_free(zTest2);
  135965. #endif
  135966. return rc;
  135967. }
  135968. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  135969. /************** End of fts3_tokenizer.c **************************************/
  135970. /************** Begin file fts3_tokenizer1.c *********************************/
  135971. /*
  135972. ** 2006 Oct 10
  135973. **
  135974. ** The author disclaims copyright to this source code. In place of
  135975. ** a legal notice, here is a blessing:
  135976. **
  135977. ** May you do good and not evil.
  135978. ** May you find forgiveness for yourself and forgive others.
  135979. ** May you share freely, never taking more than you give.
  135980. **
  135981. ******************************************************************************
  135982. **
  135983. ** Implementation of the "simple" full-text-search tokenizer.
  135984. */
  135985. /*
  135986. ** The code in this file is only compiled if:
  135987. **
  135988. ** * The FTS3 module is being built as an extension
  135989. ** (in which case SQLITE_CORE is not defined), or
  135990. **
  135991. ** * The FTS3 module is being built into the core of
  135992. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  135993. */
  135994. /* #include "fts3Int.h" */
  135995. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135996. /* #include <assert.h> */
  135997. /* #include <stdlib.h> */
  135998. /* #include <stdio.h> */
  135999. /* #include <string.h> */
  136000. /* #include "fts3_tokenizer.h" */
  136001. typedef struct simple_tokenizer {
  136002. sqlite3_tokenizer base;
  136003. char delim[128]; /* flag ASCII delimiters */
  136004. } simple_tokenizer;
  136005. typedef struct simple_tokenizer_cursor {
  136006. sqlite3_tokenizer_cursor base;
  136007. const char *pInput; /* input we are tokenizing */
  136008. int nBytes; /* size of the input */
  136009. int iOffset; /* current position in pInput */
  136010. int iToken; /* index of next token to be returned */
  136011. char *pToken; /* storage for current token */
  136012. int nTokenAllocated; /* space allocated to zToken buffer */
  136013. } simple_tokenizer_cursor;
  136014. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  136015. return c<0x80 && t->delim[c];
  136016. }
  136017. static int fts3_isalnum(int x){
  136018. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  136019. }
  136020. /*
  136021. ** Create a new tokenizer instance.
  136022. */
  136023. static int simpleCreate(
  136024. int argc, const char * const *argv,
  136025. sqlite3_tokenizer **ppTokenizer
  136026. ){
  136027. simple_tokenizer *t;
  136028. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  136029. if( t==NULL ) return SQLITE_NOMEM;
  136030. memset(t, 0, sizeof(*t));
  136031. /* TODO(shess) Delimiters need to remain the same from run to run,
  136032. ** else we need to reindex. One solution would be a meta-table to
  136033. ** track such information in the database, then we'd only want this
  136034. ** information on the initial create.
  136035. */
  136036. if( argc>1 ){
  136037. int i, n = (int)strlen(argv[1]);
  136038. for(i=0; i<n; i++){
  136039. unsigned char ch = argv[1][i];
  136040. /* We explicitly don't support UTF-8 delimiters for now. */
  136041. if( ch>=0x80 ){
  136042. sqlite3_free(t);
  136043. return SQLITE_ERROR;
  136044. }
  136045. t->delim[ch] = 1;
  136046. }
  136047. } else {
  136048. /* Mark non-alphanumeric ASCII characters as delimiters */
  136049. int i;
  136050. for(i=1; i<0x80; i++){
  136051. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  136052. }
  136053. }
  136054. *ppTokenizer = &t->base;
  136055. return SQLITE_OK;
  136056. }
  136057. /*
  136058. ** Destroy a tokenizer
  136059. */
  136060. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  136061. sqlite3_free(pTokenizer);
  136062. return SQLITE_OK;
  136063. }
  136064. /*
  136065. ** Prepare to begin tokenizing a particular string. The input
  136066. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  136067. ** used to incrementally tokenize this string is returned in
  136068. ** *ppCursor.
  136069. */
  136070. static int simpleOpen(
  136071. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  136072. const char *pInput, int nBytes, /* String to be tokenized */
  136073. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  136074. ){
  136075. simple_tokenizer_cursor *c;
  136076. UNUSED_PARAMETER(pTokenizer);
  136077. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  136078. if( c==NULL ) return SQLITE_NOMEM;
  136079. c->pInput = pInput;
  136080. if( pInput==0 ){
  136081. c->nBytes = 0;
  136082. }else if( nBytes<0 ){
  136083. c->nBytes = (int)strlen(pInput);
  136084. }else{
  136085. c->nBytes = nBytes;
  136086. }
  136087. c->iOffset = 0; /* start tokenizing at the beginning */
  136088. c->iToken = 0;
  136089. c->pToken = NULL; /* no space allocated, yet. */
  136090. c->nTokenAllocated = 0;
  136091. *ppCursor = &c->base;
  136092. return SQLITE_OK;
  136093. }
  136094. /*
  136095. ** Close a tokenization cursor previously opened by a call to
  136096. ** simpleOpen() above.
  136097. */
  136098. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  136099. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  136100. sqlite3_free(c->pToken);
  136101. sqlite3_free(c);
  136102. return SQLITE_OK;
  136103. }
  136104. /*
  136105. ** Extract the next token from a tokenization cursor. The cursor must
  136106. ** have been opened by a prior call to simpleOpen().
  136107. */
  136108. static int simpleNext(
  136109. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  136110. const char **ppToken, /* OUT: *ppToken is the token text */
  136111. int *pnBytes, /* OUT: Number of bytes in token */
  136112. int *piStartOffset, /* OUT: Starting offset of token */
  136113. int *piEndOffset, /* OUT: Ending offset of token */
  136114. int *piPosition /* OUT: Position integer of token */
  136115. ){
  136116. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  136117. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  136118. unsigned char *p = (unsigned char *)c->pInput;
  136119. while( c->iOffset<c->nBytes ){
  136120. int iStartOffset;
  136121. /* Scan past delimiter characters */
  136122. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  136123. c->iOffset++;
  136124. }
  136125. /* Count non-delimiter characters. */
  136126. iStartOffset = c->iOffset;
  136127. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  136128. c->iOffset++;
  136129. }
  136130. if( c->iOffset>iStartOffset ){
  136131. int i, n = c->iOffset-iStartOffset;
  136132. if( n>c->nTokenAllocated ){
  136133. char *pNew;
  136134. c->nTokenAllocated = n+20;
  136135. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  136136. if( !pNew ) return SQLITE_NOMEM;
  136137. c->pToken = pNew;
  136138. }
  136139. for(i=0; i<n; i++){
  136140. /* TODO(shess) This needs expansion to handle UTF-8
  136141. ** case-insensitivity.
  136142. */
  136143. unsigned char ch = p[iStartOffset+i];
  136144. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  136145. }
  136146. *ppToken = c->pToken;
  136147. *pnBytes = n;
  136148. *piStartOffset = iStartOffset;
  136149. *piEndOffset = c->iOffset;
  136150. *piPosition = c->iToken++;
  136151. return SQLITE_OK;
  136152. }
  136153. }
  136154. return SQLITE_DONE;
  136155. }
  136156. /*
  136157. ** The set of routines that implement the simple tokenizer
  136158. */
  136159. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  136160. 0,
  136161. simpleCreate,
  136162. simpleDestroy,
  136163. simpleOpen,
  136164. simpleClose,
  136165. simpleNext,
  136166. 0,
  136167. };
  136168. /*
  136169. ** Allocate a new simple tokenizer. Return a pointer to the new
  136170. ** tokenizer in *ppModule
  136171. */
  136172. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  136173. sqlite3_tokenizer_module const**ppModule
  136174. ){
  136175. *ppModule = &simpleTokenizerModule;
  136176. }
  136177. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136178. /************** End of fts3_tokenizer1.c *************************************/
  136179. /************** Begin file fts3_tokenize_vtab.c ******************************/
  136180. /*
  136181. ** 2013 Apr 22
  136182. **
  136183. ** The author disclaims copyright to this source code. In place of
  136184. ** a legal notice, here is a blessing:
  136185. **
  136186. ** May you do good and not evil.
  136187. ** May you find forgiveness for yourself and forgive others.
  136188. ** May you share freely, never taking more than you give.
  136189. **
  136190. ******************************************************************************
  136191. **
  136192. ** This file contains code for the "fts3tokenize" virtual table module.
  136193. ** An fts3tokenize virtual table is created as follows:
  136194. **
  136195. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  136196. ** <tokenizer-name>, <arg-1>, ...
  136197. ** );
  136198. **
  136199. ** The table created has the following schema:
  136200. **
  136201. ** CREATE TABLE <tbl>(input, token, start, end, position)
  136202. **
  136203. ** When queried, the query must include a WHERE clause of type:
  136204. **
  136205. ** input = <string>
  136206. **
  136207. ** The virtual table module tokenizes this <string>, using the FTS3
  136208. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  136209. ** statement and returns one row for each token in the result. With
  136210. ** fields set as follows:
  136211. **
  136212. ** input: Always set to a copy of <string>
  136213. ** token: A token from the input.
  136214. ** start: Byte offset of the token within the input <string>.
  136215. ** end: Byte offset of the byte immediately following the end of the
  136216. ** token within the input string.
  136217. ** pos: Token offset of token within input.
  136218. **
  136219. */
  136220. /* #include "fts3Int.h" */
  136221. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136222. /* #include <string.h> */
  136223. /* #include <assert.h> */
  136224. typedef struct Fts3tokTable Fts3tokTable;
  136225. typedef struct Fts3tokCursor Fts3tokCursor;
  136226. /*
  136227. ** Virtual table structure.
  136228. */
  136229. struct Fts3tokTable {
  136230. sqlite3_vtab base; /* Base class used by SQLite core */
  136231. const sqlite3_tokenizer_module *pMod;
  136232. sqlite3_tokenizer *pTok;
  136233. };
  136234. /*
  136235. ** Virtual table cursor structure.
  136236. */
  136237. struct Fts3tokCursor {
  136238. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  136239. char *zInput; /* Input string */
  136240. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  136241. int iRowid; /* Current 'rowid' value */
  136242. const char *zToken; /* Current 'token' value */
  136243. int nToken; /* Size of zToken in bytes */
  136244. int iStart; /* Current 'start' value */
  136245. int iEnd; /* Current 'end' value */
  136246. int iPos; /* Current 'pos' value */
  136247. };
  136248. /*
  136249. ** Query FTS for the tokenizer implementation named zName.
  136250. */
  136251. static int fts3tokQueryTokenizer(
  136252. Fts3Hash *pHash,
  136253. const char *zName,
  136254. const sqlite3_tokenizer_module **pp,
  136255. char **pzErr
  136256. ){
  136257. sqlite3_tokenizer_module *p;
  136258. int nName = (int)strlen(zName);
  136259. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  136260. if( !p ){
  136261. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  136262. return SQLITE_ERROR;
  136263. }
  136264. *pp = p;
  136265. return SQLITE_OK;
  136266. }
  136267. /*
  136268. ** The second argument, argv[], is an array of pointers to nul-terminated
  136269. ** strings. This function makes a copy of the array and strings into a
  136270. ** single block of memory. It then dequotes any of the strings that appear
  136271. ** to be quoted.
  136272. **
  136273. ** If successful, output parameter *pazDequote is set to point at the
  136274. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  136275. ** responsible for eventually calling sqlite3_free() to free the array
  136276. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  136277. ** The final value of *pazDequote is undefined in this case.
  136278. */
  136279. static int fts3tokDequoteArray(
  136280. int argc, /* Number of elements in argv[] */
  136281. const char * const *argv, /* Input array */
  136282. char ***pazDequote /* Output array */
  136283. ){
  136284. int rc = SQLITE_OK; /* Return code */
  136285. if( argc==0 ){
  136286. *pazDequote = 0;
  136287. }else{
  136288. int i;
  136289. int nByte = 0;
  136290. char **azDequote;
  136291. for(i=0; i<argc; i++){
  136292. nByte += (int)(strlen(argv[i]) + 1);
  136293. }
  136294. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  136295. if( azDequote==0 ){
  136296. rc = SQLITE_NOMEM;
  136297. }else{
  136298. char *pSpace = (char *)&azDequote[argc];
  136299. for(i=0; i<argc; i++){
  136300. int n = (int)strlen(argv[i]);
  136301. azDequote[i] = pSpace;
  136302. memcpy(pSpace, argv[i], n+1);
  136303. sqlite3Fts3Dequote(pSpace);
  136304. pSpace += (n+1);
  136305. }
  136306. }
  136307. }
  136308. return rc;
  136309. }
  136310. /*
  136311. ** Schema of the tokenizer table.
  136312. */
  136313. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  136314. /*
  136315. ** This function does all the work for both the xConnect and xCreate methods.
  136316. ** These tables have no persistent representation of their own, so xConnect
  136317. ** and xCreate are identical operations.
  136318. **
  136319. ** argv[0]: module name
  136320. ** argv[1]: database name
  136321. ** argv[2]: table name
  136322. ** argv[3]: first argument (tokenizer name)
  136323. */
  136324. static int fts3tokConnectMethod(
  136325. sqlite3 *db, /* Database connection */
  136326. void *pHash, /* Hash table of tokenizers */
  136327. int argc, /* Number of elements in argv array */
  136328. const char * const *argv, /* xCreate/xConnect argument array */
  136329. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  136330. char **pzErr /* OUT: sqlite3_malloc'd error message */
  136331. ){
  136332. Fts3tokTable *pTab = 0;
  136333. const sqlite3_tokenizer_module *pMod = 0;
  136334. sqlite3_tokenizer *pTok = 0;
  136335. int rc;
  136336. char **azDequote = 0;
  136337. int nDequote;
  136338. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  136339. if( rc!=SQLITE_OK ) return rc;
  136340. nDequote = argc-3;
  136341. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  136342. if( rc==SQLITE_OK ){
  136343. const char *zModule;
  136344. if( nDequote<1 ){
  136345. zModule = "simple";
  136346. }else{
  136347. zModule = azDequote[0];
  136348. }
  136349. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  136350. }
  136351. assert( (rc==SQLITE_OK)==(pMod!=0) );
  136352. if( rc==SQLITE_OK ){
  136353. const char * const *azArg = (const char * const *)&azDequote[1];
  136354. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  136355. }
  136356. if( rc==SQLITE_OK ){
  136357. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  136358. if( pTab==0 ){
  136359. rc = SQLITE_NOMEM;
  136360. }
  136361. }
  136362. if( rc==SQLITE_OK ){
  136363. memset(pTab, 0, sizeof(Fts3tokTable));
  136364. pTab->pMod = pMod;
  136365. pTab->pTok = pTok;
  136366. *ppVtab = &pTab->base;
  136367. }else{
  136368. if( pTok ){
  136369. pMod->xDestroy(pTok);
  136370. }
  136371. }
  136372. sqlite3_free(azDequote);
  136373. return rc;
  136374. }
  136375. /*
  136376. ** This function does the work for both the xDisconnect and xDestroy methods.
  136377. ** These tables have no persistent representation of their own, so xDisconnect
  136378. ** and xDestroy are identical operations.
  136379. */
  136380. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  136381. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  136382. pTab->pMod->xDestroy(pTab->pTok);
  136383. sqlite3_free(pTab);
  136384. return SQLITE_OK;
  136385. }
  136386. /*
  136387. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  136388. */
  136389. static int fts3tokBestIndexMethod(
  136390. sqlite3_vtab *pVTab,
  136391. sqlite3_index_info *pInfo
  136392. ){
  136393. int i;
  136394. UNUSED_PARAMETER(pVTab);
  136395. for(i=0; i<pInfo->nConstraint; i++){
  136396. if( pInfo->aConstraint[i].usable
  136397. && pInfo->aConstraint[i].iColumn==0
  136398. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  136399. ){
  136400. pInfo->idxNum = 1;
  136401. pInfo->aConstraintUsage[i].argvIndex = 1;
  136402. pInfo->aConstraintUsage[i].omit = 1;
  136403. pInfo->estimatedCost = 1;
  136404. return SQLITE_OK;
  136405. }
  136406. }
  136407. pInfo->idxNum = 0;
  136408. assert( pInfo->estimatedCost>1000000.0 );
  136409. return SQLITE_OK;
  136410. }
  136411. /*
  136412. ** xOpen - Open a cursor.
  136413. */
  136414. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  136415. Fts3tokCursor *pCsr;
  136416. UNUSED_PARAMETER(pVTab);
  136417. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  136418. if( pCsr==0 ){
  136419. return SQLITE_NOMEM;
  136420. }
  136421. memset(pCsr, 0, sizeof(Fts3tokCursor));
  136422. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  136423. return SQLITE_OK;
  136424. }
  136425. /*
  136426. ** Reset the tokenizer cursor passed as the only argument. As if it had
  136427. ** just been returned by fts3tokOpenMethod().
  136428. */
  136429. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  136430. if( pCsr->pCsr ){
  136431. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  136432. pTab->pMod->xClose(pCsr->pCsr);
  136433. pCsr->pCsr = 0;
  136434. }
  136435. sqlite3_free(pCsr->zInput);
  136436. pCsr->zInput = 0;
  136437. pCsr->zToken = 0;
  136438. pCsr->nToken = 0;
  136439. pCsr->iStart = 0;
  136440. pCsr->iEnd = 0;
  136441. pCsr->iPos = 0;
  136442. pCsr->iRowid = 0;
  136443. }
  136444. /*
  136445. ** xClose - Close a cursor.
  136446. */
  136447. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  136448. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136449. fts3tokResetCursor(pCsr);
  136450. sqlite3_free(pCsr);
  136451. return SQLITE_OK;
  136452. }
  136453. /*
  136454. ** xNext - Advance the cursor to the next row, if any.
  136455. */
  136456. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  136457. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136458. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  136459. int rc; /* Return code */
  136460. pCsr->iRowid++;
  136461. rc = pTab->pMod->xNext(pCsr->pCsr,
  136462. &pCsr->zToken, &pCsr->nToken,
  136463. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  136464. );
  136465. if( rc!=SQLITE_OK ){
  136466. fts3tokResetCursor(pCsr);
  136467. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  136468. }
  136469. return rc;
  136470. }
  136471. /*
  136472. ** xFilter - Initialize a cursor to point at the start of its data.
  136473. */
  136474. static int fts3tokFilterMethod(
  136475. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  136476. int idxNum, /* Strategy index */
  136477. const char *idxStr, /* Unused */
  136478. int nVal, /* Number of elements in apVal */
  136479. sqlite3_value **apVal /* Arguments for the indexing scheme */
  136480. ){
  136481. int rc = SQLITE_ERROR;
  136482. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136483. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  136484. UNUSED_PARAMETER(idxStr);
  136485. UNUSED_PARAMETER(nVal);
  136486. fts3tokResetCursor(pCsr);
  136487. if( idxNum==1 ){
  136488. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  136489. int nByte = sqlite3_value_bytes(apVal[0]);
  136490. pCsr->zInput = sqlite3_malloc(nByte+1);
  136491. if( pCsr->zInput==0 ){
  136492. rc = SQLITE_NOMEM;
  136493. }else{
  136494. memcpy(pCsr->zInput, zByte, nByte);
  136495. pCsr->zInput[nByte] = 0;
  136496. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  136497. if( rc==SQLITE_OK ){
  136498. pCsr->pCsr->pTokenizer = pTab->pTok;
  136499. }
  136500. }
  136501. }
  136502. if( rc!=SQLITE_OK ) return rc;
  136503. return fts3tokNextMethod(pCursor);
  136504. }
  136505. /*
  136506. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  136507. */
  136508. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  136509. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136510. return (pCsr->zToken==0);
  136511. }
  136512. /*
  136513. ** xColumn - Return a column value.
  136514. */
  136515. static int fts3tokColumnMethod(
  136516. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  136517. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  136518. int iCol /* Index of column to read value from */
  136519. ){
  136520. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136521. /* CREATE TABLE x(input, token, start, end, position) */
  136522. switch( iCol ){
  136523. case 0:
  136524. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  136525. break;
  136526. case 1:
  136527. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  136528. break;
  136529. case 2:
  136530. sqlite3_result_int(pCtx, pCsr->iStart);
  136531. break;
  136532. case 3:
  136533. sqlite3_result_int(pCtx, pCsr->iEnd);
  136534. break;
  136535. default:
  136536. assert( iCol==4 );
  136537. sqlite3_result_int(pCtx, pCsr->iPos);
  136538. break;
  136539. }
  136540. return SQLITE_OK;
  136541. }
  136542. /*
  136543. ** xRowid - Return the current rowid for the cursor.
  136544. */
  136545. static int fts3tokRowidMethod(
  136546. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  136547. sqlite_int64 *pRowid /* OUT: Rowid value */
  136548. ){
  136549. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  136550. *pRowid = (sqlite3_int64)pCsr->iRowid;
  136551. return SQLITE_OK;
  136552. }
  136553. /*
  136554. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  136555. ** if successful or an error code if sqlite3_create_module() fails.
  136556. */
  136557. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  136558. static const sqlite3_module fts3tok_module = {
  136559. 0, /* iVersion */
  136560. fts3tokConnectMethod, /* xCreate */
  136561. fts3tokConnectMethod, /* xConnect */
  136562. fts3tokBestIndexMethod, /* xBestIndex */
  136563. fts3tokDisconnectMethod, /* xDisconnect */
  136564. fts3tokDisconnectMethod, /* xDestroy */
  136565. fts3tokOpenMethod, /* xOpen */
  136566. fts3tokCloseMethod, /* xClose */
  136567. fts3tokFilterMethod, /* xFilter */
  136568. fts3tokNextMethod, /* xNext */
  136569. fts3tokEofMethod, /* xEof */
  136570. fts3tokColumnMethod, /* xColumn */
  136571. fts3tokRowidMethod, /* xRowid */
  136572. 0, /* xUpdate */
  136573. 0, /* xBegin */
  136574. 0, /* xSync */
  136575. 0, /* xCommit */
  136576. 0, /* xRollback */
  136577. 0, /* xFindFunction */
  136578. 0, /* xRename */
  136579. 0, /* xSavepoint */
  136580. 0, /* xRelease */
  136581. 0 /* xRollbackTo */
  136582. };
  136583. int rc; /* Return code */
  136584. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  136585. return rc;
  136586. }
  136587. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136588. /************** End of fts3_tokenize_vtab.c **********************************/
  136589. /************** Begin file fts3_write.c **************************************/
  136590. /*
  136591. ** 2009 Oct 23
  136592. **
  136593. ** The author disclaims copyright to this source code. In place of
  136594. ** a legal notice, here is a blessing:
  136595. **
  136596. ** May you do good and not evil.
  136597. ** May you find forgiveness for yourself and forgive others.
  136598. ** May you share freely, never taking more than you give.
  136599. **
  136600. ******************************************************************************
  136601. **
  136602. ** This file is part of the SQLite FTS3 extension module. Specifically,
  136603. ** this file contains code to insert, update and delete rows from FTS3
  136604. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  136605. ** of the sub-routines used to merge segments are also used by the query
  136606. ** code in fts3.c.
  136607. */
  136608. /* #include "fts3Int.h" */
  136609. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136610. /* #include <string.h> */
  136611. /* #include <assert.h> */
  136612. /* #include <stdlib.h> */
  136613. #define FTS_MAX_APPENDABLE_HEIGHT 16
  136614. /*
  136615. ** When full-text index nodes are loaded from disk, the buffer that they
  136616. ** are loaded into has the following number of bytes of padding at the end
  136617. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  136618. ** of 920 bytes is allocated for it.
  136619. **
  136620. ** This means that if we have a pointer into a buffer containing node data,
  136621. ** it is always safe to read up to two varints from it without risking an
  136622. ** overread, even if the node data is corrupted.
  136623. */
  136624. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  136625. /*
  136626. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  136627. ** memory incrementally instead of all at once. This can be a big performance
  136628. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  136629. ** method before retrieving all query results (as may happen, for example,
  136630. ** if a query has a LIMIT clause).
  136631. **
  136632. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  136633. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  136634. ** The code is written so that the hard lower-limit for each of these values
  136635. ** is 1. Clearly such small values would be inefficient, but can be useful
  136636. ** for testing purposes.
  136637. **
  136638. ** If this module is built with SQLITE_TEST defined, these constants may
  136639. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  136640. ** a Tcl interface to read and write the values.
  136641. */
  136642. #ifdef SQLITE_TEST
  136643. int test_fts3_node_chunksize = (4*1024);
  136644. int test_fts3_node_chunk_threshold = (4*1024)*4;
  136645. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  136646. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  136647. #else
  136648. # define FTS3_NODE_CHUNKSIZE (4*1024)
  136649. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  136650. #endif
  136651. /*
  136652. ** The two values that may be meaningfully bound to the :1 parameter in
  136653. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  136654. */
  136655. #define FTS_STAT_DOCTOTAL 0
  136656. #define FTS_STAT_INCRMERGEHINT 1
  136657. #define FTS_STAT_AUTOINCRMERGE 2
  136658. /*
  136659. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  136660. ** and incremental merge operation that takes place. This is used for
  136661. ** debugging FTS only, it should not usually be turned on in production
  136662. ** systems.
  136663. */
  136664. #ifdef FTS3_LOG_MERGES
  136665. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  136666. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  136667. }
  136668. #else
  136669. #define fts3LogMerge(x, y)
  136670. #endif
  136671. typedef struct PendingList PendingList;
  136672. typedef struct SegmentNode SegmentNode;
  136673. typedef struct SegmentWriter SegmentWriter;
  136674. /*
  136675. ** An instance of the following data structure is used to build doclists
  136676. ** incrementally. See function fts3PendingListAppend() for details.
  136677. */
  136678. struct PendingList {
  136679. int nData;
  136680. char *aData;
  136681. int nSpace;
  136682. sqlite3_int64 iLastDocid;
  136683. sqlite3_int64 iLastCol;
  136684. sqlite3_int64 iLastPos;
  136685. };
  136686. /*
  136687. ** Each cursor has a (possibly empty) linked list of the following objects.
  136688. */
  136689. struct Fts3DeferredToken {
  136690. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  136691. int iCol; /* Column token must occur in */
  136692. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  136693. PendingList *pList; /* Doclist is assembled here */
  136694. };
  136695. /*
  136696. ** An instance of this structure is used to iterate through the terms on
  136697. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  136698. ** this structure are only manipulated by code in this file, opaque handles
  136699. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  136700. ** terms when querying the full-text index. See functions:
  136701. **
  136702. ** sqlite3Fts3SegReaderNew()
  136703. ** sqlite3Fts3SegReaderFree()
  136704. ** sqlite3Fts3SegReaderIterate()
  136705. **
  136706. ** Methods used to manipulate Fts3SegReader structures:
  136707. **
  136708. ** fts3SegReaderNext()
  136709. ** fts3SegReaderFirstDocid()
  136710. ** fts3SegReaderNextDocid()
  136711. */
  136712. struct Fts3SegReader {
  136713. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  136714. u8 bLookup; /* True for a lookup only */
  136715. u8 rootOnly; /* True for a root-only reader */
  136716. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  136717. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  136718. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  136719. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  136720. char *aNode; /* Pointer to node data (or NULL) */
  136721. int nNode; /* Size of buffer at aNode (or 0) */
  136722. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  136723. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  136724. Fts3HashElem **ppNextElem;
  136725. /* Variables set by fts3SegReaderNext(). These may be read directly
  136726. ** by the caller. They are valid from the time SegmentReaderNew() returns
  136727. ** until SegmentReaderNext() returns something other than SQLITE_OK
  136728. ** (i.e. SQLITE_DONE).
  136729. */
  136730. int nTerm; /* Number of bytes in current term */
  136731. char *zTerm; /* Pointer to current term */
  136732. int nTermAlloc; /* Allocated size of zTerm buffer */
  136733. char *aDoclist; /* Pointer to doclist of current entry */
  136734. int nDoclist; /* Size of doclist in current entry */
  136735. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  136736. ** through the current doclist (aDoclist/nDoclist).
  136737. */
  136738. char *pOffsetList;
  136739. int nOffsetList; /* For descending pending seg-readers only */
  136740. sqlite3_int64 iDocid;
  136741. };
  136742. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  136743. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  136744. /*
  136745. ** An instance of this structure is used to create a segment b-tree in the
  136746. ** database. The internal details of this type are only accessed by the
  136747. ** following functions:
  136748. **
  136749. ** fts3SegWriterAdd()
  136750. ** fts3SegWriterFlush()
  136751. ** fts3SegWriterFree()
  136752. */
  136753. struct SegmentWriter {
  136754. SegmentNode *pTree; /* Pointer to interior tree structure */
  136755. sqlite3_int64 iFirst; /* First slot in %_segments written */
  136756. sqlite3_int64 iFree; /* Next free slot in %_segments */
  136757. char *zTerm; /* Pointer to previous term buffer */
  136758. int nTerm; /* Number of bytes in zTerm */
  136759. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  136760. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  136761. int nSize; /* Size of allocation at aData */
  136762. int nData; /* Bytes of data in aData */
  136763. char *aData; /* Pointer to block from malloc() */
  136764. i64 nLeafData; /* Number of bytes of leaf data written */
  136765. };
  136766. /*
  136767. ** Type SegmentNode is used by the following three functions to create
  136768. ** the interior part of the segment b+-tree structures (everything except
  136769. ** the leaf nodes). These functions and type are only ever used by code
  136770. ** within the fts3SegWriterXXX() family of functions described above.
  136771. **
  136772. ** fts3NodeAddTerm()
  136773. ** fts3NodeWrite()
  136774. ** fts3NodeFree()
  136775. **
  136776. ** When a b+tree is written to the database (either as a result of a merge
  136777. ** or the pending-terms table being flushed), leaves are written into the
  136778. ** database file as soon as they are completely populated. The interior of
  136779. ** the tree is assembled in memory and written out only once all leaves have
  136780. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  136781. ** very large, meaning that the interior of the tree consumes relatively
  136782. ** little memory.
  136783. */
  136784. struct SegmentNode {
  136785. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  136786. SegmentNode *pRight; /* Pointer to right-sibling */
  136787. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  136788. int nEntry; /* Number of terms written to node so far */
  136789. char *zTerm; /* Pointer to previous term buffer */
  136790. int nTerm; /* Number of bytes in zTerm */
  136791. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  136792. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  136793. int nData; /* Bytes of valid data so far */
  136794. char *aData; /* Node data */
  136795. };
  136796. /*
  136797. ** Valid values for the second argument to fts3SqlStmt().
  136798. */
  136799. #define SQL_DELETE_CONTENT 0
  136800. #define SQL_IS_EMPTY 1
  136801. #define SQL_DELETE_ALL_CONTENT 2
  136802. #define SQL_DELETE_ALL_SEGMENTS 3
  136803. #define SQL_DELETE_ALL_SEGDIR 4
  136804. #define SQL_DELETE_ALL_DOCSIZE 5
  136805. #define SQL_DELETE_ALL_STAT 6
  136806. #define SQL_SELECT_CONTENT_BY_ROWID 7
  136807. #define SQL_NEXT_SEGMENT_INDEX 8
  136808. #define SQL_INSERT_SEGMENTS 9
  136809. #define SQL_NEXT_SEGMENTS_ID 10
  136810. #define SQL_INSERT_SEGDIR 11
  136811. #define SQL_SELECT_LEVEL 12
  136812. #define SQL_SELECT_LEVEL_RANGE 13
  136813. #define SQL_SELECT_LEVEL_COUNT 14
  136814. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  136815. #define SQL_DELETE_SEGDIR_LEVEL 16
  136816. #define SQL_DELETE_SEGMENTS_RANGE 17
  136817. #define SQL_CONTENT_INSERT 18
  136818. #define SQL_DELETE_DOCSIZE 19
  136819. #define SQL_REPLACE_DOCSIZE 20
  136820. #define SQL_SELECT_DOCSIZE 21
  136821. #define SQL_SELECT_STAT 22
  136822. #define SQL_REPLACE_STAT 23
  136823. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  136824. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  136825. #define SQL_DELETE_SEGDIR_RANGE 26
  136826. #define SQL_SELECT_ALL_LANGID 27
  136827. #define SQL_FIND_MERGE_LEVEL 28
  136828. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  136829. #define SQL_DELETE_SEGDIR_ENTRY 30
  136830. #define SQL_SHIFT_SEGDIR_ENTRY 31
  136831. #define SQL_SELECT_SEGDIR 32
  136832. #define SQL_CHOMP_SEGDIR 33
  136833. #define SQL_SEGMENT_IS_APPENDABLE 34
  136834. #define SQL_SELECT_INDEXES 35
  136835. #define SQL_SELECT_MXLEVEL 36
  136836. #define SQL_SELECT_LEVEL_RANGE2 37
  136837. #define SQL_UPDATE_LEVEL_IDX 38
  136838. #define SQL_UPDATE_LEVEL 39
  136839. /*
  136840. ** This function is used to obtain an SQLite prepared statement handle
  136841. ** for the statement identified by the second argument. If successful,
  136842. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  136843. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  136844. **
  136845. ** If argument apVal is not NULL, then it must point to an array with
  136846. ** at least as many entries as the requested statement has bound
  136847. ** parameters. The values are bound to the statements parameters before
  136848. ** returning.
  136849. */
  136850. static int fts3SqlStmt(
  136851. Fts3Table *p, /* Virtual table handle */
  136852. int eStmt, /* One of the SQL_XXX constants above */
  136853. sqlite3_stmt **pp, /* OUT: Statement handle */
  136854. sqlite3_value **apVal /* Values to bind to statement */
  136855. ){
  136856. const char *azSql[] = {
  136857. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  136858. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  136859. /* 2 */ "DELETE FROM %Q.'%q_content'",
  136860. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  136861. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  136862. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  136863. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  136864. /* 7 */ "SELECT %s WHERE rowid=?",
  136865. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  136866. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  136867. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  136868. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  136869. /* Return segments in order from oldest to newest.*/
  136870. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  136871. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  136872. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  136873. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  136874. "ORDER BY level DESC, idx ASC",
  136875. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  136876. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  136877. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  136878. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  136879. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  136880. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  136881. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  136882. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  136883. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  136884. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  136885. /* 24 */ "",
  136886. /* 25 */ "",
  136887. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  136888. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  136889. /* This statement is used to determine which level to read the input from
  136890. ** when performing an incremental merge. It returns the absolute level number
  136891. ** of the oldest level in the db that contains at least ? segments. Or,
  136892. ** if no level in the FTS index contains more than ? segments, the statement
  136893. ** returns zero rows. */
  136894. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  136895. " ORDER BY (level %% 1024) ASC LIMIT 1",
  136896. /* Estimate the upper limit on the number of leaf nodes in a new segment
  136897. ** created by merging the oldest :2 segments from absolute level :1. See
  136898. ** function sqlite3Fts3Incrmerge() for details. */
  136899. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  136900. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  136901. /* SQL_DELETE_SEGDIR_ENTRY
  136902. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  136903. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  136904. /* SQL_SHIFT_SEGDIR_ENTRY
  136905. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  136906. ** to :1. */
  136907. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  136908. /* SQL_SELECT_SEGDIR
  136909. ** Read a single entry from the %_segdir table. The entry from absolute
  136910. ** level :1 with index value :2. */
  136911. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  136912. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  136913. /* SQL_CHOMP_SEGDIR
  136914. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  136915. ** entry located on absolute level :3 with index :4. */
  136916. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  136917. "WHERE level = ? AND idx = ?",
  136918. /* SQL_SEGMENT_IS_APPENDABLE
  136919. ** Return a single row if the segment with end_block=? is appendable. Or
  136920. ** no rows otherwise. */
  136921. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  136922. /* SQL_SELECT_INDEXES
  136923. ** Return the list of valid segment indexes for absolute level ? */
  136924. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  136925. /* SQL_SELECT_MXLEVEL
  136926. ** Return the largest relative level in the FTS index or indexes. */
  136927. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  136928. /* Return segments in order from oldest to newest.*/
  136929. /* 37 */ "SELECT level, idx, end_block "
  136930. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  136931. "ORDER BY level DESC, idx ASC",
  136932. /* Update statements used while promoting segments */
  136933. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  136934. "WHERE level=? AND idx=?",
  136935. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  136936. };
  136937. int rc = SQLITE_OK;
  136938. sqlite3_stmt *pStmt;
  136939. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  136940. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  136941. pStmt = p->aStmt[eStmt];
  136942. if( !pStmt ){
  136943. char *zSql;
  136944. if( eStmt==SQL_CONTENT_INSERT ){
  136945. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  136946. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  136947. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  136948. }else{
  136949. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  136950. }
  136951. if( !zSql ){
  136952. rc = SQLITE_NOMEM;
  136953. }else{
  136954. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  136955. sqlite3_free(zSql);
  136956. assert( rc==SQLITE_OK || pStmt==0 );
  136957. p->aStmt[eStmt] = pStmt;
  136958. }
  136959. }
  136960. if( apVal ){
  136961. int i;
  136962. int nParam = sqlite3_bind_parameter_count(pStmt);
  136963. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  136964. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  136965. }
  136966. }
  136967. *pp = pStmt;
  136968. return rc;
  136969. }
  136970. static int fts3SelectDocsize(
  136971. Fts3Table *pTab, /* FTS3 table handle */
  136972. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  136973. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  136974. ){
  136975. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  136976. int rc; /* Return code */
  136977. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  136978. if( rc==SQLITE_OK ){
  136979. sqlite3_bind_int64(pStmt, 1, iDocid);
  136980. rc = sqlite3_step(pStmt);
  136981. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  136982. rc = sqlite3_reset(pStmt);
  136983. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  136984. pStmt = 0;
  136985. }else{
  136986. rc = SQLITE_OK;
  136987. }
  136988. }
  136989. *ppStmt = pStmt;
  136990. return rc;
  136991. }
  136992. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  136993. Fts3Table *pTab, /* Fts3 table handle */
  136994. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  136995. ){
  136996. sqlite3_stmt *pStmt = 0;
  136997. int rc;
  136998. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  136999. if( rc==SQLITE_OK ){
  137000. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  137001. if( sqlite3_step(pStmt)!=SQLITE_ROW
  137002. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  137003. ){
  137004. rc = sqlite3_reset(pStmt);
  137005. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  137006. pStmt = 0;
  137007. }
  137008. }
  137009. *ppStmt = pStmt;
  137010. return rc;
  137011. }
  137012. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  137013. Fts3Table *pTab, /* Fts3 table handle */
  137014. sqlite3_int64 iDocid, /* Docid to read size data for */
  137015. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  137016. ){
  137017. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  137018. }
  137019. /*
  137020. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  137021. ** array apVal[] to the SQL statement identified by eStmt, the statement
  137022. ** is executed.
  137023. **
  137024. ** Returns SQLITE_OK if the statement is successfully executed, or an
  137025. ** SQLite error code otherwise.
  137026. */
  137027. static void fts3SqlExec(
  137028. int *pRC, /* Result code */
  137029. Fts3Table *p, /* The FTS3 table */
  137030. int eStmt, /* Index of statement to evaluate */
  137031. sqlite3_value **apVal /* Parameters to bind */
  137032. ){
  137033. sqlite3_stmt *pStmt;
  137034. int rc;
  137035. if( *pRC ) return;
  137036. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  137037. if( rc==SQLITE_OK ){
  137038. sqlite3_step(pStmt);
  137039. rc = sqlite3_reset(pStmt);
  137040. }
  137041. *pRC = rc;
  137042. }
  137043. /*
  137044. ** This function ensures that the caller has obtained an exclusive
  137045. ** shared-cache table-lock on the %_segdir table. This is required before
  137046. ** writing data to the fts3 table. If this lock is not acquired first, then
  137047. ** the caller may end up attempting to take this lock as part of committing
  137048. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  137049. ** LOCKED_SHAREDCACHEto a COMMIT command.
  137050. **
  137051. ** It is best to avoid this because if FTS3 returns any error when
  137052. ** committing a transaction, the whole transaction will be rolled back.
  137053. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  137054. ** It can still happen if the user locks the underlying tables directly
  137055. ** instead of accessing them via FTS.
  137056. */
  137057. static int fts3Writelock(Fts3Table *p){
  137058. int rc = SQLITE_OK;
  137059. if( p->nPendingData==0 ){
  137060. sqlite3_stmt *pStmt;
  137061. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  137062. if( rc==SQLITE_OK ){
  137063. sqlite3_bind_null(pStmt, 1);
  137064. sqlite3_step(pStmt);
  137065. rc = sqlite3_reset(pStmt);
  137066. }
  137067. }
  137068. return rc;
  137069. }
  137070. /*
  137071. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  137072. ** Within each language id, a separate index is maintained to store the
  137073. ** document terms, and each configured prefix size (configured the FTS
  137074. ** "prefix=" option). And each index consists of multiple levels ("relative
  137075. ** levels").
  137076. **
  137077. ** All three of these values (the language id, the specific index and the
  137078. ** level within the index) are encoded in 64-bit integer values stored
  137079. ** in the %_segdir table on disk. This function is used to convert three
  137080. ** separate component values into the single 64-bit integer value that
  137081. ** can be used to query the %_segdir table.
  137082. **
  137083. ** Specifically, each language-id/index combination is allocated 1024
  137084. ** 64-bit integer level values ("absolute levels"). The main terms index
  137085. ** for language-id 0 is allocate values 0-1023. The first prefix index
  137086. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  137087. ** Language 1 indexes are allocated immediately following language 0.
  137088. **
  137089. ** So, for a system with nPrefix prefix indexes configured, the block of
  137090. ** absolute levels that corresponds to language-id iLangid and index
  137091. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  137092. */
  137093. static sqlite3_int64 getAbsoluteLevel(
  137094. Fts3Table *p, /* FTS3 table handle */
  137095. int iLangid, /* Language id */
  137096. int iIndex, /* Index in p->aIndex[] */
  137097. int iLevel /* Level of segments */
  137098. ){
  137099. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  137100. assert( iLangid>=0 );
  137101. assert( p->nIndex>0 );
  137102. assert( iIndex>=0 && iIndex<p->nIndex );
  137103. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  137104. return iBase + iLevel;
  137105. }
  137106. /*
  137107. ** Set *ppStmt to a statement handle that may be used to iterate through
  137108. ** all rows in the %_segdir table, from oldest to newest. If successful,
  137109. ** return SQLITE_OK. If an error occurs while preparing the statement,
  137110. ** return an SQLite error code.
  137111. **
  137112. ** There is only ever one instance of this SQL statement compiled for
  137113. ** each FTS3 table.
  137114. **
  137115. ** The statement returns the following columns from the %_segdir table:
  137116. **
  137117. ** 0: idx
  137118. ** 1: start_block
  137119. ** 2: leaves_end_block
  137120. ** 3: end_block
  137121. ** 4: root
  137122. */
  137123. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  137124. Fts3Table *p, /* FTS3 table */
  137125. int iLangid, /* Language being queried */
  137126. int iIndex, /* Index for p->aIndex[] */
  137127. int iLevel, /* Level to select (relative level) */
  137128. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  137129. ){
  137130. int rc;
  137131. sqlite3_stmt *pStmt = 0;
  137132. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  137133. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  137134. assert( iIndex>=0 && iIndex<p->nIndex );
  137135. if( iLevel<0 ){
  137136. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  137137. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  137138. if( rc==SQLITE_OK ){
  137139. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  137140. sqlite3_bind_int64(pStmt, 2,
  137141. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  137142. );
  137143. }
  137144. }else{
  137145. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  137146. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  137147. if( rc==SQLITE_OK ){
  137148. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  137149. }
  137150. }
  137151. *ppStmt = pStmt;
  137152. return rc;
  137153. }
  137154. /*
  137155. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  137156. ** if successful, or an SQLite error code otherwise.
  137157. **
  137158. ** This function also serves to allocate the PendingList structure itself.
  137159. ** For example, to create a new PendingList structure containing two
  137160. ** varints:
  137161. **
  137162. ** PendingList *p = 0;
  137163. ** fts3PendingListAppendVarint(&p, 1);
  137164. ** fts3PendingListAppendVarint(&p, 2);
  137165. */
  137166. static int fts3PendingListAppendVarint(
  137167. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  137168. sqlite3_int64 i /* Value to append to data */
  137169. ){
  137170. PendingList *p = *pp;
  137171. /* Allocate or grow the PendingList as required. */
  137172. if( !p ){
  137173. p = sqlite3_malloc(sizeof(*p) + 100);
  137174. if( !p ){
  137175. return SQLITE_NOMEM;
  137176. }
  137177. p->nSpace = 100;
  137178. p->aData = (char *)&p[1];
  137179. p->nData = 0;
  137180. }
  137181. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  137182. int nNew = p->nSpace * 2;
  137183. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  137184. if( !p ){
  137185. sqlite3_free(*pp);
  137186. *pp = 0;
  137187. return SQLITE_NOMEM;
  137188. }
  137189. p->nSpace = nNew;
  137190. p->aData = (char *)&p[1];
  137191. }
  137192. /* Append the new serialized varint to the end of the list. */
  137193. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  137194. p->aData[p->nData] = '\0';
  137195. *pp = p;
  137196. return SQLITE_OK;
  137197. }
  137198. /*
  137199. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  137200. ** is returned if the structure is sqlite3_realloced as part of adding
  137201. ** the entry. Otherwise, zero.
  137202. **
  137203. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  137204. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  137205. ** it is set to SQLITE_OK.
  137206. */
  137207. static int fts3PendingListAppend(
  137208. PendingList **pp, /* IN/OUT: PendingList structure */
  137209. sqlite3_int64 iDocid, /* Docid for entry to add */
  137210. sqlite3_int64 iCol, /* Column for entry to add */
  137211. sqlite3_int64 iPos, /* Position of term for entry to add */
  137212. int *pRc /* OUT: Return code */
  137213. ){
  137214. PendingList *p = *pp;
  137215. int rc = SQLITE_OK;
  137216. assert( !p || p->iLastDocid<=iDocid );
  137217. if( !p || p->iLastDocid!=iDocid ){
  137218. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  137219. if( p ){
  137220. assert( p->nData<p->nSpace );
  137221. assert( p->aData[p->nData]==0 );
  137222. p->nData++;
  137223. }
  137224. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  137225. goto pendinglistappend_out;
  137226. }
  137227. p->iLastCol = -1;
  137228. p->iLastPos = 0;
  137229. p->iLastDocid = iDocid;
  137230. }
  137231. if( iCol>0 && p->iLastCol!=iCol ){
  137232. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  137233. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  137234. ){
  137235. goto pendinglistappend_out;
  137236. }
  137237. p->iLastCol = iCol;
  137238. p->iLastPos = 0;
  137239. }
  137240. if( iCol>=0 ){
  137241. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  137242. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  137243. if( rc==SQLITE_OK ){
  137244. p->iLastPos = iPos;
  137245. }
  137246. }
  137247. pendinglistappend_out:
  137248. *pRc = rc;
  137249. if( p!=*pp ){
  137250. *pp = p;
  137251. return 1;
  137252. }
  137253. return 0;
  137254. }
  137255. /*
  137256. ** Free a PendingList object allocated by fts3PendingListAppend().
  137257. */
  137258. static void fts3PendingListDelete(PendingList *pList){
  137259. sqlite3_free(pList);
  137260. }
  137261. /*
  137262. ** Add an entry to one of the pending-terms hash tables.
  137263. */
  137264. static int fts3PendingTermsAddOne(
  137265. Fts3Table *p,
  137266. int iCol,
  137267. int iPos,
  137268. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  137269. const char *zToken,
  137270. int nToken
  137271. ){
  137272. PendingList *pList;
  137273. int rc = SQLITE_OK;
  137274. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  137275. if( pList ){
  137276. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  137277. }
  137278. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  137279. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  137280. /* Malloc failed while inserting the new entry. This can only
  137281. ** happen if there was no previous entry for this token.
  137282. */
  137283. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  137284. sqlite3_free(pList);
  137285. rc = SQLITE_NOMEM;
  137286. }
  137287. }
  137288. if( rc==SQLITE_OK ){
  137289. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  137290. }
  137291. return rc;
  137292. }
  137293. /*
  137294. ** Tokenize the nul-terminated string zText and add all tokens to the
  137295. ** pending-terms hash-table. The docid used is that currently stored in
  137296. ** p->iPrevDocid, and the column is specified by argument iCol.
  137297. **
  137298. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  137299. */
  137300. static int fts3PendingTermsAdd(
  137301. Fts3Table *p, /* Table into which text will be inserted */
  137302. int iLangid, /* Language id to use */
  137303. const char *zText, /* Text of document to be inserted */
  137304. int iCol, /* Column into which text is being inserted */
  137305. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  137306. ){
  137307. int rc;
  137308. int iStart = 0;
  137309. int iEnd = 0;
  137310. int iPos = 0;
  137311. int nWord = 0;
  137312. char const *zToken;
  137313. int nToken = 0;
  137314. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  137315. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  137316. sqlite3_tokenizer_cursor *pCsr;
  137317. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  137318. const char**,int*,int*,int*,int*);
  137319. assert( pTokenizer && pModule );
  137320. /* If the user has inserted a NULL value, this function may be called with
  137321. ** zText==0. In this case, add zero token entries to the hash table and
  137322. ** return early. */
  137323. if( zText==0 ){
  137324. *pnWord = 0;
  137325. return SQLITE_OK;
  137326. }
  137327. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  137328. if( rc!=SQLITE_OK ){
  137329. return rc;
  137330. }
  137331. xNext = pModule->xNext;
  137332. while( SQLITE_OK==rc
  137333. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  137334. ){
  137335. int i;
  137336. if( iPos>=nWord ) nWord = iPos+1;
  137337. /* Positions cannot be negative; we use -1 as a terminator internally.
  137338. ** Tokens must have a non-zero length.
  137339. */
  137340. if( iPos<0 || !zToken || nToken<=0 ){
  137341. rc = SQLITE_ERROR;
  137342. break;
  137343. }
  137344. /* Add the term to the terms index */
  137345. rc = fts3PendingTermsAddOne(
  137346. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  137347. );
  137348. /* Add the term to each of the prefix indexes that it is not too
  137349. ** short for. */
  137350. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  137351. struct Fts3Index *pIndex = &p->aIndex[i];
  137352. if( nToken<pIndex->nPrefix ) continue;
  137353. rc = fts3PendingTermsAddOne(
  137354. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  137355. );
  137356. }
  137357. }
  137358. pModule->xClose(pCsr);
  137359. *pnWord += nWord;
  137360. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  137361. }
  137362. /*
  137363. ** Calling this function indicates that subsequent calls to
  137364. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  137365. ** contents of the document with docid iDocid.
  137366. */
  137367. static int fts3PendingTermsDocid(
  137368. Fts3Table *p, /* Full-text table handle */
  137369. int bDelete, /* True if this op is a delete */
  137370. int iLangid, /* Language id of row being written */
  137371. sqlite_int64 iDocid /* Docid of row being written */
  137372. ){
  137373. assert( iLangid>=0 );
  137374. assert( bDelete==1 || bDelete==0 );
  137375. /* TODO(shess) Explore whether partially flushing the buffer on
  137376. ** forced-flush would provide better performance. I suspect that if
  137377. ** we ordered the doclists by size and flushed the largest until the
  137378. ** buffer was half empty, that would let the less frequent terms
  137379. ** generate longer doclists.
  137380. */
  137381. if( iDocid<p->iPrevDocid
  137382. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  137383. || p->iPrevLangid!=iLangid
  137384. || p->nPendingData>p->nMaxPendingData
  137385. ){
  137386. int rc = sqlite3Fts3PendingTermsFlush(p);
  137387. if( rc!=SQLITE_OK ) return rc;
  137388. }
  137389. p->iPrevDocid = iDocid;
  137390. p->iPrevLangid = iLangid;
  137391. p->bPrevDelete = bDelete;
  137392. return SQLITE_OK;
  137393. }
  137394. /*
  137395. ** Discard the contents of the pending-terms hash tables.
  137396. */
  137397. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  137398. int i;
  137399. for(i=0; i<p->nIndex; i++){
  137400. Fts3HashElem *pElem;
  137401. Fts3Hash *pHash = &p->aIndex[i].hPending;
  137402. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  137403. PendingList *pList = (PendingList *)fts3HashData(pElem);
  137404. fts3PendingListDelete(pList);
  137405. }
  137406. fts3HashClear(pHash);
  137407. }
  137408. p->nPendingData = 0;
  137409. }
  137410. /*
  137411. ** This function is called by the xUpdate() method as part of an INSERT
  137412. ** operation. It adds entries for each term in the new record to the
  137413. ** pendingTerms hash table.
  137414. **
  137415. ** Argument apVal is the same as the similarly named argument passed to
  137416. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  137417. */
  137418. static int fts3InsertTerms(
  137419. Fts3Table *p,
  137420. int iLangid,
  137421. sqlite3_value **apVal,
  137422. u32 *aSz
  137423. ){
  137424. int i; /* Iterator variable */
  137425. for(i=2; i<p->nColumn+2; i++){
  137426. int iCol = i-2;
  137427. if( p->abNotindexed[iCol]==0 ){
  137428. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  137429. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  137430. if( rc!=SQLITE_OK ){
  137431. return rc;
  137432. }
  137433. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  137434. }
  137435. }
  137436. return SQLITE_OK;
  137437. }
  137438. /*
  137439. ** This function is called by the xUpdate() method for an INSERT operation.
  137440. ** The apVal parameter is passed a copy of the apVal argument passed by
  137441. ** SQLite to the xUpdate() method. i.e:
  137442. **
  137443. ** apVal[0] Not used for INSERT.
  137444. ** apVal[1] rowid
  137445. ** apVal[2] Left-most user-defined column
  137446. ** ...
  137447. ** apVal[p->nColumn+1] Right-most user-defined column
  137448. ** apVal[p->nColumn+2] Hidden column with same name as table
  137449. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  137450. ** apVal[p->nColumn+4] Hidden languageid column
  137451. */
  137452. static int fts3InsertData(
  137453. Fts3Table *p, /* Full-text table */
  137454. sqlite3_value **apVal, /* Array of values to insert */
  137455. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  137456. ){
  137457. int rc; /* Return code */
  137458. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  137459. if( p->zContentTbl ){
  137460. sqlite3_value *pRowid = apVal[p->nColumn+3];
  137461. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  137462. pRowid = apVal[1];
  137463. }
  137464. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  137465. return SQLITE_CONSTRAINT;
  137466. }
  137467. *piDocid = sqlite3_value_int64(pRowid);
  137468. return SQLITE_OK;
  137469. }
  137470. /* Locate the statement handle used to insert data into the %_content
  137471. ** table. The SQL for this statement is:
  137472. **
  137473. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  137474. **
  137475. ** The statement features N '?' variables, where N is the number of user
  137476. ** defined columns in the FTS3 table, plus one for the docid field.
  137477. */
  137478. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  137479. if( rc==SQLITE_OK && p->zLanguageid ){
  137480. rc = sqlite3_bind_int(
  137481. pContentInsert, p->nColumn+2,
  137482. sqlite3_value_int(apVal[p->nColumn+4])
  137483. );
  137484. }
  137485. if( rc!=SQLITE_OK ) return rc;
  137486. /* There is a quirk here. The users INSERT statement may have specified
  137487. ** a value for the "rowid" field, for the "docid" field, or for both.
  137488. ** Which is a problem, since "rowid" and "docid" are aliases for the
  137489. ** same value. For example:
  137490. **
  137491. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  137492. **
  137493. ** In FTS3, this is an error. It is an error to specify non-NULL values
  137494. ** for both docid and some other rowid alias.
  137495. */
  137496. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  137497. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  137498. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  137499. ){
  137500. /* A rowid/docid conflict. */
  137501. return SQLITE_ERROR;
  137502. }
  137503. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  137504. if( rc!=SQLITE_OK ) return rc;
  137505. }
  137506. /* Execute the statement to insert the record. Set *piDocid to the
  137507. ** new docid value.
  137508. */
  137509. sqlite3_step(pContentInsert);
  137510. rc = sqlite3_reset(pContentInsert);
  137511. *piDocid = sqlite3_last_insert_rowid(p->db);
  137512. return rc;
  137513. }
  137514. /*
  137515. ** Remove all data from the FTS3 table. Clear the hash table containing
  137516. ** pending terms.
  137517. */
  137518. static int fts3DeleteAll(Fts3Table *p, int bContent){
  137519. int rc = SQLITE_OK; /* Return code */
  137520. /* Discard the contents of the pending-terms hash table. */
  137521. sqlite3Fts3PendingTermsClear(p);
  137522. /* Delete everything from the shadow tables. Except, leave %_content as
  137523. ** is if bContent is false. */
  137524. assert( p->zContentTbl==0 || bContent==0 );
  137525. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  137526. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  137527. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  137528. if( p->bHasDocsize ){
  137529. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  137530. }
  137531. if( p->bHasStat ){
  137532. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  137533. }
  137534. return rc;
  137535. }
  137536. /*
  137537. **
  137538. */
  137539. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  137540. int iLangid = 0;
  137541. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  137542. return iLangid;
  137543. }
  137544. /*
  137545. ** The first element in the apVal[] array is assumed to contain the docid
  137546. ** (an integer) of a row about to be deleted. Remove all terms from the
  137547. ** full-text index.
  137548. */
  137549. static void fts3DeleteTerms(
  137550. int *pRC, /* Result code */
  137551. Fts3Table *p, /* The FTS table to delete from */
  137552. sqlite3_value *pRowid, /* The docid to be deleted */
  137553. u32 *aSz, /* Sizes of deleted document written here */
  137554. int *pbFound /* OUT: Set to true if row really does exist */
  137555. ){
  137556. int rc;
  137557. sqlite3_stmt *pSelect;
  137558. assert( *pbFound==0 );
  137559. if( *pRC ) return;
  137560. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  137561. if( rc==SQLITE_OK ){
  137562. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  137563. int i;
  137564. int iLangid = langidFromSelect(p, pSelect);
  137565. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  137566. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  137567. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  137568. int iCol = i-1;
  137569. if( p->abNotindexed[iCol]==0 ){
  137570. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  137571. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  137572. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  137573. }
  137574. }
  137575. if( rc!=SQLITE_OK ){
  137576. sqlite3_reset(pSelect);
  137577. *pRC = rc;
  137578. return;
  137579. }
  137580. *pbFound = 1;
  137581. }
  137582. rc = sqlite3_reset(pSelect);
  137583. }else{
  137584. sqlite3_reset(pSelect);
  137585. }
  137586. *pRC = rc;
  137587. }
  137588. /*
  137589. ** Forward declaration to account for the circular dependency between
  137590. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  137591. */
  137592. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  137593. /*
  137594. ** This function allocates a new level iLevel index in the segdir table.
  137595. ** Usually, indexes are allocated within a level sequentially starting
  137596. ** with 0, so the allocated index is one greater than the value returned
  137597. ** by:
  137598. **
  137599. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  137600. **
  137601. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  137602. ** level, they are merged into a single level (iLevel+1) segment and the
  137603. ** allocated index is 0.
  137604. **
  137605. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  137606. ** returned. Otherwise, an SQLite error code is returned.
  137607. */
  137608. static int fts3AllocateSegdirIdx(
  137609. Fts3Table *p,
  137610. int iLangid, /* Language id */
  137611. int iIndex, /* Index for p->aIndex */
  137612. int iLevel,
  137613. int *piIdx
  137614. ){
  137615. int rc; /* Return Code */
  137616. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  137617. int iNext = 0; /* Result of query pNextIdx */
  137618. assert( iLangid>=0 );
  137619. assert( p->nIndex>=1 );
  137620. /* Set variable iNext to the next available segdir index at level iLevel. */
  137621. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  137622. if( rc==SQLITE_OK ){
  137623. sqlite3_bind_int64(
  137624. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  137625. );
  137626. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  137627. iNext = sqlite3_column_int(pNextIdx, 0);
  137628. }
  137629. rc = sqlite3_reset(pNextIdx);
  137630. }
  137631. if( rc==SQLITE_OK ){
  137632. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  137633. ** full, merge all segments in level iLevel into a single iLevel+1
  137634. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  137635. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  137636. */
  137637. if( iNext>=FTS3_MERGE_COUNT ){
  137638. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  137639. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  137640. *piIdx = 0;
  137641. }else{
  137642. *piIdx = iNext;
  137643. }
  137644. }
  137645. return rc;
  137646. }
  137647. /*
  137648. ** The %_segments table is declared as follows:
  137649. **
  137650. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  137651. **
  137652. ** This function reads data from a single row of the %_segments table. The
  137653. ** specific row is identified by the iBlockid parameter. If paBlob is not
  137654. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  137655. ** with the contents of the blob stored in the "block" column of the
  137656. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  137657. ** to the size of the blob in bytes before returning.
  137658. **
  137659. ** If an error occurs, or the table does not contain the specified row,
  137660. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  137661. ** paBlob is non-NULL, then it is the responsibility of the caller to
  137662. ** eventually free the returned buffer.
  137663. **
  137664. ** This function may leave an open sqlite3_blob* handle in the
  137665. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  137666. ** to this function. The handle may be closed by calling the
  137667. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  137668. ** performance improvement, but the blob handle should always be closed
  137669. ** before control is returned to the user (to prevent a lock being held
  137670. ** on the database file for longer than necessary). Thus, any virtual table
  137671. ** method (xFilter etc.) that may directly or indirectly call this function
  137672. ** must call sqlite3Fts3SegmentsClose() before returning.
  137673. */
  137674. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  137675. Fts3Table *p, /* FTS3 table handle */
  137676. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  137677. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  137678. int *pnBlob, /* OUT: Size of blob data */
  137679. int *pnLoad /* OUT: Bytes actually loaded */
  137680. ){
  137681. int rc; /* Return code */
  137682. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  137683. assert( pnBlob );
  137684. if( p->pSegments ){
  137685. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  137686. }else{
  137687. if( 0==p->zSegmentsTbl ){
  137688. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  137689. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  137690. }
  137691. rc = sqlite3_blob_open(
  137692. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  137693. );
  137694. }
  137695. if( rc==SQLITE_OK ){
  137696. int nByte = sqlite3_blob_bytes(p->pSegments);
  137697. *pnBlob = nByte;
  137698. if( paBlob ){
  137699. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  137700. if( !aByte ){
  137701. rc = SQLITE_NOMEM;
  137702. }else{
  137703. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  137704. nByte = FTS3_NODE_CHUNKSIZE;
  137705. *pnLoad = nByte;
  137706. }
  137707. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  137708. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  137709. if( rc!=SQLITE_OK ){
  137710. sqlite3_free(aByte);
  137711. aByte = 0;
  137712. }
  137713. }
  137714. *paBlob = aByte;
  137715. }
  137716. }
  137717. return rc;
  137718. }
  137719. /*
  137720. ** Close the blob handle at p->pSegments, if it is open. See comments above
  137721. ** the sqlite3Fts3ReadBlock() function for details.
  137722. */
  137723. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  137724. sqlite3_blob_close(p->pSegments);
  137725. p->pSegments = 0;
  137726. }
  137727. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  137728. int nRead; /* Number of bytes to read */
  137729. int rc; /* Return code */
  137730. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  137731. rc = sqlite3_blob_read(
  137732. pReader->pBlob,
  137733. &pReader->aNode[pReader->nPopulate],
  137734. nRead,
  137735. pReader->nPopulate
  137736. );
  137737. if( rc==SQLITE_OK ){
  137738. pReader->nPopulate += nRead;
  137739. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  137740. if( pReader->nPopulate==pReader->nNode ){
  137741. sqlite3_blob_close(pReader->pBlob);
  137742. pReader->pBlob = 0;
  137743. pReader->nPopulate = 0;
  137744. }
  137745. }
  137746. return rc;
  137747. }
  137748. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  137749. int rc = SQLITE_OK;
  137750. assert( !pReader->pBlob
  137751. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  137752. );
  137753. while( pReader->pBlob && rc==SQLITE_OK
  137754. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  137755. ){
  137756. rc = fts3SegReaderIncrRead(pReader);
  137757. }
  137758. return rc;
  137759. }
  137760. /*
  137761. ** Set an Fts3SegReader cursor to point at EOF.
  137762. */
  137763. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  137764. if( !fts3SegReaderIsRootOnly(pSeg) ){
  137765. sqlite3_free(pSeg->aNode);
  137766. sqlite3_blob_close(pSeg->pBlob);
  137767. pSeg->pBlob = 0;
  137768. }
  137769. pSeg->aNode = 0;
  137770. }
  137771. /*
  137772. ** Move the iterator passed as the first argument to the next term in the
  137773. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  137774. ** SQLITE_DONE. Otherwise, an SQLite error code.
  137775. */
  137776. static int fts3SegReaderNext(
  137777. Fts3Table *p,
  137778. Fts3SegReader *pReader,
  137779. int bIncr
  137780. ){
  137781. int rc; /* Return code of various sub-routines */
  137782. char *pNext; /* Cursor variable */
  137783. int nPrefix; /* Number of bytes in term prefix */
  137784. int nSuffix; /* Number of bytes in term suffix */
  137785. if( !pReader->aDoclist ){
  137786. pNext = pReader->aNode;
  137787. }else{
  137788. pNext = &pReader->aDoclist[pReader->nDoclist];
  137789. }
  137790. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  137791. if( fts3SegReaderIsPending(pReader) ){
  137792. Fts3HashElem *pElem = *(pReader->ppNextElem);
  137793. sqlite3_free(pReader->aNode);
  137794. pReader->aNode = 0;
  137795. if( pElem ){
  137796. char *aCopy;
  137797. PendingList *pList = (PendingList *)fts3HashData(pElem);
  137798. int nCopy = pList->nData+1;
  137799. pReader->zTerm = (char *)fts3HashKey(pElem);
  137800. pReader->nTerm = fts3HashKeysize(pElem);
  137801. aCopy = (char*)sqlite3_malloc(nCopy);
  137802. if( !aCopy ) return SQLITE_NOMEM;
  137803. memcpy(aCopy, pList->aData, nCopy);
  137804. pReader->nNode = pReader->nDoclist = nCopy;
  137805. pReader->aNode = pReader->aDoclist = aCopy;
  137806. pReader->ppNextElem++;
  137807. assert( pReader->aNode );
  137808. }
  137809. return SQLITE_OK;
  137810. }
  137811. fts3SegReaderSetEof(pReader);
  137812. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  137813. ** blocks have already been traversed. */
  137814. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  137815. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  137816. return SQLITE_OK;
  137817. }
  137818. rc = sqlite3Fts3ReadBlock(
  137819. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  137820. (bIncr ? &pReader->nPopulate : 0)
  137821. );
  137822. if( rc!=SQLITE_OK ) return rc;
  137823. assert( pReader->pBlob==0 );
  137824. if( bIncr && pReader->nPopulate<pReader->nNode ){
  137825. pReader->pBlob = p->pSegments;
  137826. p->pSegments = 0;
  137827. }
  137828. pNext = pReader->aNode;
  137829. }
  137830. assert( !fts3SegReaderIsPending(pReader) );
  137831. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  137832. if( rc!=SQLITE_OK ) return rc;
  137833. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  137834. ** safe (no risk of overread) even if the node data is corrupted. */
  137835. pNext += fts3GetVarint32(pNext, &nPrefix);
  137836. pNext += fts3GetVarint32(pNext, &nSuffix);
  137837. if( nPrefix<0 || nSuffix<=0
  137838. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  137839. ){
  137840. return FTS_CORRUPT_VTAB;
  137841. }
  137842. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  137843. int nNew = (nPrefix+nSuffix)*2;
  137844. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  137845. if( !zNew ){
  137846. return SQLITE_NOMEM;
  137847. }
  137848. pReader->zTerm = zNew;
  137849. pReader->nTermAlloc = nNew;
  137850. }
  137851. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  137852. if( rc!=SQLITE_OK ) return rc;
  137853. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  137854. pReader->nTerm = nPrefix+nSuffix;
  137855. pNext += nSuffix;
  137856. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  137857. pReader->aDoclist = pNext;
  137858. pReader->pOffsetList = 0;
  137859. /* Check that the doclist does not appear to extend past the end of the
  137860. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  137861. ** of these statements is untrue, then the data structure is corrupt.
  137862. */
  137863. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  137864. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  137865. ){
  137866. return FTS_CORRUPT_VTAB;
  137867. }
  137868. return SQLITE_OK;
  137869. }
  137870. /*
  137871. ** Set the SegReader to point to the first docid in the doclist associated
  137872. ** with the current term.
  137873. */
  137874. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  137875. int rc = SQLITE_OK;
  137876. assert( pReader->aDoclist );
  137877. assert( !pReader->pOffsetList );
  137878. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  137879. u8 bEof = 0;
  137880. pReader->iDocid = 0;
  137881. pReader->nOffsetList = 0;
  137882. sqlite3Fts3DoclistPrev(0,
  137883. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  137884. &pReader->iDocid, &pReader->nOffsetList, &bEof
  137885. );
  137886. }else{
  137887. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  137888. if( rc==SQLITE_OK ){
  137889. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  137890. pReader->pOffsetList = &pReader->aDoclist[n];
  137891. }
  137892. }
  137893. return rc;
  137894. }
  137895. /*
  137896. ** Advance the SegReader to point to the next docid in the doclist
  137897. ** associated with the current term.
  137898. **
  137899. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  137900. ** *ppOffsetList is set to point to the first column-offset list
  137901. ** in the doclist entry (i.e. immediately past the docid varint).
  137902. ** *pnOffsetList is set to the length of the set of column-offset
  137903. ** lists, not including the nul-terminator byte. For example:
  137904. */
  137905. static int fts3SegReaderNextDocid(
  137906. Fts3Table *pTab,
  137907. Fts3SegReader *pReader, /* Reader to advance to next docid */
  137908. char **ppOffsetList, /* OUT: Pointer to current position-list */
  137909. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  137910. ){
  137911. int rc = SQLITE_OK;
  137912. char *p = pReader->pOffsetList;
  137913. char c = 0;
  137914. assert( p );
  137915. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  137916. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  137917. ** Pending-terms doclists are always built up in ascending order, so
  137918. ** we have to iterate through them backwards here. */
  137919. u8 bEof = 0;
  137920. if( ppOffsetList ){
  137921. *ppOffsetList = pReader->pOffsetList;
  137922. *pnOffsetList = pReader->nOffsetList - 1;
  137923. }
  137924. sqlite3Fts3DoclistPrev(0,
  137925. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  137926. &pReader->nOffsetList, &bEof
  137927. );
  137928. if( bEof ){
  137929. pReader->pOffsetList = 0;
  137930. }else{
  137931. pReader->pOffsetList = p;
  137932. }
  137933. }else{
  137934. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  137935. /* Pointer p currently points at the first byte of an offset list. The
  137936. ** following block advances it to point one byte past the end of
  137937. ** the same offset list. */
  137938. while( 1 ){
  137939. /* The following line of code (and the "p++" below the while() loop) is
  137940. ** normally all that is required to move pointer p to the desired
  137941. ** position. The exception is if this node is being loaded from disk
  137942. ** incrementally and pointer "p" now points to the first byte past
  137943. ** the populated part of pReader->aNode[].
  137944. */
  137945. while( *p | c ) c = *p++ & 0x80;
  137946. assert( *p==0 );
  137947. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  137948. rc = fts3SegReaderIncrRead(pReader);
  137949. if( rc!=SQLITE_OK ) return rc;
  137950. }
  137951. p++;
  137952. /* If required, populate the output variables with a pointer to and the
  137953. ** size of the previous offset-list.
  137954. */
  137955. if( ppOffsetList ){
  137956. *ppOffsetList = pReader->pOffsetList;
  137957. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  137958. }
  137959. /* List may have been edited in place by fts3EvalNearTrim() */
  137960. while( p<pEnd && *p==0 ) p++;
  137961. /* If there are no more entries in the doclist, set pOffsetList to
  137962. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  137963. ** Fts3SegReader.pOffsetList to point to the next offset list before
  137964. ** returning.
  137965. */
  137966. if( p>=pEnd ){
  137967. pReader->pOffsetList = 0;
  137968. }else{
  137969. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  137970. if( rc==SQLITE_OK ){
  137971. sqlite3_int64 iDelta;
  137972. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  137973. if( pTab->bDescIdx ){
  137974. pReader->iDocid -= iDelta;
  137975. }else{
  137976. pReader->iDocid += iDelta;
  137977. }
  137978. }
  137979. }
  137980. }
  137981. return SQLITE_OK;
  137982. }
  137983. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  137984. Fts3Cursor *pCsr,
  137985. Fts3MultiSegReader *pMsr,
  137986. int *pnOvfl
  137987. ){
  137988. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  137989. int nOvfl = 0;
  137990. int ii;
  137991. int rc = SQLITE_OK;
  137992. int pgsz = p->nPgsz;
  137993. assert( p->bFts4 );
  137994. assert( pgsz>0 );
  137995. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  137996. Fts3SegReader *pReader = pMsr->apSegment[ii];
  137997. if( !fts3SegReaderIsPending(pReader)
  137998. && !fts3SegReaderIsRootOnly(pReader)
  137999. ){
  138000. sqlite3_int64 jj;
  138001. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  138002. int nBlob;
  138003. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  138004. if( rc!=SQLITE_OK ) break;
  138005. if( (nBlob+35)>pgsz ){
  138006. nOvfl += (nBlob + 34)/pgsz;
  138007. }
  138008. }
  138009. }
  138010. }
  138011. *pnOvfl = nOvfl;
  138012. return rc;
  138013. }
  138014. /*
  138015. ** Free all allocations associated with the iterator passed as the
  138016. ** second argument.
  138017. */
  138018. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  138019. if( pReader ){
  138020. if( !fts3SegReaderIsPending(pReader) ){
  138021. sqlite3_free(pReader->zTerm);
  138022. }
  138023. if( !fts3SegReaderIsRootOnly(pReader) ){
  138024. sqlite3_free(pReader->aNode);
  138025. }
  138026. sqlite3_blob_close(pReader->pBlob);
  138027. }
  138028. sqlite3_free(pReader);
  138029. }
  138030. /*
  138031. ** Allocate a new SegReader object.
  138032. */
  138033. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  138034. int iAge, /* Segment "age". */
  138035. int bLookup, /* True for a lookup only */
  138036. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  138037. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  138038. sqlite3_int64 iEndBlock, /* Final block of segment */
  138039. const char *zRoot, /* Buffer containing root node */
  138040. int nRoot, /* Size of buffer containing root node */
  138041. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  138042. ){
  138043. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  138044. int nExtra = 0; /* Bytes to allocate segment root node */
  138045. assert( iStartLeaf<=iEndLeaf );
  138046. if( iStartLeaf==0 ){
  138047. nExtra = nRoot + FTS3_NODE_PADDING;
  138048. }
  138049. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  138050. if( !pReader ){
  138051. return SQLITE_NOMEM;
  138052. }
  138053. memset(pReader, 0, sizeof(Fts3SegReader));
  138054. pReader->iIdx = iAge;
  138055. pReader->bLookup = bLookup!=0;
  138056. pReader->iStartBlock = iStartLeaf;
  138057. pReader->iLeafEndBlock = iEndLeaf;
  138058. pReader->iEndBlock = iEndBlock;
  138059. if( nExtra ){
  138060. /* The entire segment is stored in the root node. */
  138061. pReader->aNode = (char *)&pReader[1];
  138062. pReader->rootOnly = 1;
  138063. pReader->nNode = nRoot;
  138064. memcpy(pReader->aNode, zRoot, nRoot);
  138065. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  138066. }else{
  138067. pReader->iCurrentBlock = iStartLeaf-1;
  138068. }
  138069. *ppReader = pReader;
  138070. return SQLITE_OK;
  138071. }
  138072. /*
  138073. ** This is a comparison function used as a qsort() callback when sorting
  138074. ** an array of pending terms by term. This occurs as part of flushing
  138075. ** the contents of the pending-terms hash table to the database.
  138076. */
  138077. static int SQLITE_CDECL fts3CompareElemByTerm(
  138078. const void *lhs,
  138079. const void *rhs
  138080. ){
  138081. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  138082. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  138083. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  138084. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  138085. int n = (n1<n2 ? n1 : n2);
  138086. int c = memcmp(z1, z2, n);
  138087. if( c==0 ){
  138088. c = n1 - n2;
  138089. }
  138090. return c;
  138091. }
  138092. /*
  138093. ** This function is used to allocate an Fts3SegReader that iterates through
  138094. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  138095. **
  138096. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  138097. ** through each term in the pending-terms table. Or, if isPrefixIter is
  138098. ** non-zero, it iterates through each term and its prefixes. For example, if
  138099. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  138100. ** "firebird", then the iterator visits the following 'terms' (in the order
  138101. ** shown):
  138102. **
  138103. ** f fi fir fire fireb firebi firebir firebird
  138104. ** m my mys mysq mysql
  138105. ** s sq sql sqli sqlit sqlite
  138106. **
  138107. ** Whereas if isPrefixIter is zero, the terms visited are:
  138108. **
  138109. ** firebird mysql sqlite
  138110. */
  138111. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  138112. Fts3Table *p, /* Virtual table handle */
  138113. int iIndex, /* Index for p->aIndex */
  138114. const char *zTerm, /* Term to search for */
  138115. int nTerm, /* Size of buffer zTerm */
  138116. int bPrefix, /* True for a prefix iterator */
  138117. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  138118. ){
  138119. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  138120. Fts3HashElem *pE; /* Iterator variable */
  138121. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  138122. int nElem = 0; /* Size of array at aElem */
  138123. int rc = SQLITE_OK; /* Return Code */
  138124. Fts3Hash *pHash;
  138125. pHash = &p->aIndex[iIndex].hPending;
  138126. if( bPrefix ){
  138127. int nAlloc = 0; /* Size of allocated array at aElem */
  138128. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  138129. char *zKey = (char *)fts3HashKey(pE);
  138130. int nKey = fts3HashKeysize(pE);
  138131. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  138132. if( nElem==nAlloc ){
  138133. Fts3HashElem **aElem2;
  138134. nAlloc += 16;
  138135. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  138136. aElem, nAlloc*sizeof(Fts3HashElem *)
  138137. );
  138138. if( !aElem2 ){
  138139. rc = SQLITE_NOMEM;
  138140. nElem = 0;
  138141. break;
  138142. }
  138143. aElem = aElem2;
  138144. }
  138145. aElem[nElem++] = pE;
  138146. }
  138147. }
  138148. /* If more than one term matches the prefix, sort the Fts3HashElem
  138149. ** objects in term order using qsort(). This uses the same comparison
  138150. ** callback as is used when flushing terms to disk.
  138151. */
  138152. if( nElem>1 ){
  138153. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  138154. }
  138155. }else{
  138156. /* The query is a simple term lookup that matches at most one term in
  138157. ** the index. All that is required is a straight hash-lookup.
  138158. **
  138159. ** Because the stack address of pE may be accessed via the aElem pointer
  138160. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  138161. ** within this entire function, not just this "else{...}" block.
  138162. */
  138163. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  138164. if( pE ){
  138165. aElem = &pE;
  138166. nElem = 1;
  138167. }
  138168. }
  138169. if( nElem>0 ){
  138170. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  138171. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  138172. if( !pReader ){
  138173. rc = SQLITE_NOMEM;
  138174. }else{
  138175. memset(pReader, 0, nByte);
  138176. pReader->iIdx = 0x7FFFFFFF;
  138177. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  138178. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  138179. }
  138180. }
  138181. if( bPrefix ){
  138182. sqlite3_free(aElem);
  138183. }
  138184. *ppReader = pReader;
  138185. return rc;
  138186. }
  138187. /*
  138188. ** Compare the entries pointed to by two Fts3SegReader structures.
  138189. ** Comparison is as follows:
  138190. **
  138191. ** 1) EOF is greater than not EOF.
  138192. **
  138193. ** 2) The current terms (if any) are compared using memcmp(). If one
  138194. ** term is a prefix of another, the longer term is considered the
  138195. ** larger.
  138196. **
  138197. ** 3) By segment age. An older segment is considered larger.
  138198. */
  138199. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  138200. int rc;
  138201. if( pLhs->aNode && pRhs->aNode ){
  138202. int rc2 = pLhs->nTerm - pRhs->nTerm;
  138203. if( rc2<0 ){
  138204. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  138205. }else{
  138206. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  138207. }
  138208. if( rc==0 ){
  138209. rc = rc2;
  138210. }
  138211. }else{
  138212. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  138213. }
  138214. if( rc==0 ){
  138215. rc = pRhs->iIdx - pLhs->iIdx;
  138216. }
  138217. assert( rc!=0 );
  138218. return rc;
  138219. }
  138220. /*
  138221. ** A different comparison function for SegReader structures. In this
  138222. ** version, it is assumed that each SegReader points to an entry in
  138223. ** a doclist for identical terms. Comparison is made as follows:
  138224. **
  138225. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  138226. **
  138227. ** 2) By current docid.
  138228. **
  138229. ** 3) By segment age. An older segment is considered larger.
  138230. */
  138231. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  138232. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  138233. if( rc==0 ){
  138234. if( pLhs->iDocid==pRhs->iDocid ){
  138235. rc = pRhs->iIdx - pLhs->iIdx;
  138236. }else{
  138237. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  138238. }
  138239. }
  138240. assert( pLhs->aNode && pRhs->aNode );
  138241. return rc;
  138242. }
  138243. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  138244. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  138245. if( rc==0 ){
  138246. if( pLhs->iDocid==pRhs->iDocid ){
  138247. rc = pRhs->iIdx - pLhs->iIdx;
  138248. }else{
  138249. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  138250. }
  138251. }
  138252. assert( pLhs->aNode && pRhs->aNode );
  138253. return rc;
  138254. }
  138255. /*
  138256. ** Compare the term that the Fts3SegReader object passed as the first argument
  138257. ** points to with the term specified by arguments zTerm and nTerm.
  138258. **
  138259. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  138260. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  138261. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  138262. */
  138263. static int fts3SegReaderTermCmp(
  138264. Fts3SegReader *pSeg, /* Segment reader object */
  138265. const char *zTerm, /* Term to compare to */
  138266. int nTerm /* Size of term zTerm in bytes */
  138267. ){
  138268. int res = 0;
  138269. if( pSeg->aNode ){
  138270. if( pSeg->nTerm>nTerm ){
  138271. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  138272. }else{
  138273. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  138274. }
  138275. if( res==0 ){
  138276. res = pSeg->nTerm-nTerm;
  138277. }
  138278. }
  138279. return res;
  138280. }
  138281. /*
  138282. ** Argument apSegment is an array of nSegment elements. It is known that
  138283. ** the final (nSegment-nSuspect) members are already in sorted order
  138284. ** (according to the comparison function provided). This function shuffles
  138285. ** the array around until all entries are in sorted order.
  138286. */
  138287. static void fts3SegReaderSort(
  138288. Fts3SegReader **apSegment, /* Array to sort entries of */
  138289. int nSegment, /* Size of apSegment array */
  138290. int nSuspect, /* Unsorted entry count */
  138291. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  138292. ){
  138293. int i; /* Iterator variable */
  138294. assert( nSuspect<=nSegment );
  138295. if( nSuspect==nSegment ) nSuspect--;
  138296. for(i=nSuspect-1; i>=0; i--){
  138297. int j;
  138298. for(j=i; j<(nSegment-1); j++){
  138299. Fts3SegReader *pTmp;
  138300. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  138301. pTmp = apSegment[j+1];
  138302. apSegment[j+1] = apSegment[j];
  138303. apSegment[j] = pTmp;
  138304. }
  138305. }
  138306. #ifndef NDEBUG
  138307. /* Check that the list really is sorted now. */
  138308. for(i=0; i<(nSuspect-1); i++){
  138309. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  138310. }
  138311. #endif
  138312. }
  138313. /*
  138314. ** Insert a record into the %_segments table.
  138315. */
  138316. static int fts3WriteSegment(
  138317. Fts3Table *p, /* Virtual table handle */
  138318. sqlite3_int64 iBlock, /* Block id for new block */
  138319. char *z, /* Pointer to buffer containing block data */
  138320. int n /* Size of buffer z in bytes */
  138321. ){
  138322. sqlite3_stmt *pStmt;
  138323. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  138324. if( rc==SQLITE_OK ){
  138325. sqlite3_bind_int64(pStmt, 1, iBlock);
  138326. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  138327. sqlite3_step(pStmt);
  138328. rc = sqlite3_reset(pStmt);
  138329. }
  138330. return rc;
  138331. }
  138332. /*
  138333. ** Find the largest relative level number in the table. If successful, set
  138334. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  138335. ** set *pnMax to zero and return an SQLite error code.
  138336. */
  138337. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  138338. int rc;
  138339. int mxLevel = 0;
  138340. sqlite3_stmt *pStmt = 0;
  138341. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  138342. if( rc==SQLITE_OK ){
  138343. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138344. mxLevel = sqlite3_column_int(pStmt, 0);
  138345. }
  138346. rc = sqlite3_reset(pStmt);
  138347. }
  138348. *pnMax = mxLevel;
  138349. return rc;
  138350. }
  138351. /*
  138352. ** Insert a record into the %_segdir table.
  138353. */
  138354. static int fts3WriteSegdir(
  138355. Fts3Table *p, /* Virtual table handle */
  138356. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  138357. int iIdx, /* Value for "idx" field */
  138358. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  138359. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  138360. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  138361. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  138362. char *zRoot, /* Blob value for "root" field */
  138363. int nRoot /* Number of bytes in buffer zRoot */
  138364. ){
  138365. sqlite3_stmt *pStmt;
  138366. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  138367. if( rc==SQLITE_OK ){
  138368. sqlite3_bind_int64(pStmt, 1, iLevel);
  138369. sqlite3_bind_int(pStmt, 2, iIdx);
  138370. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  138371. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  138372. if( nLeafData==0 ){
  138373. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  138374. }else{
  138375. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  138376. if( !zEnd ) return SQLITE_NOMEM;
  138377. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  138378. }
  138379. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  138380. sqlite3_step(pStmt);
  138381. rc = sqlite3_reset(pStmt);
  138382. }
  138383. return rc;
  138384. }
  138385. /*
  138386. ** Return the size of the common prefix (if any) shared by zPrev and
  138387. ** zNext, in bytes. For example,
  138388. **
  138389. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  138390. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  138391. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  138392. */
  138393. static int fts3PrefixCompress(
  138394. const char *zPrev, /* Buffer containing previous term */
  138395. int nPrev, /* Size of buffer zPrev in bytes */
  138396. const char *zNext, /* Buffer containing next term */
  138397. int nNext /* Size of buffer zNext in bytes */
  138398. ){
  138399. int n;
  138400. UNUSED_PARAMETER(nNext);
  138401. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  138402. return n;
  138403. }
  138404. /*
  138405. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  138406. ** (according to memcmp) than the previous term.
  138407. */
  138408. static int fts3NodeAddTerm(
  138409. Fts3Table *p, /* Virtual table handle */
  138410. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  138411. int isCopyTerm, /* True if zTerm/nTerm is transient */
  138412. const char *zTerm, /* Pointer to buffer containing term */
  138413. int nTerm /* Size of term in bytes */
  138414. ){
  138415. SegmentNode *pTree = *ppTree;
  138416. int rc;
  138417. SegmentNode *pNew;
  138418. /* First try to append the term to the current node. Return early if
  138419. ** this is possible.
  138420. */
  138421. if( pTree ){
  138422. int nData = pTree->nData; /* Current size of node in bytes */
  138423. int nReq = nData; /* Required space after adding zTerm */
  138424. int nPrefix; /* Number of bytes of prefix compression */
  138425. int nSuffix; /* Suffix length */
  138426. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  138427. nSuffix = nTerm-nPrefix;
  138428. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  138429. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  138430. if( nReq>p->nNodeSize ){
  138431. /* An unusual case: this is the first term to be added to the node
  138432. ** and the static node buffer (p->nNodeSize bytes) is not large
  138433. ** enough. Use a separately malloced buffer instead This wastes
  138434. ** p->nNodeSize bytes, but since this scenario only comes about when
  138435. ** the database contain two terms that share a prefix of almost 2KB,
  138436. ** this is not expected to be a serious problem.
  138437. */
  138438. assert( pTree->aData==(char *)&pTree[1] );
  138439. pTree->aData = (char *)sqlite3_malloc(nReq);
  138440. if( !pTree->aData ){
  138441. return SQLITE_NOMEM;
  138442. }
  138443. }
  138444. if( pTree->zTerm ){
  138445. /* There is no prefix-length field for first term in a node */
  138446. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  138447. }
  138448. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  138449. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  138450. pTree->nData = nData + nSuffix;
  138451. pTree->nEntry++;
  138452. if( isCopyTerm ){
  138453. if( pTree->nMalloc<nTerm ){
  138454. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  138455. if( !zNew ){
  138456. return SQLITE_NOMEM;
  138457. }
  138458. pTree->nMalloc = nTerm*2;
  138459. pTree->zMalloc = zNew;
  138460. }
  138461. pTree->zTerm = pTree->zMalloc;
  138462. memcpy(pTree->zTerm, zTerm, nTerm);
  138463. pTree->nTerm = nTerm;
  138464. }else{
  138465. pTree->zTerm = (char *)zTerm;
  138466. pTree->nTerm = nTerm;
  138467. }
  138468. return SQLITE_OK;
  138469. }
  138470. }
  138471. /* If control flows to here, it was not possible to append zTerm to the
  138472. ** current node. Create a new node (a right-sibling of the current node).
  138473. ** If this is the first node in the tree, the term is added to it.
  138474. **
  138475. ** Otherwise, the term is not added to the new node, it is left empty for
  138476. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  138477. ** has no parent, one is created here.
  138478. */
  138479. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  138480. if( !pNew ){
  138481. return SQLITE_NOMEM;
  138482. }
  138483. memset(pNew, 0, sizeof(SegmentNode));
  138484. pNew->nData = 1 + FTS3_VARINT_MAX;
  138485. pNew->aData = (char *)&pNew[1];
  138486. if( pTree ){
  138487. SegmentNode *pParent = pTree->pParent;
  138488. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  138489. if( pTree->pParent==0 ){
  138490. pTree->pParent = pParent;
  138491. }
  138492. pTree->pRight = pNew;
  138493. pNew->pLeftmost = pTree->pLeftmost;
  138494. pNew->pParent = pParent;
  138495. pNew->zMalloc = pTree->zMalloc;
  138496. pNew->nMalloc = pTree->nMalloc;
  138497. pTree->zMalloc = 0;
  138498. }else{
  138499. pNew->pLeftmost = pNew;
  138500. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  138501. }
  138502. *ppTree = pNew;
  138503. return rc;
  138504. }
  138505. /*
  138506. ** Helper function for fts3NodeWrite().
  138507. */
  138508. static int fts3TreeFinishNode(
  138509. SegmentNode *pTree,
  138510. int iHeight,
  138511. sqlite3_int64 iLeftChild
  138512. ){
  138513. int nStart;
  138514. assert( iHeight>=1 && iHeight<128 );
  138515. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  138516. pTree->aData[nStart] = (char)iHeight;
  138517. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  138518. return nStart;
  138519. }
  138520. /*
  138521. ** Write the buffer for the segment node pTree and all of its peers to the
  138522. ** database. Then call this function recursively to write the parent of
  138523. ** pTree and its peers to the database.
  138524. **
  138525. ** Except, if pTree is a root node, do not write it to the database. Instead,
  138526. ** set output variables *paRoot and *pnRoot to contain the root node.
  138527. **
  138528. ** If successful, SQLITE_OK is returned and output variable *piLast is
  138529. ** set to the largest blockid written to the database (or zero if no
  138530. ** blocks were written to the db). Otherwise, an SQLite error code is
  138531. ** returned.
  138532. */
  138533. static int fts3NodeWrite(
  138534. Fts3Table *p, /* Virtual table handle */
  138535. SegmentNode *pTree, /* SegmentNode handle */
  138536. int iHeight, /* Height of this node in tree */
  138537. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  138538. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  138539. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  138540. char **paRoot, /* OUT: Data for root node */
  138541. int *pnRoot /* OUT: Size of root node in bytes */
  138542. ){
  138543. int rc = SQLITE_OK;
  138544. if( !pTree->pParent ){
  138545. /* Root node of the tree. */
  138546. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  138547. *piLast = iFree-1;
  138548. *pnRoot = pTree->nData - nStart;
  138549. *paRoot = &pTree->aData[nStart];
  138550. }else{
  138551. SegmentNode *pIter;
  138552. sqlite3_int64 iNextFree = iFree;
  138553. sqlite3_int64 iNextLeaf = iLeaf;
  138554. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  138555. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  138556. int nWrite = pIter->nData - nStart;
  138557. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  138558. iNextFree++;
  138559. iNextLeaf += (pIter->nEntry+1);
  138560. }
  138561. if( rc==SQLITE_OK ){
  138562. assert( iNextLeaf==iFree );
  138563. rc = fts3NodeWrite(
  138564. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  138565. );
  138566. }
  138567. }
  138568. return rc;
  138569. }
  138570. /*
  138571. ** Free all memory allocations associated with the tree pTree.
  138572. */
  138573. static void fts3NodeFree(SegmentNode *pTree){
  138574. if( pTree ){
  138575. SegmentNode *p = pTree->pLeftmost;
  138576. fts3NodeFree(p->pParent);
  138577. while( p ){
  138578. SegmentNode *pRight = p->pRight;
  138579. if( p->aData!=(char *)&p[1] ){
  138580. sqlite3_free(p->aData);
  138581. }
  138582. assert( pRight==0 || p->zMalloc==0 );
  138583. sqlite3_free(p->zMalloc);
  138584. sqlite3_free(p);
  138585. p = pRight;
  138586. }
  138587. }
  138588. }
  138589. /*
  138590. ** Add a term to the segment being constructed by the SegmentWriter object
  138591. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  138592. ** be passed NULL. This function will allocate a new SegmentWriter object
  138593. ** and return it via the input/output variable *ppWriter in this case.
  138594. **
  138595. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  138596. */
  138597. static int fts3SegWriterAdd(
  138598. Fts3Table *p, /* Virtual table handle */
  138599. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  138600. int isCopyTerm, /* True if buffer zTerm must be copied */
  138601. const char *zTerm, /* Pointer to buffer containing term */
  138602. int nTerm, /* Size of term in bytes */
  138603. const char *aDoclist, /* Pointer to buffer containing doclist */
  138604. int nDoclist /* Size of doclist in bytes */
  138605. ){
  138606. int nPrefix; /* Size of term prefix in bytes */
  138607. int nSuffix; /* Size of term suffix in bytes */
  138608. int nReq; /* Number of bytes required on leaf page */
  138609. int nData;
  138610. SegmentWriter *pWriter = *ppWriter;
  138611. if( !pWriter ){
  138612. int rc;
  138613. sqlite3_stmt *pStmt;
  138614. /* Allocate the SegmentWriter structure */
  138615. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  138616. if( !pWriter ) return SQLITE_NOMEM;
  138617. memset(pWriter, 0, sizeof(SegmentWriter));
  138618. *ppWriter = pWriter;
  138619. /* Allocate a buffer in which to accumulate data */
  138620. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  138621. if( !pWriter->aData ) return SQLITE_NOMEM;
  138622. pWriter->nSize = p->nNodeSize;
  138623. /* Find the next free blockid in the %_segments table */
  138624. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  138625. if( rc!=SQLITE_OK ) return rc;
  138626. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138627. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  138628. pWriter->iFirst = pWriter->iFree;
  138629. }
  138630. rc = sqlite3_reset(pStmt);
  138631. if( rc!=SQLITE_OK ) return rc;
  138632. }
  138633. nData = pWriter->nData;
  138634. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  138635. nSuffix = nTerm-nPrefix;
  138636. /* Figure out how many bytes are required by this new entry */
  138637. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  138638. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  138639. nSuffix + /* Term suffix */
  138640. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  138641. nDoclist; /* Doclist data */
  138642. if( nData>0 && nData+nReq>p->nNodeSize ){
  138643. int rc;
  138644. /* The current leaf node is full. Write it out to the database. */
  138645. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  138646. if( rc!=SQLITE_OK ) return rc;
  138647. p->nLeafAdd++;
  138648. /* Add the current term to the interior node tree. The term added to
  138649. ** the interior tree must:
  138650. **
  138651. ** a) be greater than the largest term on the leaf node just written
  138652. ** to the database (still available in pWriter->zTerm), and
  138653. **
  138654. ** b) be less than or equal to the term about to be added to the new
  138655. ** leaf node (zTerm/nTerm).
  138656. **
  138657. ** In other words, it must be the prefix of zTerm 1 byte longer than
  138658. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  138659. */
  138660. assert( nPrefix<nTerm );
  138661. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  138662. if( rc!=SQLITE_OK ) return rc;
  138663. nData = 0;
  138664. pWriter->nTerm = 0;
  138665. nPrefix = 0;
  138666. nSuffix = nTerm;
  138667. nReq = 1 + /* varint containing prefix size */
  138668. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  138669. nTerm + /* Term suffix */
  138670. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  138671. nDoclist; /* Doclist data */
  138672. }
  138673. /* Increase the total number of bytes written to account for the new entry. */
  138674. pWriter->nLeafData += nReq;
  138675. /* If the buffer currently allocated is too small for this entry, realloc
  138676. ** the buffer to make it large enough.
  138677. */
  138678. if( nReq>pWriter->nSize ){
  138679. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  138680. if( !aNew ) return SQLITE_NOMEM;
  138681. pWriter->aData = aNew;
  138682. pWriter->nSize = nReq;
  138683. }
  138684. assert( nData+nReq<=pWriter->nSize );
  138685. /* Append the prefix-compressed term and doclist to the buffer. */
  138686. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  138687. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  138688. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  138689. nData += nSuffix;
  138690. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  138691. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  138692. pWriter->nData = nData + nDoclist;
  138693. /* Save the current term so that it can be used to prefix-compress the next.
  138694. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  138695. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  138696. ** store a copy of the pointer.
  138697. */
  138698. if( isCopyTerm ){
  138699. if( nTerm>pWriter->nMalloc ){
  138700. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  138701. if( !zNew ){
  138702. return SQLITE_NOMEM;
  138703. }
  138704. pWriter->nMalloc = nTerm*2;
  138705. pWriter->zMalloc = zNew;
  138706. pWriter->zTerm = zNew;
  138707. }
  138708. assert( pWriter->zTerm==pWriter->zMalloc );
  138709. memcpy(pWriter->zTerm, zTerm, nTerm);
  138710. }else{
  138711. pWriter->zTerm = (char *)zTerm;
  138712. }
  138713. pWriter->nTerm = nTerm;
  138714. return SQLITE_OK;
  138715. }
  138716. /*
  138717. ** Flush all data associated with the SegmentWriter object pWriter to the
  138718. ** database. This function must be called after all terms have been added
  138719. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  138720. ** returned. Otherwise, an SQLite error code.
  138721. */
  138722. static int fts3SegWriterFlush(
  138723. Fts3Table *p, /* Virtual table handle */
  138724. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  138725. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  138726. int iIdx /* Value for 'idx' column of %_segdir */
  138727. ){
  138728. int rc; /* Return code */
  138729. if( pWriter->pTree ){
  138730. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  138731. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  138732. char *zRoot = NULL; /* Pointer to buffer containing root node */
  138733. int nRoot = 0; /* Size of buffer zRoot */
  138734. iLastLeaf = pWriter->iFree;
  138735. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  138736. if( rc==SQLITE_OK ){
  138737. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  138738. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  138739. }
  138740. if( rc==SQLITE_OK ){
  138741. rc = fts3WriteSegdir(p, iLevel, iIdx,
  138742. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  138743. }
  138744. }else{
  138745. /* The entire tree fits on the root node. Write it to the segdir table. */
  138746. rc = fts3WriteSegdir(p, iLevel, iIdx,
  138747. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  138748. }
  138749. p->nLeafAdd++;
  138750. return rc;
  138751. }
  138752. /*
  138753. ** Release all memory held by the SegmentWriter object passed as the
  138754. ** first argument.
  138755. */
  138756. static void fts3SegWriterFree(SegmentWriter *pWriter){
  138757. if( pWriter ){
  138758. sqlite3_free(pWriter->aData);
  138759. sqlite3_free(pWriter->zMalloc);
  138760. fts3NodeFree(pWriter->pTree);
  138761. sqlite3_free(pWriter);
  138762. }
  138763. }
  138764. /*
  138765. ** The first value in the apVal[] array is assumed to contain an integer.
  138766. ** This function tests if there exist any documents with docid values that
  138767. ** are different from that integer. i.e. if deleting the document with docid
  138768. ** pRowid would mean the FTS3 table were empty.
  138769. **
  138770. ** If successful, *pisEmpty is set to true if the table is empty except for
  138771. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  138772. ** error occurs, an SQLite error code is returned.
  138773. */
  138774. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  138775. sqlite3_stmt *pStmt;
  138776. int rc;
  138777. if( p->zContentTbl ){
  138778. /* If using the content=xxx option, assume the table is never empty */
  138779. *pisEmpty = 0;
  138780. rc = SQLITE_OK;
  138781. }else{
  138782. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  138783. if( rc==SQLITE_OK ){
  138784. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138785. *pisEmpty = sqlite3_column_int(pStmt, 0);
  138786. }
  138787. rc = sqlite3_reset(pStmt);
  138788. }
  138789. }
  138790. return rc;
  138791. }
  138792. /*
  138793. ** Set *pnMax to the largest segment level in the database for the index
  138794. ** iIndex.
  138795. **
  138796. ** Segment levels are stored in the 'level' column of the %_segdir table.
  138797. **
  138798. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  138799. */
  138800. static int fts3SegmentMaxLevel(
  138801. Fts3Table *p,
  138802. int iLangid,
  138803. int iIndex,
  138804. sqlite3_int64 *pnMax
  138805. ){
  138806. sqlite3_stmt *pStmt;
  138807. int rc;
  138808. assert( iIndex>=0 && iIndex<p->nIndex );
  138809. /* Set pStmt to the compiled version of:
  138810. **
  138811. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  138812. **
  138813. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  138814. */
  138815. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  138816. if( rc!=SQLITE_OK ) return rc;
  138817. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  138818. sqlite3_bind_int64(pStmt, 2,
  138819. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  138820. );
  138821. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138822. *pnMax = sqlite3_column_int64(pStmt, 0);
  138823. }
  138824. return sqlite3_reset(pStmt);
  138825. }
  138826. /*
  138827. ** iAbsLevel is an absolute level that may be assumed to exist within
  138828. ** the database. This function checks if it is the largest level number
  138829. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  138830. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  138831. ** is returned. If an error occurs, an error code is returned and the
  138832. ** final value of *pbMax is undefined.
  138833. */
  138834. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  138835. /* Set pStmt to the compiled version of:
  138836. **
  138837. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  138838. **
  138839. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  138840. */
  138841. sqlite3_stmt *pStmt;
  138842. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  138843. if( rc!=SQLITE_OK ) return rc;
  138844. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  138845. sqlite3_bind_int64(pStmt, 2,
  138846. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  138847. );
  138848. *pbMax = 0;
  138849. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138850. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  138851. }
  138852. return sqlite3_reset(pStmt);
  138853. }
  138854. /*
  138855. ** Delete all entries in the %_segments table associated with the segment
  138856. ** opened with seg-reader pSeg. This function does not affect the contents
  138857. ** of the %_segdir table.
  138858. */
  138859. static int fts3DeleteSegment(
  138860. Fts3Table *p, /* FTS table handle */
  138861. Fts3SegReader *pSeg /* Segment to delete */
  138862. ){
  138863. int rc = SQLITE_OK; /* Return code */
  138864. if( pSeg->iStartBlock ){
  138865. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  138866. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  138867. if( rc==SQLITE_OK ){
  138868. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  138869. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  138870. sqlite3_step(pDelete);
  138871. rc = sqlite3_reset(pDelete);
  138872. }
  138873. }
  138874. return rc;
  138875. }
  138876. /*
  138877. ** This function is used after merging multiple segments into a single large
  138878. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  138879. ** it:
  138880. **
  138881. ** 1) Deletes all %_segments entries for the segments associated with
  138882. ** each of the SegReader objects in the array passed as the third
  138883. ** argument, and
  138884. **
  138885. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  138886. ** entries regardless of level if (iLevel<0).
  138887. **
  138888. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  138889. */
  138890. static int fts3DeleteSegdir(
  138891. Fts3Table *p, /* Virtual table handle */
  138892. int iLangid, /* Language id */
  138893. int iIndex, /* Index for p->aIndex */
  138894. int iLevel, /* Level of %_segdir entries to delete */
  138895. Fts3SegReader **apSegment, /* Array of SegReader objects */
  138896. int nReader /* Size of array apSegment */
  138897. ){
  138898. int rc = SQLITE_OK; /* Return Code */
  138899. int i; /* Iterator variable */
  138900. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  138901. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  138902. rc = fts3DeleteSegment(p, apSegment[i]);
  138903. }
  138904. if( rc!=SQLITE_OK ){
  138905. return rc;
  138906. }
  138907. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  138908. if( iLevel==FTS3_SEGCURSOR_ALL ){
  138909. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  138910. if( rc==SQLITE_OK ){
  138911. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  138912. sqlite3_bind_int64(pDelete, 2,
  138913. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  138914. );
  138915. }
  138916. }else{
  138917. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  138918. if( rc==SQLITE_OK ){
  138919. sqlite3_bind_int64(
  138920. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  138921. );
  138922. }
  138923. }
  138924. if( rc==SQLITE_OK ){
  138925. sqlite3_step(pDelete);
  138926. rc = sqlite3_reset(pDelete);
  138927. }
  138928. return rc;
  138929. }
  138930. /*
  138931. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  138932. ** a position list that may (or may not) feature multiple columns. This
  138933. ** function adjusts the pointer *ppList and the length *pnList so that they
  138934. ** identify the subset of the position list that corresponds to column iCol.
  138935. **
  138936. ** If there are no entries in the input position list for column iCol, then
  138937. ** *pnList is set to zero before returning.
  138938. **
  138939. ** If parameter bZero is non-zero, then any part of the input list following
  138940. ** the end of the output list is zeroed before returning.
  138941. */
  138942. static void fts3ColumnFilter(
  138943. int iCol, /* Column to filter on */
  138944. int bZero, /* Zero out anything following *ppList */
  138945. char **ppList, /* IN/OUT: Pointer to position list */
  138946. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  138947. ){
  138948. char *pList = *ppList;
  138949. int nList = *pnList;
  138950. char *pEnd = &pList[nList];
  138951. int iCurrent = 0;
  138952. char *p = pList;
  138953. assert( iCol>=0 );
  138954. while( 1 ){
  138955. char c = 0;
  138956. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  138957. if( iCol==iCurrent ){
  138958. nList = (int)(p - pList);
  138959. break;
  138960. }
  138961. nList -= (int)(p - pList);
  138962. pList = p;
  138963. if( nList==0 ){
  138964. break;
  138965. }
  138966. p = &pList[1];
  138967. p += fts3GetVarint32(p, &iCurrent);
  138968. }
  138969. if( bZero && &pList[nList]!=pEnd ){
  138970. memset(&pList[nList], 0, pEnd - &pList[nList]);
  138971. }
  138972. *ppList = pList;
  138973. *pnList = nList;
  138974. }
  138975. /*
  138976. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  138977. ** existing data). Grow the buffer if required.
  138978. **
  138979. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  138980. ** trying to resize the buffer, return SQLITE_NOMEM.
  138981. */
  138982. static int fts3MsrBufferData(
  138983. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  138984. char *pList,
  138985. int nList
  138986. ){
  138987. if( nList>pMsr->nBuffer ){
  138988. char *pNew;
  138989. pMsr->nBuffer = nList*2;
  138990. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  138991. if( !pNew ) return SQLITE_NOMEM;
  138992. pMsr->aBuffer = pNew;
  138993. }
  138994. memcpy(pMsr->aBuffer, pList, nList);
  138995. return SQLITE_OK;
  138996. }
  138997. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  138998. Fts3Table *p, /* Virtual table handle */
  138999. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  139000. sqlite3_int64 *piDocid, /* OUT: Docid value */
  139001. char **paPoslist, /* OUT: Pointer to position list */
  139002. int *pnPoslist /* OUT: Size of position list in bytes */
  139003. ){
  139004. int nMerge = pMsr->nAdvance;
  139005. Fts3SegReader **apSegment = pMsr->apSegment;
  139006. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  139007. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  139008. );
  139009. if( nMerge==0 ){
  139010. *paPoslist = 0;
  139011. return SQLITE_OK;
  139012. }
  139013. while( 1 ){
  139014. Fts3SegReader *pSeg;
  139015. pSeg = pMsr->apSegment[0];
  139016. if( pSeg->pOffsetList==0 ){
  139017. *paPoslist = 0;
  139018. break;
  139019. }else{
  139020. int rc;
  139021. char *pList;
  139022. int nList;
  139023. int j;
  139024. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  139025. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  139026. j = 1;
  139027. while( rc==SQLITE_OK
  139028. && j<nMerge
  139029. && apSegment[j]->pOffsetList
  139030. && apSegment[j]->iDocid==iDocid
  139031. ){
  139032. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  139033. j++;
  139034. }
  139035. if( rc!=SQLITE_OK ) return rc;
  139036. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  139037. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  139038. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  139039. if( rc!=SQLITE_OK ) return rc;
  139040. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  139041. pList = pMsr->aBuffer;
  139042. }
  139043. if( pMsr->iColFilter>=0 ){
  139044. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  139045. }
  139046. if( nList>0 ){
  139047. *paPoslist = pList;
  139048. *piDocid = iDocid;
  139049. *pnPoslist = nList;
  139050. break;
  139051. }
  139052. }
  139053. }
  139054. return SQLITE_OK;
  139055. }
  139056. static int fts3SegReaderStart(
  139057. Fts3Table *p, /* Virtual table handle */
  139058. Fts3MultiSegReader *pCsr, /* Cursor object */
  139059. const char *zTerm, /* Term searched for (or NULL) */
  139060. int nTerm /* Length of zTerm in bytes */
  139061. ){
  139062. int i;
  139063. int nSeg = pCsr->nSegment;
  139064. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  139065. ** for, then advance each segment iterator until it points to a term of
  139066. ** equal or greater value than the specified term. This prevents many
  139067. ** unnecessary merge/sort operations for the case where single segment
  139068. ** b-tree leaf nodes contain more than one term.
  139069. */
  139070. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  139071. int res = 0;
  139072. Fts3SegReader *pSeg = pCsr->apSegment[i];
  139073. do {
  139074. int rc = fts3SegReaderNext(p, pSeg, 0);
  139075. if( rc!=SQLITE_OK ) return rc;
  139076. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  139077. if( pSeg->bLookup && res!=0 ){
  139078. fts3SegReaderSetEof(pSeg);
  139079. }
  139080. }
  139081. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  139082. return SQLITE_OK;
  139083. }
  139084. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  139085. Fts3Table *p, /* Virtual table handle */
  139086. Fts3MultiSegReader *pCsr, /* Cursor object */
  139087. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  139088. ){
  139089. pCsr->pFilter = pFilter;
  139090. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  139091. }
  139092. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  139093. Fts3Table *p, /* Virtual table handle */
  139094. Fts3MultiSegReader *pCsr, /* Cursor object */
  139095. int iCol, /* Column to match on. */
  139096. const char *zTerm, /* Term to iterate through a doclist for */
  139097. int nTerm /* Number of bytes in zTerm */
  139098. ){
  139099. int i;
  139100. int rc;
  139101. int nSegment = pCsr->nSegment;
  139102. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  139103. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  139104. );
  139105. assert( pCsr->pFilter==0 );
  139106. assert( zTerm && nTerm>0 );
  139107. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  139108. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  139109. if( rc!=SQLITE_OK ) return rc;
  139110. /* Determine how many of the segments actually point to zTerm/nTerm. */
  139111. for(i=0; i<nSegment; i++){
  139112. Fts3SegReader *pSeg = pCsr->apSegment[i];
  139113. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  139114. break;
  139115. }
  139116. }
  139117. pCsr->nAdvance = i;
  139118. /* Advance each of the segments to point to the first docid. */
  139119. for(i=0; i<pCsr->nAdvance; i++){
  139120. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  139121. if( rc!=SQLITE_OK ) return rc;
  139122. }
  139123. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  139124. assert( iCol<0 || iCol<p->nColumn );
  139125. pCsr->iColFilter = iCol;
  139126. return SQLITE_OK;
  139127. }
  139128. /*
  139129. ** This function is called on a MultiSegReader that has been started using
  139130. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  139131. ** have been made. Calling this function puts the MultiSegReader in such
  139132. ** a state that if the next two calls are:
  139133. **
  139134. ** sqlite3Fts3SegReaderStart()
  139135. ** sqlite3Fts3SegReaderStep()
  139136. **
  139137. ** then the entire doclist for the term is available in
  139138. ** MultiSegReader.aDoclist/nDoclist.
  139139. */
  139140. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  139141. int i; /* Used to iterate through segment-readers */
  139142. assert( pCsr->zTerm==0 );
  139143. assert( pCsr->nTerm==0 );
  139144. assert( pCsr->aDoclist==0 );
  139145. assert( pCsr->nDoclist==0 );
  139146. pCsr->nAdvance = 0;
  139147. pCsr->bRestart = 1;
  139148. for(i=0; i<pCsr->nSegment; i++){
  139149. pCsr->apSegment[i]->pOffsetList = 0;
  139150. pCsr->apSegment[i]->nOffsetList = 0;
  139151. pCsr->apSegment[i]->iDocid = 0;
  139152. }
  139153. return SQLITE_OK;
  139154. }
  139155. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  139156. Fts3Table *p, /* Virtual table handle */
  139157. Fts3MultiSegReader *pCsr /* Cursor object */
  139158. ){
  139159. int rc = SQLITE_OK;
  139160. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  139161. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  139162. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  139163. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  139164. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  139165. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  139166. Fts3SegReader **apSegment = pCsr->apSegment;
  139167. int nSegment = pCsr->nSegment;
  139168. Fts3SegFilter *pFilter = pCsr->pFilter;
  139169. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  139170. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  139171. );
  139172. if( pCsr->nSegment==0 ) return SQLITE_OK;
  139173. do {
  139174. int nMerge;
  139175. int i;
  139176. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  139177. ** forward. Then sort the list in order of current term again.
  139178. */
  139179. for(i=0; i<pCsr->nAdvance; i++){
  139180. Fts3SegReader *pSeg = apSegment[i];
  139181. if( pSeg->bLookup ){
  139182. fts3SegReaderSetEof(pSeg);
  139183. }else{
  139184. rc = fts3SegReaderNext(p, pSeg, 0);
  139185. }
  139186. if( rc!=SQLITE_OK ) return rc;
  139187. }
  139188. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  139189. pCsr->nAdvance = 0;
  139190. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  139191. assert( rc==SQLITE_OK );
  139192. if( apSegment[0]->aNode==0 ) break;
  139193. pCsr->nTerm = apSegment[0]->nTerm;
  139194. pCsr->zTerm = apSegment[0]->zTerm;
  139195. /* If this is a prefix-search, and if the term that apSegment[0] points
  139196. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  139197. ** required callbacks have been made. In this case exit early.
  139198. **
  139199. ** Similarly, if this is a search for an exact match, and the first term
  139200. ** of segment apSegment[0] is not a match, exit early.
  139201. */
  139202. if( pFilter->zTerm && !isScan ){
  139203. if( pCsr->nTerm<pFilter->nTerm
  139204. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  139205. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  139206. ){
  139207. break;
  139208. }
  139209. }
  139210. nMerge = 1;
  139211. while( nMerge<nSegment
  139212. && apSegment[nMerge]->aNode
  139213. && apSegment[nMerge]->nTerm==pCsr->nTerm
  139214. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  139215. ){
  139216. nMerge++;
  139217. }
  139218. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  139219. if( nMerge==1
  139220. && !isIgnoreEmpty
  139221. && !isFirst
  139222. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  139223. ){
  139224. pCsr->nDoclist = apSegment[0]->nDoclist;
  139225. if( fts3SegReaderIsPending(apSegment[0]) ){
  139226. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  139227. pCsr->aDoclist = pCsr->aBuffer;
  139228. }else{
  139229. pCsr->aDoclist = apSegment[0]->aDoclist;
  139230. }
  139231. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  139232. }else{
  139233. int nDoclist = 0; /* Size of doclist */
  139234. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  139235. /* The current term of the first nMerge entries in the array
  139236. ** of Fts3SegReader objects is the same. The doclists must be merged
  139237. ** and a single term returned with the merged doclist.
  139238. */
  139239. for(i=0; i<nMerge; i++){
  139240. fts3SegReaderFirstDocid(p, apSegment[i]);
  139241. }
  139242. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  139243. while( apSegment[0]->pOffsetList ){
  139244. int j; /* Number of segments that share a docid */
  139245. char *pList = 0;
  139246. int nList = 0;
  139247. int nByte;
  139248. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  139249. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  139250. j = 1;
  139251. while( j<nMerge
  139252. && apSegment[j]->pOffsetList
  139253. && apSegment[j]->iDocid==iDocid
  139254. ){
  139255. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  139256. j++;
  139257. }
  139258. if( isColFilter ){
  139259. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  139260. }
  139261. if( !isIgnoreEmpty || nList>0 ){
  139262. /* Calculate the 'docid' delta value to write into the merged
  139263. ** doclist. */
  139264. sqlite3_int64 iDelta;
  139265. if( p->bDescIdx && nDoclist>0 ){
  139266. iDelta = iPrev - iDocid;
  139267. }else{
  139268. iDelta = iDocid - iPrev;
  139269. }
  139270. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  139271. assert( nDoclist>0 || iDelta==iDocid );
  139272. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  139273. if( nDoclist+nByte>pCsr->nBuffer ){
  139274. char *aNew;
  139275. pCsr->nBuffer = (nDoclist+nByte)*2;
  139276. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  139277. if( !aNew ){
  139278. return SQLITE_NOMEM;
  139279. }
  139280. pCsr->aBuffer = aNew;
  139281. }
  139282. if( isFirst ){
  139283. char *a = &pCsr->aBuffer[nDoclist];
  139284. int nWrite;
  139285. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  139286. if( nWrite ){
  139287. iPrev = iDocid;
  139288. nDoclist += nWrite;
  139289. }
  139290. }else{
  139291. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  139292. iPrev = iDocid;
  139293. if( isRequirePos ){
  139294. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  139295. nDoclist += nList;
  139296. pCsr->aBuffer[nDoclist++] = '\0';
  139297. }
  139298. }
  139299. }
  139300. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  139301. }
  139302. if( nDoclist>0 ){
  139303. pCsr->aDoclist = pCsr->aBuffer;
  139304. pCsr->nDoclist = nDoclist;
  139305. rc = SQLITE_ROW;
  139306. }
  139307. }
  139308. pCsr->nAdvance = nMerge;
  139309. }while( rc==SQLITE_OK );
  139310. return rc;
  139311. }
  139312. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  139313. Fts3MultiSegReader *pCsr /* Cursor object */
  139314. ){
  139315. if( pCsr ){
  139316. int i;
  139317. for(i=0; i<pCsr->nSegment; i++){
  139318. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  139319. }
  139320. sqlite3_free(pCsr->apSegment);
  139321. sqlite3_free(pCsr->aBuffer);
  139322. pCsr->nSegment = 0;
  139323. pCsr->apSegment = 0;
  139324. pCsr->aBuffer = 0;
  139325. }
  139326. }
  139327. /*
  139328. ** Decode the "end_block" field, selected by column iCol of the SELECT
  139329. ** statement passed as the first argument.
  139330. **
  139331. ** The "end_block" field may contain either an integer, or a text field
  139332. ** containing the text representation of two non-negative integers separated
  139333. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  139334. ** to the integer value and *pnByte to zero before returning. In the second,
  139335. ** set *piEndBlock to the first value and *pnByte to the second.
  139336. */
  139337. static void fts3ReadEndBlockField(
  139338. sqlite3_stmt *pStmt,
  139339. int iCol,
  139340. i64 *piEndBlock,
  139341. i64 *pnByte
  139342. ){
  139343. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  139344. if( zText ){
  139345. int i;
  139346. int iMul = 1;
  139347. i64 iVal = 0;
  139348. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  139349. iVal = iVal*10 + (zText[i] - '0');
  139350. }
  139351. *piEndBlock = iVal;
  139352. while( zText[i]==' ' ) i++;
  139353. iVal = 0;
  139354. if( zText[i]=='-' ){
  139355. i++;
  139356. iMul = -1;
  139357. }
  139358. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  139359. iVal = iVal*10 + (zText[i] - '0');
  139360. }
  139361. *pnByte = (iVal * (i64)iMul);
  139362. }
  139363. }
  139364. /*
  139365. ** A segment of size nByte bytes has just been written to absolute level
  139366. ** iAbsLevel. Promote any segments that should be promoted as a result.
  139367. */
  139368. static int fts3PromoteSegments(
  139369. Fts3Table *p, /* FTS table handle */
  139370. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  139371. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  139372. ){
  139373. int rc = SQLITE_OK;
  139374. sqlite3_stmt *pRange;
  139375. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  139376. if( rc==SQLITE_OK ){
  139377. int bOk = 0;
  139378. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  139379. i64 nLimit = (nByte*3)/2;
  139380. /* Loop through all entries in the %_segdir table corresponding to
  139381. ** segments in this index on levels greater than iAbsLevel. If there is
  139382. ** at least one such segment, and it is possible to determine that all
  139383. ** such segments are smaller than nLimit bytes in size, they will be
  139384. ** promoted to level iAbsLevel. */
  139385. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  139386. sqlite3_bind_int64(pRange, 2, iLast);
  139387. while( SQLITE_ROW==sqlite3_step(pRange) ){
  139388. i64 nSize = 0, dummy;
  139389. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  139390. if( nSize<=0 || nSize>nLimit ){
  139391. /* If nSize==0, then the %_segdir.end_block field does not not
  139392. ** contain a size value. This happens if it was written by an
  139393. ** old version of FTS. In this case it is not possible to determine
  139394. ** the size of the segment, and so segment promotion does not
  139395. ** take place. */
  139396. bOk = 0;
  139397. break;
  139398. }
  139399. bOk = 1;
  139400. }
  139401. rc = sqlite3_reset(pRange);
  139402. if( bOk ){
  139403. int iIdx = 0;
  139404. sqlite3_stmt *pUpdate1 = 0;
  139405. sqlite3_stmt *pUpdate2 = 0;
  139406. if( rc==SQLITE_OK ){
  139407. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  139408. }
  139409. if( rc==SQLITE_OK ){
  139410. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  139411. }
  139412. if( rc==SQLITE_OK ){
  139413. /* Loop through all %_segdir entries for segments in this index with
  139414. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  139415. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  139416. ** oldest segment in the range, 1 for the next oldest, and so on.
  139417. **
  139418. ** In other words, move all segments being promoted to level -1,
  139419. ** setting the "idx" fields as appropriate to keep them in the same
  139420. ** order. The contents of level -1 (which is never used, except
  139421. ** transiently here), will be moved back to level iAbsLevel below. */
  139422. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  139423. while( SQLITE_ROW==sqlite3_step(pRange) ){
  139424. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  139425. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  139426. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  139427. sqlite3_step(pUpdate1);
  139428. rc = sqlite3_reset(pUpdate1);
  139429. if( rc!=SQLITE_OK ){
  139430. sqlite3_reset(pRange);
  139431. break;
  139432. }
  139433. }
  139434. }
  139435. if( rc==SQLITE_OK ){
  139436. rc = sqlite3_reset(pRange);
  139437. }
  139438. /* Move level -1 to level iAbsLevel */
  139439. if( rc==SQLITE_OK ){
  139440. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  139441. sqlite3_step(pUpdate2);
  139442. rc = sqlite3_reset(pUpdate2);
  139443. }
  139444. }
  139445. }
  139446. return rc;
  139447. }
  139448. /*
  139449. ** Merge all level iLevel segments in the database into a single
  139450. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  139451. ** single segment with a level equal to the numerically largest level
  139452. ** currently present in the database.
  139453. **
  139454. ** If this function is called with iLevel<0, but there is only one
  139455. ** segment in the database, SQLITE_DONE is returned immediately.
  139456. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  139457. ** an SQLite error code is returned.
  139458. */
  139459. static int fts3SegmentMerge(
  139460. Fts3Table *p,
  139461. int iLangid, /* Language id to merge */
  139462. int iIndex, /* Index in p->aIndex[] to merge */
  139463. int iLevel /* Level to merge */
  139464. ){
  139465. int rc; /* Return code */
  139466. int iIdx = 0; /* Index of new segment */
  139467. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  139468. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  139469. Fts3SegFilter filter; /* Segment term filter condition */
  139470. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  139471. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  139472. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  139473. assert( iLevel==FTS3_SEGCURSOR_ALL
  139474. || iLevel==FTS3_SEGCURSOR_PENDING
  139475. || iLevel>=0
  139476. );
  139477. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  139478. assert( iIndex>=0 && iIndex<p->nIndex );
  139479. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  139480. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  139481. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  139482. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  139483. if( rc!=SQLITE_OK ) goto finished;
  139484. }
  139485. if( iLevel==FTS3_SEGCURSOR_ALL ){
  139486. /* This call is to merge all segments in the database to a single
  139487. ** segment. The level of the new segment is equal to the numerically
  139488. ** greatest segment level currently present in the database for this
  139489. ** index. The idx of the new segment is always 0. */
  139490. if( csr.nSegment==1 ){
  139491. rc = SQLITE_DONE;
  139492. goto finished;
  139493. }
  139494. iNewLevel = iMaxLevel;
  139495. bIgnoreEmpty = 1;
  139496. }else{
  139497. /* This call is to merge all segments at level iLevel. find the next
  139498. ** available segment index at level iLevel+1. The call to
  139499. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  139500. ** a single iLevel+2 segment if necessary. */
  139501. assert( FTS3_SEGCURSOR_PENDING==-1 );
  139502. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  139503. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  139504. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  139505. }
  139506. if( rc!=SQLITE_OK ) goto finished;
  139507. assert( csr.nSegment>0 );
  139508. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  139509. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  139510. memset(&filter, 0, sizeof(Fts3SegFilter));
  139511. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  139512. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  139513. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  139514. while( SQLITE_OK==rc ){
  139515. rc = sqlite3Fts3SegReaderStep(p, &csr);
  139516. if( rc!=SQLITE_ROW ) break;
  139517. rc = fts3SegWriterAdd(p, &pWriter, 1,
  139518. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  139519. }
  139520. if( rc!=SQLITE_OK ) goto finished;
  139521. assert( pWriter || bIgnoreEmpty );
  139522. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  139523. rc = fts3DeleteSegdir(
  139524. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  139525. );
  139526. if( rc!=SQLITE_OK ) goto finished;
  139527. }
  139528. if( pWriter ){
  139529. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  139530. if( rc==SQLITE_OK ){
  139531. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  139532. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  139533. }
  139534. }
  139535. }
  139536. finished:
  139537. fts3SegWriterFree(pWriter);
  139538. sqlite3Fts3SegReaderFinish(&csr);
  139539. return rc;
  139540. }
  139541. /*
  139542. ** Flush the contents of pendingTerms to level 0 segments.
  139543. */
  139544. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  139545. int rc = SQLITE_OK;
  139546. int i;
  139547. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  139548. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  139549. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  139550. }
  139551. sqlite3Fts3PendingTermsClear(p);
  139552. /* Determine the auto-incr-merge setting if unknown. If enabled,
  139553. ** estimate the number of leaf blocks of content to be written
  139554. */
  139555. if( rc==SQLITE_OK && p->bHasStat
  139556. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  139557. ){
  139558. sqlite3_stmt *pStmt = 0;
  139559. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  139560. if( rc==SQLITE_OK ){
  139561. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  139562. rc = sqlite3_step(pStmt);
  139563. if( rc==SQLITE_ROW ){
  139564. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  139565. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  139566. }else if( rc==SQLITE_DONE ){
  139567. p->nAutoincrmerge = 0;
  139568. }
  139569. rc = sqlite3_reset(pStmt);
  139570. }
  139571. }
  139572. return rc;
  139573. }
  139574. /*
  139575. ** Encode N integers as varints into a blob.
  139576. */
  139577. static void fts3EncodeIntArray(
  139578. int N, /* The number of integers to encode */
  139579. u32 *a, /* The integer values */
  139580. char *zBuf, /* Write the BLOB here */
  139581. int *pNBuf /* Write number of bytes if zBuf[] used here */
  139582. ){
  139583. int i, j;
  139584. for(i=j=0; i<N; i++){
  139585. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  139586. }
  139587. *pNBuf = j;
  139588. }
  139589. /*
  139590. ** Decode a blob of varints into N integers
  139591. */
  139592. static void fts3DecodeIntArray(
  139593. int N, /* The number of integers to decode */
  139594. u32 *a, /* Write the integer values */
  139595. const char *zBuf, /* The BLOB containing the varints */
  139596. int nBuf /* size of the BLOB */
  139597. ){
  139598. int i, j;
  139599. UNUSED_PARAMETER(nBuf);
  139600. for(i=j=0; i<N; i++){
  139601. sqlite3_int64 x;
  139602. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  139603. assert(j<=nBuf);
  139604. a[i] = (u32)(x & 0xffffffff);
  139605. }
  139606. }
  139607. /*
  139608. ** Insert the sizes (in tokens) for each column of the document
  139609. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  139610. ** a blob of varints.
  139611. */
  139612. static void fts3InsertDocsize(
  139613. int *pRC, /* Result code */
  139614. Fts3Table *p, /* Table into which to insert */
  139615. u32 *aSz /* Sizes of each column, in tokens */
  139616. ){
  139617. char *pBlob; /* The BLOB encoding of the document size */
  139618. int nBlob; /* Number of bytes in the BLOB */
  139619. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  139620. int rc; /* Result code from subfunctions */
  139621. if( *pRC ) return;
  139622. pBlob = sqlite3_malloc( 10*p->nColumn );
  139623. if( pBlob==0 ){
  139624. *pRC = SQLITE_NOMEM;
  139625. return;
  139626. }
  139627. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  139628. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  139629. if( rc ){
  139630. sqlite3_free(pBlob);
  139631. *pRC = rc;
  139632. return;
  139633. }
  139634. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  139635. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  139636. sqlite3_step(pStmt);
  139637. *pRC = sqlite3_reset(pStmt);
  139638. }
  139639. /*
  139640. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  139641. ** where N is the number of user defined columns in the fts3 table plus
  139642. ** two. If nCol is the number of user defined columns, then values of the
  139643. ** varints are set as follows:
  139644. **
  139645. ** Varint 0: Total number of rows in the table.
  139646. **
  139647. ** Varint 1..nCol: For each column, the total number of tokens stored in
  139648. ** the column for all rows of the table.
  139649. **
  139650. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  139651. ** columns of all rows of the table.
  139652. **
  139653. */
  139654. static void fts3UpdateDocTotals(
  139655. int *pRC, /* The result code */
  139656. Fts3Table *p, /* Table being updated */
  139657. u32 *aSzIns, /* Size increases */
  139658. u32 *aSzDel, /* Size decreases */
  139659. int nChng /* Change in the number of documents */
  139660. ){
  139661. char *pBlob; /* Storage for BLOB written into %_stat */
  139662. int nBlob; /* Size of BLOB written into %_stat */
  139663. u32 *a; /* Array of integers that becomes the BLOB */
  139664. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  139665. int i; /* Loop counter */
  139666. int rc; /* Result code from subfunctions */
  139667. const int nStat = p->nColumn+2;
  139668. if( *pRC ) return;
  139669. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  139670. if( a==0 ){
  139671. *pRC = SQLITE_NOMEM;
  139672. return;
  139673. }
  139674. pBlob = (char*)&a[nStat];
  139675. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  139676. if( rc ){
  139677. sqlite3_free(a);
  139678. *pRC = rc;
  139679. return;
  139680. }
  139681. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  139682. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  139683. fts3DecodeIntArray(nStat, a,
  139684. sqlite3_column_blob(pStmt, 0),
  139685. sqlite3_column_bytes(pStmt, 0));
  139686. }else{
  139687. memset(a, 0, sizeof(u32)*(nStat) );
  139688. }
  139689. rc = sqlite3_reset(pStmt);
  139690. if( rc!=SQLITE_OK ){
  139691. sqlite3_free(a);
  139692. *pRC = rc;
  139693. return;
  139694. }
  139695. if( nChng<0 && a[0]<(u32)(-nChng) ){
  139696. a[0] = 0;
  139697. }else{
  139698. a[0] += nChng;
  139699. }
  139700. for(i=0; i<p->nColumn+1; i++){
  139701. u32 x = a[i+1];
  139702. if( x+aSzIns[i] < aSzDel[i] ){
  139703. x = 0;
  139704. }else{
  139705. x = x + aSzIns[i] - aSzDel[i];
  139706. }
  139707. a[i+1] = x;
  139708. }
  139709. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  139710. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  139711. if( rc ){
  139712. sqlite3_free(a);
  139713. *pRC = rc;
  139714. return;
  139715. }
  139716. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  139717. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  139718. sqlite3_step(pStmt);
  139719. *pRC = sqlite3_reset(pStmt);
  139720. sqlite3_free(a);
  139721. }
  139722. /*
  139723. ** Merge the entire database so that there is one segment for each
  139724. ** iIndex/iLangid combination.
  139725. */
  139726. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  139727. int bSeenDone = 0;
  139728. int rc;
  139729. sqlite3_stmt *pAllLangid = 0;
  139730. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  139731. if( rc==SQLITE_OK ){
  139732. int rc2;
  139733. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  139734. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  139735. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  139736. int i;
  139737. int iLangid = sqlite3_column_int(pAllLangid, 0);
  139738. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  139739. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  139740. if( rc==SQLITE_DONE ){
  139741. bSeenDone = 1;
  139742. rc = SQLITE_OK;
  139743. }
  139744. }
  139745. }
  139746. rc2 = sqlite3_reset(pAllLangid);
  139747. if( rc==SQLITE_OK ) rc = rc2;
  139748. }
  139749. sqlite3Fts3SegmentsClose(p);
  139750. sqlite3Fts3PendingTermsClear(p);
  139751. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  139752. }
  139753. /*
  139754. ** This function is called when the user executes the following statement:
  139755. **
  139756. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  139757. **
  139758. ** The entire FTS index is discarded and rebuilt. If the table is one
  139759. ** created using the content=xxx option, then the new index is based on
  139760. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  139761. ** on the contents of the %_content table.
  139762. */
  139763. static int fts3DoRebuild(Fts3Table *p){
  139764. int rc; /* Return Code */
  139765. rc = fts3DeleteAll(p, 0);
  139766. if( rc==SQLITE_OK ){
  139767. u32 *aSz = 0;
  139768. u32 *aSzIns = 0;
  139769. u32 *aSzDel = 0;
  139770. sqlite3_stmt *pStmt = 0;
  139771. int nEntry = 0;
  139772. /* Compose and prepare an SQL statement to loop through the content table */
  139773. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  139774. if( !zSql ){
  139775. rc = SQLITE_NOMEM;
  139776. }else{
  139777. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  139778. sqlite3_free(zSql);
  139779. }
  139780. if( rc==SQLITE_OK ){
  139781. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  139782. aSz = (u32 *)sqlite3_malloc(nByte);
  139783. if( aSz==0 ){
  139784. rc = SQLITE_NOMEM;
  139785. }else{
  139786. memset(aSz, 0, nByte);
  139787. aSzIns = &aSz[p->nColumn+1];
  139788. aSzDel = &aSzIns[p->nColumn+1];
  139789. }
  139790. }
  139791. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  139792. int iCol;
  139793. int iLangid = langidFromSelect(p, pStmt);
  139794. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  139795. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  139796. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  139797. if( p->abNotindexed[iCol]==0 ){
  139798. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  139799. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  139800. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  139801. }
  139802. }
  139803. if( p->bHasDocsize ){
  139804. fts3InsertDocsize(&rc, p, aSz);
  139805. }
  139806. if( rc!=SQLITE_OK ){
  139807. sqlite3_finalize(pStmt);
  139808. pStmt = 0;
  139809. }else{
  139810. nEntry++;
  139811. for(iCol=0; iCol<=p->nColumn; iCol++){
  139812. aSzIns[iCol] += aSz[iCol];
  139813. }
  139814. }
  139815. }
  139816. if( p->bFts4 ){
  139817. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  139818. }
  139819. sqlite3_free(aSz);
  139820. if( pStmt ){
  139821. int rc2 = sqlite3_finalize(pStmt);
  139822. if( rc==SQLITE_OK ){
  139823. rc = rc2;
  139824. }
  139825. }
  139826. }
  139827. return rc;
  139828. }
  139829. /*
  139830. ** This function opens a cursor used to read the input data for an
  139831. ** incremental merge operation. Specifically, it opens a cursor to scan
  139832. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  139833. ** level iAbsLevel.
  139834. */
  139835. static int fts3IncrmergeCsr(
  139836. Fts3Table *p, /* FTS3 table handle */
  139837. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  139838. int nSeg, /* Number of segments to merge */
  139839. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  139840. ){
  139841. int rc; /* Return Code */
  139842. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  139843. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  139844. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  139845. memset(pCsr, 0, sizeof(*pCsr));
  139846. nByte = sizeof(Fts3SegReader *) * nSeg;
  139847. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  139848. if( pCsr->apSegment==0 ){
  139849. rc = SQLITE_NOMEM;
  139850. }else{
  139851. memset(pCsr->apSegment, 0, nByte);
  139852. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  139853. }
  139854. if( rc==SQLITE_OK ){
  139855. int i;
  139856. int rc2;
  139857. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  139858. assert( pCsr->nSegment==0 );
  139859. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  139860. rc = sqlite3Fts3SegReaderNew(i, 0,
  139861. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  139862. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  139863. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  139864. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  139865. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  139866. &pCsr->apSegment[i]
  139867. );
  139868. pCsr->nSegment++;
  139869. }
  139870. rc2 = sqlite3_reset(pStmt);
  139871. if( rc==SQLITE_OK ) rc = rc2;
  139872. }
  139873. return rc;
  139874. }
  139875. typedef struct IncrmergeWriter IncrmergeWriter;
  139876. typedef struct NodeWriter NodeWriter;
  139877. typedef struct Blob Blob;
  139878. typedef struct NodeReader NodeReader;
  139879. /*
  139880. ** An instance of the following structure is used as a dynamic buffer
  139881. ** to build up nodes or other blobs of data in.
  139882. **
  139883. ** The function blobGrowBuffer() is used to extend the allocation.
  139884. */
  139885. struct Blob {
  139886. char *a; /* Pointer to allocation */
  139887. int n; /* Number of valid bytes of data in a[] */
  139888. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  139889. };
  139890. /*
  139891. ** This structure is used to build up buffers containing segment b-tree
  139892. ** nodes (blocks).
  139893. */
  139894. struct NodeWriter {
  139895. sqlite3_int64 iBlock; /* Current block id */
  139896. Blob key; /* Last key written to the current block */
  139897. Blob block; /* Current block image */
  139898. };
  139899. /*
  139900. ** An object of this type contains the state required to create or append
  139901. ** to an appendable b-tree segment.
  139902. */
  139903. struct IncrmergeWriter {
  139904. int nLeafEst; /* Space allocated for leaf blocks */
  139905. int nWork; /* Number of leaf pages flushed */
  139906. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  139907. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  139908. sqlite3_int64 iStart; /* Block number of first allocated block */
  139909. sqlite3_int64 iEnd; /* Block number of last allocated block */
  139910. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  139911. u8 bNoLeafData; /* If true, store 0 for segment size */
  139912. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  139913. };
  139914. /*
  139915. ** An object of the following type is used to read data from a single
  139916. ** FTS segment node. See the following functions:
  139917. **
  139918. ** nodeReaderInit()
  139919. ** nodeReaderNext()
  139920. ** nodeReaderRelease()
  139921. */
  139922. struct NodeReader {
  139923. const char *aNode;
  139924. int nNode;
  139925. int iOff; /* Current offset within aNode[] */
  139926. /* Output variables. Containing the current node entry. */
  139927. sqlite3_int64 iChild; /* Pointer to child node */
  139928. Blob term; /* Current term */
  139929. const char *aDoclist; /* Pointer to doclist */
  139930. int nDoclist; /* Size of doclist in bytes */
  139931. };
  139932. /*
  139933. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  139934. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  139935. ** bytes in size, extend (realloc) it to be so.
  139936. **
  139937. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  139938. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  139939. ** to reflect the new size of the pBlob->a[] buffer.
  139940. */
  139941. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  139942. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  139943. int nAlloc = nMin;
  139944. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  139945. if( a ){
  139946. pBlob->nAlloc = nAlloc;
  139947. pBlob->a = a;
  139948. }else{
  139949. *pRc = SQLITE_NOMEM;
  139950. }
  139951. }
  139952. }
  139953. /*
  139954. ** Attempt to advance the node-reader object passed as the first argument to
  139955. ** the next entry on the node.
  139956. **
  139957. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  139958. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  139959. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  139960. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  139961. ** variables for the new entry.
  139962. */
  139963. static int nodeReaderNext(NodeReader *p){
  139964. int bFirst = (p->term.n==0); /* True for first term on the node */
  139965. int nPrefix = 0; /* Bytes to copy from previous term */
  139966. int nSuffix = 0; /* Bytes to append to the prefix */
  139967. int rc = SQLITE_OK; /* Return code */
  139968. assert( p->aNode );
  139969. if( p->iChild && bFirst==0 ) p->iChild++;
  139970. if( p->iOff>=p->nNode ){
  139971. /* EOF */
  139972. p->aNode = 0;
  139973. }else{
  139974. if( bFirst==0 ){
  139975. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  139976. }
  139977. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  139978. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  139979. if( rc==SQLITE_OK ){
  139980. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  139981. p->term.n = nPrefix+nSuffix;
  139982. p->iOff += nSuffix;
  139983. if( p->iChild==0 ){
  139984. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  139985. p->aDoclist = &p->aNode[p->iOff];
  139986. p->iOff += p->nDoclist;
  139987. }
  139988. }
  139989. }
  139990. assert( p->iOff<=p->nNode );
  139991. return rc;
  139992. }
  139993. /*
  139994. ** Release all dynamic resources held by node-reader object *p.
  139995. */
  139996. static void nodeReaderRelease(NodeReader *p){
  139997. sqlite3_free(p->term.a);
  139998. }
  139999. /*
  140000. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  140001. **
  140002. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  140003. ** point to the first entry on the node (if any). Otherwise, an SQLite
  140004. ** error code is returned.
  140005. */
  140006. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  140007. memset(p, 0, sizeof(NodeReader));
  140008. p->aNode = aNode;
  140009. p->nNode = nNode;
  140010. /* Figure out if this is a leaf or an internal node. */
  140011. if( p->aNode[0] ){
  140012. /* An internal node. */
  140013. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  140014. }else{
  140015. p->iOff = 1;
  140016. }
  140017. return nodeReaderNext(p);
  140018. }
  140019. /*
  140020. ** This function is called while writing an FTS segment each time a leaf o
  140021. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  140022. ** to be greater than the largest key on the node just written, but smaller
  140023. ** than or equal to the first key that will be written to the next leaf
  140024. ** node.
  140025. **
  140026. ** The block id of the leaf node just written to disk may be found in
  140027. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  140028. */
  140029. static int fts3IncrmergePush(
  140030. Fts3Table *p, /* Fts3 table handle */
  140031. IncrmergeWriter *pWriter, /* Writer object */
  140032. const char *zTerm, /* Term to write to internal node */
  140033. int nTerm /* Bytes at zTerm */
  140034. ){
  140035. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  140036. int iLayer;
  140037. assert( nTerm>0 );
  140038. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  140039. sqlite3_int64 iNextPtr = 0;
  140040. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  140041. int rc = SQLITE_OK;
  140042. int nPrefix;
  140043. int nSuffix;
  140044. int nSpace;
  140045. /* Figure out how much space the key will consume if it is written to
  140046. ** the current node of layer iLayer. Due to the prefix compression,
  140047. ** the space required changes depending on which node the key is to
  140048. ** be added to. */
  140049. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  140050. nSuffix = nTerm - nPrefix;
  140051. nSpace = sqlite3Fts3VarintLen(nPrefix);
  140052. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  140053. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  140054. /* If the current node of layer iLayer contains zero keys, or if adding
  140055. ** the key to it will not cause it to grow to larger than nNodeSize
  140056. ** bytes in size, write the key here. */
  140057. Blob *pBlk = &pNode->block;
  140058. if( pBlk->n==0 ){
  140059. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  140060. if( rc==SQLITE_OK ){
  140061. pBlk->a[0] = (char)iLayer;
  140062. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  140063. }
  140064. }
  140065. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  140066. blobGrowBuffer(&pNode->key, nTerm, &rc);
  140067. if( rc==SQLITE_OK ){
  140068. if( pNode->key.n ){
  140069. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  140070. }
  140071. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  140072. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  140073. pBlk->n += nSuffix;
  140074. memcpy(pNode->key.a, zTerm, nTerm);
  140075. pNode->key.n = nTerm;
  140076. }
  140077. }else{
  140078. /* Otherwise, flush the current node of layer iLayer to disk.
  140079. ** Then allocate a new, empty sibling node. The key will be written
  140080. ** into the parent of this node. */
  140081. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  140082. assert( pNode->block.nAlloc>=p->nNodeSize );
  140083. pNode->block.a[0] = (char)iLayer;
  140084. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  140085. iNextPtr = pNode->iBlock;
  140086. pNode->iBlock++;
  140087. pNode->key.n = 0;
  140088. }
  140089. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  140090. iPtr = iNextPtr;
  140091. }
  140092. assert( 0 );
  140093. return 0;
  140094. }
  140095. /*
  140096. ** Append a term and (optionally) doclist to the FTS segment node currently
  140097. ** stored in blob *pNode. The node need not contain any terms, but the
  140098. ** header must be written before this function is called.
  140099. **
  140100. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  140101. ** followed by the left-hand-child varint for an internal node.
  140102. **
  140103. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  140104. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  140105. ** node, both aDoclist and nDoclist must be passed 0.
  140106. **
  140107. ** If the size of the value in blob pPrev is zero, then this is the first
  140108. ** term written to the node. Otherwise, pPrev contains a copy of the
  140109. ** previous term. Before this function returns, it is updated to contain a
  140110. ** copy of zTerm/nTerm.
  140111. **
  140112. ** It is assumed that the buffer associated with pNode is already large
  140113. ** enough to accommodate the new entry. The buffer associated with pPrev
  140114. ** is extended by this function if requrired.
  140115. **
  140116. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  140117. ** returned. Otherwise, SQLITE_OK.
  140118. */
  140119. static int fts3AppendToNode(
  140120. Blob *pNode, /* Current node image to append to */
  140121. Blob *pPrev, /* Buffer containing previous term written */
  140122. const char *zTerm, /* New term to write */
  140123. int nTerm, /* Size of zTerm in bytes */
  140124. const char *aDoclist, /* Doclist (or NULL) to write */
  140125. int nDoclist /* Size of aDoclist in bytes */
  140126. ){
  140127. int rc = SQLITE_OK; /* Return code */
  140128. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  140129. int nPrefix; /* Size of term prefix in bytes */
  140130. int nSuffix; /* Size of term suffix in bytes */
  140131. /* Node must have already been started. There must be a doclist for a
  140132. ** leaf node, and there must not be a doclist for an internal node. */
  140133. assert( pNode->n>0 );
  140134. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  140135. blobGrowBuffer(pPrev, nTerm, &rc);
  140136. if( rc!=SQLITE_OK ) return rc;
  140137. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  140138. nSuffix = nTerm - nPrefix;
  140139. memcpy(pPrev->a, zTerm, nTerm);
  140140. pPrev->n = nTerm;
  140141. if( bFirst==0 ){
  140142. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  140143. }
  140144. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  140145. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  140146. pNode->n += nSuffix;
  140147. if( aDoclist ){
  140148. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  140149. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  140150. pNode->n += nDoclist;
  140151. }
  140152. assert( pNode->n<=pNode->nAlloc );
  140153. return SQLITE_OK;
  140154. }
  140155. /*
  140156. ** Append the current term and doclist pointed to by cursor pCsr to the
  140157. ** appendable b-tree segment opened for writing by pWriter.
  140158. **
  140159. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  140160. */
  140161. static int fts3IncrmergeAppend(
  140162. Fts3Table *p, /* Fts3 table handle */
  140163. IncrmergeWriter *pWriter, /* Writer object */
  140164. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  140165. ){
  140166. const char *zTerm = pCsr->zTerm;
  140167. int nTerm = pCsr->nTerm;
  140168. const char *aDoclist = pCsr->aDoclist;
  140169. int nDoclist = pCsr->nDoclist;
  140170. int rc = SQLITE_OK; /* Return code */
  140171. int nSpace; /* Total space in bytes required on leaf */
  140172. int nPrefix; /* Size of prefix shared with previous term */
  140173. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  140174. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  140175. pLeaf = &pWriter->aNodeWriter[0];
  140176. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  140177. nSuffix = nTerm - nPrefix;
  140178. nSpace = sqlite3Fts3VarintLen(nPrefix);
  140179. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  140180. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  140181. /* If the current block is not empty, and if adding this term/doclist
  140182. ** to the current block would make it larger than Fts3Table.nNodeSize
  140183. ** bytes, write this block out to the database. */
  140184. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  140185. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  140186. pWriter->nWork++;
  140187. /* Add the current term to the parent node. The term added to the
  140188. ** parent must:
  140189. **
  140190. ** a) be greater than the largest term on the leaf node just written
  140191. ** to the database (still available in pLeaf->key), and
  140192. **
  140193. ** b) be less than or equal to the term about to be added to the new
  140194. ** leaf node (zTerm/nTerm).
  140195. **
  140196. ** In other words, it must be the prefix of zTerm 1 byte longer than
  140197. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  140198. */
  140199. if( rc==SQLITE_OK ){
  140200. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  140201. }
  140202. /* Advance to the next output block */
  140203. pLeaf->iBlock++;
  140204. pLeaf->key.n = 0;
  140205. pLeaf->block.n = 0;
  140206. nSuffix = nTerm;
  140207. nSpace = 1;
  140208. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  140209. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  140210. }
  140211. pWriter->nLeafData += nSpace;
  140212. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  140213. if( rc==SQLITE_OK ){
  140214. if( pLeaf->block.n==0 ){
  140215. pLeaf->block.n = 1;
  140216. pLeaf->block.a[0] = '\0';
  140217. }
  140218. rc = fts3AppendToNode(
  140219. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  140220. );
  140221. }
  140222. return rc;
  140223. }
  140224. /*
  140225. ** This function is called to release all dynamic resources held by the
  140226. ** merge-writer object pWriter, and if no error has occurred, to flush
  140227. ** all outstanding node buffers held by pWriter to disk.
  140228. **
  140229. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  140230. ** is made to write any data to disk. Instead, this function serves only
  140231. ** to release outstanding resources.
  140232. **
  140233. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  140234. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  140235. ** returning.
  140236. */
  140237. static void fts3IncrmergeRelease(
  140238. Fts3Table *p, /* FTS3 table handle */
  140239. IncrmergeWriter *pWriter, /* Merge-writer object */
  140240. int *pRc /* IN/OUT: Error code */
  140241. ){
  140242. int i; /* Used to iterate through non-root layers */
  140243. int iRoot; /* Index of root in pWriter->aNodeWriter */
  140244. NodeWriter *pRoot; /* NodeWriter for root node */
  140245. int rc = *pRc; /* Error code */
  140246. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  140247. ** root node. If the segment fits entirely on a single leaf node, iRoot
  140248. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  140249. ** will be 1. And so on. */
  140250. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  140251. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  140252. if( pNode->block.n>0 ) break;
  140253. assert( *pRc || pNode->block.nAlloc==0 );
  140254. assert( *pRc || pNode->key.nAlloc==0 );
  140255. sqlite3_free(pNode->block.a);
  140256. sqlite3_free(pNode->key.a);
  140257. }
  140258. /* Empty output segment. This is a no-op. */
  140259. if( iRoot<0 ) return;
  140260. /* The entire output segment fits on a single node. Normally, this means
  140261. ** the node would be stored as a blob in the "root" column of the %_segdir
  140262. ** table. However, this is not permitted in this case. The problem is that
  140263. ** space has already been reserved in the %_segments table, and so the
  140264. ** start_block and end_block fields of the %_segdir table must be populated.
  140265. ** And, by design or by accident, released versions of FTS cannot handle
  140266. ** segments that fit entirely on the root node with start_block!=0.
  140267. **
  140268. ** Instead, create a synthetic root node that contains nothing but a
  140269. ** pointer to the single content node. So that the segment consists of a
  140270. ** single leaf and a single interior (root) node.
  140271. **
  140272. ** Todo: Better might be to defer allocating space in the %_segments
  140273. ** table until we are sure it is needed.
  140274. */
  140275. if( iRoot==0 ){
  140276. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  140277. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  140278. if( rc==SQLITE_OK ){
  140279. pBlock->a[0] = 0x01;
  140280. pBlock->n = 1 + sqlite3Fts3PutVarint(
  140281. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  140282. );
  140283. }
  140284. iRoot = 1;
  140285. }
  140286. pRoot = &pWriter->aNodeWriter[iRoot];
  140287. /* Flush all currently outstanding nodes to disk. */
  140288. for(i=0; i<iRoot; i++){
  140289. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  140290. if( pNode->block.n>0 && rc==SQLITE_OK ){
  140291. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  140292. }
  140293. sqlite3_free(pNode->block.a);
  140294. sqlite3_free(pNode->key.a);
  140295. }
  140296. /* Write the %_segdir record. */
  140297. if( rc==SQLITE_OK ){
  140298. rc = fts3WriteSegdir(p,
  140299. pWriter->iAbsLevel+1, /* level */
  140300. pWriter->iIdx, /* idx */
  140301. pWriter->iStart, /* start_block */
  140302. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  140303. pWriter->iEnd, /* end_block */
  140304. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  140305. pRoot->block.a, pRoot->block.n /* root */
  140306. );
  140307. }
  140308. sqlite3_free(pRoot->block.a);
  140309. sqlite3_free(pRoot->key.a);
  140310. *pRc = rc;
  140311. }
  140312. /*
  140313. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  140314. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  140315. ** the other, it is considered to be smaller than the other.
  140316. **
  140317. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  140318. ** if it is greater.
  140319. */
  140320. static int fts3TermCmp(
  140321. const char *zLhs, int nLhs, /* LHS of comparison */
  140322. const char *zRhs, int nRhs /* RHS of comparison */
  140323. ){
  140324. int nCmp = MIN(nLhs, nRhs);
  140325. int res;
  140326. res = memcmp(zLhs, zRhs, nCmp);
  140327. if( res==0 ) res = nLhs - nRhs;
  140328. return res;
  140329. }
  140330. /*
  140331. ** Query to see if the entry in the %_segments table with blockid iEnd is
  140332. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  140333. ** returning. Otherwise, set *pbRes to 0.
  140334. **
  140335. ** Or, if an error occurs while querying the database, return an SQLite
  140336. ** error code. The final value of *pbRes is undefined in this case.
  140337. **
  140338. ** This is used to test if a segment is an "appendable" segment. If it
  140339. ** is, then a NULL entry has been inserted into the %_segments table
  140340. ** with blockid %_segdir.end_block.
  140341. */
  140342. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  140343. int bRes = 0; /* Result to set *pbRes to */
  140344. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  140345. int rc; /* Return code */
  140346. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  140347. if( rc==SQLITE_OK ){
  140348. sqlite3_bind_int64(pCheck, 1, iEnd);
  140349. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  140350. rc = sqlite3_reset(pCheck);
  140351. }
  140352. *pbRes = bRes;
  140353. return rc;
  140354. }
  140355. /*
  140356. ** This function is called when initializing an incremental-merge operation.
  140357. ** It checks if the existing segment with index value iIdx at absolute level
  140358. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  140359. ** merge-writer object *pWriter is initialized to write to it.
  140360. **
  140361. ** An existing segment can be appended to by an incremental merge if:
  140362. **
  140363. ** * It was initially created as an appendable segment (with all required
  140364. ** space pre-allocated), and
  140365. **
  140366. ** * The first key read from the input (arguments zKey and nKey) is
  140367. ** greater than the largest key currently stored in the potential
  140368. ** output segment.
  140369. */
  140370. static int fts3IncrmergeLoad(
  140371. Fts3Table *p, /* Fts3 table handle */
  140372. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  140373. int iIdx, /* Index of candidate output segment */
  140374. const char *zKey, /* First key to write */
  140375. int nKey, /* Number of bytes in nKey */
  140376. IncrmergeWriter *pWriter /* Populate this object */
  140377. ){
  140378. int rc; /* Return code */
  140379. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  140380. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  140381. if( rc==SQLITE_OK ){
  140382. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  140383. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  140384. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  140385. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  140386. int nRoot = 0; /* Size of aRoot[] in bytes */
  140387. int rc2; /* Return code from sqlite3_reset() */
  140388. int bAppendable = 0; /* Set to true if segment is appendable */
  140389. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  140390. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  140391. sqlite3_bind_int(pSelect, 2, iIdx);
  140392. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  140393. iStart = sqlite3_column_int64(pSelect, 1);
  140394. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  140395. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  140396. if( pWriter->nLeafData<0 ){
  140397. pWriter->nLeafData = pWriter->nLeafData * -1;
  140398. }
  140399. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  140400. nRoot = sqlite3_column_bytes(pSelect, 4);
  140401. aRoot = sqlite3_column_blob(pSelect, 4);
  140402. }else{
  140403. return sqlite3_reset(pSelect);
  140404. }
  140405. /* Check for the zero-length marker in the %_segments table */
  140406. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  140407. /* Check that zKey/nKey is larger than the largest key the candidate */
  140408. if( rc==SQLITE_OK && bAppendable ){
  140409. char *aLeaf = 0;
  140410. int nLeaf = 0;
  140411. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  140412. if( rc==SQLITE_OK ){
  140413. NodeReader reader;
  140414. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  140415. rc==SQLITE_OK && reader.aNode;
  140416. rc = nodeReaderNext(&reader)
  140417. ){
  140418. assert( reader.aNode );
  140419. }
  140420. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  140421. bAppendable = 0;
  140422. }
  140423. nodeReaderRelease(&reader);
  140424. }
  140425. sqlite3_free(aLeaf);
  140426. }
  140427. if( rc==SQLITE_OK && bAppendable ){
  140428. /* It is possible to append to this segment. Set up the IncrmergeWriter
  140429. ** object to do so. */
  140430. int i;
  140431. int nHeight = (int)aRoot[0];
  140432. NodeWriter *pNode;
  140433. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  140434. pWriter->iStart = iStart;
  140435. pWriter->iEnd = iEnd;
  140436. pWriter->iAbsLevel = iAbsLevel;
  140437. pWriter->iIdx = iIdx;
  140438. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  140439. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  140440. }
  140441. pNode = &pWriter->aNodeWriter[nHeight];
  140442. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  140443. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  140444. if( rc==SQLITE_OK ){
  140445. memcpy(pNode->block.a, aRoot, nRoot);
  140446. pNode->block.n = nRoot;
  140447. }
  140448. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  140449. NodeReader reader;
  140450. pNode = &pWriter->aNodeWriter[i];
  140451. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  140452. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  140453. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  140454. if( rc==SQLITE_OK ){
  140455. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  140456. pNode->key.n = reader.term.n;
  140457. if( i>0 ){
  140458. char *aBlock = 0;
  140459. int nBlock = 0;
  140460. pNode = &pWriter->aNodeWriter[i-1];
  140461. pNode->iBlock = reader.iChild;
  140462. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  140463. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  140464. if( rc==SQLITE_OK ){
  140465. memcpy(pNode->block.a, aBlock, nBlock);
  140466. pNode->block.n = nBlock;
  140467. }
  140468. sqlite3_free(aBlock);
  140469. }
  140470. }
  140471. nodeReaderRelease(&reader);
  140472. }
  140473. }
  140474. rc2 = sqlite3_reset(pSelect);
  140475. if( rc==SQLITE_OK ) rc = rc2;
  140476. }
  140477. return rc;
  140478. }
  140479. /*
  140480. ** Determine the largest segment index value that exists within absolute
  140481. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  140482. ** one before returning SQLITE_OK. Or, if there are no segments at all
  140483. ** within level iAbsLevel, set *piIdx to zero.
  140484. **
  140485. ** If an error occurs, return an SQLite error code. The final value of
  140486. ** *piIdx is undefined in this case.
  140487. */
  140488. static int fts3IncrmergeOutputIdx(
  140489. Fts3Table *p, /* FTS Table handle */
  140490. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  140491. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  140492. ){
  140493. int rc;
  140494. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  140495. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  140496. if( rc==SQLITE_OK ){
  140497. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  140498. sqlite3_step(pOutputIdx);
  140499. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  140500. rc = sqlite3_reset(pOutputIdx);
  140501. }
  140502. return rc;
  140503. }
  140504. /*
  140505. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  140506. ** with idx value iIdx.
  140507. **
  140508. ** In the %_segdir table, a segment is defined by the values in three
  140509. ** columns:
  140510. **
  140511. ** start_block
  140512. ** leaves_end_block
  140513. ** end_block
  140514. **
  140515. ** When an appendable segment is allocated, it is estimated that the
  140516. ** maximum number of leaf blocks that may be required is the sum of the
  140517. ** number of leaf blocks consumed by the input segments, plus the number
  140518. ** of input segments, multiplied by two. This value is stored in stack
  140519. ** variable nLeafEst.
  140520. **
  140521. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  140522. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  140523. ** array of leaf nodes starts at the first block allocated. The array
  140524. ** of interior nodes that are parents of the leaf nodes start at block
  140525. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  140526. **
  140527. ** In the actual code below, the value "16" is replaced with the
  140528. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  140529. */
  140530. static int fts3IncrmergeWriter(
  140531. Fts3Table *p, /* Fts3 table handle */
  140532. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  140533. int iIdx, /* Index of new output segment */
  140534. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  140535. IncrmergeWriter *pWriter /* Populate this object */
  140536. ){
  140537. int rc; /* Return Code */
  140538. int i; /* Iterator variable */
  140539. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  140540. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  140541. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  140542. /* Calculate nLeafEst. */
  140543. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  140544. if( rc==SQLITE_OK ){
  140545. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  140546. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  140547. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  140548. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  140549. }
  140550. rc = sqlite3_reset(pLeafEst);
  140551. }
  140552. if( rc!=SQLITE_OK ) return rc;
  140553. /* Calculate the first block to use in the output segment */
  140554. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  140555. if( rc==SQLITE_OK ){
  140556. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  140557. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  140558. pWriter->iEnd = pWriter->iStart - 1;
  140559. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  140560. }
  140561. rc = sqlite3_reset(pFirstBlock);
  140562. }
  140563. if( rc!=SQLITE_OK ) return rc;
  140564. /* Insert the marker in the %_segments table to make sure nobody tries
  140565. ** to steal the space just allocated. This is also used to identify
  140566. ** appendable segments. */
  140567. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  140568. if( rc!=SQLITE_OK ) return rc;
  140569. pWriter->iAbsLevel = iAbsLevel;
  140570. pWriter->nLeafEst = nLeafEst;
  140571. pWriter->iIdx = iIdx;
  140572. /* Set up the array of NodeWriter objects */
  140573. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  140574. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  140575. }
  140576. return SQLITE_OK;
  140577. }
  140578. /*
  140579. ** Remove an entry from the %_segdir table. This involves running the
  140580. ** following two statements:
  140581. **
  140582. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  140583. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  140584. **
  140585. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  140586. ** statement ensures that the remaining segments have contiguously allocated
  140587. ** idx values.
  140588. */
  140589. static int fts3RemoveSegdirEntry(
  140590. Fts3Table *p, /* FTS3 table handle */
  140591. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  140592. int iIdx /* Index of %_segdir entry to delete */
  140593. ){
  140594. int rc; /* Return code */
  140595. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  140596. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  140597. if( rc==SQLITE_OK ){
  140598. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  140599. sqlite3_bind_int(pDelete, 2, iIdx);
  140600. sqlite3_step(pDelete);
  140601. rc = sqlite3_reset(pDelete);
  140602. }
  140603. return rc;
  140604. }
  140605. /*
  140606. ** One or more segments have just been removed from absolute level iAbsLevel.
  140607. ** Update the 'idx' values of the remaining segments in the level so that
  140608. ** the idx values are a contiguous sequence starting from 0.
  140609. */
  140610. static int fts3RepackSegdirLevel(
  140611. Fts3Table *p, /* FTS3 table handle */
  140612. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  140613. ){
  140614. int rc; /* Return code */
  140615. int *aIdx = 0; /* Array of remaining idx values */
  140616. int nIdx = 0; /* Valid entries in aIdx[] */
  140617. int nAlloc = 0; /* Allocated size of aIdx[] */
  140618. int i; /* Iterator variable */
  140619. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  140620. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  140621. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  140622. if( rc==SQLITE_OK ){
  140623. int rc2;
  140624. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  140625. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  140626. if( nIdx>=nAlloc ){
  140627. int *aNew;
  140628. nAlloc += 16;
  140629. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  140630. if( !aNew ){
  140631. rc = SQLITE_NOMEM;
  140632. break;
  140633. }
  140634. aIdx = aNew;
  140635. }
  140636. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  140637. }
  140638. rc2 = sqlite3_reset(pSelect);
  140639. if( rc==SQLITE_OK ) rc = rc2;
  140640. }
  140641. if( rc==SQLITE_OK ){
  140642. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  140643. }
  140644. if( rc==SQLITE_OK ){
  140645. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  140646. }
  140647. assert( p->bIgnoreSavepoint==0 );
  140648. p->bIgnoreSavepoint = 1;
  140649. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  140650. if( aIdx[i]!=i ){
  140651. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  140652. sqlite3_bind_int(pUpdate, 1, i);
  140653. sqlite3_step(pUpdate);
  140654. rc = sqlite3_reset(pUpdate);
  140655. }
  140656. }
  140657. p->bIgnoreSavepoint = 0;
  140658. sqlite3_free(aIdx);
  140659. return rc;
  140660. }
  140661. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  140662. pNode->a[0] = (char)iHeight;
  140663. if( iChild ){
  140664. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  140665. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  140666. }else{
  140667. assert( pNode->nAlloc>=1 );
  140668. pNode->n = 1;
  140669. }
  140670. }
  140671. /*
  140672. ** The first two arguments are a pointer to and the size of a segment b-tree
  140673. ** node. The node may be a leaf or an internal node.
  140674. **
  140675. ** This function creates a new node image in blob object *pNew by copying
  140676. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  140677. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  140678. */
  140679. static int fts3TruncateNode(
  140680. const char *aNode, /* Current node image */
  140681. int nNode, /* Size of aNode in bytes */
  140682. Blob *pNew, /* OUT: Write new node image here */
  140683. const char *zTerm, /* Omit all terms smaller than this */
  140684. int nTerm, /* Size of zTerm in bytes */
  140685. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  140686. ){
  140687. NodeReader reader; /* Reader object */
  140688. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  140689. int rc = SQLITE_OK; /* Return code */
  140690. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  140691. /* Allocate required output space */
  140692. blobGrowBuffer(pNew, nNode, &rc);
  140693. if( rc!=SQLITE_OK ) return rc;
  140694. pNew->n = 0;
  140695. /* Populate new node buffer */
  140696. for(rc = nodeReaderInit(&reader, aNode, nNode);
  140697. rc==SQLITE_OK && reader.aNode;
  140698. rc = nodeReaderNext(&reader)
  140699. ){
  140700. if( pNew->n==0 ){
  140701. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  140702. if( res<0 || (bLeaf==0 && res==0) ) continue;
  140703. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  140704. *piBlock = reader.iChild;
  140705. }
  140706. rc = fts3AppendToNode(
  140707. pNew, &prev, reader.term.a, reader.term.n,
  140708. reader.aDoclist, reader.nDoclist
  140709. );
  140710. if( rc!=SQLITE_OK ) break;
  140711. }
  140712. if( pNew->n==0 ){
  140713. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  140714. *piBlock = reader.iChild;
  140715. }
  140716. assert( pNew->n<=pNew->nAlloc );
  140717. nodeReaderRelease(&reader);
  140718. sqlite3_free(prev.a);
  140719. return rc;
  140720. }
  140721. /*
  140722. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  140723. ** level iAbsLevel. This may involve deleting entries from the %_segments
  140724. ** table, and modifying existing entries in both the %_segments and %_segdir
  140725. ** tables.
  140726. **
  140727. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  140728. ** SQLite error code otherwise.
  140729. */
  140730. static int fts3TruncateSegment(
  140731. Fts3Table *p, /* FTS3 table handle */
  140732. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  140733. int iIdx, /* Index within level of segment to modify */
  140734. const char *zTerm, /* Remove terms smaller than this */
  140735. int nTerm /* Number of bytes in buffer zTerm */
  140736. ){
  140737. int rc = SQLITE_OK; /* Return code */
  140738. Blob root = {0,0,0}; /* New root page image */
  140739. Blob block = {0,0,0}; /* Buffer used for any other block */
  140740. sqlite3_int64 iBlock = 0; /* Block id */
  140741. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  140742. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  140743. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  140744. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  140745. if( rc==SQLITE_OK ){
  140746. int rc2; /* sqlite3_reset() return code */
  140747. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  140748. sqlite3_bind_int(pFetch, 2, iIdx);
  140749. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  140750. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  140751. int nRoot = sqlite3_column_bytes(pFetch, 4);
  140752. iOldStart = sqlite3_column_int64(pFetch, 1);
  140753. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  140754. }
  140755. rc2 = sqlite3_reset(pFetch);
  140756. if( rc==SQLITE_OK ) rc = rc2;
  140757. }
  140758. while( rc==SQLITE_OK && iBlock ){
  140759. char *aBlock = 0;
  140760. int nBlock = 0;
  140761. iNewStart = iBlock;
  140762. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  140763. if( rc==SQLITE_OK ){
  140764. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  140765. }
  140766. if( rc==SQLITE_OK ){
  140767. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  140768. }
  140769. sqlite3_free(aBlock);
  140770. }
  140771. /* Variable iNewStart now contains the first valid leaf node. */
  140772. if( rc==SQLITE_OK && iNewStart ){
  140773. sqlite3_stmt *pDel = 0;
  140774. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  140775. if( rc==SQLITE_OK ){
  140776. sqlite3_bind_int64(pDel, 1, iOldStart);
  140777. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  140778. sqlite3_step(pDel);
  140779. rc = sqlite3_reset(pDel);
  140780. }
  140781. }
  140782. if( rc==SQLITE_OK ){
  140783. sqlite3_stmt *pChomp = 0;
  140784. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  140785. if( rc==SQLITE_OK ){
  140786. sqlite3_bind_int64(pChomp, 1, iNewStart);
  140787. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  140788. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  140789. sqlite3_bind_int(pChomp, 4, iIdx);
  140790. sqlite3_step(pChomp);
  140791. rc = sqlite3_reset(pChomp);
  140792. }
  140793. }
  140794. sqlite3_free(root.a);
  140795. sqlite3_free(block.a);
  140796. return rc;
  140797. }
  140798. /*
  140799. ** This function is called after an incrmental-merge operation has run to
  140800. ** merge (or partially merge) two or more segments from absolute level
  140801. ** iAbsLevel.
  140802. **
  140803. ** Each input segment is either removed from the db completely (if all of
  140804. ** its data was copied to the output segment by the incrmerge operation)
  140805. ** or modified in place so that it no longer contains those entries that
  140806. ** have been duplicated in the output segment.
  140807. */
  140808. static int fts3IncrmergeChomp(
  140809. Fts3Table *p, /* FTS table handle */
  140810. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  140811. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  140812. int *pnRem /* Number of segments not deleted */
  140813. ){
  140814. int i;
  140815. int nRem = 0;
  140816. int rc = SQLITE_OK;
  140817. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  140818. Fts3SegReader *pSeg = 0;
  140819. int j;
  140820. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  140821. ** somewhere in the pCsr->apSegment[] array. */
  140822. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  140823. pSeg = pCsr->apSegment[j];
  140824. if( pSeg->iIdx==i ) break;
  140825. }
  140826. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  140827. if( pSeg->aNode==0 ){
  140828. /* Seg-reader is at EOF. Remove the entire input segment. */
  140829. rc = fts3DeleteSegment(p, pSeg);
  140830. if( rc==SQLITE_OK ){
  140831. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  140832. }
  140833. *pnRem = 0;
  140834. }else{
  140835. /* The incremental merge did not copy all the data from this
  140836. ** segment to the upper level. The segment is modified in place
  140837. ** so that it contains no keys smaller than zTerm/nTerm. */
  140838. const char *zTerm = pSeg->zTerm;
  140839. int nTerm = pSeg->nTerm;
  140840. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  140841. nRem++;
  140842. }
  140843. }
  140844. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  140845. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  140846. }
  140847. *pnRem = nRem;
  140848. return rc;
  140849. }
  140850. /*
  140851. ** Store an incr-merge hint in the database.
  140852. */
  140853. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  140854. sqlite3_stmt *pReplace = 0;
  140855. int rc; /* Return code */
  140856. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  140857. if( rc==SQLITE_OK ){
  140858. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  140859. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  140860. sqlite3_step(pReplace);
  140861. rc = sqlite3_reset(pReplace);
  140862. }
  140863. return rc;
  140864. }
  140865. /*
  140866. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  140867. ** exists, is stored in the rowid==1 row of the %_stat table.
  140868. **
  140869. ** If successful, populate blob *pHint with the value read from the %_stat
  140870. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  140871. ** SQLite error code.
  140872. */
  140873. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  140874. sqlite3_stmt *pSelect = 0;
  140875. int rc;
  140876. pHint->n = 0;
  140877. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  140878. if( rc==SQLITE_OK ){
  140879. int rc2;
  140880. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  140881. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  140882. const char *aHint = sqlite3_column_blob(pSelect, 0);
  140883. int nHint = sqlite3_column_bytes(pSelect, 0);
  140884. if( aHint ){
  140885. blobGrowBuffer(pHint, nHint, &rc);
  140886. if( rc==SQLITE_OK ){
  140887. memcpy(pHint->a, aHint, nHint);
  140888. pHint->n = nHint;
  140889. }
  140890. }
  140891. }
  140892. rc2 = sqlite3_reset(pSelect);
  140893. if( rc==SQLITE_OK ) rc = rc2;
  140894. }
  140895. return rc;
  140896. }
  140897. /*
  140898. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  140899. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  140900. ** consists of two varints, the absolute level number of the input segments
  140901. ** and the number of input segments.
  140902. **
  140903. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  140904. ** set *pRc to an SQLite error code before returning.
  140905. */
  140906. static void fts3IncrmergeHintPush(
  140907. Blob *pHint, /* Hint blob to append to */
  140908. i64 iAbsLevel, /* First varint to store in hint */
  140909. int nInput, /* Second varint to store in hint */
  140910. int *pRc /* IN/OUT: Error code */
  140911. ){
  140912. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  140913. if( *pRc==SQLITE_OK ){
  140914. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  140915. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  140916. }
  140917. }
  140918. /*
  140919. ** Read the last entry (most recently pushed) from the hint blob *pHint
  140920. ** and then remove the entry. Write the two values read to *piAbsLevel and
  140921. ** *pnInput before returning.
  140922. **
  140923. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  140924. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  140925. */
  140926. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  140927. const int nHint = pHint->n;
  140928. int i;
  140929. i = pHint->n-2;
  140930. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  140931. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  140932. pHint->n = i;
  140933. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  140934. i += fts3GetVarint32(&pHint->a[i], pnInput);
  140935. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  140936. return SQLITE_OK;
  140937. }
  140938. /*
  140939. ** Attempt an incremental merge that writes nMerge leaf blocks.
  140940. **
  140941. ** Incremental merges happen nMin segments at a time. The segments
  140942. ** to be merged are the nMin oldest segments (the ones with the smallest
  140943. ** values for the _segdir.idx field) in the highest level that contains
  140944. ** at least nMin segments. Multiple merges might occur in an attempt to
  140945. ** write the quota of nMerge leaf blocks.
  140946. */
  140947. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  140948. int rc; /* Return code */
  140949. int nRem = nMerge; /* Number of leaf pages yet to be written */
  140950. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  140951. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  140952. IncrmergeWriter *pWriter; /* Writer object */
  140953. int nSeg = 0; /* Number of input segments */
  140954. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  140955. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  140956. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  140957. /* Allocate space for the cursor, filter and writer objects */
  140958. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  140959. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  140960. if( !pWriter ) return SQLITE_NOMEM;
  140961. pFilter = (Fts3SegFilter *)&pWriter[1];
  140962. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  140963. rc = fts3IncrmergeHintLoad(p, &hint);
  140964. while( rc==SQLITE_OK && nRem>0 ){
  140965. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  140966. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  140967. int bUseHint = 0; /* True if attempting to append */
  140968. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  140969. /* Search the %_segdir table for the absolute level with the smallest
  140970. ** relative level number that contains at least nMin segments, if any.
  140971. ** If one is found, set iAbsLevel to the absolute level number and
  140972. ** nSeg to nMin. If no level with at least nMin segments can be found,
  140973. ** set nSeg to -1.
  140974. */
  140975. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  140976. sqlite3_bind_int(pFindLevel, 1, nMin);
  140977. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  140978. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  140979. nSeg = nMin;
  140980. }else{
  140981. nSeg = -1;
  140982. }
  140983. rc = sqlite3_reset(pFindLevel);
  140984. /* If the hint read from the %_stat table is not empty, check if the
  140985. ** last entry in it specifies a relative level smaller than or equal
  140986. ** to the level identified by the block above (if any). If so, this
  140987. ** iteration of the loop will work on merging at the hinted level.
  140988. */
  140989. if( rc==SQLITE_OK && hint.n ){
  140990. int nHint = hint.n;
  140991. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  140992. int nHintSeg = 0; /* Hint number of segments */
  140993. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  140994. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  140995. iAbsLevel = iHintAbsLevel;
  140996. nSeg = nHintSeg;
  140997. bUseHint = 1;
  140998. bDirtyHint = 1;
  140999. }else{
  141000. /* This undoes the effect of the HintPop() above - so that no entry
  141001. ** is removed from the hint blob. */
  141002. hint.n = nHint;
  141003. }
  141004. }
  141005. /* If nSeg is less that zero, then there is no level with at least
  141006. ** nMin segments and no hint in the %_stat table. No work to do.
  141007. ** Exit early in this case. */
  141008. if( nSeg<0 ) break;
  141009. /* Open a cursor to iterate through the contents of the oldest nSeg
  141010. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  141011. ** the 'hint' parameters, it is possible that there are less than nSeg
  141012. ** segments available in level iAbsLevel. In this case, no work is
  141013. ** done on iAbsLevel - fall through to the next iteration of the loop
  141014. ** to start work on some other level. */
  141015. memset(pWriter, 0, nAlloc);
  141016. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  141017. if( rc==SQLITE_OK ){
  141018. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  141019. assert( bUseHint==1 || bUseHint==0 );
  141020. if( iIdx==0 || (bUseHint && iIdx==1) ){
  141021. int bIgnore = 0;
  141022. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  141023. if( bIgnore ){
  141024. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  141025. }
  141026. }
  141027. }
  141028. if( rc==SQLITE_OK ){
  141029. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  141030. }
  141031. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  141032. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  141033. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  141034. ){
  141035. if( bUseHint && iIdx>0 ){
  141036. const char *zKey = pCsr->zTerm;
  141037. int nKey = pCsr->nTerm;
  141038. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  141039. }else{
  141040. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  141041. }
  141042. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  141043. fts3LogMerge(nSeg, iAbsLevel);
  141044. do {
  141045. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  141046. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  141047. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  141048. }while( rc==SQLITE_ROW );
  141049. /* Update or delete the input segments */
  141050. if( rc==SQLITE_OK ){
  141051. nRem -= (1 + pWriter->nWork);
  141052. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  141053. if( nSeg!=0 ){
  141054. bDirtyHint = 1;
  141055. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  141056. }
  141057. }
  141058. }
  141059. if( nSeg!=0 ){
  141060. pWriter->nLeafData = pWriter->nLeafData * -1;
  141061. }
  141062. fts3IncrmergeRelease(p, pWriter, &rc);
  141063. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  141064. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  141065. }
  141066. }
  141067. sqlite3Fts3SegReaderFinish(pCsr);
  141068. }
  141069. /* Write the hint values into the %_stat table for the next incr-merger */
  141070. if( bDirtyHint && rc==SQLITE_OK ){
  141071. rc = fts3IncrmergeHintStore(p, &hint);
  141072. }
  141073. sqlite3_free(pWriter);
  141074. sqlite3_free(hint.a);
  141075. return rc;
  141076. }
  141077. /*
  141078. ** Convert the text beginning at *pz into an integer and return
  141079. ** its value. Advance *pz to point to the first character past
  141080. ** the integer.
  141081. */
  141082. static int fts3Getint(const char **pz){
  141083. const char *z = *pz;
  141084. int i = 0;
  141085. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  141086. *pz = z;
  141087. return i;
  141088. }
  141089. /*
  141090. ** Process statements of the form:
  141091. **
  141092. ** INSERT INTO table(table) VALUES('merge=A,B');
  141093. **
  141094. ** A and B are integers that decode to be the number of leaf pages
  141095. ** written for the merge, and the minimum number of segments on a level
  141096. ** before it will be selected for a merge, respectively.
  141097. */
  141098. static int fts3DoIncrmerge(
  141099. Fts3Table *p, /* FTS3 table handle */
  141100. const char *zParam /* Nul-terminated string containing "A,B" */
  141101. ){
  141102. int rc;
  141103. int nMin = (FTS3_MERGE_COUNT / 2);
  141104. int nMerge = 0;
  141105. const char *z = zParam;
  141106. /* Read the first integer value */
  141107. nMerge = fts3Getint(&z);
  141108. /* If the first integer value is followed by a ',', read the second
  141109. ** integer value. */
  141110. if( z[0]==',' && z[1]!='\0' ){
  141111. z++;
  141112. nMin = fts3Getint(&z);
  141113. }
  141114. if( z[0]!='\0' || nMin<2 ){
  141115. rc = SQLITE_ERROR;
  141116. }else{
  141117. rc = SQLITE_OK;
  141118. if( !p->bHasStat ){
  141119. assert( p->bFts4==0 );
  141120. sqlite3Fts3CreateStatTable(&rc, p);
  141121. }
  141122. if( rc==SQLITE_OK ){
  141123. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  141124. }
  141125. sqlite3Fts3SegmentsClose(p);
  141126. }
  141127. return rc;
  141128. }
  141129. /*
  141130. ** Process statements of the form:
  141131. **
  141132. ** INSERT INTO table(table) VALUES('automerge=X');
  141133. **
  141134. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  141135. ** turn it on. The setting is persistent.
  141136. */
  141137. static int fts3DoAutoincrmerge(
  141138. Fts3Table *p, /* FTS3 table handle */
  141139. const char *zParam /* Nul-terminated string containing boolean */
  141140. ){
  141141. int rc = SQLITE_OK;
  141142. sqlite3_stmt *pStmt = 0;
  141143. p->nAutoincrmerge = fts3Getint(&zParam);
  141144. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  141145. p->nAutoincrmerge = 8;
  141146. }
  141147. if( !p->bHasStat ){
  141148. assert( p->bFts4==0 );
  141149. sqlite3Fts3CreateStatTable(&rc, p);
  141150. if( rc ) return rc;
  141151. }
  141152. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  141153. if( rc ) return rc;
  141154. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  141155. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  141156. sqlite3_step(pStmt);
  141157. rc = sqlite3_reset(pStmt);
  141158. return rc;
  141159. }
  141160. /*
  141161. ** Return a 64-bit checksum for the FTS index entry specified by the
  141162. ** arguments to this function.
  141163. */
  141164. static u64 fts3ChecksumEntry(
  141165. const char *zTerm, /* Pointer to buffer containing term */
  141166. int nTerm, /* Size of zTerm in bytes */
  141167. int iLangid, /* Language id for current row */
  141168. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  141169. i64 iDocid, /* Docid for current row. */
  141170. int iCol, /* Column number */
  141171. int iPos /* Position */
  141172. ){
  141173. int i;
  141174. u64 ret = (u64)iDocid;
  141175. ret += (ret<<3) + iLangid;
  141176. ret += (ret<<3) + iIndex;
  141177. ret += (ret<<3) + iCol;
  141178. ret += (ret<<3) + iPos;
  141179. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  141180. return ret;
  141181. }
  141182. /*
  141183. ** Return a checksum of all entries in the FTS index that correspond to
  141184. ** language id iLangid. The checksum is calculated by XORing the checksums
  141185. ** of each individual entry (see fts3ChecksumEntry()) together.
  141186. **
  141187. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  141188. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  141189. ** return value is undefined in this case.
  141190. */
  141191. static u64 fts3ChecksumIndex(
  141192. Fts3Table *p, /* FTS3 table handle */
  141193. int iLangid, /* Language id to return cksum for */
  141194. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  141195. int *pRc /* OUT: Return code */
  141196. ){
  141197. Fts3SegFilter filter;
  141198. Fts3MultiSegReader csr;
  141199. int rc;
  141200. u64 cksum = 0;
  141201. assert( *pRc==SQLITE_OK );
  141202. memset(&filter, 0, sizeof(filter));
  141203. memset(&csr, 0, sizeof(csr));
  141204. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  141205. filter.flags |= FTS3_SEGMENT_SCAN;
  141206. rc = sqlite3Fts3SegReaderCursor(
  141207. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  141208. );
  141209. if( rc==SQLITE_OK ){
  141210. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  141211. }
  141212. if( rc==SQLITE_OK ){
  141213. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  141214. char *pCsr = csr.aDoclist;
  141215. char *pEnd = &pCsr[csr.nDoclist];
  141216. i64 iDocid = 0;
  141217. i64 iCol = 0;
  141218. i64 iPos = 0;
  141219. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  141220. while( pCsr<pEnd ){
  141221. i64 iVal = 0;
  141222. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  141223. if( pCsr<pEnd ){
  141224. if( iVal==0 || iVal==1 ){
  141225. iCol = 0;
  141226. iPos = 0;
  141227. if( iVal ){
  141228. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  141229. }else{
  141230. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  141231. iDocid += iVal;
  141232. }
  141233. }else{
  141234. iPos += (iVal - 2);
  141235. cksum = cksum ^ fts3ChecksumEntry(
  141236. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  141237. (int)iCol, (int)iPos
  141238. );
  141239. }
  141240. }
  141241. }
  141242. }
  141243. }
  141244. sqlite3Fts3SegReaderFinish(&csr);
  141245. *pRc = rc;
  141246. return cksum;
  141247. }
  141248. /*
  141249. ** Check if the contents of the FTS index match the current contents of the
  141250. ** content table. If no error occurs and the contents do match, set *pbOk
  141251. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  141252. ** to false before returning.
  141253. **
  141254. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  141255. ** code. The final value of *pbOk is undefined in this case.
  141256. */
  141257. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  141258. int rc = SQLITE_OK; /* Return code */
  141259. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  141260. u64 cksum2 = 0; /* Checksum based on %_content contents */
  141261. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  141262. /* This block calculates the checksum according to the FTS index. */
  141263. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  141264. if( rc==SQLITE_OK ){
  141265. int rc2;
  141266. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  141267. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  141268. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  141269. int iLangid = sqlite3_column_int(pAllLangid, 0);
  141270. int i;
  141271. for(i=0; i<p->nIndex; i++){
  141272. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  141273. }
  141274. }
  141275. rc2 = sqlite3_reset(pAllLangid);
  141276. if( rc==SQLITE_OK ) rc = rc2;
  141277. }
  141278. /* This block calculates the checksum according to the %_content table */
  141279. if( rc==SQLITE_OK ){
  141280. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  141281. sqlite3_stmt *pStmt = 0;
  141282. char *zSql;
  141283. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  141284. if( !zSql ){
  141285. rc = SQLITE_NOMEM;
  141286. }else{
  141287. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  141288. sqlite3_free(zSql);
  141289. }
  141290. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  141291. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  141292. int iLang = langidFromSelect(p, pStmt);
  141293. int iCol;
  141294. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  141295. if( p->abNotindexed[iCol]==0 ){
  141296. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  141297. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  141298. sqlite3_tokenizer_cursor *pT = 0;
  141299. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  141300. while( rc==SQLITE_OK ){
  141301. char const *zToken; /* Buffer containing token */
  141302. int nToken = 0; /* Number of bytes in token */
  141303. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  141304. int iPos = 0; /* Position of token in zText */
  141305. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  141306. if( rc==SQLITE_OK ){
  141307. int i;
  141308. cksum2 = cksum2 ^ fts3ChecksumEntry(
  141309. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  141310. );
  141311. for(i=1; i<p->nIndex; i++){
  141312. if( p->aIndex[i].nPrefix<=nToken ){
  141313. cksum2 = cksum2 ^ fts3ChecksumEntry(
  141314. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  141315. );
  141316. }
  141317. }
  141318. }
  141319. }
  141320. if( pT ) pModule->xClose(pT);
  141321. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  141322. }
  141323. }
  141324. }
  141325. sqlite3_finalize(pStmt);
  141326. }
  141327. *pbOk = (cksum1==cksum2);
  141328. return rc;
  141329. }
  141330. /*
  141331. ** Run the integrity-check. If no error occurs and the current contents of
  141332. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  141333. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  141334. **
  141335. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  141336. ** error code.
  141337. **
  141338. ** The integrity-check works as follows. For each token and indexed token
  141339. ** prefix in the document set, a 64-bit checksum is calculated (by code
  141340. ** in fts3ChecksumEntry()) based on the following:
  141341. **
  141342. ** + The index number (0 for the main index, 1 for the first prefix
  141343. ** index etc.),
  141344. ** + The token (or token prefix) text itself,
  141345. ** + The language-id of the row it appears in,
  141346. ** + The docid of the row it appears in,
  141347. ** + The column it appears in, and
  141348. ** + The tokens position within that column.
  141349. **
  141350. ** The checksums for all entries in the index are XORed together to create
  141351. ** a single checksum for the entire index.
  141352. **
  141353. ** The integrity-check code calculates the same checksum in two ways:
  141354. **
  141355. ** 1. By scanning the contents of the FTS index, and
  141356. ** 2. By scanning and tokenizing the content table.
  141357. **
  141358. ** If the two checksums are identical, the integrity-check is deemed to have
  141359. ** passed.
  141360. */
  141361. static int fts3DoIntegrityCheck(
  141362. Fts3Table *p /* FTS3 table handle */
  141363. ){
  141364. int rc;
  141365. int bOk = 0;
  141366. rc = fts3IntegrityCheck(p, &bOk);
  141367. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  141368. return rc;
  141369. }
  141370. /*
  141371. ** Handle a 'special' INSERT of the form:
  141372. **
  141373. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  141374. **
  141375. ** Argument pVal contains the result of <expr>. Currently the only
  141376. ** meaningful value to insert is the text 'optimize'.
  141377. */
  141378. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  141379. int rc; /* Return Code */
  141380. const char *zVal = (const char *)sqlite3_value_text(pVal);
  141381. int nVal = sqlite3_value_bytes(pVal);
  141382. if( !zVal ){
  141383. return SQLITE_NOMEM;
  141384. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  141385. rc = fts3DoOptimize(p, 0);
  141386. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  141387. rc = fts3DoRebuild(p);
  141388. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  141389. rc = fts3DoIntegrityCheck(p);
  141390. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  141391. rc = fts3DoIncrmerge(p, &zVal[6]);
  141392. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  141393. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  141394. #ifdef SQLITE_TEST
  141395. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  141396. p->nNodeSize = atoi(&zVal[9]);
  141397. rc = SQLITE_OK;
  141398. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  141399. p->nMaxPendingData = atoi(&zVal[11]);
  141400. rc = SQLITE_OK;
  141401. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  141402. p->bNoIncrDoclist = atoi(&zVal[21]);
  141403. rc = SQLITE_OK;
  141404. #endif
  141405. }else{
  141406. rc = SQLITE_ERROR;
  141407. }
  141408. return rc;
  141409. }
  141410. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141411. /*
  141412. ** Delete all cached deferred doclists. Deferred doclists are cached
  141413. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  141414. */
  141415. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  141416. Fts3DeferredToken *pDef;
  141417. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  141418. fts3PendingListDelete(pDef->pList);
  141419. pDef->pList = 0;
  141420. }
  141421. }
  141422. /*
  141423. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  141424. ** this list using sqlite3Fts3DeferToken().
  141425. */
  141426. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  141427. Fts3DeferredToken *pDef;
  141428. Fts3DeferredToken *pNext;
  141429. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  141430. pNext = pDef->pNext;
  141431. fts3PendingListDelete(pDef->pList);
  141432. sqlite3_free(pDef);
  141433. }
  141434. pCsr->pDeferred = 0;
  141435. }
  141436. /*
  141437. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  141438. ** based on the row that pCsr currently points to.
  141439. **
  141440. ** A deferred-doclist is like any other doclist with position information
  141441. ** included, except that it only contains entries for a single row of the
  141442. ** table, not for all rows.
  141443. */
  141444. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  141445. int rc = SQLITE_OK; /* Return code */
  141446. if( pCsr->pDeferred ){
  141447. int i; /* Used to iterate through table columns */
  141448. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  141449. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  141450. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  141451. sqlite3_tokenizer *pT = p->pTokenizer;
  141452. sqlite3_tokenizer_module const *pModule = pT->pModule;
  141453. assert( pCsr->isRequireSeek==0 );
  141454. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  141455. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  141456. if( p->abNotindexed[i]==0 ){
  141457. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  141458. sqlite3_tokenizer_cursor *pTC = 0;
  141459. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  141460. while( rc==SQLITE_OK ){
  141461. char const *zToken; /* Buffer containing token */
  141462. int nToken = 0; /* Number of bytes in token */
  141463. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  141464. int iPos = 0; /* Position of token in zText */
  141465. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  141466. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  141467. Fts3PhraseToken *pPT = pDef->pToken;
  141468. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  141469. && (pPT->bFirst==0 || iPos==0)
  141470. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  141471. && (0==memcmp(zToken, pPT->z, pPT->n))
  141472. ){
  141473. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  141474. }
  141475. }
  141476. }
  141477. if( pTC ) pModule->xClose(pTC);
  141478. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  141479. }
  141480. }
  141481. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  141482. if( pDef->pList ){
  141483. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  141484. }
  141485. }
  141486. }
  141487. return rc;
  141488. }
  141489. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  141490. Fts3DeferredToken *p,
  141491. char **ppData,
  141492. int *pnData
  141493. ){
  141494. char *pRet;
  141495. int nSkip;
  141496. sqlite3_int64 dummy;
  141497. *ppData = 0;
  141498. *pnData = 0;
  141499. if( p->pList==0 ){
  141500. return SQLITE_OK;
  141501. }
  141502. pRet = (char *)sqlite3_malloc(p->pList->nData);
  141503. if( !pRet ) return SQLITE_NOMEM;
  141504. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  141505. *pnData = p->pList->nData - nSkip;
  141506. *ppData = pRet;
  141507. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  141508. return SQLITE_OK;
  141509. }
  141510. /*
  141511. ** Add an entry for token pToken to the pCsr->pDeferred list.
  141512. */
  141513. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  141514. Fts3Cursor *pCsr, /* Fts3 table cursor */
  141515. Fts3PhraseToken *pToken, /* Token to defer */
  141516. int iCol /* Column that token must appear in (or -1) */
  141517. ){
  141518. Fts3DeferredToken *pDeferred;
  141519. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  141520. if( !pDeferred ){
  141521. return SQLITE_NOMEM;
  141522. }
  141523. memset(pDeferred, 0, sizeof(*pDeferred));
  141524. pDeferred->pToken = pToken;
  141525. pDeferred->pNext = pCsr->pDeferred;
  141526. pDeferred->iCol = iCol;
  141527. pCsr->pDeferred = pDeferred;
  141528. assert( pToken->pDeferred==0 );
  141529. pToken->pDeferred = pDeferred;
  141530. return SQLITE_OK;
  141531. }
  141532. #endif
  141533. /*
  141534. ** SQLite value pRowid contains the rowid of a row that may or may not be
  141535. ** present in the FTS3 table. If it is, delete it and adjust the contents
  141536. ** of subsiduary data structures accordingly.
  141537. */
  141538. static int fts3DeleteByRowid(
  141539. Fts3Table *p,
  141540. sqlite3_value *pRowid,
  141541. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  141542. u32 *aSzDel
  141543. ){
  141544. int rc = SQLITE_OK; /* Return code */
  141545. int bFound = 0; /* True if *pRowid really is in the table */
  141546. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  141547. if( bFound && rc==SQLITE_OK ){
  141548. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  141549. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  141550. if( rc==SQLITE_OK ){
  141551. if( isEmpty ){
  141552. /* Deleting this row means the whole table is empty. In this case
  141553. ** delete the contents of all three tables and throw away any
  141554. ** data in the pendingTerms hash table. */
  141555. rc = fts3DeleteAll(p, 1);
  141556. *pnChng = 0;
  141557. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  141558. }else{
  141559. *pnChng = *pnChng - 1;
  141560. if( p->zContentTbl==0 ){
  141561. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  141562. }
  141563. if( p->bHasDocsize ){
  141564. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  141565. }
  141566. }
  141567. }
  141568. }
  141569. return rc;
  141570. }
  141571. /*
  141572. ** This function does the work for the xUpdate method of FTS3 virtual
  141573. ** tables. The schema of the virtual table being:
  141574. **
  141575. ** CREATE TABLE <table name>(
  141576. ** <user columns>,
  141577. ** <table name> HIDDEN,
  141578. ** docid HIDDEN,
  141579. ** <langid> HIDDEN
  141580. ** );
  141581. **
  141582. **
  141583. */
  141584. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  141585. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  141586. int nArg, /* Size of argument array */
  141587. sqlite3_value **apVal, /* Array of arguments */
  141588. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  141589. ){
  141590. Fts3Table *p = (Fts3Table *)pVtab;
  141591. int rc = SQLITE_OK; /* Return Code */
  141592. int isRemove = 0; /* True for an UPDATE or DELETE */
  141593. u32 *aSzIns = 0; /* Sizes of inserted documents */
  141594. u32 *aSzDel = 0; /* Sizes of deleted documents */
  141595. int nChng = 0; /* Net change in number of documents */
  141596. int bInsertDone = 0;
  141597. /* At this point it must be known if the %_stat table exists or not.
  141598. ** So bHasStat may not be 2. */
  141599. assert( p->bHasStat==0 || p->bHasStat==1 );
  141600. assert( p->pSegments==0 );
  141601. assert(
  141602. nArg==1 /* DELETE operations */
  141603. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  141604. );
  141605. /* Check for a "special" INSERT operation. One of the form:
  141606. **
  141607. ** INSERT INTO xyz(xyz) VALUES('command');
  141608. */
  141609. if( nArg>1
  141610. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  141611. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  141612. ){
  141613. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  141614. goto update_out;
  141615. }
  141616. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  141617. rc = SQLITE_CONSTRAINT;
  141618. goto update_out;
  141619. }
  141620. /* Allocate space to hold the change in document sizes */
  141621. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  141622. if( aSzDel==0 ){
  141623. rc = SQLITE_NOMEM;
  141624. goto update_out;
  141625. }
  141626. aSzIns = &aSzDel[p->nColumn+1];
  141627. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  141628. rc = fts3Writelock(p);
  141629. if( rc!=SQLITE_OK ) goto update_out;
  141630. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  141631. ** value, then this operation requires constraint handling.
  141632. **
  141633. ** If the on-conflict mode is REPLACE, this means that the existing row
  141634. ** should be deleted from the database before inserting the new row. Or,
  141635. ** if the on-conflict mode is other than REPLACE, then this method must
  141636. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  141637. ** modify the database file.
  141638. */
  141639. if( nArg>1 && p->zContentTbl==0 ){
  141640. /* Find the value object that holds the new rowid value. */
  141641. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  141642. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  141643. pNewRowid = apVal[1];
  141644. }
  141645. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  141646. sqlite3_value_type(apVal[0])==SQLITE_NULL
  141647. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  141648. )){
  141649. /* The new rowid is not NULL (in this case the rowid will be
  141650. ** automatically assigned and there is no chance of a conflict), and
  141651. ** the statement is either an INSERT or an UPDATE that modifies the
  141652. ** rowid column. So if the conflict mode is REPLACE, then delete any
  141653. ** existing row with rowid=pNewRowid.
  141654. **
  141655. ** Or, if the conflict mode is not REPLACE, insert the new record into
  141656. ** the %_content table. If we hit the duplicate rowid constraint (or any
  141657. ** other error) while doing so, return immediately.
  141658. **
  141659. ** This branch may also run if pNewRowid contains a value that cannot
  141660. ** be losslessly converted to an integer. In this case, the eventual
  141661. ** call to fts3InsertData() (either just below or further on in this
  141662. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  141663. ** invoked, it will delete zero rows (since no row will have
  141664. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  141665. */
  141666. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  141667. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  141668. }else{
  141669. rc = fts3InsertData(p, apVal, pRowid);
  141670. bInsertDone = 1;
  141671. }
  141672. }
  141673. }
  141674. if( rc!=SQLITE_OK ){
  141675. goto update_out;
  141676. }
  141677. /* If this is a DELETE or UPDATE operation, remove the old record. */
  141678. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  141679. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  141680. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  141681. isRemove = 1;
  141682. }
  141683. /* If this is an INSERT or UPDATE operation, insert the new record. */
  141684. if( nArg>1 && rc==SQLITE_OK ){
  141685. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  141686. if( bInsertDone==0 ){
  141687. rc = fts3InsertData(p, apVal, pRowid);
  141688. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  141689. rc = FTS_CORRUPT_VTAB;
  141690. }
  141691. }
  141692. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  141693. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  141694. }
  141695. if( rc==SQLITE_OK ){
  141696. assert( p->iPrevDocid==*pRowid );
  141697. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  141698. }
  141699. if( p->bHasDocsize ){
  141700. fts3InsertDocsize(&rc, p, aSzIns);
  141701. }
  141702. nChng++;
  141703. }
  141704. if( p->bFts4 ){
  141705. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  141706. }
  141707. update_out:
  141708. sqlite3_free(aSzDel);
  141709. sqlite3Fts3SegmentsClose(p);
  141710. return rc;
  141711. }
  141712. /*
  141713. ** Flush any data in the pending-terms hash table to disk. If successful,
  141714. ** merge all segments in the database (including the new segment, if
  141715. ** there was any data to flush) into a single segment.
  141716. */
  141717. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  141718. int rc;
  141719. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  141720. if( rc==SQLITE_OK ){
  141721. rc = fts3DoOptimize(p, 1);
  141722. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  141723. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  141724. if( rc2!=SQLITE_OK ) rc = rc2;
  141725. }else{
  141726. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  141727. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  141728. }
  141729. }
  141730. sqlite3Fts3SegmentsClose(p);
  141731. return rc;
  141732. }
  141733. #endif
  141734. /************** End of fts3_write.c ******************************************/
  141735. /************** Begin file fts3_snippet.c ************************************/
  141736. /*
  141737. ** 2009 Oct 23
  141738. **
  141739. ** The author disclaims copyright to this source code. In place of
  141740. ** a legal notice, here is a blessing:
  141741. **
  141742. ** May you do good and not evil.
  141743. ** May you find forgiveness for yourself and forgive others.
  141744. ** May you share freely, never taking more than you give.
  141745. **
  141746. ******************************************************************************
  141747. */
  141748. /* #include "fts3Int.h" */
  141749. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141750. /* #include <string.h> */
  141751. /* #include <assert.h> */
  141752. /*
  141753. ** Characters that may appear in the second argument to matchinfo().
  141754. */
  141755. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  141756. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  141757. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  141758. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  141759. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  141760. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  141761. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  141762. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  141763. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  141764. /*
  141765. ** The default value for the second argument to matchinfo().
  141766. */
  141767. #define FTS3_MATCHINFO_DEFAULT "pcx"
  141768. /*
  141769. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  141770. ** Fts3Expr.aDoclist[]/nDoclist.
  141771. */
  141772. typedef struct LoadDoclistCtx LoadDoclistCtx;
  141773. struct LoadDoclistCtx {
  141774. Fts3Cursor *pCsr; /* FTS3 Cursor */
  141775. int nPhrase; /* Number of phrases seen so far */
  141776. int nToken; /* Number of tokens seen so far */
  141777. };
  141778. /*
  141779. ** The following types are used as part of the implementation of the
  141780. ** fts3BestSnippet() routine.
  141781. */
  141782. typedef struct SnippetIter SnippetIter;
  141783. typedef struct SnippetPhrase SnippetPhrase;
  141784. typedef struct SnippetFragment SnippetFragment;
  141785. struct SnippetIter {
  141786. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  141787. int iCol; /* Extract snippet from this column */
  141788. int nSnippet; /* Requested snippet length (in tokens) */
  141789. int nPhrase; /* Number of phrases in query */
  141790. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  141791. int iCurrent; /* First token of current snippet */
  141792. };
  141793. struct SnippetPhrase {
  141794. int nToken; /* Number of tokens in phrase */
  141795. char *pList; /* Pointer to start of phrase position list */
  141796. int iHead; /* Next value in position list */
  141797. char *pHead; /* Position list data following iHead */
  141798. int iTail; /* Next value in trailing position list */
  141799. char *pTail; /* Position list data following iTail */
  141800. };
  141801. struct SnippetFragment {
  141802. int iCol; /* Column snippet is extracted from */
  141803. int iPos; /* Index of first token in snippet */
  141804. u64 covered; /* Mask of query phrases covered */
  141805. u64 hlmask; /* Mask of snippet terms to highlight */
  141806. };
  141807. /*
  141808. ** This type is used as an fts3ExprIterate() context object while
  141809. ** accumulating the data returned by the matchinfo() function.
  141810. */
  141811. typedef struct MatchInfo MatchInfo;
  141812. struct MatchInfo {
  141813. Fts3Cursor *pCursor; /* FTS3 Cursor */
  141814. int nCol; /* Number of columns in table */
  141815. int nPhrase; /* Number of matchable phrases in query */
  141816. sqlite3_int64 nDoc; /* Number of docs in database */
  141817. char flag;
  141818. u32 *aMatchinfo; /* Pre-allocated buffer */
  141819. };
  141820. /*
  141821. ** An instance of this structure is used to manage a pair of buffers, each
  141822. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  141823. ** for details.
  141824. */
  141825. struct MatchinfoBuffer {
  141826. u8 aRef[3];
  141827. int nElem;
  141828. int bGlobal; /* Set if global data is loaded */
  141829. char *zMatchinfo;
  141830. u32 aMatchinfo[1];
  141831. };
  141832. /*
  141833. ** The snippet() and offsets() functions both return text values. An instance
  141834. ** of the following structure is used to accumulate those values while the
  141835. ** functions are running. See fts3StringAppend() for details.
  141836. */
  141837. typedef struct StrBuffer StrBuffer;
  141838. struct StrBuffer {
  141839. char *z; /* Pointer to buffer containing string */
  141840. int n; /* Length of z in bytes (excl. nul-term) */
  141841. int nAlloc; /* Allocated size of buffer z in bytes */
  141842. };
  141843. /*************************************************************************
  141844. ** Start of MatchinfoBuffer code.
  141845. */
  141846. /*
  141847. ** Allocate a two-slot MatchinfoBuffer object.
  141848. */
  141849. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  141850. MatchinfoBuffer *pRet;
  141851. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  141852. int nStr = (int)strlen(zMatchinfo);
  141853. pRet = sqlite3_malloc(nByte + nStr+1);
  141854. if( pRet ){
  141855. memset(pRet, 0, nByte);
  141856. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  141857. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  141858. pRet->nElem = nElem;
  141859. pRet->zMatchinfo = ((char*)pRet) + nByte;
  141860. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  141861. pRet->aRef[0] = 1;
  141862. }
  141863. return pRet;
  141864. }
  141865. static void fts3MIBufferFree(void *p){
  141866. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  141867. assert( (u32*)p==&pBuf->aMatchinfo[1]
  141868. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  141869. );
  141870. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  141871. pBuf->aRef[1] = 0;
  141872. }else{
  141873. pBuf->aRef[2] = 0;
  141874. }
  141875. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  141876. sqlite3_free(pBuf);
  141877. }
  141878. }
  141879. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  141880. void (*xRet)(void*) = 0;
  141881. u32 *aOut = 0;
  141882. if( p->aRef[1]==0 ){
  141883. p->aRef[1] = 1;
  141884. aOut = &p->aMatchinfo[1];
  141885. xRet = fts3MIBufferFree;
  141886. }
  141887. else if( p->aRef[2]==0 ){
  141888. p->aRef[2] = 1;
  141889. aOut = &p->aMatchinfo[p->nElem+2];
  141890. xRet = fts3MIBufferFree;
  141891. }else{
  141892. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  141893. if( aOut ){
  141894. xRet = sqlite3_free;
  141895. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  141896. }
  141897. }
  141898. *paOut = aOut;
  141899. return xRet;
  141900. }
  141901. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  141902. p->bGlobal = 1;
  141903. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  141904. }
  141905. /*
  141906. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  141907. */
  141908. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  141909. if( p ){
  141910. assert( p->aRef[0]==1 );
  141911. p->aRef[0] = 0;
  141912. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  141913. sqlite3_free(p);
  141914. }
  141915. }
  141916. }
  141917. /*
  141918. ** End of MatchinfoBuffer code.
  141919. *************************************************************************/
  141920. /*
  141921. ** This function is used to help iterate through a position-list. A position
  141922. ** list is a list of unique integers, sorted from smallest to largest. Each
  141923. ** element of the list is represented by an FTS3 varint that takes the value
  141924. ** of the difference between the current element and the previous one plus
  141925. ** two. For example, to store the position-list:
  141926. **
  141927. ** 4 9 113
  141928. **
  141929. ** the three varints:
  141930. **
  141931. ** 6 7 106
  141932. **
  141933. ** are encoded.
  141934. **
  141935. ** When this function is called, *pp points to the start of an element of
  141936. ** the list. *piPos contains the value of the previous entry in the list.
  141937. ** After it returns, *piPos contains the value of the next element of the
  141938. ** list and *pp is advanced to the following varint.
  141939. */
  141940. static void fts3GetDeltaPosition(char **pp, int *piPos){
  141941. int iVal;
  141942. *pp += fts3GetVarint32(*pp, &iVal);
  141943. *piPos += (iVal-2);
  141944. }
  141945. /*
  141946. ** Helper function for fts3ExprIterate() (see below).
  141947. */
  141948. static int fts3ExprIterate2(
  141949. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  141950. int *piPhrase, /* Pointer to phrase counter */
  141951. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  141952. void *pCtx /* Second argument to pass to callback */
  141953. ){
  141954. int rc; /* Return code */
  141955. int eType = pExpr->eType; /* Type of expression node pExpr */
  141956. if( eType!=FTSQUERY_PHRASE ){
  141957. assert( pExpr->pLeft && pExpr->pRight );
  141958. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  141959. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  141960. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  141961. }
  141962. }else{
  141963. rc = x(pExpr, *piPhrase, pCtx);
  141964. (*piPhrase)++;
  141965. }
  141966. return rc;
  141967. }
  141968. /*
  141969. ** Iterate through all phrase nodes in an FTS3 query, except those that
  141970. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  141971. ** For each phrase node found, the supplied callback function is invoked.
  141972. **
  141973. ** If the callback function returns anything other than SQLITE_OK,
  141974. ** the iteration is abandoned and the error code returned immediately.
  141975. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  141976. ** all eligible phrase nodes.
  141977. */
  141978. static int fts3ExprIterate(
  141979. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  141980. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  141981. void *pCtx /* Second argument to pass to callback */
  141982. ){
  141983. int iPhrase = 0; /* Variable used as the phrase counter */
  141984. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  141985. }
  141986. /*
  141987. ** This is an fts3ExprIterate() callback used while loading the doclists
  141988. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  141989. ** fts3ExprLoadDoclists().
  141990. */
  141991. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  141992. int rc = SQLITE_OK;
  141993. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141994. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  141995. UNUSED_PARAMETER(iPhrase);
  141996. p->nPhrase++;
  141997. p->nToken += pPhrase->nToken;
  141998. return rc;
  141999. }
  142000. /*
  142001. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  142002. ** pCsr.
  142003. **
  142004. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  142005. ** phrases in the expression (all phrases except those directly or
  142006. ** indirectly descended from the right-hand-side of a NOT operator). If
  142007. ** pnToken is not NULL, then it is set to the number of tokens in all
  142008. ** matchable phrases of the expression.
  142009. */
  142010. static int fts3ExprLoadDoclists(
  142011. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  142012. int *pnPhrase, /* OUT: Number of phrases in query */
  142013. int *pnToken /* OUT: Number of tokens in query */
  142014. ){
  142015. int rc; /* Return Code */
  142016. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  142017. sCtx.pCsr = pCsr;
  142018. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  142019. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  142020. if( pnToken ) *pnToken = sCtx.nToken;
  142021. return rc;
  142022. }
  142023. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  142024. (*(int *)ctx)++;
  142025. pExpr->iPhrase = iPhrase;
  142026. return SQLITE_OK;
  142027. }
  142028. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  142029. int nPhrase = 0;
  142030. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  142031. return nPhrase;
  142032. }
  142033. /*
  142034. ** Advance the position list iterator specified by the first two
  142035. ** arguments so that it points to the first element with a value greater
  142036. ** than or equal to parameter iNext.
  142037. */
  142038. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  142039. char *pIter = *ppIter;
  142040. if( pIter ){
  142041. int iIter = *piIter;
  142042. while( iIter<iNext ){
  142043. if( 0==(*pIter & 0xFE) ){
  142044. iIter = -1;
  142045. pIter = 0;
  142046. break;
  142047. }
  142048. fts3GetDeltaPosition(&pIter, &iIter);
  142049. }
  142050. *piIter = iIter;
  142051. *ppIter = pIter;
  142052. }
  142053. }
  142054. /*
  142055. ** Advance the snippet iterator to the next candidate snippet.
  142056. */
  142057. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  142058. int i; /* Loop counter */
  142059. if( pIter->iCurrent<0 ){
  142060. /* The SnippetIter object has just been initialized. The first snippet
  142061. ** candidate always starts at offset 0 (even if this candidate has a
  142062. ** score of 0.0).
  142063. */
  142064. pIter->iCurrent = 0;
  142065. /* Advance the 'head' iterator of each phrase to the first offset that
  142066. ** is greater than or equal to (iNext+nSnippet).
  142067. */
  142068. for(i=0; i<pIter->nPhrase; i++){
  142069. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  142070. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  142071. }
  142072. }else{
  142073. int iStart;
  142074. int iEnd = 0x7FFFFFFF;
  142075. for(i=0; i<pIter->nPhrase; i++){
  142076. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  142077. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  142078. iEnd = pPhrase->iHead;
  142079. }
  142080. }
  142081. if( iEnd==0x7FFFFFFF ){
  142082. return 1;
  142083. }
  142084. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  142085. for(i=0; i<pIter->nPhrase; i++){
  142086. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  142087. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  142088. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  142089. }
  142090. }
  142091. return 0;
  142092. }
  142093. /*
  142094. ** Retrieve information about the current candidate snippet of snippet
  142095. ** iterator pIter.
  142096. */
  142097. static void fts3SnippetDetails(
  142098. SnippetIter *pIter, /* Snippet iterator */
  142099. u64 mCovered, /* Bitmask of phrases already covered */
  142100. int *piToken, /* OUT: First token of proposed snippet */
  142101. int *piScore, /* OUT: "Score" for this snippet */
  142102. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  142103. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  142104. ){
  142105. int iStart = pIter->iCurrent; /* First token of snippet */
  142106. int iScore = 0; /* Score of this snippet */
  142107. int i; /* Loop counter */
  142108. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  142109. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  142110. for(i=0; i<pIter->nPhrase; i++){
  142111. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  142112. if( pPhrase->pTail ){
  142113. char *pCsr = pPhrase->pTail;
  142114. int iCsr = pPhrase->iTail;
  142115. while( iCsr<(iStart+pIter->nSnippet) ){
  142116. int j;
  142117. u64 mPhrase = (u64)1 << i;
  142118. u64 mPos = (u64)1 << (iCsr - iStart);
  142119. assert( iCsr>=iStart );
  142120. if( (mCover|mCovered)&mPhrase ){
  142121. iScore++;
  142122. }else{
  142123. iScore += 1000;
  142124. }
  142125. mCover |= mPhrase;
  142126. for(j=0; j<pPhrase->nToken; j++){
  142127. mHighlight |= (mPos>>j);
  142128. }
  142129. if( 0==(*pCsr & 0x0FE) ) break;
  142130. fts3GetDeltaPosition(&pCsr, &iCsr);
  142131. }
  142132. }
  142133. }
  142134. /* Set the output variables before returning. */
  142135. *piToken = iStart;
  142136. *piScore = iScore;
  142137. *pmCover = mCover;
  142138. *pmHighlight = mHighlight;
  142139. }
  142140. /*
  142141. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  142142. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  142143. */
  142144. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  142145. SnippetIter *p = (SnippetIter *)ctx;
  142146. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  142147. char *pCsr;
  142148. int rc;
  142149. pPhrase->nToken = pExpr->pPhrase->nToken;
  142150. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  142151. assert( rc==SQLITE_OK || pCsr==0 );
  142152. if( pCsr ){
  142153. int iFirst = 0;
  142154. pPhrase->pList = pCsr;
  142155. fts3GetDeltaPosition(&pCsr, &iFirst);
  142156. assert( iFirst>=0 );
  142157. pPhrase->pHead = pCsr;
  142158. pPhrase->pTail = pCsr;
  142159. pPhrase->iHead = iFirst;
  142160. pPhrase->iTail = iFirst;
  142161. }else{
  142162. assert( rc!=SQLITE_OK || (
  142163. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  142164. ));
  142165. }
  142166. return rc;
  142167. }
  142168. /*
  142169. ** Select the fragment of text consisting of nFragment contiguous tokens
  142170. ** from column iCol that represent the "best" snippet. The best snippet
  142171. ** is the snippet with the highest score, where scores are calculated
  142172. ** by adding:
  142173. **
  142174. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  142175. **
  142176. ** (b) +1000 points for the first occurrence of each matchable phrase in
  142177. ** the snippet for which the corresponding mCovered bit is not set.
  142178. **
  142179. ** The selected snippet parameters are stored in structure *pFragment before
  142180. ** returning. The score of the selected snippet is stored in *piScore
  142181. ** before returning.
  142182. */
  142183. static int fts3BestSnippet(
  142184. int nSnippet, /* Desired snippet length */
  142185. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  142186. int iCol, /* Index of column to create snippet from */
  142187. u64 mCovered, /* Mask of phrases already covered */
  142188. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  142189. SnippetFragment *pFragment, /* OUT: Best snippet found */
  142190. int *piScore /* OUT: Score of snippet pFragment */
  142191. ){
  142192. int rc; /* Return Code */
  142193. int nList; /* Number of phrases in expression */
  142194. SnippetIter sIter; /* Iterates through snippet candidates */
  142195. int nByte; /* Number of bytes of space to allocate */
  142196. int iBestScore = -1; /* Best snippet score found so far */
  142197. int i; /* Loop counter */
  142198. memset(&sIter, 0, sizeof(sIter));
  142199. /* Iterate through the phrases in the expression to count them. The same
  142200. ** callback makes sure the doclists are loaded for each phrase.
  142201. */
  142202. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  142203. if( rc!=SQLITE_OK ){
  142204. return rc;
  142205. }
  142206. /* Now that it is known how many phrases there are, allocate and zero
  142207. ** the required space using malloc().
  142208. */
  142209. nByte = sizeof(SnippetPhrase) * nList;
  142210. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  142211. if( !sIter.aPhrase ){
  142212. return SQLITE_NOMEM;
  142213. }
  142214. memset(sIter.aPhrase, 0, nByte);
  142215. /* Initialize the contents of the SnippetIter object. Then iterate through
  142216. ** the set of phrases in the expression to populate the aPhrase[] array.
  142217. */
  142218. sIter.pCsr = pCsr;
  142219. sIter.iCol = iCol;
  142220. sIter.nSnippet = nSnippet;
  142221. sIter.nPhrase = nList;
  142222. sIter.iCurrent = -1;
  142223. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  142224. if( rc==SQLITE_OK ){
  142225. /* Set the *pmSeen output variable. */
  142226. for(i=0; i<nList; i++){
  142227. if( sIter.aPhrase[i].pHead ){
  142228. *pmSeen |= (u64)1 << i;
  142229. }
  142230. }
  142231. /* Loop through all candidate snippets. Store the best snippet in
  142232. ** *pFragment. Store its associated 'score' in iBestScore.
  142233. */
  142234. pFragment->iCol = iCol;
  142235. while( !fts3SnippetNextCandidate(&sIter) ){
  142236. int iPos;
  142237. int iScore;
  142238. u64 mCover;
  142239. u64 mHighlite;
  142240. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  142241. assert( iScore>=0 );
  142242. if( iScore>iBestScore ){
  142243. pFragment->iPos = iPos;
  142244. pFragment->hlmask = mHighlite;
  142245. pFragment->covered = mCover;
  142246. iBestScore = iScore;
  142247. }
  142248. }
  142249. *piScore = iBestScore;
  142250. }
  142251. sqlite3_free(sIter.aPhrase);
  142252. return rc;
  142253. }
  142254. /*
  142255. ** Append a string to the string-buffer passed as the first argument.
  142256. **
  142257. ** If nAppend is negative, then the length of the string zAppend is
  142258. ** determined using strlen().
  142259. */
  142260. static int fts3StringAppend(
  142261. StrBuffer *pStr, /* Buffer to append to */
  142262. const char *zAppend, /* Pointer to data to append to buffer */
  142263. int nAppend /* Size of zAppend in bytes (or -1) */
  142264. ){
  142265. if( nAppend<0 ){
  142266. nAppend = (int)strlen(zAppend);
  142267. }
  142268. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  142269. ** to grow the buffer until so that it is big enough to accomadate the
  142270. ** appended data.
  142271. */
  142272. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  142273. int nAlloc = pStr->nAlloc+nAppend+100;
  142274. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  142275. if( !zNew ){
  142276. return SQLITE_NOMEM;
  142277. }
  142278. pStr->z = zNew;
  142279. pStr->nAlloc = nAlloc;
  142280. }
  142281. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  142282. /* Append the data to the string buffer. */
  142283. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  142284. pStr->n += nAppend;
  142285. pStr->z[pStr->n] = '\0';
  142286. return SQLITE_OK;
  142287. }
  142288. /*
  142289. ** The fts3BestSnippet() function often selects snippets that end with a
  142290. ** query term. That is, the final term of the snippet is always a term
  142291. ** that requires highlighting. For example, if 'X' is a highlighted term
  142292. ** and '.' is a non-highlighted term, BestSnippet() may select:
  142293. **
  142294. ** ........X.....X
  142295. **
  142296. ** This function "shifts" the beginning of the snippet forward in the
  142297. ** document so that there are approximately the same number of
  142298. ** non-highlighted terms to the right of the final highlighted term as there
  142299. ** are to the left of the first highlighted term. For example, to this:
  142300. **
  142301. ** ....X.....X....
  142302. **
  142303. ** This is done as part of extracting the snippet text, not when selecting
  142304. ** the snippet. Snippet selection is done based on doclists only, so there
  142305. ** is no way for fts3BestSnippet() to know whether or not the document
  142306. ** actually contains terms that follow the final highlighted term.
  142307. */
  142308. static int fts3SnippetShift(
  142309. Fts3Table *pTab, /* FTS3 table snippet comes from */
  142310. int iLangid, /* Language id to use in tokenizing */
  142311. int nSnippet, /* Number of tokens desired for snippet */
  142312. const char *zDoc, /* Document text to extract snippet from */
  142313. int nDoc, /* Size of buffer zDoc in bytes */
  142314. int *piPos, /* IN/OUT: First token of snippet */
  142315. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  142316. ){
  142317. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  142318. if( hlmask ){
  142319. int nLeft; /* Tokens to the left of first highlight */
  142320. int nRight; /* Tokens to the right of last highlight */
  142321. int nDesired; /* Ideal number of tokens to shift forward */
  142322. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  142323. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  142324. nDesired = (nLeft-nRight)/2;
  142325. /* Ideally, the start of the snippet should be pushed forward in the
  142326. ** document nDesired tokens. This block checks if there are actually
  142327. ** nDesired tokens to the right of the snippet. If so, *piPos and
  142328. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  142329. ** right. Otherwise, the snippet is shifted by the number of tokens
  142330. ** available.
  142331. */
  142332. if( nDesired>0 ){
  142333. int nShift; /* Number of tokens to shift snippet by */
  142334. int iCurrent = 0; /* Token counter */
  142335. int rc; /* Return Code */
  142336. sqlite3_tokenizer_module *pMod;
  142337. sqlite3_tokenizer_cursor *pC;
  142338. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  142339. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  142340. ** or more tokens in zDoc/nDoc.
  142341. */
  142342. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  142343. if( rc!=SQLITE_OK ){
  142344. return rc;
  142345. }
  142346. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  142347. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  142348. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  142349. }
  142350. pMod->xClose(pC);
  142351. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  142352. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  142353. assert( nShift<=nDesired );
  142354. if( nShift>0 ){
  142355. *piPos += nShift;
  142356. *pHlmask = hlmask >> nShift;
  142357. }
  142358. }
  142359. }
  142360. return SQLITE_OK;
  142361. }
  142362. /*
  142363. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  142364. ** append it to string buffer pOut.
  142365. */
  142366. static int fts3SnippetText(
  142367. Fts3Cursor *pCsr, /* FTS3 Cursor */
  142368. SnippetFragment *pFragment, /* Snippet to extract */
  142369. int iFragment, /* Fragment number */
  142370. int isLast, /* True for final fragment in snippet */
  142371. int nSnippet, /* Number of tokens in extracted snippet */
  142372. const char *zOpen, /* String inserted before highlighted term */
  142373. const char *zClose, /* String inserted after highlighted term */
  142374. const char *zEllipsis, /* String inserted between snippets */
  142375. StrBuffer *pOut /* Write output here */
  142376. ){
  142377. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142378. int rc; /* Return code */
  142379. const char *zDoc; /* Document text to extract snippet from */
  142380. int nDoc; /* Size of zDoc in bytes */
  142381. int iCurrent = 0; /* Current token number of document */
  142382. int iEnd = 0; /* Byte offset of end of current token */
  142383. int isShiftDone = 0; /* True after snippet is shifted */
  142384. int iPos = pFragment->iPos; /* First token of snippet */
  142385. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  142386. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  142387. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  142388. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  142389. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  142390. if( zDoc==0 ){
  142391. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  142392. return SQLITE_NOMEM;
  142393. }
  142394. return SQLITE_OK;
  142395. }
  142396. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  142397. /* Open a token cursor on the document. */
  142398. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  142399. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  142400. if( rc!=SQLITE_OK ){
  142401. return rc;
  142402. }
  142403. while( rc==SQLITE_OK ){
  142404. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  142405. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  142406. int iBegin = 0; /* Offset in zDoc of start of token */
  142407. int iFin = 0; /* Offset in zDoc of end of token */
  142408. int isHighlight = 0; /* True for highlighted terms */
  142409. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  142410. ** in the FTS code the variable that the third argument to xNext points to
  142411. ** is initialized to zero before the first (*but not necessarily
  142412. ** subsequent*) call to xNext(). This is done for a particular application
  142413. ** that needs to know whether or not the tokenizer is being used for
  142414. ** snippet generation or for some other purpose.
  142415. **
  142416. ** Extreme care is required when writing code to depend on this
  142417. ** initialization. It is not a documented part of the tokenizer interface.
  142418. ** If a tokenizer is used directly by any code outside of FTS, this
  142419. ** convention might not be respected. */
  142420. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  142421. if( rc!=SQLITE_OK ){
  142422. if( rc==SQLITE_DONE ){
  142423. /* Special case - the last token of the snippet is also the last token
  142424. ** of the column. Append any punctuation that occurred between the end
  142425. ** of the previous token and the end of the document to the output.
  142426. ** Then break out of the loop. */
  142427. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  142428. }
  142429. break;
  142430. }
  142431. if( iCurrent<iPos ){ continue; }
  142432. if( !isShiftDone ){
  142433. int n = nDoc - iBegin;
  142434. rc = fts3SnippetShift(
  142435. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  142436. );
  142437. isShiftDone = 1;
  142438. /* Now that the shift has been done, check if the initial "..." are
  142439. ** required. They are required if (a) this is not the first fragment,
  142440. ** or (b) this fragment does not begin at position 0 of its column.
  142441. */
  142442. if( rc==SQLITE_OK ){
  142443. if( iPos>0 || iFragment>0 ){
  142444. rc = fts3StringAppend(pOut, zEllipsis, -1);
  142445. }else if( iBegin ){
  142446. rc = fts3StringAppend(pOut, zDoc, iBegin);
  142447. }
  142448. }
  142449. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  142450. }
  142451. if( iCurrent>=(iPos+nSnippet) ){
  142452. if( isLast ){
  142453. rc = fts3StringAppend(pOut, zEllipsis, -1);
  142454. }
  142455. break;
  142456. }
  142457. /* Set isHighlight to true if this term should be highlighted. */
  142458. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  142459. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  142460. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  142461. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  142462. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  142463. iEnd = iFin;
  142464. }
  142465. pMod->xClose(pC);
  142466. return rc;
  142467. }
  142468. /*
  142469. ** This function is used to count the entries in a column-list (a
  142470. ** delta-encoded list of term offsets within a single column of a single
  142471. ** row). When this function is called, *ppCollist should point to the
  142472. ** beginning of the first varint in the column-list (the varint that
  142473. ** contains the position of the first matching term in the column data).
  142474. ** Before returning, *ppCollist is set to point to the first byte after
  142475. ** the last varint in the column-list (either the 0x00 signifying the end
  142476. ** of the position-list, or the 0x01 that precedes the column number of
  142477. ** the next column in the position-list).
  142478. **
  142479. ** The number of elements in the column-list is returned.
  142480. */
  142481. static int fts3ColumnlistCount(char **ppCollist){
  142482. char *pEnd = *ppCollist;
  142483. char c = 0;
  142484. int nEntry = 0;
  142485. /* A column-list is terminated by either a 0x01 or 0x00. */
  142486. while( 0xFE & (*pEnd | c) ){
  142487. c = *pEnd++ & 0x80;
  142488. if( !c ) nEntry++;
  142489. }
  142490. *ppCollist = pEnd;
  142491. return nEntry;
  142492. }
  142493. /*
  142494. ** This function gathers 'y' or 'b' data for a single phrase.
  142495. */
  142496. static void fts3ExprLHits(
  142497. Fts3Expr *pExpr, /* Phrase expression node */
  142498. MatchInfo *p /* Matchinfo context */
  142499. ){
  142500. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  142501. int iStart;
  142502. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142503. char *pIter = pPhrase->doclist.pList;
  142504. int iCol = 0;
  142505. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  142506. if( p->flag==FTS3_MATCHINFO_LHITS ){
  142507. iStart = pExpr->iPhrase * p->nCol;
  142508. }else{
  142509. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  142510. }
  142511. while( 1 ){
  142512. int nHit = fts3ColumnlistCount(&pIter);
  142513. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  142514. if( p->flag==FTS3_MATCHINFO_LHITS ){
  142515. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  142516. }else if( nHit ){
  142517. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  142518. }
  142519. }
  142520. assert( *pIter==0x00 || *pIter==0x01 );
  142521. if( *pIter!=0x01 ) break;
  142522. pIter++;
  142523. pIter += fts3GetVarint32(pIter, &iCol);
  142524. }
  142525. }
  142526. /*
  142527. ** Gather the results for matchinfo directives 'y' and 'b'.
  142528. */
  142529. static void fts3ExprLHitGather(
  142530. Fts3Expr *pExpr,
  142531. MatchInfo *p
  142532. ){
  142533. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  142534. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  142535. if( pExpr->pLeft ){
  142536. fts3ExprLHitGather(pExpr->pLeft, p);
  142537. fts3ExprLHitGather(pExpr->pRight, p);
  142538. }else{
  142539. fts3ExprLHits(pExpr, p);
  142540. }
  142541. }
  142542. }
  142543. /*
  142544. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  142545. ** for a single query.
  142546. **
  142547. ** fts3ExprIterate() callback to load the 'global' elements of a
  142548. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  142549. ** of the matchinfo array that are constant for all rows returned by the
  142550. ** current query.
  142551. **
  142552. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  142553. ** function populates Matchinfo.aMatchinfo[] as follows:
  142554. **
  142555. ** for(iCol=0; iCol<nCol; iCol++){
  142556. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  142557. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  142558. ** }
  142559. **
  142560. ** where X is the number of matches for phrase iPhrase is column iCol of all
  142561. ** rows of the table. Y is the number of rows for which column iCol contains
  142562. ** at least one instance of phrase iPhrase.
  142563. **
  142564. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  142565. ** Y values are set to nDoc, where nDoc is the number of documents in the
  142566. ** file system. This is done because the full-text index doclist is required
  142567. ** to calculate these values properly, and the full-text index doclist is
  142568. ** not available for deferred tokens.
  142569. */
  142570. static int fts3ExprGlobalHitsCb(
  142571. Fts3Expr *pExpr, /* Phrase expression node */
  142572. int iPhrase, /* Phrase number (numbered from zero) */
  142573. void *pCtx /* Pointer to MatchInfo structure */
  142574. ){
  142575. MatchInfo *p = (MatchInfo *)pCtx;
  142576. return sqlite3Fts3EvalPhraseStats(
  142577. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  142578. );
  142579. }
  142580. /*
  142581. ** fts3ExprIterate() callback used to collect the "local" part of the
  142582. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  142583. ** array that are different for each row returned by the query.
  142584. */
  142585. static int fts3ExprLocalHitsCb(
  142586. Fts3Expr *pExpr, /* Phrase expression node */
  142587. int iPhrase, /* Phrase number */
  142588. void *pCtx /* Pointer to MatchInfo structure */
  142589. ){
  142590. int rc = SQLITE_OK;
  142591. MatchInfo *p = (MatchInfo *)pCtx;
  142592. int iStart = iPhrase * p->nCol * 3;
  142593. int i;
  142594. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  142595. char *pCsr;
  142596. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  142597. if( pCsr ){
  142598. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  142599. }else{
  142600. p->aMatchinfo[iStart+i*3] = 0;
  142601. }
  142602. }
  142603. return rc;
  142604. }
  142605. static int fts3MatchinfoCheck(
  142606. Fts3Table *pTab,
  142607. char cArg,
  142608. char **pzErr
  142609. ){
  142610. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  142611. || (cArg==FTS3_MATCHINFO_NCOL)
  142612. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  142613. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  142614. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  142615. || (cArg==FTS3_MATCHINFO_LCS)
  142616. || (cArg==FTS3_MATCHINFO_HITS)
  142617. || (cArg==FTS3_MATCHINFO_LHITS)
  142618. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  142619. ){
  142620. return SQLITE_OK;
  142621. }
  142622. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  142623. return SQLITE_ERROR;
  142624. }
  142625. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  142626. int nVal; /* Number of integers output by cArg */
  142627. switch( cArg ){
  142628. case FTS3_MATCHINFO_NDOC:
  142629. case FTS3_MATCHINFO_NPHRASE:
  142630. case FTS3_MATCHINFO_NCOL:
  142631. nVal = 1;
  142632. break;
  142633. case FTS3_MATCHINFO_AVGLENGTH:
  142634. case FTS3_MATCHINFO_LENGTH:
  142635. case FTS3_MATCHINFO_LCS:
  142636. nVal = pInfo->nCol;
  142637. break;
  142638. case FTS3_MATCHINFO_LHITS:
  142639. nVal = pInfo->nCol * pInfo->nPhrase;
  142640. break;
  142641. case FTS3_MATCHINFO_LHITS_BM:
  142642. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  142643. break;
  142644. default:
  142645. assert( cArg==FTS3_MATCHINFO_HITS );
  142646. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  142647. break;
  142648. }
  142649. return nVal;
  142650. }
  142651. static int fts3MatchinfoSelectDoctotal(
  142652. Fts3Table *pTab,
  142653. sqlite3_stmt **ppStmt,
  142654. sqlite3_int64 *pnDoc,
  142655. const char **paLen
  142656. ){
  142657. sqlite3_stmt *pStmt;
  142658. const char *a;
  142659. sqlite3_int64 nDoc;
  142660. if( !*ppStmt ){
  142661. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  142662. if( rc!=SQLITE_OK ) return rc;
  142663. }
  142664. pStmt = *ppStmt;
  142665. assert( sqlite3_data_count(pStmt)==1 );
  142666. a = sqlite3_column_blob(pStmt, 0);
  142667. a += sqlite3Fts3GetVarint(a, &nDoc);
  142668. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  142669. *pnDoc = (u32)nDoc;
  142670. if( paLen ) *paLen = a;
  142671. return SQLITE_OK;
  142672. }
  142673. /*
  142674. ** An instance of the following structure is used to store state while
  142675. ** iterating through a multi-column position-list corresponding to the
  142676. ** hits for a single phrase on a single row in order to calculate the
  142677. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  142678. */
  142679. typedef struct LcsIterator LcsIterator;
  142680. struct LcsIterator {
  142681. Fts3Expr *pExpr; /* Pointer to phrase expression */
  142682. int iPosOffset; /* Tokens count up to end of this phrase */
  142683. char *pRead; /* Cursor used to iterate through aDoclist */
  142684. int iPos; /* Current position */
  142685. };
  142686. /*
  142687. ** If LcsIterator.iCol is set to the following value, the iterator has
  142688. ** finished iterating through all offsets for all columns.
  142689. */
  142690. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  142691. static int fts3MatchinfoLcsCb(
  142692. Fts3Expr *pExpr, /* Phrase expression node */
  142693. int iPhrase, /* Phrase number (numbered from zero) */
  142694. void *pCtx /* Pointer to MatchInfo structure */
  142695. ){
  142696. LcsIterator *aIter = (LcsIterator *)pCtx;
  142697. aIter[iPhrase].pExpr = pExpr;
  142698. return SQLITE_OK;
  142699. }
  142700. /*
  142701. ** Advance the iterator passed as an argument to the next position. Return
  142702. ** 1 if the iterator is at EOF or if it now points to the start of the
  142703. ** position list for the next column.
  142704. */
  142705. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  142706. char *pRead = pIter->pRead;
  142707. sqlite3_int64 iRead;
  142708. int rc = 0;
  142709. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  142710. if( iRead==0 || iRead==1 ){
  142711. pRead = 0;
  142712. rc = 1;
  142713. }else{
  142714. pIter->iPos += (int)(iRead-2);
  142715. }
  142716. pIter->pRead = pRead;
  142717. return rc;
  142718. }
  142719. /*
  142720. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  142721. **
  142722. ** If the call is successful, the longest-common-substring lengths for each
  142723. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  142724. ** array before returning. SQLITE_OK is returned in this case.
  142725. **
  142726. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  142727. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  142728. ** undefined.
  142729. */
  142730. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  142731. LcsIterator *aIter;
  142732. int i;
  142733. int iCol;
  142734. int nToken = 0;
  142735. /* Allocate and populate the array of LcsIterator objects. The array
  142736. ** contains one element for each matchable phrase in the query.
  142737. **/
  142738. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  142739. if( !aIter ) return SQLITE_NOMEM;
  142740. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  142741. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  142742. for(i=0; i<pInfo->nPhrase; i++){
  142743. LcsIterator *pIter = &aIter[i];
  142744. nToken -= pIter->pExpr->pPhrase->nToken;
  142745. pIter->iPosOffset = nToken;
  142746. }
  142747. for(iCol=0; iCol<pInfo->nCol; iCol++){
  142748. int nLcs = 0; /* LCS value for this column */
  142749. int nLive = 0; /* Number of iterators in aIter not at EOF */
  142750. for(i=0; i<pInfo->nPhrase; i++){
  142751. int rc;
  142752. LcsIterator *pIt = &aIter[i];
  142753. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  142754. if( rc!=SQLITE_OK ) return rc;
  142755. if( pIt->pRead ){
  142756. pIt->iPos = pIt->iPosOffset;
  142757. fts3LcsIteratorAdvance(&aIter[i]);
  142758. nLive++;
  142759. }
  142760. }
  142761. while( nLive>0 ){
  142762. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  142763. int nThisLcs = 0; /* LCS for the current iterator positions */
  142764. for(i=0; i<pInfo->nPhrase; i++){
  142765. LcsIterator *pIter = &aIter[i];
  142766. if( pIter->pRead==0 ){
  142767. /* This iterator is already at EOF for this column. */
  142768. nThisLcs = 0;
  142769. }else{
  142770. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  142771. pAdv = pIter;
  142772. }
  142773. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  142774. nThisLcs++;
  142775. }else{
  142776. nThisLcs = 1;
  142777. }
  142778. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  142779. }
  142780. }
  142781. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  142782. }
  142783. pInfo->aMatchinfo[iCol] = nLcs;
  142784. }
  142785. sqlite3_free(aIter);
  142786. return SQLITE_OK;
  142787. }
  142788. /*
  142789. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  142790. ** be returned by the matchinfo() function. Argument zArg contains the
  142791. ** format string passed as the second argument to matchinfo (or the
  142792. ** default value "pcx" if no second argument was specified). The format
  142793. ** string has already been validated and the pInfo->aMatchinfo[] array
  142794. ** is guaranteed to be large enough for the output.
  142795. **
  142796. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  142797. ** If it is false, then assume that those fields that do not change between
  142798. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  142799. ** have already been populated.
  142800. **
  142801. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  142802. ** occurs. If a value other than SQLITE_OK is returned, the state the
  142803. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  142804. */
  142805. static int fts3MatchinfoValues(
  142806. Fts3Cursor *pCsr, /* FTS3 cursor object */
  142807. int bGlobal, /* True to grab the global stats */
  142808. MatchInfo *pInfo, /* Matchinfo context object */
  142809. const char *zArg /* Matchinfo format string */
  142810. ){
  142811. int rc = SQLITE_OK;
  142812. int i;
  142813. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142814. sqlite3_stmt *pSelect = 0;
  142815. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  142816. pInfo->flag = zArg[i];
  142817. switch( zArg[i] ){
  142818. case FTS3_MATCHINFO_NPHRASE:
  142819. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  142820. break;
  142821. case FTS3_MATCHINFO_NCOL:
  142822. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  142823. break;
  142824. case FTS3_MATCHINFO_NDOC:
  142825. if( bGlobal ){
  142826. sqlite3_int64 nDoc = 0;
  142827. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  142828. pInfo->aMatchinfo[0] = (u32)nDoc;
  142829. }
  142830. break;
  142831. case FTS3_MATCHINFO_AVGLENGTH:
  142832. if( bGlobal ){
  142833. sqlite3_int64 nDoc; /* Number of rows in table */
  142834. const char *a; /* Aggregate column length array */
  142835. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  142836. if( rc==SQLITE_OK ){
  142837. int iCol;
  142838. for(iCol=0; iCol<pInfo->nCol; iCol++){
  142839. u32 iVal;
  142840. sqlite3_int64 nToken;
  142841. a += sqlite3Fts3GetVarint(a, &nToken);
  142842. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  142843. pInfo->aMatchinfo[iCol] = iVal;
  142844. }
  142845. }
  142846. }
  142847. break;
  142848. case FTS3_MATCHINFO_LENGTH: {
  142849. sqlite3_stmt *pSelectDocsize = 0;
  142850. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  142851. if( rc==SQLITE_OK ){
  142852. int iCol;
  142853. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  142854. for(iCol=0; iCol<pInfo->nCol; iCol++){
  142855. sqlite3_int64 nToken;
  142856. a += sqlite3Fts3GetVarint(a, &nToken);
  142857. pInfo->aMatchinfo[iCol] = (u32)nToken;
  142858. }
  142859. }
  142860. sqlite3_reset(pSelectDocsize);
  142861. break;
  142862. }
  142863. case FTS3_MATCHINFO_LCS:
  142864. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  142865. if( rc==SQLITE_OK ){
  142866. rc = fts3MatchinfoLcs(pCsr, pInfo);
  142867. }
  142868. break;
  142869. case FTS3_MATCHINFO_LHITS_BM:
  142870. case FTS3_MATCHINFO_LHITS: {
  142871. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  142872. memset(pInfo->aMatchinfo, 0, nZero);
  142873. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  142874. break;
  142875. }
  142876. default: {
  142877. Fts3Expr *pExpr;
  142878. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  142879. pExpr = pCsr->pExpr;
  142880. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  142881. if( rc!=SQLITE_OK ) break;
  142882. if( bGlobal ){
  142883. if( pCsr->pDeferred ){
  142884. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  142885. if( rc!=SQLITE_OK ) break;
  142886. }
  142887. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  142888. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  142889. if( rc!=SQLITE_OK ) break;
  142890. }
  142891. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  142892. break;
  142893. }
  142894. }
  142895. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  142896. }
  142897. sqlite3_reset(pSelect);
  142898. return rc;
  142899. }
  142900. /*
  142901. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  142902. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  142903. */
  142904. static void fts3GetMatchinfo(
  142905. sqlite3_context *pCtx, /* Return results here */
  142906. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  142907. const char *zArg /* Second argument to matchinfo() function */
  142908. ){
  142909. MatchInfo sInfo;
  142910. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142911. int rc = SQLITE_OK;
  142912. int bGlobal = 0; /* Collect 'global' stats as well as local */
  142913. u32 *aOut = 0;
  142914. void (*xDestroyOut)(void*) = 0;
  142915. memset(&sInfo, 0, sizeof(MatchInfo));
  142916. sInfo.pCursor = pCsr;
  142917. sInfo.nCol = pTab->nColumn;
  142918. /* If there is cached matchinfo() data, but the format string for the
  142919. ** cache does not match the format string for this request, discard
  142920. ** the cached data. */
  142921. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  142922. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  142923. pCsr->pMIBuffer = 0;
  142924. }
  142925. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  142926. ** matchinfo function has been called for this query. In this case
  142927. ** allocate the array used to accumulate the matchinfo data and
  142928. ** initialize those elements that are constant for every row.
  142929. */
  142930. if( pCsr->pMIBuffer==0 ){
  142931. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  142932. int i; /* Used to iterate through zArg */
  142933. /* Determine the number of phrases in the query */
  142934. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  142935. sInfo.nPhrase = pCsr->nPhrase;
  142936. /* Determine the number of integers in the buffer returned by this call. */
  142937. for(i=0; zArg[i]; i++){
  142938. char *zErr = 0;
  142939. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  142940. sqlite3_result_error(pCtx, zErr, -1);
  142941. sqlite3_free(zErr);
  142942. return;
  142943. }
  142944. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  142945. }
  142946. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  142947. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  142948. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  142949. pCsr->isMatchinfoNeeded = 1;
  142950. bGlobal = 1;
  142951. }
  142952. if( rc==SQLITE_OK ){
  142953. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  142954. if( xDestroyOut==0 ){
  142955. rc = SQLITE_NOMEM;
  142956. }
  142957. }
  142958. if( rc==SQLITE_OK ){
  142959. sInfo.aMatchinfo = aOut;
  142960. sInfo.nPhrase = pCsr->nPhrase;
  142961. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  142962. if( bGlobal ){
  142963. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  142964. }
  142965. }
  142966. if( rc!=SQLITE_OK ){
  142967. sqlite3_result_error_code(pCtx, rc);
  142968. if( xDestroyOut ) xDestroyOut(aOut);
  142969. }else{
  142970. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  142971. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  142972. }
  142973. }
  142974. /*
  142975. ** Implementation of snippet() function.
  142976. */
  142977. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  142978. sqlite3_context *pCtx, /* SQLite function call context */
  142979. Fts3Cursor *pCsr, /* Cursor object */
  142980. const char *zStart, /* Snippet start text - "<b>" */
  142981. const char *zEnd, /* Snippet end text - "</b>" */
  142982. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  142983. int iCol, /* Extract snippet from this column */
  142984. int nToken /* Approximate number of tokens in snippet */
  142985. ){
  142986. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142987. int rc = SQLITE_OK;
  142988. int i;
  142989. StrBuffer res = {0, 0, 0};
  142990. /* The returned text includes up to four fragments of text extracted from
  142991. ** the data in the current row. The first iteration of the for(...) loop
  142992. ** below attempts to locate a single fragment of text nToken tokens in
  142993. ** size that contains at least one instance of all phrases in the query
  142994. ** expression that appear in the current row. If such a fragment of text
  142995. ** cannot be found, the second iteration of the loop attempts to locate
  142996. ** a pair of fragments, and so on.
  142997. */
  142998. int nSnippet = 0; /* Number of fragments in this snippet */
  142999. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  143000. int nFToken = -1; /* Number of tokens in each fragment */
  143001. if( !pCsr->pExpr ){
  143002. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  143003. return;
  143004. }
  143005. for(nSnippet=1; 1; nSnippet++){
  143006. int iSnip; /* Loop counter 0..nSnippet-1 */
  143007. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  143008. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  143009. if( nToken>=0 ){
  143010. nFToken = (nToken+nSnippet-1) / nSnippet;
  143011. }else{
  143012. nFToken = -1 * nToken;
  143013. }
  143014. for(iSnip=0; iSnip<nSnippet; iSnip++){
  143015. int iBestScore = -1; /* Best score of columns checked so far */
  143016. int iRead; /* Used to iterate through columns */
  143017. SnippetFragment *pFragment = &aSnippet[iSnip];
  143018. memset(pFragment, 0, sizeof(*pFragment));
  143019. /* Loop through all columns of the table being considered for snippets.
  143020. ** If the iCol argument to this function was negative, this means all
  143021. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  143022. */
  143023. for(iRead=0; iRead<pTab->nColumn; iRead++){
  143024. SnippetFragment sF = {0, 0, 0, 0};
  143025. int iS = 0;
  143026. if( iCol>=0 && iRead!=iCol ) continue;
  143027. /* Find the best snippet of nFToken tokens in column iRead. */
  143028. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  143029. if( rc!=SQLITE_OK ){
  143030. goto snippet_out;
  143031. }
  143032. if( iS>iBestScore ){
  143033. *pFragment = sF;
  143034. iBestScore = iS;
  143035. }
  143036. }
  143037. mCovered |= pFragment->covered;
  143038. }
  143039. /* If all query phrases seen by fts3BestSnippet() are present in at least
  143040. ** one of the nSnippet snippet fragments, break out of the loop.
  143041. */
  143042. assert( (mCovered&mSeen)==mCovered );
  143043. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  143044. }
  143045. assert( nFToken>0 );
  143046. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  143047. rc = fts3SnippetText(pCsr, &aSnippet[i],
  143048. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  143049. );
  143050. }
  143051. snippet_out:
  143052. sqlite3Fts3SegmentsClose(pTab);
  143053. if( rc!=SQLITE_OK ){
  143054. sqlite3_result_error_code(pCtx, rc);
  143055. sqlite3_free(res.z);
  143056. }else{
  143057. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  143058. }
  143059. }
  143060. typedef struct TermOffset TermOffset;
  143061. typedef struct TermOffsetCtx TermOffsetCtx;
  143062. struct TermOffset {
  143063. char *pList; /* Position-list */
  143064. int iPos; /* Position just read from pList */
  143065. int iOff; /* Offset of this term from read positions */
  143066. };
  143067. struct TermOffsetCtx {
  143068. Fts3Cursor *pCsr;
  143069. int iCol; /* Column of table to populate aTerm for */
  143070. int iTerm;
  143071. sqlite3_int64 iDocid;
  143072. TermOffset *aTerm;
  143073. };
  143074. /*
  143075. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  143076. */
  143077. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  143078. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  143079. int nTerm; /* Number of tokens in phrase */
  143080. int iTerm; /* For looping through nTerm phrase terms */
  143081. char *pList; /* Pointer to position list for phrase */
  143082. int iPos = 0; /* First position in position-list */
  143083. int rc;
  143084. UNUSED_PARAMETER(iPhrase);
  143085. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  143086. nTerm = pExpr->pPhrase->nToken;
  143087. if( pList ){
  143088. fts3GetDeltaPosition(&pList, &iPos);
  143089. assert( iPos>=0 );
  143090. }
  143091. for(iTerm=0; iTerm<nTerm; iTerm++){
  143092. TermOffset *pT = &p->aTerm[p->iTerm++];
  143093. pT->iOff = nTerm-iTerm-1;
  143094. pT->pList = pList;
  143095. pT->iPos = iPos;
  143096. }
  143097. return rc;
  143098. }
  143099. /*
  143100. ** Implementation of offsets() function.
  143101. */
  143102. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  143103. sqlite3_context *pCtx, /* SQLite function call context */
  143104. Fts3Cursor *pCsr /* Cursor object */
  143105. ){
  143106. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143107. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  143108. int rc; /* Return Code */
  143109. int nToken; /* Number of tokens in query */
  143110. int iCol; /* Column currently being processed */
  143111. StrBuffer res = {0, 0, 0}; /* Result string */
  143112. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  143113. if( !pCsr->pExpr ){
  143114. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  143115. return;
  143116. }
  143117. memset(&sCtx, 0, sizeof(sCtx));
  143118. assert( pCsr->isRequireSeek==0 );
  143119. /* Count the number of terms in the query */
  143120. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  143121. if( rc!=SQLITE_OK ) goto offsets_out;
  143122. /* Allocate the array of TermOffset iterators. */
  143123. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  143124. if( 0==sCtx.aTerm ){
  143125. rc = SQLITE_NOMEM;
  143126. goto offsets_out;
  143127. }
  143128. sCtx.iDocid = pCsr->iPrevId;
  143129. sCtx.pCsr = pCsr;
  143130. /* Loop through the table columns, appending offset information to
  143131. ** string-buffer res for each column.
  143132. */
  143133. for(iCol=0; iCol<pTab->nColumn; iCol++){
  143134. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  143135. const char *ZDUMMY; /* Dummy argument used with xNext() */
  143136. int NDUMMY = 0; /* Dummy argument used with xNext() */
  143137. int iStart = 0;
  143138. int iEnd = 0;
  143139. int iCurrent = 0;
  143140. const char *zDoc;
  143141. int nDoc;
  143142. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  143143. ** no way that this operation can fail, so the return code from
  143144. ** fts3ExprIterate() can be discarded.
  143145. */
  143146. sCtx.iCol = iCol;
  143147. sCtx.iTerm = 0;
  143148. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  143149. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  143150. ** in column iCol, jump immediately to the next iteration of the loop.
  143151. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  143152. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  143153. ** to the caller.
  143154. */
  143155. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  143156. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  143157. if( zDoc==0 ){
  143158. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  143159. continue;
  143160. }
  143161. rc = SQLITE_NOMEM;
  143162. goto offsets_out;
  143163. }
  143164. /* Initialize a tokenizer iterator to iterate through column iCol. */
  143165. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  143166. zDoc, nDoc, &pC
  143167. );
  143168. if( rc!=SQLITE_OK ) goto offsets_out;
  143169. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  143170. while( rc==SQLITE_OK ){
  143171. int i; /* Used to loop through terms */
  143172. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  143173. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  143174. for(i=0; i<nToken; i++){
  143175. TermOffset *pT = &sCtx.aTerm[i];
  143176. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  143177. iMinPos = pT->iPos-pT->iOff;
  143178. pTerm = pT;
  143179. }
  143180. }
  143181. if( !pTerm ){
  143182. /* All offsets for this column have been gathered. */
  143183. rc = SQLITE_DONE;
  143184. }else{
  143185. assert( iCurrent<=iMinPos );
  143186. if( 0==(0xFE&*pTerm->pList) ){
  143187. pTerm->pList = 0;
  143188. }else{
  143189. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  143190. }
  143191. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  143192. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  143193. }
  143194. if( rc==SQLITE_OK ){
  143195. char aBuffer[64];
  143196. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  143197. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  143198. );
  143199. rc = fts3StringAppend(&res, aBuffer, -1);
  143200. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  143201. rc = FTS_CORRUPT_VTAB;
  143202. }
  143203. }
  143204. }
  143205. if( rc==SQLITE_DONE ){
  143206. rc = SQLITE_OK;
  143207. }
  143208. pMod->xClose(pC);
  143209. if( rc!=SQLITE_OK ) goto offsets_out;
  143210. }
  143211. offsets_out:
  143212. sqlite3_free(sCtx.aTerm);
  143213. assert( rc!=SQLITE_DONE );
  143214. sqlite3Fts3SegmentsClose(pTab);
  143215. if( rc!=SQLITE_OK ){
  143216. sqlite3_result_error_code(pCtx, rc);
  143217. sqlite3_free(res.z);
  143218. }else{
  143219. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  143220. }
  143221. return;
  143222. }
  143223. /*
  143224. ** Implementation of matchinfo() function.
  143225. */
  143226. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  143227. sqlite3_context *pContext, /* Function call context */
  143228. Fts3Cursor *pCsr, /* FTS3 table cursor */
  143229. const char *zArg /* Second arg to matchinfo() function */
  143230. ){
  143231. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143232. const char *zFormat;
  143233. if( zArg ){
  143234. zFormat = zArg;
  143235. }else{
  143236. zFormat = FTS3_MATCHINFO_DEFAULT;
  143237. }
  143238. if( !pCsr->pExpr ){
  143239. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  143240. return;
  143241. }else{
  143242. /* Retrieve matchinfo() data. */
  143243. fts3GetMatchinfo(pContext, pCsr, zFormat);
  143244. sqlite3Fts3SegmentsClose(pTab);
  143245. }
  143246. }
  143247. #endif
  143248. /************** End of fts3_snippet.c ****************************************/
  143249. /************** Begin file fts3_unicode.c ************************************/
  143250. /*
  143251. ** 2012 May 24
  143252. **
  143253. ** The author disclaims copyright to this source code. In place of
  143254. ** a legal notice, here is a blessing:
  143255. **
  143256. ** May you do good and not evil.
  143257. ** May you find forgiveness for yourself and forgive others.
  143258. ** May you share freely, never taking more than you give.
  143259. **
  143260. ******************************************************************************
  143261. **
  143262. ** Implementation of the "unicode" full-text-search tokenizer.
  143263. */
  143264. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  143265. /* #include "fts3Int.h" */
  143266. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  143267. /* #include <assert.h> */
  143268. /* #include <stdlib.h> */
  143269. /* #include <stdio.h> */
  143270. /* #include <string.h> */
  143271. /* #include "fts3_tokenizer.h" */
  143272. /*
  143273. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  143274. ** from the sqlite3 source file utf.c. If this file is compiled as part
  143275. ** of the amalgamation, they are not required.
  143276. */
  143277. #ifndef SQLITE_AMALGAMATION
  143278. static const unsigned char sqlite3Utf8Trans1[] = {
  143279. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  143280. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  143281. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  143282. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  143283. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  143284. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  143285. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  143286. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  143287. };
  143288. #define READ_UTF8(zIn, zTerm, c) \
  143289. c = *(zIn++); \
  143290. if( c>=0xc0 ){ \
  143291. c = sqlite3Utf8Trans1[c-0xc0]; \
  143292. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  143293. c = (c<<6) + (0x3f & *(zIn++)); \
  143294. } \
  143295. if( c<0x80 \
  143296. || (c&0xFFFFF800)==0xD800 \
  143297. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  143298. }
  143299. #define WRITE_UTF8(zOut, c) { \
  143300. if( c<0x00080 ){ \
  143301. *zOut++ = (u8)(c&0xFF); \
  143302. } \
  143303. else if( c<0x00800 ){ \
  143304. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  143305. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  143306. } \
  143307. else if( c<0x10000 ){ \
  143308. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  143309. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  143310. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  143311. }else{ \
  143312. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  143313. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  143314. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  143315. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  143316. } \
  143317. }
  143318. #endif /* ifndef SQLITE_AMALGAMATION */
  143319. typedef struct unicode_tokenizer unicode_tokenizer;
  143320. typedef struct unicode_cursor unicode_cursor;
  143321. struct unicode_tokenizer {
  143322. sqlite3_tokenizer base;
  143323. int bRemoveDiacritic;
  143324. int nException;
  143325. int *aiException;
  143326. };
  143327. struct unicode_cursor {
  143328. sqlite3_tokenizer_cursor base;
  143329. const unsigned char *aInput; /* Input text being tokenized */
  143330. int nInput; /* Size of aInput[] in bytes */
  143331. int iOff; /* Current offset within aInput[] */
  143332. int iToken; /* Index of next token to be returned */
  143333. char *zToken; /* storage for current token */
  143334. int nAlloc; /* space allocated at zToken */
  143335. };
  143336. /*
  143337. ** Destroy a tokenizer allocated by unicodeCreate().
  143338. */
  143339. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  143340. if( pTokenizer ){
  143341. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  143342. sqlite3_free(p->aiException);
  143343. sqlite3_free(p);
  143344. }
  143345. return SQLITE_OK;
  143346. }
  143347. /*
  143348. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  143349. ** statement has specified that the tokenizer for this table shall consider
  143350. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  143351. ** token characters (if bAlnum==1).
  143352. **
  143353. ** For each codepoint in the zIn/nIn string, this function checks if the
  143354. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  143355. ** If so, no action is taken. Otherwise, the codepoint is added to the
  143356. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  143357. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  143358. ** codepoints in the aiException[] array.
  143359. **
  143360. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  143361. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  143362. ** It is not possible to change the behavior of the tokenizer with respect
  143363. ** to these codepoints.
  143364. */
  143365. static int unicodeAddExceptions(
  143366. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  143367. int bAlnum, /* Replace Isalnum() return value with this */
  143368. const char *zIn, /* Array of characters to make exceptions */
  143369. int nIn /* Length of z in bytes */
  143370. ){
  143371. const unsigned char *z = (const unsigned char *)zIn;
  143372. const unsigned char *zTerm = &z[nIn];
  143373. int iCode;
  143374. int nEntry = 0;
  143375. assert( bAlnum==0 || bAlnum==1 );
  143376. while( z<zTerm ){
  143377. READ_UTF8(z, zTerm, iCode);
  143378. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  143379. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  143380. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  143381. ){
  143382. nEntry++;
  143383. }
  143384. }
  143385. if( nEntry ){
  143386. int *aNew; /* New aiException[] array */
  143387. int nNew; /* Number of valid entries in array aNew[] */
  143388. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  143389. if( aNew==0 ) return SQLITE_NOMEM;
  143390. nNew = p->nException;
  143391. z = (const unsigned char *)zIn;
  143392. while( z<zTerm ){
  143393. READ_UTF8(z, zTerm, iCode);
  143394. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  143395. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  143396. ){
  143397. int i, j;
  143398. for(i=0; i<nNew && aNew[i]<iCode; i++);
  143399. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  143400. aNew[i] = iCode;
  143401. nNew++;
  143402. }
  143403. }
  143404. p->aiException = aNew;
  143405. p->nException = nNew;
  143406. }
  143407. return SQLITE_OK;
  143408. }
  143409. /*
  143410. ** Return true if the p->aiException[] array contains the value iCode.
  143411. */
  143412. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  143413. if( p->nException>0 ){
  143414. int *a = p->aiException;
  143415. int iLo = 0;
  143416. int iHi = p->nException-1;
  143417. while( iHi>=iLo ){
  143418. int iTest = (iHi + iLo) / 2;
  143419. if( iCode==a[iTest] ){
  143420. return 1;
  143421. }else if( iCode>a[iTest] ){
  143422. iLo = iTest+1;
  143423. }else{
  143424. iHi = iTest-1;
  143425. }
  143426. }
  143427. }
  143428. return 0;
  143429. }
  143430. /*
  143431. ** Return true if, for the purposes of tokenization, codepoint iCode is
  143432. ** considered a token character (not a separator).
  143433. */
  143434. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  143435. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  143436. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  143437. }
  143438. /*
  143439. ** Create a new tokenizer instance.
  143440. */
  143441. static int unicodeCreate(
  143442. int nArg, /* Size of array argv[] */
  143443. const char * const *azArg, /* Tokenizer creation arguments */
  143444. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  143445. ){
  143446. unicode_tokenizer *pNew; /* New tokenizer object */
  143447. int i;
  143448. int rc = SQLITE_OK;
  143449. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  143450. if( pNew==NULL ) return SQLITE_NOMEM;
  143451. memset(pNew, 0, sizeof(unicode_tokenizer));
  143452. pNew->bRemoveDiacritic = 1;
  143453. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  143454. const char *z = azArg[i];
  143455. int n = (int)strlen(z);
  143456. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  143457. pNew->bRemoveDiacritic = 1;
  143458. }
  143459. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  143460. pNew->bRemoveDiacritic = 0;
  143461. }
  143462. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  143463. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  143464. }
  143465. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  143466. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  143467. }
  143468. else{
  143469. /* Unrecognized argument */
  143470. rc = SQLITE_ERROR;
  143471. }
  143472. }
  143473. if( rc!=SQLITE_OK ){
  143474. unicodeDestroy((sqlite3_tokenizer *)pNew);
  143475. pNew = 0;
  143476. }
  143477. *pp = (sqlite3_tokenizer *)pNew;
  143478. return rc;
  143479. }
  143480. /*
  143481. ** Prepare to begin tokenizing a particular string. The input
  143482. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  143483. ** used to incrementally tokenize this string is returned in
  143484. ** *ppCursor.
  143485. */
  143486. static int unicodeOpen(
  143487. sqlite3_tokenizer *p, /* The tokenizer */
  143488. const char *aInput, /* Input string */
  143489. int nInput, /* Size of string aInput in bytes */
  143490. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  143491. ){
  143492. unicode_cursor *pCsr;
  143493. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  143494. if( pCsr==0 ){
  143495. return SQLITE_NOMEM;
  143496. }
  143497. memset(pCsr, 0, sizeof(unicode_cursor));
  143498. pCsr->aInput = (const unsigned char *)aInput;
  143499. if( aInput==0 ){
  143500. pCsr->nInput = 0;
  143501. }else if( nInput<0 ){
  143502. pCsr->nInput = (int)strlen(aInput);
  143503. }else{
  143504. pCsr->nInput = nInput;
  143505. }
  143506. *pp = &pCsr->base;
  143507. UNUSED_PARAMETER(p);
  143508. return SQLITE_OK;
  143509. }
  143510. /*
  143511. ** Close a tokenization cursor previously opened by a call to
  143512. ** simpleOpen() above.
  143513. */
  143514. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  143515. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  143516. sqlite3_free(pCsr->zToken);
  143517. sqlite3_free(pCsr);
  143518. return SQLITE_OK;
  143519. }
  143520. /*
  143521. ** Extract the next token from a tokenization cursor. The cursor must
  143522. ** have been opened by a prior call to simpleOpen().
  143523. */
  143524. static int unicodeNext(
  143525. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  143526. const char **paToken, /* OUT: Token text */
  143527. int *pnToken, /* OUT: Number of bytes at *paToken */
  143528. int *piStart, /* OUT: Starting offset of token */
  143529. int *piEnd, /* OUT: Ending offset of token */
  143530. int *piPos /* OUT: Position integer of token */
  143531. ){
  143532. unicode_cursor *pCsr = (unicode_cursor *)pC;
  143533. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  143534. int iCode = 0;
  143535. char *zOut;
  143536. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  143537. const unsigned char *zStart = z;
  143538. const unsigned char *zEnd;
  143539. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  143540. /* Scan past any delimiter characters before the start of the next token.
  143541. ** Return SQLITE_DONE early if this takes us all the way to the end of
  143542. ** the input. */
  143543. while( z<zTerm ){
  143544. READ_UTF8(z, zTerm, iCode);
  143545. if( unicodeIsAlnum(p, iCode) ) break;
  143546. zStart = z;
  143547. }
  143548. if( zStart>=zTerm ) return SQLITE_DONE;
  143549. zOut = pCsr->zToken;
  143550. do {
  143551. int iOut;
  143552. /* Grow the output buffer if required. */
  143553. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  143554. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  143555. if( !zNew ) return SQLITE_NOMEM;
  143556. zOut = &zNew[zOut - pCsr->zToken];
  143557. pCsr->zToken = zNew;
  143558. pCsr->nAlloc += 64;
  143559. }
  143560. /* Write the folded case of the last character read to the output */
  143561. zEnd = z;
  143562. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  143563. if( iOut ){
  143564. WRITE_UTF8(zOut, iOut);
  143565. }
  143566. /* If the cursor is not at EOF, read the next character */
  143567. if( z>=zTerm ) break;
  143568. READ_UTF8(z, zTerm, iCode);
  143569. }while( unicodeIsAlnum(p, iCode)
  143570. || sqlite3FtsUnicodeIsdiacritic(iCode)
  143571. );
  143572. /* Set the output variables and return. */
  143573. pCsr->iOff = (int)(z - pCsr->aInput);
  143574. *paToken = pCsr->zToken;
  143575. *pnToken = (int)(zOut - pCsr->zToken);
  143576. *piStart = (int)(zStart - pCsr->aInput);
  143577. *piEnd = (int)(zEnd - pCsr->aInput);
  143578. *piPos = pCsr->iToken++;
  143579. return SQLITE_OK;
  143580. }
  143581. /*
  143582. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  143583. ** structure for the unicode tokenizer.
  143584. */
  143585. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  143586. static const sqlite3_tokenizer_module module = {
  143587. 0,
  143588. unicodeCreate,
  143589. unicodeDestroy,
  143590. unicodeOpen,
  143591. unicodeClose,
  143592. unicodeNext,
  143593. 0,
  143594. };
  143595. *ppModule = &module;
  143596. }
  143597. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  143598. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  143599. /************** End of fts3_unicode.c ****************************************/
  143600. /************** Begin file fts3_unicode2.c ***********************************/
  143601. /*
  143602. ** 2012 May 25
  143603. **
  143604. ** The author disclaims copyright to this source code. In place of
  143605. ** a legal notice, here is a blessing:
  143606. **
  143607. ** May you do good and not evil.
  143608. ** May you find forgiveness for yourself and forgive others.
  143609. ** May you share freely, never taking more than you give.
  143610. **
  143611. ******************************************************************************
  143612. */
  143613. /*
  143614. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  143615. */
  143616. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  143617. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  143618. /* #include <assert.h> */
  143619. /*
  143620. ** Return true if the argument corresponds to a unicode codepoint
  143621. ** classified as either a letter or a number. Otherwise false.
  143622. **
  143623. ** The results are undefined if the value passed to this function
  143624. ** is less than zero.
  143625. */
  143626. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  143627. /* Each unsigned integer in the following array corresponds to a contiguous
  143628. ** range of unicode codepoints that are not either letters or numbers (i.e.
  143629. ** codepoints for which this function should return 0).
  143630. **
  143631. ** The most significant 22 bits in each 32-bit value contain the first
  143632. ** codepoint in the range. The least significant 10 bits are used to store
  143633. ** the size of the range (always at least 1). In other words, the value
  143634. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  143635. ** C. It is not possible to represent a range larger than 1023 codepoints
  143636. ** using this format.
  143637. */
  143638. static const unsigned int aEntry[] = {
  143639. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  143640. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  143641. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  143642. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  143643. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  143644. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  143645. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  143646. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  143647. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  143648. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  143649. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  143650. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  143651. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  143652. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  143653. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  143654. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  143655. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  143656. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  143657. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  143658. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  143659. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  143660. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  143661. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  143662. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  143663. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  143664. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  143665. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  143666. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  143667. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  143668. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  143669. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  143670. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  143671. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  143672. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  143673. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  143674. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  143675. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  143676. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  143677. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  143678. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  143679. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  143680. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  143681. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  143682. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  143683. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  143684. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  143685. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  143686. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  143687. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  143688. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  143689. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  143690. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  143691. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  143692. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  143693. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  143694. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  143695. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  143696. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  143697. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  143698. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  143699. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  143700. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  143701. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  143702. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  143703. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  143704. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  143705. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  143706. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  143707. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  143708. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  143709. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  143710. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  143711. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  143712. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  143713. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  143714. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  143715. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  143716. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  143717. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  143718. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  143719. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  143720. 0x380400F0,
  143721. };
  143722. static const unsigned int aAscii[4] = {
  143723. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  143724. };
  143725. if( c<128 ){
  143726. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  143727. }else if( c<(1<<22) ){
  143728. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  143729. int iRes = 0;
  143730. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  143731. int iLo = 0;
  143732. while( iHi>=iLo ){
  143733. int iTest = (iHi + iLo) / 2;
  143734. if( key >= aEntry[iTest] ){
  143735. iRes = iTest;
  143736. iLo = iTest+1;
  143737. }else{
  143738. iHi = iTest-1;
  143739. }
  143740. }
  143741. assert( aEntry[0]<key );
  143742. assert( key>=aEntry[iRes] );
  143743. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  143744. }
  143745. return 1;
  143746. }
  143747. /*
  143748. ** If the argument is a codepoint corresponding to a lowercase letter
  143749. ** in the ASCII range with a diacritic added, return the codepoint
  143750. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  143751. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  143752. ** E"). The resuls of passing a codepoint that corresponds to an
  143753. ** uppercase letter are undefined.
  143754. */
  143755. static int remove_diacritic(int c){
  143756. unsigned short aDia[] = {
  143757. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  143758. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  143759. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  143760. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  143761. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  143762. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  143763. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  143764. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  143765. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  143766. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  143767. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  143768. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  143769. 62924, 63050, 63082, 63274, 63390,
  143770. };
  143771. char aChar[] = {
  143772. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  143773. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  143774. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  143775. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  143776. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  143777. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  143778. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  143779. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  143780. 'e', 'i', 'o', 'u', 'y',
  143781. };
  143782. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  143783. int iRes = 0;
  143784. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  143785. int iLo = 0;
  143786. while( iHi>=iLo ){
  143787. int iTest = (iHi + iLo) / 2;
  143788. if( key >= aDia[iTest] ){
  143789. iRes = iTest;
  143790. iLo = iTest+1;
  143791. }else{
  143792. iHi = iTest-1;
  143793. }
  143794. }
  143795. assert( key>=aDia[iRes] );
  143796. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  143797. }
  143798. /*
  143799. ** Return true if the argument interpreted as a unicode codepoint
  143800. ** is a diacritical modifier character.
  143801. */
  143802. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  143803. unsigned int mask0 = 0x08029FDF;
  143804. unsigned int mask1 = 0x000361F8;
  143805. if( c<768 || c>817 ) return 0;
  143806. return (c < 768+32) ?
  143807. (mask0 & (1 << (c-768))) :
  143808. (mask1 & (1 << (c-768-32)));
  143809. }
  143810. /*
  143811. ** Interpret the argument as a unicode codepoint. If the codepoint
  143812. ** is an upper case character that has a lower case equivalent,
  143813. ** return the codepoint corresponding to the lower case version.
  143814. ** Otherwise, return a copy of the argument.
  143815. **
  143816. ** The results are undefined if the value passed to this function
  143817. ** is less than zero.
  143818. */
  143819. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  143820. /* Each entry in the following array defines a rule for folding a range
  143821. ** of codepoints to lower case. The rule applies to a range of nRange
  143822. ** codepoints starting at codepoint iCode.
  143823. **
  143824. ** If the least significant bit in flags is clear, then the rule applies
  143825. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  143826. ** need to be folded). Or, if it is set, then the rule only applies to
  143827. ** every second codepoint in the range, starting with codepoint C.
  143828. **
  143829. ** The 7 most significant bits in flags are an index into the aiOff[]
  143830. ** array. If a specific codepoint C does require folding, then its lower
  143831. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  143832. **
  143833. ** The contents of this array are generated by parsing the CaseFolding.txt
  143834. ** file distributed as part of the "Unicode Character Database". See
  143835. ** http://www.unicode.org for details.
  143836. */
  143837. static const struct TableEntry {
  143838. unsigned short iCode;
  143839. unsigned char flags;
  143840. unsigned char nRange;
  143841. } aEntry[] = {
  143842. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  143843. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  143844. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  143845. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  143846. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  143847. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  143848. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  143849. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  143850. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  143851. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  143852. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  143853. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  143854. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  143855. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  143856. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  143857. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  143858. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  143859. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  143860. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  143861. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  143862. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  143863. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  143864. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  143865. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  143866. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  143867. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  143868. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  143869. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  143870. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  143871. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  143872. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  143873. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  143874. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  143875. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  143876. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  143877. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  143878. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  143879. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  143880. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  143881. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  143882. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  143883. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  143884. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  143885. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  143886. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  143887. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  143888. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  143889. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  143890. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  143891. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  143892. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  143893. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  143894. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  143895. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  143896. {65313, 14, 26},
  143897. };
  143898. static const unsigned short aiOff[] = {
  143899. 1, 2, 8, 15, 16, 26, 28, 32,
  143900. 37, 38, 40, 48, 63, 64, 69, 71,
  143901. 79, 80, 116, 202, 203, 205, 206, 207,
  143902. 209, 210, 211, 213, 214, 217, 218, 219,
  143903. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  143904. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  143905. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  143906. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  143907. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  143908. 65514, 65521, 65527, 65528, 65529,
  143909. };
  143910. int ret = c;
  143911. assert( c>=0 );
  143912. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  143913. if( c<128 ){
  143914. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  143915. }else if( c<65536 ){
  143916. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  143917. int iLo = 0;
  143918. int iRes = -1;
  143919. while( iHi>=iLo ){
  143920. int iTest = (iHi + iLo) / 2;
  143921. int cmp = (c - aEntry[iTest].iCode);
  143922. if( cmp>=0 ){
  143923. iRes = iTest;
  143924. iLo = iTest+1;
  143925. }else{
  143926. iHi = iTest-1;
  143927. }
  143928. }
  143929. assert( iRes<0 || c>=aEntry[iRes].iCode );
  143930. if( iRes>=0 ){
  143931. const struct TableEntry *p = &aEntry[iRes];
  143932. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  143933. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  143934. assert( ret>0 );
  143935. }
  143936. }
  143937. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  143938. }
  143939. else if( c>=66560 && c<66600 ){
  143940. ret = c + 40;
  143941. }
  143942. return ret;
  143943. }
  143944. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  143945. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  143946. /************** End of fts3_unicode2.c ***************************************/
  143947. /************** Begin file rtree.c *******************************************/
  143948. /*
  143949. ** 2001 September 15
  143950. **
  143951. ** The author disclaims copyright to this source code. In place of
  143952. ** a legal notice, here is a blessing:
  143953. **
  143954. ** May you do good and not evil.
  143955. ** May you find forgiveness for yourself and forgive others.
  143956. ** May you share freely, never taking more than you give.
  143957. **
  143958. *************************************************************************
  143959. ** This file contains code for implementations of the r-tree and r*-tree
  143960. ** algorithms packaged as an SQLite virtual table module.
  143961. */
  143962. /*
  143963. ** Database Format of R-Tree Tables
  143964. ** --------------------------------
  143965. **
  143966. ** The data structure for a single virtual r-tree table is stored in three
  143967. ** native SQLite tables declared as follows. In each case, the '%' character
  143968. ** in the table name is replaced with the user-supplied name of the r-tree
  143969. ** table.
  143970. **
  143971. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  143972. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  143973. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  143974. **
  143975. ** The data for each node of the r-tree structure is stored in the %_node
  143976. ** table. For each node that is not the root node of the r-tree, there is
  143977. ** an entry in the %_parent table associating the node with its parent.
  143978. ** And for each row of data in the table, there is an entry in the %_rowid
  143979. ** table that maps from the entries rowid to the id of the node that it
  143980. ** is stored on.
  143981. **
  143982. ** The root node of an r-tree always exists, even if the r-tree table is
  143983. ** empty. The nodeno of the root node is always 1. All other nodes in the
  143984. ** table must be the same size as the root node. The content of each node
  143985. ** is formatted as follows:
  143986. **
  143987. ** 1. If the node is the root node (node 1), then the first 2 bytes
  143988. ** of the node contain the tree depth as a big-endian integer.
  143989. ** For non-root nodes, the first 2 bytes are left unused.
  143990. **
  143991. ** 2. The next 2 bytes contain the number of entries currently
  143992. ** stored in the node.
  143993. **
  143994. ** 3. The remainder of the node contains the node entries. Each entry
  143995. ** consists of a single 8-byte integer followed by an even number
  143996. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  143997. ** of a record. For internal nodes it is the node number of a
  143998. ** child page.
  143999. */
  144000. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  144001. #ifndef SQLITE_CORE
  144002. /* #include "sqlite3ext.h" */
  144003. SQLITE_EXTENSION_INIT1
  144004. #else
  144005. /* #include "sqlite3.h" */
  144006. #endif
  144007. /* #include <string.h> */
  144008. /* #include <assert.h> */
  144009. /* #include <stdio.h> */
  144010. #ifndef SQLITE_AMALGAMATION
  144011. #include "sqlite3rtree.h"
  144012. typedef sqlite3_int64 i64;
  144013. typedef unsigned char u8;
  144014. typedef unsigned short u16;
  144015. typedef unsigned int u32;
  144016. #endif
  144017. /* The following macro is used to suppress compiler warnings.
  144018. */
  144019. #ifndef UNUSED_PARAMETER
  144020. # define UNUSED_PARAMETER(x) (void)(x)
  144021. #endif
  144022. typedef struct Rtree Rtree;
  144023. typedef struct RtreeCursor RtreeCursor;
  144024. typedef struct RtreeNode RtreeNode;
  144025. typedef struct RtreeCell RtreeCell;
  144026. typedef struct RtreeConstraint RtreeConstraint;
  144027. typedef struct RtreeMatchArg RtreeMatchArg;
  144028. typedef struct RtreeGeomCallback RtreeGeomCallback;
  144029. typedef union RtreeCoord RtreeCoord;
  144030. typedef struct RtreeSearchPoint RtreeSearchPoint;
  144031. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  144032. #define RTREE_MAX_DIMENSIONS 5
  144033. /* Size of hash table Rtree.aHash. This hash table is not expected to
  144034. ** ever contain very many entries, so a fixed number of buckets is
  144035. ** used.
  144036. */
  144037. #define HASHSIZE 97
  144038. /* The xBestIndex method of this virtual table requires an estimate of
  144039. ** the number of rows in the virtual table to calculate the costs of
  144040. ** various strategies. If possible, this estimate is loaded from the
  144041. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  144042. ** Otherwise, if no sqlite_stat1 entry is available, use
  144043. ** RTREE_DEFAULT_ROWEST.
  144044. */
  144045. #define RTREE_DEFAULT_ROWEST 1048576
  144046. #define RTREE_MIN_ROWEST 100
  144047. /*
  144048. ** An rtree virtual-table object.
  144049. */
  144050. struct Rtree {
  144051. sqlite3_vtab base; /* Base class. Must be first */
  144052. sqlite3 *db; /* Host database connection */
  144053. int iNodeSize; /* Size in bytes of each node in the node table */
  144054. u8 nDim; /* Number of dimensions */
  144055. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  144056. u8 nBytesPerCell; /* Bytes consumed per cell */
  144057. int iDepth; /* Current depth of the r-tree structure */
  144058. char *zDb; /* Name of database containing r-tree table */
  144059. char *zName; /* Name of r-tree table */
  144060. int nBusy; /* Current number of users of this structure */
  144061. i64 nRowEst; /* Estimated number of rows in this table */
  144062. /* List of nodes removed during a CondenseTree operation. List is
  144063. ** linked together via the pointer normally used for hash chains -
  144064. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  144065. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  144066. */
  144067. RtreeNode *pDeleted;
  144068. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  144069. /* Statements to read/write/delete a record from xxx_node */
  144070. sqlite3_stmt *pReadNode;
  144071. sqlite3_stmt *pWriteNode;
  144072. sqlite3_stmt *pDeleteNode;
  144073. /* Statements to read/write/delete a record from xxx_rowid */
  144074. sqlite3_stmt *pReadRowid;
  144075. sqlite3_stmt *pWriteRowid;
  144076. sqlite3_stmt *pDeleteRowid;
  144077. /* Statements to read/write/delete a record from xxx_parent */
  144078. sqlite3_stmt *pReadParent;
  144079. sqlite3_stmt *pWriteParent;
  144080. sqlite3_stmt *pDeleteParent;
  144081. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  144082. };
  144083. /* Possible values for Rtree.eCoordType: */
  144084. #define RTREE_COORD_REAL32 0
  144085. #define RTREE_COORD_INT32 1
  144086. /*
  144087. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  144088. ** only deal with integer coordinates. No floating point operations
  144089. ** will be done.
  144090. */
  144091. #ifdef SQLITE_RTREE_INT_ONLY
  144092. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  144093. typedef int RtreeValue; /* Low accuracy coordinate */
  144094. # define RTREE_ZERO 0
  144095. #else
  144096. typedef double RtreeDValue; /* High accuracy coordinate */
  144097. typedef float RtreeValue; /* Low accuracy coordinate */
  144098. # define RTREE_ZERO 0.0
  144099. #endif
  144100. /*
  144101. ** When doing a search of an r-tree, instances of the following structure
  144102. ** record intermediate results from the tree walk.
  144103. **
  144104. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  144105. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  144106. ** the id is of the parent node and the cell that RtreeSearchPoint
  144107. ** represents is the iCell-th entry in the parent node.
  144108. */
  144109. struct RtreeSearchPoint {
  144110. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  144111. sqlite3_int64 id; /* Node ID */
  144112. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  144113. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  144114. u8 iCell; /* Cell index within the node */
  144115. };
  144116. /*
  144117. ** The minimum number of cells allowed for a node is a third of the
  144118. ** maximum. In Gutman's notation:
  144119. **
  144120. ** m = M/3
  144121. **
  144122. ** If an R*-tree "Reinsert" operation is required, the same number of
  144123. ** cells are removed from the overfull node and reinserted into the tree.
  144124. */
  144125. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  144126. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  144127. #define RTREE_MAXCELLS 51
  144128. /*
  144129. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  144130. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  144131. ** Therefore all non-root nodes must contain at least 3 entries. Since
  144132. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  144133. ** 40 or less.
  144134. */
  144135. #define RTREE_MAX_DEPTH 40
  144136. /*
  144137. ** Number of entries in the cursor RtreeNode cache. The first entry is
  144138. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  144139. ** entries cache the RtreeNode for the first elements of the priority queue.
  144140. */
  144141. #define RTREE_CACHE_SZ 5
  144142. /*
  144143. ** An rtree cursor object.
  144144. */
  144145. struct RtreeCursor {
  144146. sqlite3_vtab_cursor base; /* Base class. Must be first */
  144147. u8 atEOF; /* True if at end of search */
  144148. u8 bPoint; /* True if sPoint is valid */
  144149. int iStrategy; /* Copy of idxNum search parameter */
  144150. int nConstraint; /* Number of entries in aConstraint */
  144151. RtreeConstraint *aConstraint; /* Search constraints. */
  144152. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  144153. int nPoint; /* Number of slots used in aPoint[] */
  144154. int mxLevel; /* iLevel value for root of the tree */
  144155. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  144156. RtreeSearchPoint sPoint; /* Cached next search point */
  144157. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  144158. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  144159. };
  144160. /* Return the Rtree of a RtreeCursor */
  144161. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  144162. /*
  144163. ** A coordinate can be either a floating point number or a integer. All
  144164. ** coordinates within a single R-Tree are always of the same time.
  144165. */
  144166. union RtreeCoord {
  144167. RtreeValue f; /* Floating point value */
  144168. int i; /* Integer value */
  144169. u32 u; /* Unsigned for byte-order conversions */
  144170. };
  144171. /*
  144172. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  144173. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  144174. ** variable pRtree points to the Rtree structure associated with the
  144175. ** RtreeCoord.
  144176. */
  144177. #ifdef SQLITE_RTREE_INT_ONLY
  144178. # define DCOORD(coord) ((RtreeDValue)coord.i)
  144179. #else
  144180. # define DCOORD(coord) ( \
  144181. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  144182. ((double)coord.f) : \
  144183. ((double)coord.i) \
  144184. )
  144185. #endif
  144186. /*
  144187. ** A search constraint.
  144188. */
  144189. struct RtreeConstraint {
  144190. int iCoord; /* Index of constrained coordinate */
  144191. int op; /* Constraining operation */
  144192. union {
  144193. RtreeDValue rValue; /* Constraint value. */
  144194. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  144195. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  144196. } u;
  144197. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  144198. };
  144199. /* Possible values for RtreeConstraint.op */
  144200. #define RTREE_EQ 0x41 /* A */
  144201. #define RTREE_LE 0x42 /* B */
  144202. #define RTREE_LT 0x43 /* C */
  144203. #define RTREE_GE 0x44 /* D */
  144204. #define RTREE_GT 0x45 /* E */
  144205. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  144206. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  144207. /*
  144208. ** An rtree structure node.
  144209. */
  144210. struct RtreeNode {
  144211. RtreeNode *pParent; /* Parent node */
  144212. i64 iNode; /* The node number */
  144213. int nRef; /* Number of references to this node */
  144214. int isDirty; /* True if the node needs to be written to disk */
  144215. u8 *zData; /* Content of the node, as should be on disk */
  144216. RtreeNode *pNext; /* Next node in this hash collision chain */
  144217. };
  144218. /* Return the number of cells in a node */
  144219. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  144220. /*
  144221. ** A single cell from a node, deserialized
  144222. */
  144223. struct RtreeCell {
  144224. i64 iRowid; /* Node or entry ID */
  144225. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  144226. };
  144227. /*
  144228. ** This object becomes the sqlite3_user_data() for the SQL functions
  144229. ** that are created by sqlite3_rtree_geometry_callback() and
  144230. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  144231. ** operators in order to constrain a search.
  144232. **
  144233. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  144234. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  144235. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  144236. ** sqlite3_rtree_query_callback().
  144237. **
  144238. ** This object is deleted automatically by the destructor mechanism in
  144239. ** sqlite3_create_function_v2().
  144240. */
  144241. struct RtreeGeomCallback {
  144242. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  144243. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  144244. void (*xDestructor)(void*);
  144245. void *pContext;
  144246. };
  144247. /*
  144248. ** Value for the first field of every RtreeMatchArg object. The MATCH
  144249. ** operator tests that the first field of a blob operand matches this
  144250. ** value to avoid operating on invalid blobs (which could cause a segfault).
  144251. */
  144252. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  144253. /*
  144254. ** An instance of this structure (in the form of a BLOB) is returned by
  144255. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  144256. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  144257. ** operand to the MATCH operator of an R-Tree.
  144258. */
  144259. struct RtreeMatchArg {
  144260. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  144261. RtreeGeomCallback cb; /* Info about the callback functions */
  144262. int nParam; /* Number of parameters to the SQL function */
  144263. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  144264. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  144265. };
  144266. #ifndef MAX
  144267. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  144268. #endif
  144269. #ifndef MIN
  144270. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  144271. #endif
  144272. /*
  144273. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  144274. ** 64 bit integer. The deserialized value is returned.
  144275. */
  144276. static int readInt16(u8 *p){
  144277. return (p[0]<<8) + p[1];
  144278. }
  144279. static void readCoord(u8 *p, RtreeCoord *pCoord){
  144280. pCoord->u = (
  144281. (((u32)p[0]) << 24) +
  144282. (((u32)p[1]) << 16) +
  144283. (((u32)p[2]) << 8) +
  144284. (((u32)p[3]) << 0)
  144285. );
  144286. }
  144287. static i64 readInt64(u8 *p){
  144288. return (
  144289. (((i64)p[0]) << 56) +
  144290. (((i64)p[1]) << 48) +
  144291. (((i64)p[2]) << 40) +
  144292. (((i64)p[3]) << 32) +
  144293. (((i64)p[4]) << 24) +
  144294. (((i64)p[5]) << 16) +
  144295. (((i64)p[6]) << 8) +
  144296. (((i64)p[7]) << 0)
  144297. );
  144298. }
  144299. /*
  144300. ** Functions to serialize a 16 bit integer, 32 bit real number and
  144301. ** 64 bit integer. The value returned is the number of bytes written
  144302. ** to the argument buffer (always 2, 4 and 8 respectively).
  144303. */
  144304. static int writeInt16(u8 *p, int i){
  144305. p[0] = (i>> 8)&0xFF;
  144306. p[1] = (i>> 0)&0xFF;
  144307. return 2;
  144308. }
  144309. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  144310. u32 i;
  144311. assert( sizeof(RtreeCoord)==4 );
  144312. assert( sizeof(u32)==4 );
  144313. i = pCoord->u;
  144314. p[0] = (i>>24)&0xFF;
  144315. p[1] = (i>>16)&0xFF;
  144316. p[2] = (i>> 8)&0xFF;
  144317. p[3] = (i>> 0)&0xFF;
  144318. return 4;
  144319. }
  144320. static int writeInt64(u8 *p, i64 i){
  144321. p[0] = (i>>56)&0xFF;
  144322. p[1] = (i>>48)&0xFF;
  144323. p[2] = (i>>40)&0xFF;
  144324. p[3] = (i>>32)&0xFF;
  144325. p[4] = (i>>24)&0xFF;
  144326. p[5] = (i>>16)&0xFF;
  144327. p[6] = (i>> 8)&0xFF;
  144328. p[7] = (i>> 0)&0xFF;
  144329. return 8;
  144330. }
  144331. /*
  144332. ** Increment the reference count of node p.
  144333. */
  144334. static void nodeReference(RtreeNode *p){
  144335. if( p ){
  144336. p->nRef++;
  144337. }
  144338. }
  144339. /*
  144340. ** Clear the content of node p (set all bytes to 0x00).
  144341. */
  144342. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  144343. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  144344. p->isDirty = 1;
  144345. }
  144346. /*
  144347. ** Given a node number iNode, return the corresponding key to use
  144348. ** in the Rtree.aHash table.
  144349. */
  144350. static int nodeHash(i64 iNode){
  144351. return iNode % HASHSIZE;
  144352. }
  144353. /*
  144354. ** Search the node hash table for node iNode. If found, return a pointer
  144355. ** to it. Otherwise, return 0.
  144356. */
  144357. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  144358. RtreeNode *p;
  144359. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  144360. return p;
  144361. }
  144362. /*
  144363. ** Add node pNode to the node hash table.
  144364. */
  144365. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  144366. int iHash;
  144367. assert( pNode->pNext==0 );
  144368. iHash = nodeHash(pNode->iNode);
  144369. pNode->pNext = pRtree->aHash[iHash];
  144370. pRtree->aHash[iHash] = pNode;
  144371. }
  144372. /*
  144373. ** Remove node pNode from the node hash table.
  144374. */
  144375. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  144376. RtreeNode **pp;
  144377. if( pNode->iNode!=0 ){
  144378. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  144379. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  144380. *pp = pNode->pNext;
  144381. pNode->pNext = 0;
  144382. }
  144383. }
  144384. /*
  144385. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  144386. ** indicating that node has not yet been assigned a node number. It is
  144387. ** assigned a node number when nodeWrite() is called to write the
  144388. ** node contents out to the database.
  144389. */
  144390. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  144391. RtreeNode *pNode;
  144392. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  144393. if( pNode ){
  144394. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  144395. pNode->zData = (u8 *)&pNode[1];
  144396. pNode->nRef = 1;
  144397. pNode->pParent = pParent;
  144398. pNode->isDirty = 1;
  144399. nodeReference(pParent);
  144400. }
  144401. return pNode;
  144402. }
  144403. /*
  144404. ** Obtain a reference to an r-tree node.
  144405. */
  144406. static int nodeAcquire(
  144407. Rtree *pRtree, /* R-tree structure */
  144408. i64 iNode, /* Node number to load */
  144409. RtreeNode *pParent, /* Either the parent node or NULL */
  144410. RtreeNode **ppNode /* OUT: Acquired node */
  144411. ){
  144412. int rc;
  144413. int rc2 = SQLITE_OK;
  144414. RtreeNode *pNode;
  144415. /* Check if the requested node is already in the hash table. If so,
  144416. ** increase its reference count and return it.
  144417. */
  144418. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  144419. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  144420. if( pParent && !pNode->pParent ){
  144421. nodeReference(pParent);
  144422. pNode->pParent = pParent;
  144423. }
  144424. pNode->nRef++;
  144425. *ppNode = pNode;
  144426. return SQLITE_OK;
  144427. }
  144428. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  144429. rc = sqlite3_step(pRtree->pReadNode);
  144430. if( rc==SQLITE_ROW ){
  144431. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  144432. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  144433. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  144434. if( !pNode ){
  144435. rc2 = SQLITE_NOMEM;
  144436. }else{
  144437. pNode->pParent = pParent;
  144438. pNode->zData = (u8 *)&pNode[1];
  144439. pNode->nRef = 1;
  144440. pNode->iNode = iNode;
  144441. pNode->isDirty = 0;
  144442. pNode->pNext = 0;
  144443. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  144444. nodeReference(pParent);
  144445. }
  144446. }
  144447. }
  144448. rc = sqlite3_reset(pRtree->pReadNode);
  144449. if( rc==SQLITE_OK ) rc = rc2;
  144450. /* If the root node was just loaded, set pRtree->iDepth to the height
  144451. ** of the r-tree structure. A height of zero means all data is stored on
  144452. ** the root node. A height of one means the children of the root node
  144453. ** are the leaves, and so on. If the depth as specified on the root node
  144454. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  144455. */
  144456. if( pNode && iNode==1 ){
  144457. pRtree->iDepth = readInt16(pNode->zData);
  144458. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  144459. rc = SQLITE_CORRUPT_VTAB;
  144460. }
  144461. }
  144462. /* If no error has occurred so far, check if the "number of entries"
  144463. ** field on the node is too large. If so, set the return code to
  144464. ** SQLITE_CORRUPT_VTAB.
  144465. */
  144466. if( pNode && rc==SQLITE_OK ){
  144467. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  144468. rc = SQLITE_CORRUPT_VTAB;
  144469. }
  144470. }
  144471. if( rc==SQLITE_OK ){
  144472. if( pNode!=0 ){
  144473. nodeHashInsert(pRtree, pNode);
  144474. }else{
  144475. rc = SQLITE_CORRUPT_VTAB;
  144476. }
  144477. *ppNode = pNode;
  144478. }else{
  144479. sqlite3_free(pNode);
  144480. *ppNode = 0;
  144481. }
  144482. return rc;
  144483. }
  144484. /*
  144485. ** Overwrite cell iCell of node pNode with the contents of pCell.
  144486. */
  144487. static void nodeOverwriteCell(
  144488. Rtree *pRtree, /* The overall R-Tree */
  144489. RtreeNode *pNode, /* The node into which the cell is to be written */
  144490. RtreeCell *pCell, /* The cell to write */
  144491. int iCell /* Index into pNode into which pCell is written */
  144492. ){
  144493. int ii;
  144494. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  144495. p += writeInt64(p, pCell->iRowid);
  144496. for(ii=0; ii<(pRtree->nDim*2); ii++){
  144497. p += writeCoord(p, &pCell->aCoord[ii]);
  144498. }
  144499. pNode->isDirty = 1;
  144500. }
  144501. /*
  144502. ** Remove the cell with index iCell from node pNode.
  144503. */
  144504. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  144505. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  144506. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  144507. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  144508. memmove(pDst, pSrc, nByte);
  144509. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  144510. pNode->isDirty = 1;
  144511. }
  144512. /*
  144513. ** Insert the contents of cell pCell into node pNode. If the insert
  144514. ** is successful, return SQLITE_OK.
  144515. **
  144516. ** If there is not enough free space in pNode, return SQLITE_FULL.
  144517. */
  144518. static int nodeInsertCell(
  144519. Rtree *pRtree, /* The overall R-Tree */
  144520. RtreeNode *pNode, /* Write new cell into this node */
  144521. RtreeCell *pCell /* The cell to be inserted */
  144522. ){
  144523. int nCell; /* Current number of cells in pNode */
  144524. int nMaxCell; /* Maximum number of cells for pNode */
  144525. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  144526. nCell = NCELL(pNode);
  144527. assert( nCell<=nMaxCell );
  144528. if( nCell<nMaxCell ){
  144529. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  144530. writeInt16(&pNode->zData[2], nCell+1);
  144531. pNode->isDirty = 1;
  144532. }
  144533. return (nCell==nMaxCell);
  144534. }
  144535. /*
  144536. ** If the node is dirty, write it out to the database.
  144537. */
  144538. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  144539. int rc = SQLITE_OK;
  144540. if( pNode->isDirty ){
  144541. sqlite3_stmt *p = pRtree->pWriteNode;
  144542. if( pNode->iNode ){
  144543. sqlite3_bind_int64(p, 1, pNode->iNode);
  144544. }else{
  144545. sqlite3_bind_null(p, 1);
  144546. }
  144547. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  144548. sqlite3_step(p);
  144549. pNode->isDirty = 0;
  144550. rc = sqlite3_reset(p);
  144551. if( pNode->iNode==0 && rc==SQLITE_OK ){
  144552. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  144553. nodeHashInsert(pRtree, pNode);
  144554. }
  144555. }
  144556. return rc;
  144557. }
  144558. /*
  144559. ** Release a reference to a node. If the node is dirty and the reference
  144560. ** count drops to zero, the node data is written to the database.
  144561. */
  144562. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  144563. int rc = SQLITE_OK;
  144564. if( pNode ){
  144565. assert( pNode->nRef>0 );
  144566. pNode->nRef--;
  144567. if( pNode->nRef==0 ){
  144568. if( pNode->iNode==1 ){
  144569. pRtree->iDepth = -1;
  144570. }
  144571. if( pNode->pParent ){
  144572. rc = nodeRelease(pRtree, pNode->pParent);
  144573. }
  144574. if( rc==SQLITE_OK ){
  144575. rc = nodeWrite(pRtree, pNode);
  144576. }
  144577. nodeHashDelete(pRtree, pNode);
  144578. sqlite3_free(pNode);
  144579. }
  144580. }
  144581. return rc;
  144582. }
  144583. /*
  144584. ** Return the 64-bit integer value associated with cell iCell of
  144585. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  144586. ** an internal node, then the 64-bit integer is a child page number.
  144587. */
  144588. static i64 nodeGetRowid(
  144589. Rtree *pRtree, /* The overall R-Tree */
  144590. RtreeNode *pNode, /* The node from which to extract the ID */
  144591. int iCell /* The cell index from which to extract the ID */
  144592. ){
  144593. assert( iCell<NCELL(pNode) );
  144594. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  144595. }
  144596. /*
  144597. ** Return coordinate iCoord from cell iCell in node pNode.
  144598. */
  144599. static void nodeGetCoord(
  144600. Rtree *pRtree, /* The overall R-Tree */
  144601. RtreeNode *pNode, /* The node from which to extract a coordinate */
  144602. int iCell, /* The index of the cell within the node */
  144603. int iCoord, /* Which coordinate to extract */
  144604. RtreeCoord *pCoord /* OUT: Space to write result to */
  144605. ){
  144606. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  144607. }
  144608. /*
  144609. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  144610. ** to by pCell with the results.
  144611. */
  144612. static void nodeGetCell(
  144613. Rtree *pRtree, /* The overall R-Tree */
  144614. RtreeNode *pNode, /* The node containing the cell to be read */
  144615. int iCell, /* Index of the cell within the node */
  144616. RtreeCell *pCell /* OUT: Write the cell contents here */
  144617. ){
  144618. u8 *pData;
  144619. RtreeCoord *pCoord;
  144620. int ii;
  144621. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  144622. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  144623. pCoord = pCell->aCoord;
  144624. for(ii=0; ii<pRtree->nDim*2; ii++){
  144625. readCoord(&pData[ii*4], &pCoord[ii]);
  144626. }
  144627. }
  144628. /* Forward declaration for the function that does the work of
  144629. ** the virtual table module xCreate() and xConnect() methods.
  144630. */
  144631. static int rtreeInit(
  144632. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  144633. );
  144634. /*
  144635. ** Rtree virtual table module xCreate method.
  144636. */
  144637. static int rtreeCreate(
  144638. sqlite3 *db,
  144639. void *pAux,
  144640. int argc, const char *const*argv,
  144641. sqlite3_vtab **ppVtab,
  144642. char **pzErr
  144643. ){
  144644. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  144645. }
  144646. /*
  144647. ** Rtree virtual table module xConnect method.
  144648. */
  144649. static int rtreeConnect(
  144650. sqlite3 *db,
  144651. void *pAux,
  144652. int argc, const char *const*argv,
  144653. sqlite3_vtab **ppVtab,
  144654. char **pzErr
  144655. ){
  144656. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  144657. }
  144658. /*
  144659. ** Increment the r-tree reference count.
  144660. */
  144661. static void rtreeReference(Rtree *pRtree){
  144662. pRtree->nBusy++;
  144663. }
  144664. /*
  144665. ** Decrement the r-tree reference count. When the reference count reaches
  144666. ** zero the structure is deleted.
  144667. */
  144668. static void rtreeRelease(Rtree *pRtree){
  144669. pRtree->nBusy--;
  144670. if( pRtree->nBusy==0 ){
  144671. sqlite3_finalize(pRtree->pReadNode);
  144672. sqlite3_finalize(pRtree->pWriteNode);
  144673. sqlite3_finalize(pRtree->pDeleteNode);
  144674. sqlite3_finalize(pRtree->pReadRowid);
  144675. sqlite3_finalize(pRtree->pWriteRowid);
  144676. sqlite3_finalize(pRtree->pDeleteRowid);
  144677. sqlite3_finalize(pRtree->pReadParent);
  144678. sqlite3_finalize(pRtree->pWriteParent);
  144679. sqlite3_finalize(pRtree->pDeleteParent);
  144680. sqlite3_free(pRtree);
  144681. }
  144682. }
  144683. /*
  144684. ** Rtree virtual table module xDisconnect method.
  144685. */
  144686. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  144687. rtreeRelease((Rtree *)pVtab);
  144688. return SQLITE_OK;
  144689. }
  144690. /*
  144691. ** Rtree virtual table module xDestroy method.
  144692. */
  144693. static int rtreeDestroy(sqlite3_vtab *pVtab){
  144694. Rtree *pRtree = (Rtree *)pVtab;
  144695. int rc;
  144696. char *zCreate = sqlite3_mprintf(
  144697. "DROP TABLE '%q'.'%q_node';"
  144698. "DROP TABLE '%q'.'%q_rowid';"
  144699. "DROP TABLE '%q'.'%q_parent';",
  144700. pRtree->zDb, pRtree->zName,
  144701. pRtree->zDb, pRtree->zName,
  144702. pRtree->zDb, pRtree->zName
  144703. );
  144704. if( !zCreate ){
  144705. rc = SQLITE_NOMEM;
  144706. }else{
  144707. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  144708. sqlite3_free(zCreate);
  144709. }
  144710. if( rc==SQLITE_OK ){
  144711. rtreeRelease(pRtree);
  144712. }
  144713. return rc;
  144714. }
  144715. /*
  144716. ** Rtree virtual table module xOpen method.
  144717. */
  144718. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  144719. int rc = SQLITE_NOMEM;
  144720. RtreeCursor *pCsr;
  144721. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  144722. if( pCsr ){
  144723. memset(pCsr, 0, sizeof(RtreeCursor));
  144724. pCsr->base.pVtab = pVTab;
  144725. rc = SQLITE_OK;
  144726. }
  144727. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  144728. return rc;
  144729. }
  144730. /*
  144731. ** Free the RtreeCursor.aConstraint[] array and its contents.
  144732. */
  144733. static void freeCursorConstraints(RtreeCursor *pCsr){
  144734. if( pCsr->aConstraint ){
  144735. int i; /* Used to iterate through constraint array */
  144736. for(i=0; i<pCsr->nConstraint; i++){
  144737. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  144738. if( pInfo ){
  144739. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  144740. sqlite3_free(pInfo);
  144741. }
  144742. }
  144743. sqlite3_free(pCsr->aConstraint);
  144744. pCsr->aConstraint = 0;
  144745. }
  144746. }
  144747. /*
  144748. ** Rtree virtual table module xClose method.
  144749. */
  144750. static int rtreeClose(sqlite3_vtab_cursor *cur){
  144751. Rtree *pRtree = (Rtree *)(cur->pVtab);
  144752. int ii;
  144753. RtreeCursor *pCsr = (RtreeCursor *)cur;
  144754. freeCursorConstraints(pCsr);
  144755. sqlite3_free(pCsr->aPoint);
  144756. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  144757. sqlite3_free(pCsr);
  144758. return SQLITE_OK;
  144759. }
  144760. /*
  144761. ** Rtree virtual table module xEof method.
  144762. **
  144763. ** Return non-zero if the cursor does not currently point to a valid
  144764. ** record (i.e if the scan has finished), or zero otherwise.
  144765. */
  144766. static int rtreeEof(sqlite3_vtab_cursor *cur){
  144767. RtreeCursor *pCsr = (RtreeCursor *)cur;
  144768. return pCsr->atEOF;
  144769. }
  144770. /*
  144771. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  144772. ** The on-disk format is big-endian and needs to be converted for little-
  144773. ** endian platforms. The on-disk record stores integer coordinates if
  144774. ** eInt is true and it stores 32-bit floating point records if eInt is
  144775. ** false. a[] is the four bytes of the on-disk record to be decoded.
  144776. ** Store the results in "r".
  144777. **
  144778. ** There are three versions of this macro, one each for little-endian and
  144779. ** big-endian processors and a third generic implementation. The endian-
  144780. ** specific implementations are much faster and are preferred if the
  144781. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  144782. ** macro is part of sqliteInt.h and hence the endian-specific
  144783. ** implementation will only be used if this module is compiled as part
  144784. ** of the amalgamation.
  144785. */
  144786. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  144787. #define RTREE_DECODE_COORD(eInt, a, r) { \
  144788. RtreeCoord c; /* Coordinate decoded */ \
  144789. memcpy(&c.u,a,4); \
  144790. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  144791. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  144792. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  144793. }
  144794. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  144795. #define RTREE_DECODE_COORD(eInt, a, r) { \
  144796. RtreeCoord c; /* Coordinate decoded */ \
  144797. memcpy(&c.u,a,4); \
  144798. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  144799. }
  144800. #else
  144801. #define RTREE_DECODE_COORD(eInt, a, r) { \
  144802. RtreeCoord c; /* Coordinate decoded */ \
  144803. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  144804. +((u32)a[2]<<8) + a[3]; \
  144805. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  144806. }
  144807. #endif
  144808. /*
  144809. ** Check the RTree node or entry given by pCellData and p against the MATCH
  144810. ** constraint pConstraint.
  144811. */
  144812. static int rtreeCallbackConstraint(
  144813. RtreeConstraint *pConstraint, /* The constraint to test */
  144814. int eInt, /* True if RTree holding integer coordinates */
  144815. u8 *pCellData, /* Raw cell content */
  144816. RtreeSearchPoint *pSearch, /* Container of this cell */
  144817. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  144818. int *peWithin /* OUT: visibility of the cell */
  144819. ){
  144820. int i; /* Loop counter */
  144821. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  144822. int nCoord = pInfo->nCoord; /* No. of coordinates */
  144823. int rc; /* Callback return code */
  144824. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  144825. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  144826. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  144827. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  144828. pInfo->iRowid = readInt64(pCellData);
  144829. }
  144830. pCellData += 8;
  144831. for(i=0; i<nCoord; i++, pCellData += 4){
  144832. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  144833. }
  144834. if( pConstraint->op==RTREE_MATCH ){
  144835. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  144836. nCoord, aCoord, &i);
  144837. if( i==0 ) *peWithin = NOT_WITHIN;
  144838. *prScore = RTREE_ZERO;
  144839. }else{
  144840. pInfo->aCoord = aCoord;
  144841. pInfo->iLevel = pSearch->iLevel - 1;
  144842. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  144843. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  144844. rc = pConstraint->u.xQueryFunc(pInfo);
  144845. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  144846. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  144847. *prScore = pInfo->rScore;
  144848. }
  144849. }
  144850. return rc;
  144851. }
  144852. /*
  144853. ** Check the internal RTree node given by pCellData against constraint p.
  144854. ** If this constraint cannot be satisfied by any child within the node,
  144855. ** set *peWithin to NOT_WITHIN.
  144856. */
  144857. static void rtreeNonleafConstraint(
  144858. RtreeConstraint *p, /* The constraint to test */
  144859. int eInt, /* True if RTree holds integer coordinates */
  144860. u8 *pCellData, /* Raw cell content as appears on disk */
  144861. int *peWithin /* Adjust downward, as appropriate */
  144862. ){
  144863. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  144864. /* p->iCoord might point to either a lower or upper bound coordinate
  144865. ** in a coordinate pair. But make pCellData point to the lower bound.
  144866. */
  144867. pCellData += 8 + 4*(p->iCoord&0xfe);
  144868. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  144869. || p->op==RTREE_GT || p->op==RTREE_EQ );
  144870. switch( p->op ){
  144871. case RTREE_LE:
  144872. case RTREE_LT:
  144873. case RTREE_EQ:
  144874. RTREE_DECODE_COORD(eInt, pCellData, val);
  144875. /* val now holds the lower bound of the coordinate pair */
  144876. if( p->u.rValue>=val ) return;
  144877. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  144878. /* Fall through for the RTREE_EQ case */
  144879. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  144880. pCellData += 4;
  144881. RTREE_DECODE_COORD(eInt, pCellData, val);
  144882. /* val now holds the upper bound of the coordinate pair */
  144883. if( p->u.rValue<=val ) return;
  144884. }
  144885. *peWithin = NOT_WITHIN;
  144886. }
  144887. /*
  144888. ** Check the leaf RTree cell given by pCellData against constraint p.
  144889. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  144890. ** If the constraint is satisfied, leave *peWithin unchanged.
  144891. **
  144892. ** The constraint is of the form: xN op $val
  144893. **
  144894. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  144895. ** pCellData. $val is given by p->u.rValue.
  144896. */
  144897. static void rtreeLeafConstraint(
  144898. RtreeConstraint *p, /* The constraint to test */
  144899. int eInt, /* True if RTree holds integer coordinates */
  144900. u8 *pCellData, /* Raw cell content as appears on disk */
  144901. int *peWithin /* Adjust downward, as appropriate */
  144902. ){
  144903. RtreeDValue xN; /* Coordinate value converted to a double */
  144904. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  144905. || p->op==RTREE_GT || p->op==RTREE_EQ );
  144906. pCellData += 8 + p->iCoord*4;
  144907. RTREE_DECODE_COORD(eInt, pCellData, xN);
  144908. switch( p->op ){
  144909. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  144910. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  144911. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  144912. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  144913. default: if( xN == p->u.rValue ) return; break;
  144914. }
  144915. *peWithin = NOT_WITHIN;
  144916. }
  144917. /*
  144918. ** One of the cells in node pNode is guaranteed to have a 64-bit
  144919. ** integer value equal to iRowid. Return the index of this cell.
  144920. */
  144921. static int nodeRowidIndex(
  144922. Rtree *pRtree,
  144923. RtreeNode *pNode,
  144924. i64 iRowid,
  144925. int *piIndex
  144926. ){
  144927. int ii;
  144928. int nCell = NCELL(pNode);
  144929. assert( nCell<200 );
  144930. for(ii=0; ii<nCell; ii++){
  144931. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  144932. *piIndex = ii;
  144933. return SQLITE_OK;
  144934. }
  144935. }
  144936. return SQLITE_CORRUPT_VTAB;
  144937. }
  144938. /*
  144939. ** Return the index of the cell containing a pointer to node pNode
  144940. ** in its parent. If pNode is the root node, return -1.
  144941. */
  144942. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  144943. RtreeNode *pParent = pNode->pParent;
  144944. if( pParent ){
  144945. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  144946. }
  144947. *piIndex = -1;
  144948. return SQLITE_OK;
  144949. }
  144950. /*
  144951. ** Compare two search points. Return negative, zero, or positive if the first
  144952. ** is less than, equal to, or greater than the second.
  144953. **
  144954. ** The rScore is the primary key. Smaller rScore values come first.
  144955. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  144956. ** iLevel values coming first. In this way, if rScore is the same for all
  144957. ** SearchPoints, then iLevel becomes the deciding factor and the result
  144958. ** is a depth-first search, which is the desired default behavior.
  144959. */
  144960. static int rtreeSearchPointCompare(
  144961. const RtreeSearchPoint *pA,
  144962. const RtreeSearchPoint *pB
  144963. ){
  144964. if( pA->rScore<pB->rScore ) return -1;
  144965. if( pA->rScore>pB->rScore ) return +1;
  144966. if( pA->iLevel<pB->iLevel ) return -1;
  144967. if( pA->iLevel>pB->iLevel ) return +1;
  144968. return 0;
  144969. }
  144970. /*
  144971. ** Interchange to search points in a cursor.
  144972. */
  144973. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  144974. RtreeSearchPoint t = p->aPoint[i];
  144975. assert( i<j );
  144976. p->aPoint[i] = p->aPoint[j];
  144977. p->aPoint[j] = t;
  144978. i++; j++;
  144979. if( i<RTREE_CACHE_SZ ){
  144980. if( j>=RTREE_CACHE_SZ ){
  144981. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  144982. p->aNode[i] = 0;
  144983. }else{
  144984. RtreeNode *pTemp = p->aNode[i];
  144985. p->aNode[i] = p->aNode[j];
  144986. p->aNode[j] = pTemp;
  144987. }
  144988. }
  144989. }
  144990. /*
  144991. ** Return the search point with the lowest current score.
  144992. */
  144993. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  144994. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  144995. }
  144996. /*
  144997. ** Get the RtreeNode for the search point with the lowest score.
  144998. */
  144999. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  145000. sqlite3_int64 id;
  145001. int ii = 1 - pCur->bPoint;
  145002. assert( ii==0 || ii==1 );
  145003. assert( pCur->bPoint || pCur->nPoint );
  145004. if( pCur->aNode[ii]==0 ){
  145005. assert( pRC!=0 );
  145006. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  145007. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  145008. }
  145009. return pCur->aNode[ii];
  145010. }
  145011. /*
  145012. ** Push a new element onto the priority queue
  145013. */
  145014. static RtreeSearchPoint *rtreeEnqueue(
  145015. RtreeCursor *pCur, /* The cursor */
  145016. RtreeDValue rScore, /* Score for the new search point */
  145017. u8 iLevel /* Level for the new search point */
  145018. ){
  145019. int i, j;
  145020. RtreeSearchPoint *pNew;
  145021. if( pCur->nPoint>=pCur->nPointAlloc ){
  145022. int nNew = pCur->nPointAlloc*2 + 8;
  145023. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  145024. if( pNew==0 ) return 0;
  145025. pCur->aPoint = pNew;
  145026. pCur->nPointAlloc = nNew;
  145027. }
  145028. i = pCur->nPoint++;
  145029. pNew = pCur->aPoint + i;
  145030. pNew->rScore = rScore;
  145031. pNew->iLevel = iLevel;
  145032. assert( iLevel<=RTREE_MAX_DEPTH );
  145033. while( i>0 ){
  145034. RtreeSearchPoint *pParent;
  145035. j = (i-1)/2;
  145036. pParent = pCur->aPoint + j;
  145037. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  145038. rtreeSearchPointSwap(pCur, j, i);
  145039. i = j;
  145040. pNew = pParent;
  145041. }
  145042. return pNew;
  145043. }
  145044. /*
  145045. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  145046. ** NULL if malloc fails.
  145047. */
  145048. static RtreeSearchPoint *rtreeSearchPointNew(
  145049. RtreeCursor *pCur, /* The cursor */
  145050. RtreeDValue rScore, /* Score for the new search point */
  145051. u8 iLevel /* Level for the new search point */
  145052. ){
  145053. RtreeSearchPoint *pNew, *pFirst;
  145054. pFirst = rtreeSearchPointFirst(pCur);
  145055. pCur->anQueue[iLevel]++;
  145056. if( pFirst==0
  145057. || pFirst->rScore>rScore
  145058. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  145059. ){
  145060. if( pCur->bPoint ){
  145061. int ii;
  145062. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  145063. if( pNew==0 ) return 0;
  145064. ii = (int)(pNew - pCur->aPoint) + 1;
  145065. if( ii<RTREE_CACHE_SZ ){
  145066. assert( pCur->aNode[ii]==0 );
  145067. pCur->aNode[ii] = pCur->aNode[0];
  145068. }else{
  145069. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  145070. }
  145071. pCur->aNode[0] = 0;
  145072. *pNew = pCur->sPoint;
  145073. }
  145074. pCur->sPoint.rScore = rScore;
  145075. pCur->sPoint.iLevel = iLevel;
  145076. pCur->bPoint = 1;
  145077. return &pCur->sPoint;
  145078. }else{
  145079. return rtreeEnqueue(pCur, rScore, iLevel);
  145080. }
  145081. }
  145082. #if 0
  145083. /* Tracing routines for the RtreeSearchPoint queue */
  145084. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  145085. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  145086. printf(" %d.%05lld.%02d %g %d",
  145087. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  145088. );
  145089. idx++;
  145090. if( idx<RTREE_CACHE_SZ ){
  145091. printf(" %p\n", pCur->aNode[idx]);
  145092. }else{
  145093. printf("\n");
  145094. }
  145095. }
  145096. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  145097. int ii;
  145098. printf("=== %9s ", zPrefix);
  145099. if( pCur->bPoint ){
  145100. tracePoint(&pCur->sPoint, -1, pCur);
  145101. }
  145102. for(ii=0; ii<pCur->nPoint; ii++){
  145103. if( ii>0 || pCur->bPoint ) printf(" ");
  145104. tracePoint(&pCur->aPoint[ii], ii, pCur);
  145105. }
  145106. }
  145107. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  145108. #else
  145109. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  145110. #endif
  145111. /* Remove the search point with the lowest current score.
  145112. */
  145113. static void rtreeSearchPointPop(RtreeCursor *p){
  145114. int i, j, k, n;
  145115. i = 1 - p->bPoint;
  145116. assert( i==0 || i==1 );
  145117. if( p->aNode[i] ){
  145118. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  145119. p->aNode[i] = 0;
  145120. }
  145121. if( p->bPoint ){
  145122. p->anQueue[p->sPoint.iLevel]--;
  145123. p->bPoint = 0;
  145124. }else if( p->nPoint ){
  145125. p->anQueue[p->aPoint[0].iLevel]--;
  145126. n = --p->nPoint;
  145127. p->aPoint[0] = p->aPoint[n];
  145128. if( n<RTREE_CACHE_SZ-1 ){
  145129. p->aNode[1] = p->aNode[n+1];
  145130. p->aNode[n+1] = 0;
  145131. }
  145132. i = 0;
  145133. while( (j = i*2+1)<n ){
  145134. k = j+1;
  145135. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  145136. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  145137. rtreeSearchPointSwap(p, i, k);
  145138. i = k;
  145139. }else{
  145140. break;
  145141. }
  145142. }else{
  145143. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  145144. rtreeSearchPointSwap(p, i, j);
  145145. i = j;
  145146. }else{
  145147. break;
  145148. }
  145149. }
  145150. }
  145151. }
  145152. }
  145153. /*
  145154. ** Continue the search on cursor pCur until the front of the queue
  145155. ** contains an entry suitable for returning as a result-set row,
  145156. ** or until the RtreeSearchPoint queue is empty, indicating that the
  145157. ** query has completed.
  145158. */
  145159. static int rtreeStepToLeaf(RtreeCursor *pCur){
  145160. RtreeSearchPoint *p;
  145161. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  145162. RtreeNode *pNode;
  145163. int eWithin;
  145164. int rc = SQLITE_OK;
  145165. int nCell;
  145166. int nConstraint = pCur->nConstraint;
  145167. int ii;
  145168. int eInt;
  145169. RtreeSearchPoint x;
  145170. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  145171. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  145172. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  145173. if( rc ) return rc;
  145174. nCell = NCELL(pNode);
  145175. assert( nCell<200 );
  145176. while( p->iCell<nCell ){
  145177. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  145178. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  145179. eWithin = FULLY_WITHIN;
  145180. for(ii=0; ii<nConstraint; ii++){
  145181. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  145182. if( pConstraint->op>=RTREE_MATCH ){
  145183. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  145184. &rScore, &eWithin);
  145185. if( rc ) return rc;
  145186. }else if( p->iLevel==1 ){
  145187. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  145188. }else{
  145189. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  145190. }
  145191. if( eWithin==NOT_WITHIN ) break;
  145192. }
  145193. p->iCell++;
  145194. if( eWithin==NOT_WITHIN ) continue;
  145195. x.iLevel = p->iLevel - 1;
  145196. if( x.iLevel ){
  145197. x.id = readInt64(pCellData);
  145198. x.iCell = 0;
  145199. }else{
  145200. x.id = p->id;
  145201. x.iCell = p->iCell - 1;
  145202. }
  145203. if( p->iCell>=nCell ){
  145204. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  145205. rtreeSearchPointPop(pCur);
  145206. }
  145207. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  145208. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  145209. if( p==0 ) return SQLITE_NOMEM;
  145210. p->eWithin = eWithin;
  145211. p->id = x.id;
  145212. p->iCell = x.iCell;
  145213. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  145214. break;
  145215. }
  145216. if( p->iCell>=nCell ){
  145217. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  145218. rtreeSearchPointPop(pCur);
  145219. }
  145220. }
  145221. pCur->atEOF = p==0;
  145222. return SQLITE_OK;
  145223. }
  145224. /*
  145225. ** Rtree virtual table module xNext method.
  145226. */
  145227. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  145228. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  145229. int rc = SQLITE_OK;
  145230. /* Move to the next entry that matches the configured constraints. */
  145231. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  145232. rtreeSearchPointPop(pCsr);
  145233. rc = rtreeStepToLeaf(pCsr);
  145234. return rc;
  145235. }
  145236. /*
  145237. ** Rtree virtual table module xRowid method.
  145238. */
  145239. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  145240. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  145241. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  145242. int rc = SQLITE_OK;
  145243. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  145244. if( rc==SQLITE_OK && p ){
  145245. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  145246. }
  145247. return rc;
  145248. }
  145249. /*
  145250. ** Rtree virtual table module xColumn method.
  145251. */
  145252. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  145253. Rtree *pRtree = (Rtree *)cur->pVtab;
  145254. RtreeCursor *pCsr = (RtreeCursor *)cur;
  145255. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  145256. RtreeCoord c;
  145257. int rc = SQLITE_OK;
  145258. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  145259. if( rc ) return rc;
  145260. if( p==0 ) return SQLITE_OK;
  145261. if( i==0 ){
  145262. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  145263. }else{
  145264. if( rc ) return rc;
  145265. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  145266. #ifndef SQLITE_RTREE_INT_ONLY
  145267. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  145268. sqlite3_result_double(ctx, c.f);
  145269. }else
  145270. #endif
  145271. {
  145272. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  145273. sqlite3_result_int(ctx, c.i);
  145274. }
  145275. }
  145276. return SQLITE_OK;
  145277. }
  145278. /*
  145279. ** Use nodeAcquire() to obtain the leaf node containing the record with
  145280. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  145281. ** return SQLITE_OK. If there is no such record in the table, set
  145282. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  145283. ** to zero and return an SQLite error code.
  145284. */
  145285. static int findLeafNode(
  145286. Rtree *pRtree, /* RTree to search */
  145287. i64 iRowid, /* The rowid searching for */
  145288. RtreeNode **ppLeaf, /* Write the node here */
  145289. sqlite3_int64 *piNode /* Write the node-id here */
  145290. ){
  145291. int rc;
  145292. *ppLeaf = 0;
  145293. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  145294. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  145295. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  145296. if( piNode ) *piNode = iNode;
  145297. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  145298. sqlite3_reset(pRtree->pReadRowid);
  145299. }else{
  145300. rc = sqlite3_reset(pRtree->pReadRowid);
  145301. }
  145302. return rc;
  145303. }
  145304. /*
  145305. ** This function is called to configure the RtreeConstraint object passed
  145306. ** as the second argument for a MATCH constraint. The value passed as the
  145307. ** first argument to this function is the right-hand operand to the MATCH
  145308. ** operator.
  145309. */
  145310. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  145311. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  145312. sqlite3_rtree_query_info *pInfo; /* Callback information */
  145313. int nBlob; /* Size of the geometry function blob */
  145314. int nExpected; /* Expected size of the BLOB */
  145315. /* Check that value is actually a blob. */
  145316. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  145317. /* Check that the blob is roughly the right size. */
  145318. nBlob = sqlite3_value_bytes(pValue);
  145319. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  145320. return SQLITE_ERROR;
  145321. }
  145322. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  145323. if( !pInfo ) return SQLITE_NOMEM;
  145324. memset(pInfo, 0, sizeof(*pInfo));
  145325. pBlob = (RtreeMatchArg*)&pInfo[1];
  145326. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  145327. nExpected = (int)(sizeof(RtreeMatchArg) +
  145328. pBlob->nParam*sizeof(sqlite3_value*) +
  145329. (pBlob->nParam-1)*sizeof(RtreeDValue));
  145330. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  145331. sqlite3_free(pInfo);
  145332. return SQLITE_ERROR;
  145333. }
  145334. pInfo->pContext = pBlob->cb.pContext;
  145335. pInfo->nParam = pBlob->nParam;
  145336. pInfo->aParam = pBlob->aParam;
  145337. pInfo->apSqlParam = pBlob->apSqlParam;
  145338. if( pBlob->cb.xGeom ){
  145339. pCons->u.xGeom = pBlob->cb.xGeom;
  145340. }else{
  145341. pCons->op = RTREE_QUERY;
  145342. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  145343. }
  145344. pCons->pInfo = pInfo;
  145345. return SQLITE_OK;
  145346. }
  145347. /*
  145348. ** Rtree virtual table module xFilter method.
  145349. */
  145350. static int rtreeFilter(
  145351. sqlite3_vtab_cursor *pVtabCursor,
  145352. int idxNum, const char *idxStr,
  145353. int argc, sqlite3_value **argv
  145354. ){
  145355. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  145356. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  145357. RtreeNode *pRoot = 0;
  145358. int ii;
  145359. int rc = SQLITE_OK;
  145360. int iCell = 0;
  145361. rtreeReference(pRtree);
  145362. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  145363. freeCursorConstraints(pCsr);
  145364. sqlite3_free(pCsr->aPoint);
  145365. memset(pCsr, 0, sizeof(RtreeCursor));
  145366. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  145367. pCsr->iStrategy = idxNum;
  145368. if( idxNum==1 ){
  145369. /* Special case - lookup by rowid. */
  145370. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  145371. RtreeSearchPoint *p; /* Search point for the the leaf */
  145372. i64 iRowid = sqlite3_value_int64(argv[0]);
  145373. i64 iNode = 0;
  145374. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  145375. if( rc==SQLITE_OK && pLeaf!=0 ){
  145376. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  145377. assert( p!=0 ); /* Always returns pCsr->sPoint */
  145378. pCsr->aNode[0] = pLeaf;
  145379. p->id = iNode;
  145380. p->eWithin = PARTLY_WITHIN;
  145381. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  145382. p->iCell = iCell;
  145383. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  145384. }else{
  145385. pCsr->atEOF = 1;
  145386. }
  145387. }else{
  145388. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  145389. ** with the configured constraints.
  145390. */
  145391. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  145392. if( rc==SQLITE_OK && argc>0 ){
  145393. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  145394. pCsr->nConstraint = argc;
  145395. if( !pCsr->aConstraint ){
  145396. rc = SQLITE_NOMEM;
  145397. }else{
  145398. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  145399. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  145400. assert( (idxStr==0 && argc==0)
  145401. || (idxStr && (int)strlen(idxStr)==argc*2) );
  145402. for(ii=0; ii<argc; ii++){
  145403. RtreeConstraint *p = &pCsr->aConstraint[ii];
  145404. p->op = idxStr[ii*2];
  145405. p->iCoord = idxStr[ii*2+1]-'0';
  145406. if( p->op>=RTREE_MATCH ){
  145407. /* A MATCH operator. The right-hand-side must be a blob that
  145408. ** can be cast into an RtreeMatchArg object. One created using
  145409. ** an sqlite3_rtree_geometry_callback() SQL user function.
  145410. */
  145411. rc = deserializeGeometry(argv[ii], p);
  145412. if( rc!=SQLITE_OK ){
  145413. break;
  145414. }
  145415. p->pInfo->nCoord = pRtree->nDim*2;
  145416. p->pInfo->anQueue = pCsr->anQueue;
  145417. p->pInfo->mxLevel = pRtree->iDepth + 1;
  145418. }else{
  145419. #ifdef SQLITE_RTREE_INT_ONLY
  145420. p->u.rValue = sqlite3_value_int64(argv[ii]);
  145421. #else
  145422. p->u.rValue = sqlite3_value_double(argv[ii]);
  145423. #endif
  145424. }
  145425. }
  145426. }
  145427. }
  145428. if( rc==SQLITE_OK ){
  145429. RtreeSearchPoint *pNew;
  145430. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  145431. if( pNew==0 ) return SQLITE_NOMEM;
  145432. pNew->id = 1;
  145433. pNew->iCell = 0;
  145434. pNew->eWithin = PARTLY_WITHIN;
  145435. assert( pCsr->bPoint==1 );
  145436. pCsr->aNode[0] = pRoot;
  145437. pRoot = 0;
  145438. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  145439. rc = rtreeStepToLeaf(pCsr);
  145440. }
  145441. }
  145442. nodeRelease(pRtree, pRoot);
  145443. rtreeRelease(pRtree);
  145444. return rc;
  145445. }
  145446. /*
  145447. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  145448. ** extension is currently being used by a version of SQLite too old to
  145449. ** support estimatedRows. In that case this function is a no-op.
  145450. */
  145451. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  145452. #if SQLITE_VERSION_NUMBER>=3008002
  145453. if( sqlite3_libversion_number()>=3008002 ){
  145454. pIdxInfo->estimatedRows = nRow;
  145455. }
  145456. #endif
  145457. }
  145458. /*
  145459. ** Rtree virtual table module xBestIndex method. There are three
  145460. ** table scan strategies to choose from (in order from most to
  145461. ** least desirable):
  145462. **
  145463. ** idxNum idxStr Strategy
  145464. ** ------------------------------------------------
  145465. ** 1 Unused Direct lookup by rowid.
  145466. ** 2 See below R-tree query or full-table scan.
  145467. ** ------------------------------------------------
  145468. **
  145469. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  145470. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  145471. ** constraint used. The first two bytes of idxStr correspond to
  145472. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  145473. ** (argvIndex==1) etc.
  145474. **
  145475. ** The first of each pair of bytes in idxStr identifies the constraint
  145476. ** operator as follows:
  145477. **
  145478. ** Operator Byte Value
  145479. ** ----------------------
  145480. ** = 0x41 ('A')
  145481. ** <= 0x42 ('B')
  145482. ** < 0x43 ('C')
  145483. ** >= 0x44 ('D')
  145484. ** > 0x45 ('E')
  145485. ** MATCH 0x46 ('F')
  145486. ** ----------------------
  145487. **
  145488. ** The second of each pair of bytes identifies the coordinate column
  145489. ** to which the constraint applies. The leftmost coordinate column
  145490. ** is 'a', the second from the left 'b' etc.
  145491. */
  145492. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  145493. Rtree *pRtree = (Rtree*)tab;
  145494. int rc = SQLITE_OK;
  145495. int ii;
  145496. int bMatch = 0; /* True if there exists a MATCH constraint */
  145497. i64 nRow; /* Estimated rows returned by this scan */
  145498. int iIdx = 0;
  145499. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  145500. memset(zIdxStr, 0, sizeof(zIdxStr));
  145501. /* Check if there exists a MATCH constraint - even an unusable one. If there
  145502. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  145503. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  145504. ** possible. */
  145505. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  145506. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  145507. bMatch = 1;
  145508. }
  145509. }
  145510. assert( pIdxInfo->idxStr==0 );
  145511. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  145512. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  145513. if( bMatch==0 && p->usable
  145514. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  145515. ){
  145516. /* We have an equality constraint on the rowid. Use strategy 1. */
  145517. int jj;
  145518. for(jj=0; jj<ii; jj++){
  145519. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  145520. pIdxInfo->aConstraintUsage[jj].omit = 0;
  145521. }
  145522. pIdxInfo->idxNum = 1;
  145523. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  145524. pIdxInfo->aConstraintUsage[jj].omit = 1;
  145525. /* This strategy involves a two rowid lookups on an B-Tree structures
  145526. ** and then a linear search of an R-Tree node. This should be
  145527. ** considered almost as quick as a direct rowid lookup (for which
  145528. ** sqlite uses an internal cost of 0.0). It is expected to return
  145529. ** a single row.
  145530. */
  145531. pIdxInfo->estimatedCost = 30.0;
  145532. setEstimatedRows(pIdxInfo, 1);
  145533. return SQLITE_OK;
  145534. }
  145535. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  145536. u8 op;
  145537. switch( p->op ){
  145538. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  145539. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  145540. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  145541. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  145542. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  145543. default:
  145544. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  145545. op = RTREE_MATCH;
  145546. break;
  145547. }
  145548. zIdxStr[iIdx++] = op;
  145549. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  145550. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  145551. pIdxInfo->aConstraintUsage[ii].omit = 1;
  145552. }
  145553. }
  145554. pIdxInfo->idxNum = 2;
  145555. pIdxInfo->needToFreeIdxStr = 1;
  145556. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  145557. return SQLITE_NOMEM;
  145558. }
  145559. nRow = pRtree->nRowEst / (iIdx + 1);
  145560. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  145561. setEstimatedRows(pIdxInfo, nRow);
  145562. return rc;
  145563. }
  145564. /*
  145565. ** Return the N-dimensional volumn of the cell stored in *p.
  145566. */
  145567. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  145568. RtreeDValue area = (RtreeDValue)1;
  145569. int ii;
  145570. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  145571. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  145572. }
  145573. return area;
  145574. }
  145575. /*
  145576. ** Return the margin length of cell p. The margin length is the sum
  145577. ** of the objects size in each dimension.
  145578. */
  145579. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  145580. RtreeDValue margin = (RtreeDValue)0;
  145581. int ii;
  145582. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  145583. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  145584. }
  145585. return margin;
  145586. }
  145587. /*
  145588. ** Store the union of cells p1 and p2 in p1.
  145589. */
  145590. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  145591. int ii;
  145592. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  145593. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  145594. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  145595. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  145596. }
  145597. }else{
  145598. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  145599. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  145600. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  145601. }
  145602. }
  145603. }
  145604. /*
  145605. ** Return true if the area covered by p2 is a subset of the area covered
  145606. ** by p1. False otherwise.
  145607. */
  145608. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  145609. int ii;
  145610. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  145611. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  145612. RtreeCoord *a1 = &p1->aCoord[ii];
  145613. RtreeCoord *a2 = &p2->aCoord[ii];
  145614. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  145615. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  145616. ){
  145617. return 0;
  145618. }
  145619. }
  145620. return 1;
  145621. }
  145622. /*
  145623. ** Return the amount cell p would grow by if it were unioned with pCell.
  145624. */
  145625. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  145626. RtreeDValue area;
  145627. RtreeCell cell;
  145628. memcpy(&cell, p, sizeof(RtreeCell));
  145629. area = cellArea(pRtree, &cell);
  145630. cellUnion(pRtree, &cell, pCell);
  145631. return (cellArea(pRtree, &cell)-area);
  145632. }
  145633. static RtreeDValue cellOverlap(
  145634. Rtree *pRtree,
  145635. RtreeCell *p,
  145636. RtreeCell *aCell,
  145637. int nCell
  145638. ){
  145639. int ii;
  145640. RtreeDValue overlap = RTREE_ZERO;
  145641. for(ii=0; ii<nCell; ii++){
  145642. int jj;
  145643. RtreeDValue o = (RtreeDValue)1;
  145644. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  145645. RtreeDValue x1, x2;
  145646. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  145647. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  145648. if( x2<x1 ){
  145649. o = (RtreeDValue)0;
  145650. break;
  145651. }else{
  145652. o = o * (x2-x1);
  145653. }
  145654. }
  145655. overlap += o;
  145656. }
  145657. return overlap;
  145658. }
  145659. /*
  145660. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  145661. ** ChooseSubTree in r*tree terminology.
  145662. */
  145663. static int ChooseLeaf(
  145664. Rtree *pRtree, /* Rtree table */
  145665. RtreeCell *pCell, /* Cell to insert into rtree */
  145666. int iHeight, /* Height of sub-tree rooted at pCell */
  145667. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  145668. ){
  145669. int rc;
  145670. int ii;
  145671. RtreeNode *pNode;
  145672. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  145673. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  145674. int iCell;
  145675. sqlite3_int64 iBest = 0;
  145676. RtreeDValue fMinGrowth = RTREE_ZERO;
  145677. RtreeDValue fMinArea = RTREE_ZERO;
  145678. int nCell = NCELL(pNode);
  145679. RtreeCell cell;
  145680. RtreeNode *pChild;
  145681. RtreeCell *aCell = 0;
  145682. /* Select the child node which will be enlarged the least if pCell
  145683. ** is inserted into it. Resolve ties by choosing the entry with
  145684. ** the smallest area.
  145685. */
  145686. for(iCell=0; iCell<nCell; iCell++){
  145687. int bBest = 0;
  145688. RtreeDValue growth;
  145689. RtreeDValue area;
  145690. nodeGetCell(pRtree, pNode, iCell, &cell);
  145691. growth = cellGrowth(pRtree, &cell, pCell);
  145692. area = cellArea(pRtree, &cell);
  145693. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  145694. bBest = 1;
  145695. }
  145696. if( bBest ){
  145697. fMinGrowth = growth;
  145698. fMinArea = area;
  145699. iBest = cell.iRowid;
  145700. }
  145701. }
  145702. sqlite3_free(aCell);
  145703. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  145704. nodeRelease(pRtree, pNode);
  145705. pNode = pChild;
  145706. }
  145707. *ppLeaf = pNode;
  145708. return rc;
  145709. }
  145710. /*
  145711. ** A cell with the same content as pCell has just been inserted into
  145712. ** the node pNode. This function updates the bounding box cells in
  145713. ** all ancestor elements.
  145714. */
  145715. static int AdjustTree(
  145716. Rtree *pRtree, /* Rtree table */
  145717. RtreeNode *pNode, /* Adjust ancestry of this node. */
  145718. RtreeCell *pCell /* This cell was just inserted */
  145719. ){
  145720. RtreeNode *p = pNode;
  145721. while( p->pParent ){
  145722. RtreeNode *pParent = p->pParent;
  145723. RtreeCell cell;
  145724. int iCell;
  145725. if( nodeParentIndex(pRtree, p, &iCell) ){
  145726. return SQLITE_CORRUPT_VTAB;
  145727. }
  145728. nodeGetCell(pRtree, pParent, iCell, &cell);
  145729. if( !cellContains(pRtree, &cell, pCell) ){
  145730. cellUnion(pRtree, &cell, pCell);
  145731. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  145732. }
  145733. p = pParent;
  145734. }
  145735. return SQLITE_OK;
  145736. }
  145737. /*
  145738. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  145739. */
  145740. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  145741. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  145742. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  145743. sqlite3_step(pRtree->pWriteRowid);
  145744. return sqlite3_reset(pRtree->pWriteRowid);
  145745. }
  145746. /*
  145747. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  145748. */
  145749. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  145750. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  145751. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  145752. sqlite3_step(pRtree->pWriteParent);
  145753. return sqlite3_reset(pRtree->pWriteParent);
  145754. }
  145755. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  145756. /*
  145757. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  145758. ** nIdx. The aIdx array contains the set of integers from 0 to
  145759. ** (nIdx-1) in no particular order. This function sorts the values
  145760. ** in aIdx according to the indexed values in aDistance. For
  145761. ** example, assuming the inputs:
  145762. **
  145763. ** aIdx = { 0, 1, 2, 3 }
  145764. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  145765. **
  145766. ** this function sets the aIdx array to contain:
  145767. **
  145768. ** aIdx = { 0, 1, 2, 3 }
  145769. **
  145770. ** The aSpare array is used as temporary working space by the
  145771. ** sorting algorithm.
  145772. */
  145773. static void SortByDistance(
  145774. int *aIdx,
  145775. int nIdx,
  145776. RtreeDValue *aDistance,
  145777. int *aSpare
  145778. ){
  145779. if( nIdx>1 ){
  145780. int iLeft = 0;
  145781. int iRight = 0;
  145782. int nLeft = nIdx/2;
  145783. int nRight = nIdx-nLeft;
  145784. int *aLeft = aIdx;
  145785. int *aRight = &aIdx[nLeft];
  145786. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  145787. SortByDistance(aRight, nRight, aDistance, aSpare);
  145788. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  145789. aLeft = aSpare;
  145790. while( iLeft<nLeft || iRight<nRight ){
  145791. if( iLeft==nLeft ){
  145792. aIdx[iLeft+iRight] = aRight[iRight];
  145793. iRight++;
  145794. }else if( iRight==nRight ){
  145795. aIdx[iLeft+iRight] = aLeft[iLeft];
  145796. iLeft++;
  145797. }else{
  145798. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  145799. RtreeDValue fRight = aDistance[aRight[iRight]];
  145800. if( fLeft<fRight ){
  145801. aIdx[iLeft+iRight] = aLeft[iLeft];
  145802. iLeft++;
  145803. }else{
  145804. aIdx[iLeft+iRight] = aRight[iRight];
  145805. iRight++;
  145806. }
  145807. }
  145808. }
  145809. #if 0
  145810. /* Check that the sort worked */
  145811. {
  145812. int jj;
  145813. for(jj=1; jj<nIdx; jj++){
  145814. RtreeDValue left = aDistance[aIdx[jj-1]];
  145815. RtreeDValue right = aDistance[aIdx[jj]];
  145816. assert( left<=right );
  145817. }
  145818. }
  145819. #endif
  145820. }
  145821. }
  145822. /*
  145823. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  145824. ** nIdx. The aIdx array contains the set of integers from 0 to
  145825. ** (nIdx-1) in no particular order. This function sorts the values
  145826. ** in aIdx according to dimension iDim of the cells in aCell. The
  145827. ** minimum value of dimension iDim is considered first, the
  145828. ** maximum used to break ties.
  145829. **
  145830. ** The aSpare array is used as temporary working space by the
  145831. ** sorting algorithm.
  145832. */
  145833. static void SortByDimension(
  145834. Rtree *pRtree,
  145835. int *aIdx,
  145836. int nIdx,
  145837. int iDim,
  145838. RtreeCell *aCell,
  145839. int *aSpare
  145840. ){
  145841. if( nIdx>1 ){
  145842. int iLeft = 0;
  145843. int iRight = 0;
  145844. int nLeft = nIdx/2;
  145845. int nRight = nIdx-nLeft;
  145846. int *aLeft = aIdx;
  145847. int *aRight = &aIdx[nLeft];
  145848. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  145849. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  145850. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  145851. aLeft = aSpare;
  145852. while( iLeft<nLeft || iRight<nRight ){
  145853. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  145854. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  145855. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  145856. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  145857. if( (iLeft!=nLeft) && ((iRight==nRight)
  145858. || (xleft1<xright1)
  145859. || (xleft1==xright1 && xleft2<xright2)
  145860. )){
  145861. aIdx[iLeft+iRight] = aLeft[iLeft];
  145862. iLeft++;
  145863. }else{
  145864. aIdx[iLeft+iRight] = aRight[iRight];
  145865. iRight++;
  145866. }
  145867. }
  145868. #if 0
  145869. /* Check that the sort worked */
  145870. {
  145871. int jj;
  145872. for(jj=1; jj<nIdx; jj++){
  145873. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  145874. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  145875. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  145876. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  145877. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  145878. }
  145879. }
  145880. #endif
  145881. }
  145882. }
  145883. /*
  145884. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  145885. */
  145886. static int splitNodeStartree(
  145887. Rtree *pRtree,
  145888. RtreeCell *aCell,
  145889. int nCell,
  145890. RtreeNode *pLeft,
  145891. RtreeNode *pRight,
  145892. RtreeCell *pBboxLeft,
  145893. RtreeCell *pBboxRight
  145894. ){
  145895. int **aaSorted;
  145896. int *aSpare;
  145897. int ii;
  145898. int iBestDim = 0;
  145899. int iBestSplit = 0;
  145900. RtreeDValue fBestMargin = RTREE_ZERO;
  145901. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  145902. aaSorted = (int **)sqlite3_malloc(nByte);
  145903. if( !aaSorted ){
  145904. return SQLITE_NOMEM;
  145905. }
  145906. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  145907. memset(aaSorted, 0, nByte);
  145908. for(ii=0; ii<pRtree->nDim; ii++){
  145909. int jj;
  145910. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  145911. for(jj=0; jj<nCell; jj++){
  145912. aaSorted[ii][jj] = jj;
  145913. }
  145914. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  145915. }
  145916. for(ii=0; ii<pRtree->nDim; ii++){
  145917. RtreeDValue margin = RTREE_ZERO;
  145918. RtreeDValue fBestOverlap = RTREE_ZERO;
  145919. RtreeDValue fBestArea = RTREE_ZERO;
  145920. int iBestLeft = 0;
  145921. int nLeft;
  145922. for(
  145923. nLeft=RTREE_MINCELLS(pRtree);
  145924. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  145925. nLeft++
  145926. ){
  145927. RtreeCell left;
  145928. RtreeCell right;
  145929. int kk;
  145930. RtreeDValue overlap;
  145931. RtreeDValue area;
  145932. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  145933. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  145934. for(kk=1; kk<(nCell-1); kk++){
  145935. if( kk<nLeft ){
  145936. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  145937. }else{
  145938. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  145939. }
  145940. }
  145941. margin += cellMargin(pRtree, &left);
  145942. margin += cellMargin(pRtree, &right);
  145943. overlap = cellOverlap(pRtree, &left, &right, 1);
  145944. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  145945. if( (nLeft==RTREE_MINCELLS(pRtree))
  145946. || (overlap<fBestOverlap)
  145947. || (overlap==fBestOverlap && area<fBestArea)
  145948. ){
  145949. iBestLeft = nLeft;
  145950. fBestOverlap = overlap;
  145951. fBestArea = area;
  145952. }
  145953. }
  145954. if( ii==0 || margin<fBestMargin ){
  145955. iBestDim = ii;
  145956. fBestMargin = margin;
  145957. iBestSplit = iBestLeft;
  145958. }
  145959. }
  145960. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  145961. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  145962. for(ii=0; ii<nCell; ii++){
  145963. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  145964. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  145965. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  145966. nodeInsertCell(pRtree, pTarget, pCell);
  145967. cellUnion(pRtree, pBbox, pCell);
  145968. }
  145969. sqlite3_free(aaSorted);
  145970. return SQLITE_OK;
  145971. }
  145972. static int updateMapping(
  145973. Rtree *pRtree,
  145974. i64 iRowid,
  145975. RtreeNode *pNode,
  145976. int iHeight
  145977. ){
  145978. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  145979. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  145980. if( iHeight>0 ){
  145981. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  145982. if( pChild ){
  145983. nodeRelease(pRtree, pChild->pParent);
  145984. nodeReference(pNode);
  145985. pChild->pParent = pNode;
  145986. }
  145987. }
  145988. return xSetMapping(pRtree, iRowid, pNode->iNode);
  145989. }
  145990. static int SplitNode(
  145991. Rtree *pRtree,
  145992. RtreeNode *pNode,
  145993. RtreeCell *pCell,
  145994. int iHeight
  145995. ){
  145996. int i;
  145997. int newCellIsRight = 0;
  145998. int rc = SQLITE_OK;
  145999. int nCell = NCELL(pNode);
  146000. RtreeCell *aCell;
  146001. int *aiUsed;
  146002. RtreeNode *pLeft = 0;
  146003. RtreeNode *pRight = 0;
  146004. RtreeCell leftbbox;
  146005. RtreeCell rightbbox;
  146006. /* Allocate an array and populate it with a copy of pCell and
  146007. ** all cells from node pLeft. Then zero the original node.
  146008. */
  146009. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  146010. if( !aCell ){
  146011. rc = SQLITE_NOMEM;
  146012. goto splitnode_out;
  146013. }
  146014. aiUsed = (int *)&aCell[nCell+1];
  146015. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  146016. for(i=0; i<nCell; i++){
  146017. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  146018. }
  146019. nodeZero(pRtree, pNode);
  146020. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  146021. nCell++;
  146022. if( pNode->iNode==1 ){
  146023. pRight = nodeNew(pRtree, pNode);
  146024. pLeft = nodeNew(pRtree, pNode);
  146025. pRtree->iDepth++;
  146026. pNode->isDirty = 1;
  146027. writeInt16(pNode->zData, pRtree->iDepth);
  146028. }else{
  146029. pLeft = pNode;
  146030. pRight = nodeNew(pRtree, pLeft->pParent);
  146031. nodeReference(pLeft);
  146032. }
  146033. if( !pLeft || !pRight ){
  146034. rc = SQLITE_NOMEM;
  146035. goto splitnode_out;
  146036. }
  146037. memset(pLeft->zData, 0, pRtree->iNodeSize);
  146038. memset(pRight->zData, 0, pRtree->iNodeSize);
  146039. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  146040. &leftbbox, &rightbbox);
  146041. if( rc!=SQLITE_OK ){
  146042. goto splitnode_out;
  146043. }
  146044. /* Ensure both child nodes have node numbers assigned to them by calling
  146045. ** nodeWrite(). Node pRight always needs a node number, as it was created
  146046. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  146047. ** In this case avoid the all to nodeWrite().
  146048. */
  146049. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  146050. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  146051. ){
  146052. goto splitnode_out;
  146053. }
  146054. rightbbox.iRowid = pRight->iNode;
  146055. leftbbox.iRowid = pLeft->iNode;
  146056. if( pNode->iNode==1 ){
  146057. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  146058. if( rc!=SQLITE_OK ){
  146059. goto splitnode_out;
  146060. }
  146061. }else{
  146062. RtreeNode *pParent = pLeft->pParent;
  146063. int iCell;
  146064. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  146065. if( rc==SQLITE_OK ){
  146066. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  146067. rc = AdjustTree(pRtree, pParent, &leftbbox);
  146068. }
  146069. if( rc!=SQLITE_OK ){
  146070. goto splitnode_out;
  146071. }
  146072. }
  146073. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  146074. goto splitnode_out;
  146075. }
  146076. for(i=0; i<NCELL(pRight); i++){
  146077. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  146078. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  146079. if( iRowid==pCell->iRowid ){
  146080. newCellIsRight = 1;
  146081. }
  146082. if( rc!=SQLITE_OK ){
  146083. goto splitnode_out;
  146084. }
  146085. }
  146086. if( pNode->iNode==1 ){
  146087. for(i=0; i<NCELL(pLeft); i++){
  146088. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  146089. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  146090. if( rc!=SQLITE_OK ){
  146091. goto splitnode_out;
  146092. }
  146093. }
  146094. }else if( newCellIsRight==0 ){
  146095. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  146096. }
  146097. if( rc==SQLITE_OK ){
  146098. rc = nodeRelease(pRtree, pRight);
  146099. pRight = 0;
  146100. }
  146101. if( rc==SQLITE_OK ){
  146102. rc = nodeRelease(pRtree, pLeft);
  146103. pLeft = 0;
  146104. }
  146105. splitnode_out:
  146106. nodeRelease(pRtree, pRight);
  146107. nodeRelease(pRtree, pLeft);
  146108. sqlite3_free(aCell);
  146109. return rc;
  146110. }
  146111. /*
  146112. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  146113. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  146114. ** the pLeaf->pParent chain all the way up to the root node.
  146115. **
  146116. ** This operation is required when a row is deleted (or updated - an update
  146117. ** is implemented as a delete followed by an insert). SQLite provides the
  146118. ** rowid of the row to delete, which can be used to find the leaf on which
  146119. ** the entry resides (argument pLeaf). Once the leaf is located, this
  146120. ** function is called to determine its ancestry.
  146121. */
  146122. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  146123. int rc = SQLITE_OK;
  146124. RtreeNode *pChild = pLeaf;
  146125. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  146126. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  146127. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  146128. rc = sqlite3_step(pRtree->pReadParent);
  146129. if( rc==SQLITE_ROW ){
  146130. RtreeNode *pTest; /* Used to test for reference loops */
  146131. i64 iNode; /* Node number of parent node */
  146132. /* Before setting pChild->pParent, test that we are not creating a
  146133. ** loop of references (as we would if, say, pChild==pParent). We don't
  146134. ** want to do this as it leads to a memory leak when trying to delete
  146135. ** the referenced counted node structures.
  146136. */
  146137. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  146138. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  146139. if( !pTest ){
  146140. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  146141. }
  146142. }
  146143. rc = sqlite3_reset(pRtree->pReadParent);
  146144. if( rc==SQLITE_OK ) rc = rc2;
  146145. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  146146. pChild = pChild->pParent;
  146147. }
  146148. return rc;
  146149. }
  146150. static int deleteCell(Rtree *, RtreeNode *, int, int);
  146151. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  146152. int rc;
  146153. int rc2;
  146154. RtreeNode *pParent = 0;
  146155. int iCell;
  146156. assert( pNode->nRef==1 );
  146157. /* Remove the entry in the parent cell. */
  146158. rc = nodeParentIndex(pRtree, pNode, &iCell);
  146159. if( rc==SQLITE_OK ){
  146160. pParent = pNode->pParent;
  146161. pNode->pParent = 0;
  146162. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  146163. }
  146164. rc2 = nodeRelease(pRtree, pParent);
  146165. if( rc==SQLITE_OK ){
  146166. rc = rc2;
  146167. }
  146168. if( rc!=SQLITE_OK ){
  146169. return rc;
  146170. }
  146171. /* Remove the xxx_node entry. */
  146172. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  146173. sqlite3_step(pRtree->pDeleteNode);
  146174. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  146175. return rc;
  146176. }
  146177. /* Remove the xxx_parent entry. */
  146178. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  146179. sqlite3_step(pRtree->pDeleteParent);
  146180. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  146181. return rc;
  146182. }
  146183. /* Remove the node from the in-memory hash table and link it into
  146184. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  146185. */
  146186. nodeHashDelete(pRtree, pNode);
  146187. pNode->iNode = iHeight;
  146188. pNode->pNext = pRtree->pDeleted;
  146189. pNode->nRef++;
  146190. pRtree->pDeleted = pNode;
  146191. return SQLITE_OK;
  146192. }
  146193. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  146194. RtreeNode *pParent = pNode->pParent;
  146195. int rc = SQLITE_OK;
  146196. if( pParent ){
  146197. int ii;
  146198. int nCell = NCELL(pNode);
  146199. RtreeCell box; /* Bounding box for pNode */
  146200. nodeGetCell(pRtree, pNode, 0, &box);
  146201. for(ii=1; ii<nCell; ii++){
  146202. RtreeCell cell;
  146203. nodeGetCell(pRtree, pNode, ii, &cell);
  146204. cellUnion(pRtree, &box, &cell);
  146205. }
  146206. box.iRowid = pNode->iNode;
  146207. rc = nodeParentIndex(pRtree, pNode, &ii);
  146208. if( rc==SQLITE_OK ){
  146209. nodeOverwriteCell(pRtree, pParent, &box, ii);
  146210. rc = fixBoundingBox(pRtree, pParent);
  146211. }
  146212. }
  146213. return rc;
  146214. }
  146215. /*
  146216. ** Delete the cell at index iCell of node pNode. After removing the
  146217. ** cell, adjust the r-tree data structure if required.
  146218. */
  146219. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  146220. RtreeNode *pParent;
  146221. int rc;
  146222. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  146223. return rc;
  146224. }
  146225. /* Remove the cell from the node. This call just moves bytes around
  146226. ** the in-memory node image, so it cannot fail.
  146227. */
  146228. nodeDeleteCell(pRtree, pNode, iCell);
  146229. /* If the node is not the tree root and now has less than the minimum
  146230. ** number of cells, remove it from the tree. Otherwise, update the
  146231. ** cell in the parent node so that it tightly contains the updated
  146232. ** node.
  146233. */
  146234. pParent = pNode->pParent;
  146235. assert( pParent || pNode->iNode==1 );
  146236. if( pParent ){
  146237. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  146238. rc = removeNode(pRtree, pNode, iHeight);
  146239. }else{
  146240. rc = fixBoundingBox(pRtree, pNode);
  146241. }
  146242. }
  146243. return rc;
  146244. }
  146245. static int Reinsert(
  146246. Rtree *pRtree,
  146247. RtreeNode *pNode,
  146248. RtreeCell *pCell,
  146249. int iHeight
  146250. ){
  146251. int *aOrder;
  146252. int *aSpare;
  146253. RtreeCell *aCell;
  146254. RtreeDValue *aDistance;
  146255. int nCell;
  146256. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  146257. int iDim;
  146258. int ii;
  146259. int rc = SQLITE_OK;
  146260. int n;
  146261. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  146262. nCell = NCELL(pNode)+1;
  146263. n = (nCell+1)&(~1);
  146264. /* Allocate the buffers used by this operation. The allocation is
  146265. ** relinquished before this function returns.
  146266. */
  146267. aCell = (RtreeCell *)sqlite3_malloc(n * (
  146268. sizeof(RtreeCell) + /* aCell array */
  146269. sizeof(int) + /* aOrder array */
  146270. sizeof(int) + /* aSpare array */
  146271. sizeof(RtreeDValue) /* aDistance array */
  146272. ));
  146273. if( !aCell ){
  146274. return SQLITE_NOMEM;
  146275. }
  146276. aOrder = (int *)&aCell[n];
  146277. aSpare = (int *)&aOrder[n];
  146278. aDistance = (RtreeDValue *)&aSpare[n];
  146279. for(ii=0; ii<nCell; ii++){
  146280. if( ii==(nCell-1) ){
  146281. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  146282. }else{
  146283. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  146284. }
  146285. aOrder[ii] = ii;
  146286. for(iDim=0; iDim<pRtree->nDim; iDim++){
  146287. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  146288. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  146289. }
  146290. }
  146291. for(iDim=0; iDim<pRtree->nDim; iDim++){
  146292. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  146293. }
  146294. for(ii=0; ii<nCell; ii++){
  146295. aDistance[ii] = RTREE_ZERO;
  146296. for(iDim=0; iDim<pRtree->nDim; iDim++){
  146297. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  146298. DCOORD(aCell[ii].aCoord[iDim*2]));
  146299. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  146300. }
  146301. }
  146302. SortByDistance(aOrder, nCell, aDistance, aSpare);
  146303. nodeZero(pRtree, pNode);
  146304. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  146305. RtreeCell *p = &aCell[aOrder[ii]];
  146306. nodeInsertCell(pRtree, pNode, p);
  146307. if( p->iRowid==pCell->iRowid ){
  146308. if( iHeight==0 ){
  146309. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  146310. }else{
  146311. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  146312. }
  146313. }
  146314. }
  146315. if( rc==SQLITE_OK ){
  146316. rc = fixBoundingBox(pRtree, pNode);
  146317. }
  146318. for(; rc==SQLITE_OK && ii<nCell; ii++){
  146319. /* Find a node to store this cell in. pNode->iNode currently contains
  146320. ** the height of the sub-tree headed by the cell.
  146321. */
  146322. RtreeNode *pInsert;
  146323. RtreeCell *p = &aCell[aOrder[ii]];
  146324. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  146325. if( rc==SQLITE_OK ){
  146326. int rc2;
  146327. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  146328. rc2 = nodeRelease(pRtree, pInsert);
  146329. if( rc==SQLITE_OK ){
  146330. rc = rc2;
  146331. }
  146332. }
  146333. }
  146334. sqlite3_free(aCell);
  146335. return rc;
  146336. }
  146337. /*
  146338. ** Insert cell pCell into node pNode. Node pNode is the head of a
  146339. ** subtree iHeight high (leaf nodes have iHeight==0).
  146340. */
  146341. static int rtreeInsertCell(
  146342. Rtree *pRtree,
  146343. RtreeNode *pNode,
  146344. RtreeCell *pCell,
  146345. int iHeight
  146346. ){
  146347. int rc = SQLITE_OK;
  146348. if( iHeight>0 ){
  146349. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  146350. if( pChild ){
  146351. nodeRelease(pRtree, pChild->pParent);
  146352. nodeReference(pNode);
  146353. pChild->pParent = pNode;
  146354. }
  146355. }
  146356. if( nodeInsertCell(pRtree, pNode, pCell) ){
  146357. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  146358. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  146359. }else{
  146360. pRtree->iReinsertHeight = iHeight;
  146361. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  146362. }
  146363. }else{
  146364. rc = AdjustTree(pRtree, pNode, pCell);
  146365. if( rc==SQLITE_OK ){
  146366. if( iHeight==0 ){
  146367. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  146368. }else{
  146369. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  146370. }
  146371. }
  146372. }
  146373. return rc;
  146374. }
  146375. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  146376. int ii;
  146377. int rc = SQLITE_OK;
  146378. int nCell = NCELL(pNode);
  146379. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  146380. RtreeNode *pInsert;
  146381. RtreeCell cell;
  146382. nodeGetCell(pRtree, pNode, ii, &cell);
  146383. /* Find a node to store this cell in. pNode->iNode currently contains
  146384. ** the height of the sub-tree headed by the cell.
  146385. */
  146386. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  146387. if( rc==SQLITE_OK ){
  146388. int rc2;
  146389. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  146390. rc2 = nodeRelease(pRtree, pInsert);
  146391. if( rc==SQLITE_OK ){
  146392. rc = rc2;
  146393. }
  146394. }
  146395. }
  146396. return rc;
  146397. }
  146398. /*
  146399. ** Select a currently unused rowid for a new r-tree record.
  146400. */
  146401. static int newRowid(Rtree *pRtree, i64 *piRowid){
  146402. int rc;
  146403. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  146404. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  146405. sqlite3_step(pRtree->pWriteRowid);
  146406. rc = sqlite3_reset(pRtree->pWriteRowid);
  146407. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  146408. return rc;
  146409. }
  146410. /*
  146411. ** Remove the entry with rowid=iDelete from the r-tree structure.
  146412. */
  146413. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  146414. int rc; /* Return code */
  146415. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  146416. int iCell; /* Index of iDelete cell in pLeaf */
  146417. RtreeNode *pRoot; /* Root node of rtree structure */
  146418. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  146419. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  146420. /* Obtain a reference to the leaf node that contains the entry
  146421. ** about to be deleted.
  146422. */
  146423. if( rc==SQLITE_OK ){
  146424. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  146425. }
  146426. /* Delete the cell in question from the leaf node. */
  146427. if( rc==SQLITE_OK ){
  146428. int rc2;
  146429. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  146430. if( rc==SQLITE_OK ){
  146431. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  146432. }
  146433. rc2 = nodeRelease(pRtree, pLeaf);
  146434. if( rc==SQLITE_OK ){
  146435. rc = rc2;
  146436. }
  146437. }
  146438. /* Delete the corresponding entry in the <rtree>_rowid table. */
  146439. if( rc==SQLITE_OK ){
  146440. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  146441. sqlite3_step(pRtree->pDeleteRowid);
  146442. rc = sqlite3_reset(pRtree->pDeleteRowid);
  146443. }
  146444. /* Check if the root node now has exactly one child. If so, remove
  146445. ** it, schedule the contents of the child for reinsertion and
  146446. ** reduce the tree height by one.
  146447. **
  146448. ** This is equivalent to copying the contents of the child into
  146449. ** the root node (the operation that Gutman's paper says to perform
  146450. ** in this scenario).
  146451. */
  146452. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  146453. int rc2;
  146454. RtreeNode *pChild;
  146455. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  146456. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  146457. if( rc==SQLITE_OK ){
  146458. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  146459. }
  146460. rc2 = nodeRelease(pRtree, pChild);
  146461. if( rc==SQLITE_OK ) rc = rc2;
  146462. if( rc==SQLITE_OK ){
  146463. pRtree->iDepth--;
  146464. writeInt16(pRoot->zData, pRtree->iDepth);
  146465. pRoot->isDirty = 1;
  146466. }
  146467. }
  146468. /* Re-insert the contents of any underfull nodes removed from the tree. */
  146469. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  146470. if( rc==SQLITE_OK ){
  146471. rc = reinsertNodeContent(pRtree, pLeaf);
  146472. }
  146473. pRtree->pDeleted = pLeaf->pNext;
  146474. sqlite3_free(pLeaf);
  146475. }
  146476. /* Release the reference to the root node. */
  146477. if( rc==SQLITE_OK ){
  146478. rc = nodeRelease(pRtree, pRoot);
  146479. }else{
  146480. nodeRelease(pRtree, pRoot);
  146481. }
  146482. return rc;
  146483. }
  146484. /*
  146485. ** Rounding constants for float->double conversion.
  146486. */
  146487. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  146488. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  146489. #if !defined(SQLITE_RTREE_INT_ONLY)
  146490. /*
  146491. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  146492. ** while taking care to round toward negative or positive, respectively.
  146493. */
  146494. static RtreeValue rtreeValueDown(sqlite3_value *v){
  146495. double d = sqlite3_value_double(v);
  146496. float f = (float)d;
  146497. if( f>d ){
  146498. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  146499. }
  146500. return f;
  146501. }
  146502. static RtreeValue rtreeValueUp(sqlite3_value *v){
  146503. double d = sqlite3_value_double(v);
  146504. float f = (float)d;
  146505. if( f<d ){
  146506. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  146507. }
  146508. return f;
  146509. }
  146510. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  146511. /*
  146512. ** The xUpdate method for rtree module virtual tables.
  146513. */
  146514. static int rtreeUpdate(
  146515. sqlite3_vtab *pVtab,
  146516. int nData,
  146517. sqlite3_value **azData,
  146518. sqlite_int64 *pRowid
  146519. ){
  146520. Rtree *pRtree = (Rtree *)pVtab;
  146521. int rc = SQLITE_OK;
  146522. RtreeCell cell; /* New cell to insert if nData>1 */
  146523. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  146524. rtreeReference(pRtree);
  146525. assert(nData>=1);
  146526. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  146527. /* Constraint handling. A write operation on an r-tree table may return
  146528. ** SQLITE_CONSTRAINT for two reasons:
  146529. **
  146530. ** 1. A duplicate rowid value, or
  146531. ** 2. The supplied data violates the "x2>=x1" constraint.
  146532. **
  146533. ** In the first case, if the conflict-handling mode is REPLACE, then
  146534. ** the conflicting row can be removed before proceeding. In the second
  146535. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  146536. ** conflict-handling mode specified by the user.
  146537. */
  146538. if( nData>1 ){
  146539. int ii;
  146540. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  146541. **
  146542. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  146543. ** with "column" that are interpreted as table constraints.
  146544. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  146545. ** This problem was discovered after years of use, so we silently ignore
  146546. ** these kinds of misdeclared tables to avoid breaking any legacy.
  146547. */
  146548. assert( nData<=(pRtree->nDim*2 + 3) );
  146549. #ifndef SQLITE_RTREE_INT_ONLY
  146550. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  146551. for(ii=0; ii<nData-4; ii+=2){
  146552. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  146553. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  146554. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  146555. rc = SQLITE_CONSTRAINT;
  146556. goto constraint;
  146557. }
  146558. }
  146559. }else
  146560. #endif
  146561. {
  146562. for(ii=0; ii<nData-4; ii+=2){
  146563. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  146564. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  146565. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  146566. rc = SQLITE_CONSTRAINT;
  146567. goto constraint;
  146568. }
  146569. }
  146570. }
  146571. /* If a rowid value was supplied, check if it is already present in
  146572. ** the table. If so, the constraint has failed. */
  146573. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  146574. cell.iRowid = sqlite3_value_int64(azData[2]);
  146575. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  146576. || sqlite3_value_int64(azData[0])!=cell.iRowid
  146577. ){
  146578. int steprc;
  146579. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  146580. steprc = sqlite3_step(pRtree->pReadRowid);
  146581. rc = sqlite3_reset(pRtree->pReadRowid);
  146582. if( SQLITE_ROW==steprc ){
  146583. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  146584. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  146585. }else{
  146586. rc = SQLITE_CONSTRAINT;
  146587. goto constraint;
  146588. }
  146589. }
  146590. }
  146591. bHaveRowid = 1;
  146592. }
  146593. }
  146594. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  146595. ** record to delete from the r-tree table. The following block does
  146596. ** just that.
  146597. */
  146598. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  146599. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  146600. }
  146601. /* If the azData[] array contains more than one element, elements
  146602. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  146603. ** the r-tree structure.
  146604. */
  146605. if( rc==SQLITE_OK && nData>1 ){
  146606. /* Insert the new record into the r-tree */
  146607. RtreeNode *pLeaf = 0;
  146608. /* Figure out the rowid of the new row. */
  146609. if( bHaveRowid==0 ){
  146610. rc = newRowid(pRtree, &cell.iRowid);
  146611. }
  146612. *pRowid = cell.iRowid;
  146613. if( rc==SQLITE_OK ){
  146614. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  146615. }
  146616. if( rc==SQLITE_OK ){
  146617. int rc2;
  146618. pRtree->iReinsertHeight = -1;
  146619. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  146620. rc2 = nodeRelease(pRtree, pLeaf);
  146621. if( rc==SQLITE_OK ){
  146622. rc = rc2;
  146623. }
  146624. }
  146625. }
  146626. constraint:
  146627. rtreeRelease(pRtree);
  146628. return rc;
  146629. }
  146630. /*
  146631. ** The xRename method for rtree module virtual tables.
  146632. */
  146633. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  146634. Rtree *pRtree = (Rtree *)pVtab;
  146635. int rc = SQLITE_NOMEM;
  146636. char *zSql = sqlite3_mprintf(
  146637. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  146638. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  146639. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  146640. , pRtree->zDb, pRtree->zName, zNewName
  146641. , pRtree->zDb, pRtree->zName, zNewName
  146642. , pRtree->zDb, pRtree->zName, zNewName
  146643. );
  146644. if( zSql ){
  146645. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  146646. sqlite3_free(zSql);
  146647. }
  146648. return rc;
  146649. }
  146650. /*
  146651. ** This function populates the pRtree->nRowEst variable with an estimate
  146652. ** of the number of rows in the virtual table. If possible, this is based
  146653. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  146654. */
  146655. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  146656. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  146657. char *zSql;
  146658. sqlite3_stmt *p;
  146659. int rc;
  146660. i64 nRow = 0;
  146661. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  146662. if( zSql==0 ){
  146663. rc = SQLITE_NOMEM;
  146664. }else{
  146665. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  146666. if( rc==SQLITE_OK ){
  146667. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  146668. rc = sqlite3_finalize(p);
  146669. }else if( rc!=SQLITE_NOMEM ){
  146670. rc = SQLITE_OK;
  146671. }
  146672. if( rc==SQLITE_OK ){
  146673. if( nRow==0 ){
  146674. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  146675. }else{
  146676. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  146677. }
  146678. }
  146679. sqlite3_free(zSql);
  146680. }
  146681. return rc;
  146682. }
  146683. static sqlite3_module rtreeModule = {
  146684. 0, /* iVersion */
  146685. rtreeCreate, /* xCreate - create a table */
  146686. rtreeConnect, /* xConnect - connect to an existing table */
  146687. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  146688. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  146689. rtreeDestroy, /* xDestroy - Drop a table */
  146690. rtreeOpen, /* xOpen - open a cursor */
  146691. rtreeClose, /* xClose - close a cursor */
  146692. rtreeFilter, /* xFilter - configure scan constraints */
  146693. rtreeNext, /* xNext - advance a cursor */
  146694. rtreeEof, /* xEof */
  146695. rtreeColumn, /* xColumn - read data */
  146696. rtreeRowid, /* xRowid - read data */
  146697. rtreeUpdate, /* xUpdate - write data */
  146698. 0, /* xBegin - begin transaction */
  146699. 0, /* xSync - sync transaction */
  146700. 0, /* xCommit - commit transaction */
  146701. 0, /* xRollback - rollback transaction */
  146702. 0, /* xFindFunction - function overloading */
  146703. rtreeRename, /* xRename - rename the table */
  146704. 0, /* xSavepoint */
  146705. 0, /* xRelease */
  146706. 0 /* xRollbackTo */
  146707. };
  146708. static int rtreeSqlInit(
  146709. Rtree *pRtree,
  146710. sqlite3 *db,
  146711. const char *zDb,
  146712. const char *zPrefix,
  146713. int isCreate
  146714. ){
  146715. int rc = SQLITE_OK;
  146716. #define N_STATEMENT 9
  146717. static const char *azSql[N_STATEMENT] = {
  146718. /* Read and write the xxx_node table */
  146719. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  146720. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  146721. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  146722. /* Read and write the xxx_rowid table */
  146723. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  146724. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  146725. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  146726. /* Read and write the xxx_parent table */
  146727. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  146728. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  146729. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  146730. };
  146731. sqlite3_stmt **appStmt[N_STATEMENT];
  146732. int i;
  146733. pRtree->db = db;
  146734. if( isCreate ){
  146735. char *zCreate = sqlite3_mprintf(
  146736. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  146737. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  146738. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  146739. " parentnode INTEGER);"
  146740. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  146741. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  146742. );
  146743. if( !zCreate ){
  146744. return SQLITE_NOMEM;
  146745. }
  146746. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  146747. sqlite3_free(zCreate);
  146748. if( rc!=SQLITE_OK ){
  146749. return rc;
  146750. }
  146751. }
  146752. appStmt[0] = &pRtree->pReadNode;
  146753. appStmt[1] = &pRtree->pWriteNode;
  146754. appStmt[2] = &pRtree->pDeleteNode;
  146755. appStmt[3] = &pRtree->pReadRowid;
  146756. appStmt[4] = &pRtree->pWriteRowid;
  146757. appStmt[5] = &pRtree->pDeleteRowid;
  146758. appStmt[6] = &pRtree->pReadParent;
  146759. appStmt[7] = &pRtree->pWriteParent;
  146760. appStmt[8] = &pRtree->pDeleteParent;
  146761. rc = rtreeQueryStat1(db, pRtree);
  146762. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  146763. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  146764. if( zSql ){
  146765. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  146766. }else{
  146767. rc = SQLITE_NOMEM;
  146768. }
  146769. sqlite3_free(zSql);
  146770. }
  146771. return rc;
  146772. }
  146773. /*
  146774. ** The second argument to this function contains the text of an SQL statement
  146775. ** that returns a single integer value. The statement is compiled and executed
  146776. ** using database connection db. If successful, the integer value returned
  146777. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  146778. ** code is returned and the value of *piVal after returning is not defined.
  146779. */
  146780. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  146781. int rc = SQLITE_NOMEM;
  146782. if( zSql ){
  146783. sqlite3_stmt *pStmt = 0;
  146784. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  146785. if( rc==SQLITE_OK ){
  146786. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  146787. *piVal = sqlite3_column_int(pStmt, 0);
  146788. }
  146789. rc = sqlite3_finalize(pStmt);
  146790. }
  146791. }
  146792. return rc;
  146793. }
  146794. /*
  146795. ** This function is called from within the xConnect() or xCreate() method to
  146796. ** determine the node-size used by the rtree table being created or connected
  146797. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  146798. ** Otherwise, an SQLite error code is returned.
  146799. **
  146800. ** If this function is being called as part of an xConnect(), then the rtree
  146801. ** table already exists. In this case the node-size is determined by inspecting
  146802. ** the root node of the tree.
  146803. **
  146804. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  146805. ** This ensures that each node is stored on a single database page. If the
  146806. ** database page-size is so large that more than RTREE_MAXCELLS entries
  146807. ** would fit in a single node, use a smaller node-size.
  146808. */
  146809. static int getNodeSize(
  146810. sqlite3 *db, /* Database handle */
  146811. Rtree *pRtree, /* Rtree handle */
  146812. int isCreate, /* True for xCreate, false for xConnect */
  146813. char **pzErr /* OUT: Error message, if any */
  146814. ){
  146815. int rc;
  146816. char *zSql;
  146817. if( isCreate ){
  146818. int iPageSize = 0;
  146819. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  146820. rc = getIntFromStmt(db, zSql, &iPageSize);
  146821. if( rc==SQLITE_OK ){
  146822. pRtree->iNodeSize = iPageSize-64;
  146823. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  146824. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  146825. }
  146826. }else{
  146827. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  146828. }
  146829. }else{
  146830. zSql = sqlite3_mprintf(
  146831. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  146832. pRtree->zDb, pRtree->zName
  146833. );
  146834. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  146835. if( rc!=SQLITE_OK ){
  146836. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  146837. }
  146838. }
  146839. sqlite3_free(zSql);
  146840. return rc;
  146841. }
  146842. /*
  146843. ** This function is the implementation of both the xConnect and xCreate
  146844. ** methods of the r-tree virtual table.
  146845. **
  146846. ** argv[0] -> module name
  146847. ** argv[1] -> database name
  146848. ** argv[2] -> table name
  146849. ** argv[...] -> column names...
  146850. */
  146851. static int rtreeInit(
  146852. sqlite3 *db, /* Database connection */
  146853. void *pAux, /* One of the RTREE_COORD_* constants */
  146854. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  146855. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  146856. char **pzErr, /* OUT: Error message, if any */
  146857. int isCreate /* True for xCreate, false for xConnect */
  146858. ){
  146859. int rc = SQLITE_OK;
  146860. Rtree *pRtree;
  146861. int nDb; /* Length of string argv[1] */
  146862. int nName; /* Length of string argv[2] */
  146863. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  146864. const char *aErrMsg[] = {
  146865. 0, /* 0 */
  146866. "Wrong number of columns for an rtree table", /* 1 */
  146867. "Too few columns for an rtree table", /* 2 */
  146868. "Too many columns for an rtree table" /* 3 */
  146869. };
  146870. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  146871. if( aErrMsg[iErr] ){
  146872. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  146873. return SQLITE_ERROR;
  146874. }
  146875. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  146876. /* Allocate the sqlite3_vtab structure */
  146877. nDb = (int)strlen(argv[1]);
  146878. nName = (int)strlen(argv[2]);
  146879. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  146880. if( !pRtree ){
  146881. return SQLITE_NOMEM;
  146882. }
  146883. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  146884. pRtree->nBusy = 1;
  146885. pRtree->base.pModule = &rtreeModule;
  146886. pRtree->zDb = (char *)&pRtree[1];
  146887. pRtree->zName = &pRtree->zDb[nDb+1];
  146888. pRtree->nDim = (argc-4)/2;
  146889. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  146890. pRtree->eCoordType = eCoordType;
  146891. memcpy(pRtree->zDb, argv[1], nDb);
  146892. memcpy(pRtree->zName, argv[2], nName);
  146893. /* Figure out the node size to use. */
  146894. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  146895. /* Create/Connect to the underlying relational database schema. If
  146896. ** that is successful, call sqlite3_declare_vtab() to configure
  146897. ** the r-tree table schema.
  146898. */
  146899. if( rc==SQLITE_OK ){
  146900. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  146901. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  146902. }else{
  146903. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  146904. char *zTmp;
  146905. int ii;
  146906. for(ii=4; zSql && ii<argc; ii++){
  146907. zTmp = zSql;
  146908. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  146909. sqlite3_free(zTmp);
  146910. }
  146911. if( zSql ){
  146912. zTmp = zSql;
  146913. zSql = sqlite3_mprintf("%s);", zTmp);
  146914. sqlite3_free(zTmp);
  146915. }
  146916. if( !zSql ){
  146917. rc = SQLITE_NOMEM;
  146918. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  146919. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  146920. }
  146921. sqlite3_free(zSql);
  146922. }
  146923. }
  146924. if( rc==SQLITE_OK ){
  146925. *ppVtab = (sqlite3_vtab *)pRtree;
  146926. }else{
  146927. assert( *ppVtab==0 );
  146928. assert( pRtree->nBusy==1 );
  146929. rtreeRelease(pRtree);
  146930. }
  146931. return rc;
  146932. }
  146933. /*
  146934. ** Implementation of a scalar function that decodes r-tree nodes to
  146935. ** human readable strings. This can be used for debugging and analysis.
  146936. **
  146937. ** The scalar function takes two arguments: (1) the number of dimensions
  146938. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  146939. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  146940. ** deserialize all nodes, a statement like:
  146941. **
  146942. ** SELECT rtreenode(2, data) FROM rt_node;
  146943. **
  146944. ** The human readable string takes the form of a Tcl list with one
  146945. ** entry for each cell in the r-tree node. Each entry is itself a
  146946. ** list, containing the 8-byte rowid/pageno followed by the
  146947. ** <num-dimension>*2 coordinates.
  146948. */
  146949. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  146950. char *zText = 0;
  146951. RtreeNode node;
  146952. Rtree tree;
  146953. int ii;
  146954. UNUSED_PARAMETER(nArg);
  146955. memset(&node, 0, sizeof(RtreeNode));
  146956. memset(&tree, 0, sizeof(Rtree));
  146957. tree.nDim = sqlite3_value_int(apArg[0]);
  146958. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  146959. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  146960. for(ii=0; ii<NCELL(&node); ii++){
  146961. char zCell[512];
  146962. int nCell = 0;
  146963. RtreeCell cell;
  146964. int jj;
  146965. nodeGetCell(&tree, &node, ii, &cell);
  146966. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  146967. nCell = (int)strlen(zCell);
  146968. for(jj=0; jj<tree.nDim*2; jj++){
  146969. #ifndef SQLITE_RTREE_INT_ONLY
  146970. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  146971. (double)cell.aCoord[jj].f);
  146972. #else
  146973. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  146974. cell.aCoord[jj].i);
  146975. #endif
  146976. nCell = (int)strlen(zCell);
  146977. }
  146978. if( zText ){
  146979. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  146980. sqlite3_free(zText);
  146981. zText = zTextNew;
  146982. }else{
  146983. zText = sqlite3_mprintf("{%s}", zCell);
  146984. }
  146985. }
  146986. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  146987. }
  146988. /* This routine implements an SQL function that returns the "depth" parameter
  146989. ** from the front of a blob that is an r-tree node. For example:
  146990. **
  146991. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  146992. **
  146993. ** The depth value is 0 for all nodes other than the root node, and the root
  146994. ** node always has nodeno=1, so the example above is the primary use for this
  146995. ** routine. This routine is intended for testing and analysis only.
  146996. */
  146997. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  146998. UNUSED_PARAMETER(nArg);
  146999. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  147000. || sqlite3_value_bytes(apArg[0])<2
  147001. ){
  147002. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  147003. }else{
  147004. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  147005. sqlite3_result_int(ctx, readInt16(zBlob));
  147006. }
  147007. }
  147008. /*
  147009. ** Register the r-tree module with database handle db. This creates the
  147010. ** virtual table module "rtree" and the debugging/analysis scalar
  147011. ** function "rtreenode".
  147012. */
  147013. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  147014. const int utf8 = SQLITE_UTF8;
  147015. int rc;
  147016. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  147017. if( rc==SQLITE_OK ){
  147018. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  147019. }
  147020. if( rc==SQLITE_OK ){
  147021. #ifdef SQLITE_RTREE_INT_ONLY
  147022. void *c = (void *)RTREE_COORD_INT32;
  147023. #else
  147024. void *c = (void *)RTREE_COORD_REAL32;
  147025. #endif
  147026. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  147027. }
  147028. if( rc==SQLITE_OK ){
  147029. void *c = (void *)RTREE_COORD_INT32;
  147030. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  147031. }
  147032. return rc;
  147033. }
  147034. /*
  147035. ** This routine deletes the RtreeGeomCallback object that was attached
  147036. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  147037. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  147038. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  147039. ** the corresponding SQL function is deleted.
  147040. */
  147041. static void rtreeFreeCallback(void *p){
  147042. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  147043. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  147044. sqlite3_free(p);
  147045. }
  147046. /*
  147047. ** This routine frees the BLOB that is returned by geomCallback().
  147048. */
  147049. static void rtreeMatchArgFree(void *pArg){
  147050. int i;
  147051. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  147052. for(i=0; i<p->nParam; i++){
  147053. sqlite3_value_free(p->apSqlParam[i]);
  147054. }
  147055. sqlite3_free(p);
  147056. }
  147057. /*
  147058. ** Each call to sqlite3_rtree_geometry_callback() or
  147059. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  147060. ** scalar function that is implemented by this routine.
  147061. **
  147062. ** All this function does is construct an RtreeMatchArg object that
  147063. ** contains the geometry-checking callback routines and a list of
  147064. ** parameters to this function, then return that RtreeMatchArg object
  147065. ** as a BLOB.
  147066. **
  147067. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  147068. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  147069. ** out which elements of the R-Tree should be returned by the query.
  147070. */
  147071. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  147072. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  147073. RtreeMatchArg *pBlob;
  147074. int nBlob;
  147075. int memErr = 0;
  147076. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  147077. + nArg*sizeof(sqlite3_value*);
  147078. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  147079. if( !pBlob ){
  147080. sqlite3_result_error_nomem(ctx);
  147081. }else{
  147082. int i;
  147083. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  147084. pBlob->cb = pGeomCtx[0];
  147085. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  147086. pBlob->nParam = nArg;
  147087. for(i=0; i<nArg; i++){
  147088. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  147089. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  147090. #ifdef SQLITE_RTREE_INT_ONLY
  147091. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  147092. #else
  147093. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  147094. #endif
  147095. }
  147096. if( memErr ){
  147097. sqlite3_result_error_nomem(ctx);
  147098. rtreeMatchArgFree(pBlob);
  147099. }else{
  147100. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  147101. }
  147102. }
  147103. }
  147104. /*
  147105. ** Register a new geometry function for use with the r-tree MATCH operator.
  147106. */
  147107. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  147108. sqlite3 *db, /* Register SQL function on this connection */
  147109. const char *zGeom, /* Name of the new SQL function */
  147110. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  147111. void *pContext /* Extra data associated with the callback */
  147112. ){
  147113. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  147114. /* Allocate and populate the context object. */
  147115. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  147116. if( !pGeomCtx ) return SQLITE_NOMEM;
  147117. pGeomCtx->xGeom = xGeom;
  147118. pGeomCtx->xQueryFunc = 0;
  147119. pGeomCtx->xDestructor = 0;
  147120. pGeomCtx->pContext = pContext;
  147121. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  147122. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  147123. );
  147124. }
  147125. /*
  147126. ** Register a new 2nd-generation geometry function for use with the
  147127. ** r-tree MATCH operator.
  147128. */
  147129. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  147130. sqlite3 *db, /* Register SQL function on this connection */
  147131. const char *zQueryFunc, /* Name of new SQL function */
  147132. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  147133. void *pContext, /* Extra data passed into the callback */
  147134. void (*xDestructor)(void*) /* Destructor for the extra data */
  147135. ){
  147136. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  147137. /* Allocate and populate the context object. */
  147138. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  147139. if( !pGeomCtx ) return SQLITE_NOMEM;
  147140. pGeomCtx->xGeom = 0;
  147141. pGeomCtx->xQueryFunc = xQueryFunc;
  147142. pGeomCtx->xDestructor = xDestructor;
  147143. pGeomCtx->pContext = pContext;
  147144. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  147145. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  147146. );
  147147. }
  147148. #if !SQLITE_CORE
  147149. #ifdef _WIN32
  147150. __declspec(dllexport)
  147151. #endif
  147152. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
  147153. sqlite3 *db,
  147154. char **pzErrMsg,
  147155. const sqlite3_api_routines *pApi
  147156. ){
  147157. SQLITE_EXTENSION_INIT2(pApi)
  147158. return sqlite3RtreeInit(db);
  147159. }
  147160. #endif
  147161. #endif
  147162. /************** End of rtree.c ***********************************************/
  147163. /************** Begin file icu.c *********************************************/
  147164. /*
  147165. ** 2007 May 6
  147166. **
  147167. ** The author disclaims copyright to this source code. In place of
  147168. ** a legal notice, here is a blessing:
  147169. **
  147170. ** May you do good and not evil.
  147171. ** May you find forgiveness for yourself and forgive others.
  147172. ** May you share freely, never taking more than you give.
  147173. **
  147174. *************************************************************************
  147175. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  147176. **
  147177. ** This file implements an integration between the ICU library
  147178. ** ("International Components for Unicode", an open-source library
  147179. ** for handling unicode data) and SQLite. The integration uses
  147180. ** ICU to provide the following to SQLite:
  147181. **
  147182. ** * An implementation of the SQL regexp() function (and hence REGEXP
  147183. ** operator) using the ICU uregex_XX() APIs.
  147184. **
  147185. ** * Implementations of the SQL scalar upper() and lower() functions
  147186. ** for case mapping.
  147187. **
  147188. ** * Integration of ICU and SQLite collation sequences.
  147189. **
  147190. ** * An implementation of the LIKE operator that uses ICU to
  147191. ** provide case-independent matching.
  147192. */
  147193. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  147194. /* Include ICU headers */
  147195. #include <unicode/utypes.h>
  147196. #include <unicode/uregex.h>
  147197. #include <unicode/ustring.h>
  147198. #include <unicode/ucol.h>
  147199. /* #include <assert.h> */
  147200. #ifndef SQLITE_CORE
  147201. /* #include "sqlite3ext.h" */
  147202. SQLITE_EXTENSION_INIT1
  147203. #else
  147204. /* #include "sqlite3.h" */
  147205. #endif
  147206. /*
  147207. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  147208. ** operator.
  147209. */
  147210. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  147211. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  147212. #endif
  147213. /*
  147214. ** Version of sqlite3_free() that is always a function, never a macro.
  147215. */
  147216. static void xFree(void *p){
  147217. sqlite3_free(p);
  147218. }
  147219. /*
  147220. ** Compare two UTF-8 strings for equality where the first string is
  147221. ** a "LIKE" expression. Return true (1) if they are the same and
  147222. ** false (0) if they are different.
  147223. */
  147224. static int icuLikeCompare(
  147225. const uint8_t *zPattern, /* LIKE pattern */
  147226. const uint8_t *zString, /* The UTF-8 string to compare against */
  147227. const UChar32 uEsc /* The escape character */
  147228. ){
  147229. static const int MATCH_ONE = (UChar32)'_';
  147230. static const int MATCH_ALL = (UChar32)'%';
  147231. int iPattern = 0; /* Current byte index in zPattern */
  147232. int iString = 0; /* Current byte index in zString */
  147233. int prevEscape = 0; /* True if the previous character was uEsc */
  147234. while( zPattern[iPattern]!=0 ){
  147235. /* Read (and consume) the next character from the input pattern. */
  147236. UChar32 uPattern;
  147237. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  147238. /* There are now 4 possibilities:
  147239. **
  147240. ** 1. uPattern is an unescaped match-all character "%",
  147241. ** 2. uPattern is an unescaped match-one character "_",
  147242. ** 3. uPattern is an unescaped escape character, or
  147243. ** 4. uPattern is to be handled as an ordinary character
  147244. */
  147245. if( !prevEscape && uPattern==MATCH_ALL ){
  147246. /* Case 1. */
  147247. uint8_t c;
  147248. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  147249. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  147250. ** test string.
  147251. */
  147252. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  147253. if( c==MATCH_ONE ){
  147254. if( zString[iString]==0 ) return 0;
  147255. U8_FWD_1_UNSAFE(zString, iString);
  147256. }
  147257. iPattern++;
  147258. }
  147259. if( zPattern[iPattern]==0 ) return 1;
  147260. while( zString[iString] ){
  147261. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  147262. return 1;
  147263. }
  147264. U8_FWD_1_UNSAFE(zString, iString);
  147265. }
  147266. return 0;
  147267. }else if( !prevEscape && uPattern==MATCH_ONE ){
  147268. /* Case 2. */
  147269. if( zString[iString]==0 ) return 0;
  147270. U8_FWD_1_UNSAFE(zString, iString);
  147271. }else if( !prevEscape && uPattern==uEsc){
  147272. /* Case 3. */
  147273. prevEscape = 1;
  147274. }else{
  147275. /* Case 4. */
  147276. UChar32 uString;
  147277. U8_NEXT_UNSAFE(zString, iString, uString);
  147278. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  147279. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  147280. if( uString!=uPattern ){
  147281. return 0;
  147282. }
  147283. prevEscape = 0;
  147284. }
  147285. }
  147286. return zString[iString]==0;
  147287. }
  147288. /*
  147289. ** Implementation of the like() SQL function. This function implements
  147290. ** the build-in LIKE operator. The first argument to the function is the
  147291. ** pattern and the second argument is the string. So, the SQL statements:
  147292. **
  147293. ** A LIKE B
  147294. **
  147295. ** is implemented as like(B, A). If there is an escape character E,
  147296. **
  147297. ** A LIKE B ESCAPE E
  147298. **
  147299. ** is mapped to like(B, A, E).
  147300. */
  147301. static void icuLikeFunc(
  147302. sqlite3_context *context,
  147303. int argc,
  147304. sqlite3_value **argv
  147305. ){
  147306. const unsigned char *zA = sqlite3_value_text(argv[0]);
  147307. const unsigned char *zB = sqlite3_value_text(argv[1]);
  147308. UChar32 uEsc = 0;
  147309. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  147310. ** of deep recursion and N*N behavior in patternCompare().
  147311. */
  147312. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  147313. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  147314. return;
  147315. }
  147316. if( argc==3 ){
  147317. /* The escape character string must consist of a single UTF-8 character.
  147318. ** Otherwise, return an error.
  147319. */
  147320. int nE= sqlite3_value_bytes(argv[2]);
  147321. const unsigned char *zE = sqlite3_value_text(argv[2]);
  147322. int i = 0;
  147323. if( zE==0 ) return;
  147324. U8_NEXT(zE, i, nE, uEsc);
  147325. if( i!=nE){
  147326. sqlite3_result_error(context,
  147327. "ESCAPE expression must be a single character", -1);
  147328. return;
  147329. }
  147330. }
  147331. if( zA && zB ){
  147332. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  147333. }
  147334. }
  147335. /*
  147336. ** This function is called when an ICU function called from within
  147337. ** the implementation of an SQL scalar function returns an error.
  147338. **
  147339. ** The scalar function context passed as the first argument is
  147340. ** loaded with an error message based on the following two args.
  147341. */
  147342. static void icuFunctionError(
  147343. sqlite3_context *pCtx, /* SQLite scalar function context */
  147344. const char *zName, /* Name of ICU function that failed */
  147345. UErrorCode e /* Error code returned by ICU function */
  147346. ){
  147347. char zBuf[128];
  147348. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  147349. zBuf[127] = '\0';
  147350. sqlite3_result_error(pCtx, zBuf, -1);
  147351. }
  147352. /*
  147353. ** Function to delete compiled regexp objects. Registered as
  147354. ** a destructor function with sqlite3_set_auxdata().
  147355. */
  147356. static void icuRegexpDelete(void *p){
  147357. URegularExpression *pExpr = (URegularExpression *)p;
  147358. uregex_close(pExpr);
  147359. }
  147360. /*
  147361. ** Implementation of SQLite REGEXP operator. This scalar function takes
  147362. ** two arguments. The first is a regular expression pattern to compile
  147363. ** the second is a string to match against that pattern. If either
  147364. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  147365. ** is 1 if the string matches the pattern, or 0 otherwise.
  147366. **
  147367. ** SQLite maps the regexp() function to the regexp() operator such
  147368. ** that the following two are equivalent:
  147369. **
  147370. ** zString REGEXP zPattern
  147371. ** regexp(zPattern, zString)
  147372. **
  147373. ** Uses the following ICU regexp APIs:
  147374. **
  147375. ** uregex_open()
  147376. ** uregex_matches()
  147377. ** uregex_close()
  147378. */
  147379. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  147380. UErrorCode status = U_ZERO_ERROR;
  147381. URegularExpression *pExpr;
  147382. UBool res;
  147383. const UChar *zString = sqlite3_value_text16(apArg[1]);
  147384. (void)nArg; /* Unused parameter */
  147385. /* If the left hand side of the regexp operator is NULL,
  147386. ** then the result is also NULL.
  147387. */
  147388. if( !zString ){
  147389. return;
  147390. }
  147391. pExpr = sqlite3_get_auxdata(p, 0);
  147392. if( !pExpr ){
  147393. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  147394. if( !zPattern ){
  147395. return;
  147396. }
  147397. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  147398. if( U_SUCCESS(status) ){
  147399. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  147400. }else{
  147401. assert(!pExpr);
  147402. icuFunctionError(p, "uregex_open", status);
  147403. return;
  147404. }
  147405. }
  147406. /* Configure the text that the regular expression operates on. */
  147407. uregex_setText(pExpr, zString, -1, &status);
  147408. if( !U_SUCCESS(status) ){
  147409. icuFunctionError(p, "uregex_setText", status);
  147410. return;
  147411. }
  147412. /* Attempt the match */
  147413. res = uregex_matches(pExpr, 0, &status);
  147414. if( !U_SUCCESS(status) ){
  147415. icuFunctionError(p, "uregex_matches", status);
  147416. return;
  147417. }
  147418. /* Set the text that the regular expression operates on to a NULL
  147419. ** pointer. This is not really necessary, but it is tidier than
  147420. ** leaving the regular expression object configured with an invalid
  147421. ** pointer after this function returns.
  147422. */
  147423. uregex_setText(pExpr, 0, 0, &status);
  147424. /* Return 1 or 0. */
  147425. sqlite3_result_int(p, res ? 1 : 0);
  147426. }
  147427. /*
  147428. ** Implementations of scalar functions for case mapping - upper() and
  147429. ** lower(). Function upper() converts its input to upper-case (ABC).
  147430. ** Function lower() converts to lower-case (abc).
  147431. **
  147432. ** ICU provides two types of case mapping, "general" case mapping and
  147433. ** "language specific". Refer to ICU documentation for the differences
  147434. ** between the two.
  147435. **
  147436. ** To utilise "general" case mapping, the upper() or lower() scalar
  147437. ** functions are invoked with one argument:
  147438. **
  147439. ** upper('ABC') -> 'abc'
  147440. ** lower('abc') -> 'ABC'
  147441. **
  147442. ** To access ICU "language specific" case mapping, upper() or lower()
  147443. ** should be invoked with two arguments. The second argument is the name
  147444. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  147445. ** as the second argument is the same as invoking the 1 argument version
  147446. ** of upper() or lower().
  147447. **
  147448. ** lower('I', 'en_us') -> 'i'
  147449. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  147450. **
  147451. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  147452. */
  147453. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  147454. const UChar *zInput;
  147455. UChar *zOutput;
  147456. int nInput;
  147457. int nOutput;
  147458. UErrorCode status = U_ZERO_ERROR;
  147459. const char *zLocale = 0;
  147460. assert(nArg==1 || nArg==2);
  147461. if( nArg==2 ){
  147462. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  147463. }
  147464. zInput = sqlite3_value_text16(apArg[0]);
  147465. if( !zInput ){
  147466. return;
  147467. }
  147468. nInput = sqlite3_value_bytes16(apArg[0]);
  147469. nOutput = nInput * 2 + 2;
  147470. zOutput = sqlite3_malloc(nOutput);
  147471. if( !zOutput ){
  147472. return;
  147473. }
  147474. if( sqlite3_user_data(p) ){
  147475. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  147476. }else{
  147477. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  147478. }
  147479. if( !U_SUCCESS(status) ){
  147480. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  147481. return;
  147482. }
  147483. sqlite3_result_text16(p, zOutput, -1, xFree);
  147484. }
  147485. /*
  147486. ** Collation sequence destructor function. The pCtx argument points to
  147487. ** a UCollator structure previously allocated using ucol_open().
  147488. */
  147489. static void icuCollationDel(void *pCtx){
  147490. UCollator *p = (UCollator *)pCtx;
  147491. ucol_close(p);
  147492. }
  147493. /*
  147494. ** Collation sequence comparison function. The pCtx argument points to
  147495. ** a UCollator structure previously allocated using ucol_open().
  147496. */
  147497. static int icuCollationColl(
  147498. void *pCtx,
  147499. int nLeft,
  147500. const void *zLeft,
  147501. int nRight,
  147502. const void *zRight
  147503. ){
  147504. UCollationResult res;
  147505. UCollator *p = (UCollator *)pCtx;
  147506. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  147507. switch( res ){
  147508. case UCOL_LESS: return -1;
  147509. case UCOL_GREATER: return +1;
  147510. case UCOL_EQUAL: return 0;
  147511. }
  147512. assert(!"Unexpected return value from ucol_strcoll()");
  147513. return 0;
  147514. }
  147515. /*
  147516. ** Implementation of the scalar function icu_load_collation().
  147517. **
  147518. ** This scalar function is used to add ICU collation based collation
  147519. ** types to an SQLite database connection. It is intended to be called
  147520. ** as follows:
  147521. **
  147522. ** SELECT icu_load_collation(<locale>, <collation-name>);
  147523. **
  147524. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  147525. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  147526. ** collation sequence to create.
  147527. */
  147528. static void icuLoadCollation(
  147529. sqlite3_context *p,
  147530. int nArg,
  147531. sqlite3_value **apArg
  147532. ){
  147533. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  147534. UErrorCode status = U_ZERO_ERROR;
  147535. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  147536. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  147537. UCollator *pUCollator; /* ICU library collation object */
  147538. int rc; /* Return code from sqlite3_create_collation_x() */
  147539. assert(nArg==2);
  147540. (void)nArg; /* Unused parameter */
  147541. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  147542. zName = (const char *)sqlite3_value_text(apArg[1]);
  147543. if( !zLocale || !zName ){
  147544. return;
  147545. }
  147546. pUCollator = ucol_open(zLocale, &status);
  147547. if( !U_SUCCESS(status) ){
  147548. icuFunctionError(p, "ucol_open", status);
  147549. return;
  147550. }
  147551. assert(p);
  147552. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  147553. icuCollationColl, icuCollationDel
  147554. );
  147555. if( rc!=SQLITE_OK ){
  147556. ucol_close(pUCollator);
  147557. sqlite3_result_error(p, "Error registering collation function", -1);
  147558. }
  147559. }
  147560. /*
  147561. ** Register the ICU extension functions with database db.
  147562. */
  147563. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  147564. struct IcuScalar {
  147565. const char *zName; /* Function name */
  147566. int nArg; /* Number of arguments */
  147567. int enc; /* Optimal text encoding */
  147568. void *pContext; /* sqlite3_user_data() context */
  147569. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  147570. } scalars[] = {
  147571. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  147572. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  147573. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  147574. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  147575. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  147576. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  147577. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  147578. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  147579. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  147580. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  147581. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  147582. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  147583. };
  147584. int rc = SQLITE_OK;
  147585. int i;
  147586. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  147587. struct IcuScalar *p = &scalars[i];
  147588. rc = sqlite3_create_function(
  147589. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  147590. );
  147591. }
  147592. return rc;
  147593. }
  147594. #if !SQLITE_CORE
  147595. #ifdef _WIN32
  147596. __declspec(dllexport)
  147597. #endif
  147598. SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
  147599. sqlite3 *db,
  147600. char **pzErrMsg,
  147601. const sqlite3_api_routines *pApi
  147602. ){
  147603. SQLITE_EXTENSION_INIT2(pApi)
  147604. return sqlite3IcuInit(db);
  147605. }
  147606. #endif
  147607. #endif
  147608. /************** End of icu.c *************************************************/
  147609. /************** Begin file fts3_icu.c ****************************************/
  147610. /*
  147611. ** 2007 June 22
  147612. **
  147613. ** The author disclaims copyright to this source code. In place of
  147614. ** a legal notice, here is a blessing:
  147615. **
  147616. ** May you do good and not evil.
  147617. ** May you find forgiveness for yourself and forgive others.
  147618. ** May you share freely, never taking more than you give.
  147619. **
  147620. *************************************************************************
  147621. ** This file implements a tokenizer for fts3 based on the ICU library.
  147622. */
  147623. /* #include "fts3Int.h" */
  147624. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  147625. #ifdef SQLITE_ENABLE_ICU
  147626. /* #include <assert.h> */
  147627. /* #include <string.h> */
  147628. /* #include "fts3_tokenizer.h" */
  147629. #include <unicode/ubrk.h>
  147630. /* #include <unicode/ucol.h> */
  147631. /* #include <unicode/ustring.h> */
  147632. #include <unicode/utf16.h>
  147633. typedef struct IcuTokenizer IcuTokenizer;
  147634. typedef struct IcuCursor IcuCursor;
  147635. struct IcuTokenizer {
  147636. sqlite3_tokenizer base;
  147637. char *zLocale;
  147638. };
  147639. struct IcuCursor {
  147640. sqlite3_tokenizer_cursor base;
  147641. UBreakIterator *pIter; /* ICU break-iterator object */
  147642. int nChar; /* Number of UChar elements in pInput */
  147643. UChar *aChar; /* Copy of input using utf-16 encoding */
  147644. int *aOffset; /* Offsets of each character in utf-8 input */
  147645. int nBuffer;
  147646. char *zBuffer;
  147647. int iToken;
  147648. };
  147649. /*
  147650. ** Create a new tokenizer instance.
  147651. */
  147652. static int icuCreate(
  147653. int argc, /* Number of entries in argv[] */
  147654. const char * const *argv, /* Tokenizer creation arguments */
  147655. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  147656. ){
  147657. IcuTokenizer *p;
  147658. int n = 0;
  147659. if( argc>0 ){
  147660. n = strlen(argv[0])+1;
  147661. }
  147662. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  147663. if( !p ){
  147664. return SQLITE_NOMEM;
  147665. }
  147666. memset(p, 0, sizeof(IcuTokenizer));
  147667. if( n ){
  147668. p->zLocale = (char *)&p[1];
  147669. memcpy(p->zLocale, argv[0], n);
  147670. }
  147671. *ppTokenizer = (sqlite3_tokenizer *)p;
  147672. return SQLITE_OK;
  147673. }
  147674. /*
  147675. ** Destroy a tokenizer
  147676. */
  147677. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  147678. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  147679. sqlite3_free(p);
  147680. return SQLITE_OK;
  147681. }
  147682. /*
  147683. ** Prepare to begin tokenizing a particular string. The input
  147684. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  147685. ** used to incrementally tokenize this string is returned in
  147686. ** *ppCursor.
  147687. */
  147688. static int icuOpen(
  147689. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  147690. const char *zInput, /* Input string */
  147691. int nInput, /* Length of zInput in bytes */
  147692. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  147693. ){
  147694. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  147695. IcuCursor *pCsr;
  147696. const int32_t opt = U_FOLD_CASE_DEFAULT;
  147697. UErrorCode status = U_ZERO_ERROR;
  147698. int nChar;
  147699. UChar32 c;
  147700. int iInput = 0;
  147701. int iOut = 0;
  147702. *ppCursor = 0;
  147703. if( zInput==0 ){
  147704. nInput = 0;
  147705. zInput = "";
  147706. }else if( nInput<0 ){
  147707. nInput = strlen(zInput);
  147708. }
  147709. nChar = nInput+1;
  147710. pCsr = (IcuCursor *)sqlite3_malloc(
  147711. sizeof(IcuCursor) + /* IcuCursor */
  147712. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  147713. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  147714. );
  147715. if( !pCsr ){
  147716. return SQLITE_NOMEM;
  147717. }
  147718. memset(pCsr, 0, sizeof(IcuCursor));
  147719. pCsr->aChar = (UChar *)&pCsr[1];
  147720. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  147721. pCsr->aOffset[iOut] = iInput;
  147722. U8_NEXT(zInput, iInput, nInput, c);
  147723. while( c>0 ){
  147724. int isError = 0;
  147725. c = u_foldCase(c, opt);
  147726. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  147727. if( isError ){
  147728. sqlite3_free(pCsr);
  147729. return SQLITE_ERROR;
  147730. }
  147731. pCsr->aOffset[iOut] = iInput;
  147732. if( iInput<nInput ){
  147733. U8_NEXT(zInput, iInput, nInput, c);
  147734. }else{
  147735. c = 0;
  147736. }
  147737. }
  147738. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  147739. if( !U_SUCCESS(status) ){
  147740. sqlite3_free(pCsr);
  147741. return SQLITE_ERROR;
  147742. }
  147743. pCsr->nChar = iOut;
  147744. ubrk_first(pCsr->pIter);
  147745. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  147746. return SQLITE_OK;
  147747. }
  147748. /*
  147749. ** Close a tokenization cursor previously opened by a call to icuOpen().
  147750. */
  147751. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  147752. IcuCursor *pCsr = (IcuCursor *)pCursor;
  147753. ubrk_close(pCsr->pIter);
  147754. sqlite3_free(pCsr->zBuffer);
  147755. sqlite3_free(pCsr);
  147756. return SQLITE_OK;
  147757. }
  147758. /*
  147759. ** Extract the next token from a tokenization cursor.
  147760. */
  147761. static int icuNext(
  147762. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  147763. const char **ppToken, /* OUT: *ppToken is the token text */
  147764. int *pnBytes, /* OUT: Number of bytes in token */
  147765. int *piStartOffset, /* OUT: Starting offset of token */
  147766. int *piEndOffset, /* OUT: Ending offset of token */
  147767. int *piPosition /* OUT: Position integer of token */
  147768. ){
  147769. IcuCursor *pCsr = (IcuCursor *)pCursor;
  147770. int iStart = 0;
  147771. int iEnd = 0;
  147772. int nByte = 0;
  147773. while( iStart==iEnd ){
  147774. UChar32 c;
  147775. iStart = ubrk_current(pCsr->pIter);
  147776. iEnd = ubrk_next(pCsr->pIter);
  147777. if( iEnd==UBRK_DONE ){
  147778. return SQLITE_DONE;
  147779. }
  147780. while( iStart<iEnd ){
  147781. int iWhite = iStart;
  147782. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  147783. if( u_isspace(c) ){
  147784. iStart = iWhite;
  147785. }else{
  147786. break;
  147787. }
  147788. }
  147789. assert(iStart<=iEnd);
  147790. }
  147791. do {
  147792. UErrorCode status = U_ZERO_ERROR;
  147793. if( nByte ){
  147794. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  147795. if( !zNew ){
  147796. return SQLITE_NOMEM;
  147797. }
  147798. pCsr->zBuffer = zNew;
  147799. pCsr->nBuffer = nByte;
  147800. }
  147801. u_strToUTF8(
  147802. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  147803. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  147804. &status /* Output success/failure */
  147805. );
  147806. } while( nByte>pCsr->nBuffer );
  147807. *ppToken = pCsr->zBuffer;
  147808. *pnBytes = nByte;
  147809. *piStartOffset = pCsr->aOffset[iStart];
  147810. *piEndOffset = pCsr->aOffset[iEnd];
  147811. *piPosition = pCsr->iToken++;
  147812. return SQLITE_OK;
  147813. }
  147814. /*
  147815. ** The set of routines that implement the simple tokenizer
  147816. */
  147817. static const sqlite3_tokenizer_module icuTokenizerModule = {
  147818. 0, /* iVersion */
  147819. icuCreate, /* xCreate */
  147820. icuDestroy, /* xCreate */
  147821. icuOpen, /* xOpen */
  147822. icuClose, /* xClose */
  147823. icuNext, /* xNext */
  147824. 0, /* xLanguageid */
  147825. };
  147826. /*
  147827. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  147828. */
  147829. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  147830. sqlite3_tokenizer_module const**ppModule
  147831. ){
  147832. *ppModule = &icuTokenizerModule;
  147833. }
  147834. #endif /* defined(SQLITE_ENABLE_ICU) */
  147835. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  147836. /************** End of fts3_icu.c ********************************************/
  147837. /************** Begin file sqlite3rbu.c **************************************/
  147838. /*
  147839. ** 2014 August 30
  147840. **
  147841. ** The author disclaims copyright to this source code. In place of
  147842. ** a legal notice, here is a blessing:
  147843. **
  147844. ** May you do good and not evil.
  147845. ** May you find forgiveness for yourself and forgive others.
  147846. ** May you share freely, never taking more than you give.
  147847. **
  147848. *************************************************************************
  147849. **
  147850. **
  147851. ** OVERVIEW
  147852. **
  147853. ** The RBU extension requires that the RBU update be packaged as an
  147854. ** SQLite database. The tables it expects to find are described in
  147855. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  147856. ** that the user wishes to write to, a corresponding data_xyz table is
  147857. ** created in the RBU database and populated with one row for each row to
  147858. ** update, insert or delete from the target table.
  147859. **
  147860. ** The update proceeds in three stages:
  147861. **
  147862. ** 1) The database is updated. The modified database pages are written
  147863. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  147864. ** that it is named "<database>-oal" instead of "<database>-wal".
  147865. ** Because regular SQLite clients do not look for file named
  147866. ** "<database>-oal", they go on using the original database in
  147867. ** rollback mode while the *-oal file is being generated.
  147868. **
  147869. ** During this stage RBU does not update the database by writing
  147870. ** directly to the target tables. Instead it creates "imposter"
  147871. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  147872. ** to update each b-tree individually. All updates required by each
  147873. ** b-tree are completed before moving on to the next, and all
  147874. ** updates are done in sorted key order.
  147875. **
  147876. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  147877. ** location using a call to rename(2). Before doing this the RBU
  147878. ** module takes an EXCLUSIVE lock on the database file, ensuring
  147879. ** that there are no other active readers.
  147880. **
  147881. ** Once the EXCLUSIVE lock is released, any other database readers
  147882. ** detect the new *-wal file and read the database in wal mode. At
  147883. ** this point they see the new version of the database - including
  147884. ** the updates made as part of the RBU update.
  147885. **
  147886. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  147887. ** as a regular database checkpoint, except that a single frame is
  147888. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  147889. ** handle is closed before the entire *-wal file is checkpointed,
  147890. ** the checkpoint progress is saved in the RBU database and the
  147891. ** checkpoint can be resumed by another RBU client at some point in
  147892. ** the future.
  147893. **
  147894. ** POTENTIAL PROBLEMS
  147895. **
  147896. ** The rename() call might not be portable. And RBU is not currently
  147897. ** syncing the directory after renaming the file.
  147898. **
  147899. ** When state is saved, any commit to the *-oal file and the commit to
  147900. ** the RBU update database are not atomic. So if the power fails at the
  147901. ** wrong moment they might get out of sync. As the main database will be
  147902. ** committed before the RBU update database this will likely either just
  147903. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  147904. ** constraint violations).
  147905. **
  147906. ** If some client does modify the target database mid RBU update, or some
  147907. ** other error occurs, the RBU extension will keep throwing errors. It's
  147908. ** not really clear how to get out of this state. The system could just
  147909. ** by delete the RBU update database and *-oal file and have the device
  147910. ** download the update again and start over.
  147911. **
  147912. ** At present, for an UPDATE, both the new.* and old.* records are
  147913. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  147914. ** fields are collected. This means we're probably writing a lot more
  147915. ** data to disk when saving the state of an ongoing update to the RBU
  147916. ** update database than is strictly necessary.
  147917. **
  147918. */
  147919. /* #include <assert.h> */
  147920. /* #include <string.h> */
  147921. /* #include <stdio.h> */
  147922. /* #include "sqlite3.h" */
  147923. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  147924. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  147925. /************** Begin file sqlite3rbu.h **************************************/
  147926. /*
  147927. ** 2014 August 30
  147928. **
  147929. ** The author disclaims copyright to this source code. In place of
  147930. ** a legal notice, here is a blessing:
  147931. **
  147932. ** May you do good and not evil.
  147933. ** May you find forgiveness for yourself and forgive others.
  147934. ** May you share freely, never taking more than you give.
  147935. **
  147936. *************************************************************************
  147937. **
  147938. ** This file contains the public interface for the RBU extension.
  147939. */
  147940. /*
  147941. ** SUMMARY
  147942. **
  147943. ** Writing a transaction containing a large number of operations on
  147944. ** b-tree indexes that are collectively larger than the available cache
  147945. ** memory can be very inefficient.
  147946. **
  147947. ** The problem is that in order to update a b-tree, the leaf page (at least)
  147948. ** containing the entry being inserted or deleted must be modified. If the
  147949. ** working set of leaves is larger than the available cache memory, then a
  147950. ** single leaf that is modified more than once as part of the transaction
  147951. ** may be loaded from or written to the persistent media multiple times.
  147952. ** Additionally, because the index updates are likely to be applied in
  147953. ** random order, access to pages within the database is also likely to be in
  147954. ** random order, which is itself quite inefficient.
  147955. **
  147956. ** One way to improve the situation is to sort the operations on each index
  147957. ** by index key before applying them to the b-tree. This leads to an IO
  147958. ** pattern that resembles a single linear scan through the index b-tree,
  147959. ** and all but guarantees each modified leaf page is loaded and stored
  147960. ** exactly once. SQLite uses this trick to improve the performance of
  147961. ** CREATE INDEX commands. This extension allows it to be used to improve
  147962. ** the performance of large transactions on existing databases.
  147963. **
  147964. ** Additionally, this extension allows the work involved in writing the
  147965. ** large transaction to be broken down into sub-transactions performed
  147966. ** sequentially by separate processes. This is useful if the system cannot
  147967. ** guarantee that a single update process will run for long enough to apply
  147968. ** the entire update, for example because the update is being applied on a
  147969. ** mobile device that is frequently rebooted. Even after the writer process
  147970. ** has committed one or more sub-transactions, other database clients continue
  147971. ** to read from the original database snapshot. In other words, partially
  147972. ** applied transactions are not visible to other clients.
  147973. **
  147974. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  147975. ** transmitted via a wireless network to a mobile device. A transaction
  147976. ** applied using this extension is hence refered to as an "RBU update".
  147977. **
  147978. **
  147979. ** LIMITATIONS
  147980. **
  147981. ** An "RBU update" transaction is subject to the following limitations:
  147982. **
  147983. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  147984. ** only.
  147985. **
  147986. ** * INSERT statements may not use any default values.
  147987. **
  147988. ** * UPDATE and DELETE statements must identify their target rows by
  147989. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  147990. ** KEY fields may not be updated or deleted. If the table being written
  147991. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  147992. **
  147993. ** * UPDATE statements may not modify PRIMARY KEY columns.
  147994. **
  147995. ** * No triggers will be fired.
  147996. **
  147997. ** * No foreign key violations are detected or reported.
  147998. **
  147999. ** * CHECK constraints are not enforced.
  148000. **
  148001. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  148002. **
  148003. **
  148004. ** PREPARATION
  148005. **
  148006. ** An "RBU update" is stored as a separate SQLite database. A database
  148007. ** containing an RBU update is an "RBU database". For each table in the
  148008. ** target database to be updated, the RBU database should contain a table
  148009. ** named "data_<target name>" containing the same set of columns as the
  148010. ** target table, and one more - "rbu_control". The data_% table should
  148011. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  148012. ** the same type as the corresponding column in the target database.
  148013. ** The "rbu_control" column should have no type at all. For example, if
  148014. ** the target database contains:
  148015. **
  148016. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  148017. **
  148018. ** Then the RBU database should contain:
  148019. **
  148020. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  148021. **
  148022. ** The order of the columns in the data_% table does not matter.
  148023. **
  148024. ** Instead of a regular table, the RBU database may also contain virtual
  148025. ** tables or view named using the data_<target> naming scheme.
  148026. **
  148027. ** Instead of the plain data_<target> naming scheme, RBU database tables
  148028. ** may also be named data<integer>_<target>, where <integer> is any sequence
  148029. ** of zero or more numeric characters (0-9). This can be significant because
  148030. ** tables within the RBU database are always processed in order sorted by
  148031. ** name. By judicious selection of the the <integer> portion of the names
  148032. ** of the RBU tables the user can therefore control the order in which they
  148033. ** are processed. This can be useful, for example, to ensure that "external
  148034. ** content" FTS4 tables are updated before their underlying content tables.
  148035. **
  148036. ** If the target database table is a virtual table or a table that has no
  148037. ** PRIMARY KEY declaration, the data_% table must also contain a column
  148038. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  148039. ** key column - "rowid". Virtual tables for which the "rowid" column does
  148040. ** not function like a primary key value cannot be updated using RBU. For
  148041. ** example, if the target db contains either of the following:
  148042. **
  148043. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  148044. ** CREATE TABLE x1(a, b)
  148045. **
  148046. ** then the RBU database should contain:
  148047. **
  148048. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  148049. **
  148050. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  148051. ** target table must be present in the input table. For virtual tables,
  148052. ** hidden columns are optional - they are updated by RBU if present in
  148053. ** the input table, or not otherwise. For example, to write to an fts4
  148054. ** table with a hidden languageid column such as:
  148055. **
  148056. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  148057. **
  148058. ** Either of the following input table schemas may be used:
  148059. **
  148060. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  148061. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  148062. **
  148063. ** For each row to INSERT into the target database as part of the RBU
  148064. ** update, the corresponding data_% table should contain a single record
  148065. ** with the "rbu_control" column set to contain integer value 0. The
  148066. ** other columns should be set to the values that make up the new record
  148067. ** to insert.
  148068. **
  148069. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  148070. ** possible to insert a NULL value into the IPK column. Attempting to
  148071. ** do so results in an SQLITE_MISMATCH error.
  148072. **
  148073. ** For each row to DELETE from the target database as part of the RBU
  148074. ** update, the corresponding data_% table should contain a single record
  148075. ** with the "rbu_control" column set to contain integer value 1. The
  148076. ** real primary key values of the row to delete should be stored in the
  148077. ** corresponding columns of the data_% table. The values stored in the
  148078. ** other columns are not used.
  148079. **
  148080. ** For each row to UPDATE from the target database as part of the RBU
  148081. ** update, the corresponding data_% table should contain a single record
  148082. ** with the "rbu_control" column set to contain a value of type text.
  148083. ** The real primary key values identifying the row to update should be
  148084. ** stored in the corresponding columns of the data_% table row, as should
  148085. ** the new values of all columns being update. The text value in the
  148086. ** "rbu_control" column must contain the same number of characters as
  148087. ** there are columns in the target database table, and must consist entirely
  148088. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  148089. ** each column that is being updated, the corresponding character is set to
  148090. ** 'x'. For those that remain as they are, the corresponding character of the
  148091. ** rbu_control value should be set to '.'. For example, given the tables
  148092. ** above, the update statement:
  148093. **
  148094. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  148095. **
  148096. ** is represented by the data_t1 row created by:
  148097. **
  148098. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  148099. **
  148100. ** Instead of an 'x' character, characters of the rbu_control value specified
  148101. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  148102. ** target table with the value stored in the corresponding data_% column, the
  148103. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  148104. ** the target table column. rbu_delta() is invoked with two arguments - the
  148105. ** original value currently stored in the target table column and the
  148106. ** value specified in the data_xxx table.
  148107. **
  148108. ** For example, this row:
  148109. **
  148110. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  148111. **
  148112. ** is similar to an UPDATE statement such as:
  148113. **
  148114. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  148115. **
  148116. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  148117. ** ota_control string, the contents of the data_xxx table column is assumed
  148118. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  148119. ** format used by the fossil source-code management system. In this case
  148120. ** the existing value within the target database table must be of type BLOB.
  148121. ** It is replaced by the result of applying the specified fossil delta to
  148122. ** itself.
  148123. **
  148124. ** If the target database table is a virtual table or a table with no PRIMARY
  148125. ** KEY, the rbu_control value should not include a character corresponding
  148126. ** to the rbu_rowid value. For example, this:
  148127. **
  148128. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  148129. ** VALUES(NULL, 'usa', 12, '.x');
  148130. **
  148131. ** causes a result similar to:
  148132. **
  148133. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  148134. **
  148135. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  148136. ** However, RBU is more efficient if reading the rows in from each data_xxx
  148137. ** table in "rowid" order is roughly the same as reading them sorted by
  148138. ** the PRIMARY KEY of the corresponding target database table. In other
  148139. ** words, rows should be sorted using the destination table PRIMARY KEY
  148140. ** fields before they are inserted into the data_xxx tables.
  148141. **
  148142. ** USAGE
  148143. **
  148144. ** The API declared below allows an application to apply an RBU update
  148145. ** stored on disk to an existing target database. Essentially, the
  148146. ** application:
  148147. **
  148148. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  148149. **
  148150. ** 2) Registers any required virtual table modules with the database
  148151. ** handle returned by sqlite3rbu_db(). Also, if required, register
  148152. ** the rbu_delta() implementation.
  148153. **
  148154. ** 3) Calls the sqlite3rbu_step() function one or more times on
  148155. ** the new handle. Each call to sqlite3rbu_step() performs a single
  148156. ** b-tree operation, so thousands of calls may be required to apply
  148157. ** a complete update.
  148158. **
  148159. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  148160. ** sqlite3rbu_step() has been called enough times to completely
  148161. ** apply the update to the target database, then the RBU database
  148162. ** is marked as fully applied. Otherwise, the state of the RBU
  148163. ** update application is saved in the RBU database for later
  148164. ** resumption.
  148165. **
  148166. ** See comments below for more detail on APIs.
  148167. **
  148168. ** If an update is only partially applied to the target database by the
  148169. ** time sqlite3rbu_close() is called, various state information is saved
  148170. ** within the RBU database. This allows subsequent processes to automatically
  148171. ** resume the RBU update from where it left off.
  148172. **
  148173. ** To remove all RBU extension state information, returning an RBU database
  148174. ** to its original contents, it is sufficient to drop all tables that begin
  148175. ** with the prefix "rbu_"
  148176. **
  148177. ** DATABASE LOCKING
  148178. **
  148179. ** An RBU update may not be applied to a database in WAL mode. Attempting
  148180. ** to do so is an error (SQLITE_ERROR).
  148181. **
  148182. ** While an RBU handle is open, a SHARED lock may be held on the target
  148183. ** database file. This means it is possible for other clients to read the
  148184. ** database, but not to write it.
  148185. **
  148186. ** If an RBU update is started and then suspended before it is completed,
  148187. ** then an external client writes to the database, then attempting to resume
  148188. ** the suspended RBU update is also an error (SQLITE_BUSY).
  148189. */
  148190. #ifndef _SQLITE3RBU_H
  148191. #define _SQLITE3RBU_H
  148192. /* #include "sqlite3.h" ** Required for error code definitions ** */
  148193. #if 0
  148194. extern "C" {
  148195. #endif
  148196. typedef struct sqlite3rbu sqlite3rbu;
  148197. /*
  148198. ** Open an RBU handle.
  148199. **
  148200. ** Argument zTarget is the path to the target database. Argument zRbu is
  148201. ** the path to the RBU database. Each call to this function must be matched
  148202. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  148203. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  148204. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  148205. ** database URI, not a regular file name.
  148206. **
  148207. ** If the zState argument is passed a NULL value, the RBU extension stores
  148208. ** the current state of the update (how many rows have been updated, which
  148209. ** indexes are yet to be updated etc.) within the RBU database itself. This
  148210. ** can be convenient, as it means that the RBU application does not need to
  148211. ** organize removing a separate state file after the update is concluded.
  148212. ** Or, if zState is non-NULL, it must be a path to a database file in which
  148213. ** the RBU extension can store the state of the update.
  148214. **
  148215. ** When resuming an RBU update, the zState argument must be passed the same
  148216. ** value as when the RBU update was started.
  148217. **
  148218. ** Once the RBU update is finished, the RBU extension does not
  148219. ** automatically remove any zState database file, even if it created it.
  148220. **
  148221. ** By default, RBU uses the default VFS to access the files on disk. To
  148222. ** use a VFS other than the default, an SQLite "file:" URI containing a
  148223. ** "vfs=..." option may be passed as the zTarget option.
  148224. **
  148225. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  148226. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  148227. ** not work out of the box with zipvfs. Refer to the comment describing
  148228. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  148229. */
  148230. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  148231. const char *zTarget,
  148232. const char *zRbu,
  148233. const char *zState
  148234. );
  148235. /*
  148236. ** Internally, each RBU connection uses a separate SQLite database
  148237. ** connection to access the target and rbu update databases. This
  148238. ** API allows the application direct access to these database handles.
  148239. **
  148240. ** The first argument passed to this function must be a valid, open, RBU
  148241. ** handle. The second argument should be passed zero to access the target
  148242. ** database handle, or non-zero to access the rbu update database handle.
  148243. ** Accessing the underlying database handles may be useful in the
  148244. ** following scenarios:
  148245. **
  148246. ** * If any target tables are virtual tables, it may be necessary to
  148247. ** call sqlite3_create_module() on the target database handle to
  148248. ** register the required virtual table implementations.
  148249. **
  148250. ** * If the data_xxx tables in the RBU source database are virtual
  148251. ** tables, the application may need to call sqlite3_create_module() on
  148252. ** the rbu update db handle to any required virtual table
  148253. ** implementations.
  148254. **
  148255. ** * If the application uses the "rbu_delta()" feature described above,
  148256. ** it must use sqlite3_create_function() or similar to register the
  148257. ** rbu_delta() implementation with the target database handle.
  148258. **
  148259. ** If an error has occurred, either while opening or stepping the RBU object,
  148260. ** this function may return NULL. The error code and message may be collected
  148261. ** when sqlite3rbu_close() is called.
  148262. */
  148263. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
  148264. /*
  148265. ** Do some work towards applying the RBU update to the target db.
  148266. **
  148267. ** Return SQLITE_DONE if the update has been completely applied, or
  148268. ** SQLITE_OK if no error occurs but there remains work to do to apply
  148269. ** the RBU update. If an error does occur, some other error code is
  148270. ** returned.
  148271. **
  148272. ** Once a call to sqlite3rbu_step() has returned a value other than
  148273. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  148274. ** that immediately return the same value.
  148275. */
  148276. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
  148277. /*
  148278. ** Force RBU to save its state to disk.
  148279. **
  148280. ** If a power failure or application crash occurs during an update, following
  148281. ** system recovery RBU may resume the update from the point at which the state
  148282. ** was last saved. In other words, from the most recent successful call to
  148283. ** sqlite3rbu_close() or this function.
  148284. **
  148285. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  148286. */
  148287. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
  148288. /*
  148289. ** Close an RBU handle.
  148290. **
  148291. ** If the RBU update has been completely applied, mark the RBU database
  148292. ** as fully applied. Otherwise, assuming no error has occurred, save the
  148293. ** current state of the RBU update appliation to the RBU database.
  148294. **
  148295. ** If an error has already occurred as part of an sqlite3rbu_step()
  148296. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  148297. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  148298. ** point to a buffer containing a utf-8 formatted English language error
  148299. ** message. It is the responsibility of the caller to eventually free any
  148300. ** such buffer using sqlite3_free().
  148301. **
  148302. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  148303. ** update has been partially applied, or SQLITE_DONE if it has been
  148304. ** completely applied.
  148305. */
  148306. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  148307. /*
  148308. ** Return the total number of key-value operations (inserts, deletes or
  148309. ** updates) that have been performed on the target database since the
  148310. ** current RBU update was started.
  148311. */
  148312. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
  148313. /*
  148314. ** Create an RBU VFS named zName that accesses the underlying file-system
  148315. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  148316. ** then the new RBU VFS uses the default system VFS to access the file-system.
  148317. ** The new object is registered as a non-default VFS with SQLite before
  148318. ** returning.
  148319. **
  148320. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  148321. ** object is created and deleted automatically by RBU.
  148322. **
  148323. ** The exception is for applications that also use zipvfs. In this case,
  148324. ** the custom VFS must be explicitly created by the user before the RBU
  148325. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  148326. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  148327. ** (for example multiplexor) to access the file-system. For example,
  148328. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  148329. ** multiplexor (error checking omitted):
  148330. **
  148331. ** // Create a VFS named "multiplex" (not the default).
  148332. ** sqlite3_multiplex_initialize(0, 0);
  148333. **
  148334. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  148335. ** // second argument were replaced with NULL, the "rbu" VFS would
  148336. ** // access the file-system via the system default VFS, bypassing the
  148337. ** // multiplexor.
  148338. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  148339. **
  148340. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  148341. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  148342. **
  148343. ** // Make zipvfs the default VFS.
  148344. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  148345. **
  148346. ** Because the default VFS created above includes a RBU functionality, it
  148347. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  148348. ** that does not include the RBU layer results in an error.
  148349. **
  148350. ** The overhead of adding the "rbu" VFS to the system is negligible for
  148351. ** non-RBU users. There is no harm in an application accessing the
  148352. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  148353. ** occasionally.
  148354. */
  148355. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  148356. /*
  148357. ** Deregister and destroy an RBU vfs created by an earlier call to
  148358. ** sqlite3rbu_create_vfs().
  148359. **
  148360. ** VFS objects are not reference counted. If a VFS object is destroyed
  148361. ** before all database handles that use it have been closed, the results
  148362. ** are undefined.
  148363. */
  148364. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
  148365. #if 0
  148366. } /* end of the 'extern "C"' block */
  148367. #endif
  148368. #endif /* _SQLITE3RBU_H */
  148369. /************** End of sqlite3rbu.h ******************************************/
  148370. /************** Continuing where we left off in sqlite3rbu.c *****************/
  148371. #if defined(_WIN32_WCE)
  148372. /* #include "windows.h" */
  148373. #endif
  148374. /* Maximum number of prepared UPDATE statements held by this module */
  148375. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  148376. /*
  148377. ** Swap two objects of type TYPE.
  148378. */
  148379. #if !defined(SQLITE_AMALGAMATION)
  148380. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  148381. #endif
  148382. /*
  148383. ** The rbu_state table is used to save the state of a partially applied
  148384. ** update so that it can be resumed later. The table consists of integer
  148385. ** keys mapped to values as follows:
  148386. **
  148387. ** RBU_STATE_STAGE:
  148388. ** May be set to integer values 1, 2, 4 or 5. As follows:
  148389. ** 1: the *-rbu file is currently under construction.
  148390. ** 2: the *-rbu file has been constructed, but not yet moved
  148391. ** to the *-wal path.
  148392. ** 4: the checkpoint is underway.
  148393. ** 5: the rbu update has been checkpointed.
  148394. **
  148395. ** RBU_STATE_TBL:
  148396. ** Only valid if STAGE==1. The target database name of the table
  148397. ** currently being written.
  148398. **
  148399. ** RBU_STATE_IDX:
  148400. ** Only valid if STAGE==1. The target database name of the index
  148401. ** currently being written, or NULL if the main table is currently being
  148402. ** updated.
  148403. **
  148404. ** RBU_STATE_ROW:
  148405. ** Only valid if STAGE==1. Number of rows already processed for the current
  148406. ** table/index.
  148407. **
  148408. ** RBU_STATE_PROGRESS:
  148409. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  148410. ** rbu update.
  148411. **
  148412. ** RBU_STATE_CKPT:
  148413. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  148414. ** header created by recovering the *-wal file. This is used to detect
  148415. ** cases when another client appends frames to the *-wal file in the
  148416. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  148417. ** be continued if this happens).
  148418. **
  148419. ** RBU_STATE_COOKIE:
  148420. ** Valid if STAGE==1. The current change-counter cookie value in the
  148421. ** target db file.
  148422. **
  148423. ** RBU_STATE_OALSZ:
  148424. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  148425. */
  148426. #define RBU_STATE_STAGE 1
  148427. #define RBU_STATE_TBL 2
  148428. #define RBU_STATE_IDX 3
  148429. #define RBU_STATE_ROW 4
  148430. #define RBU_STATE_PROGRESS 5
  148431. #define RBU_STATE_CKPT 6
  148432. #define RBU_STATE_COOKIE 7
  148433. #define RBU_STATE_OALSZ 8
  148434. #define RBU_STAGE_OAL 1
  148435. #define RBU_STAGE_MOVE 2
  148436. #define RBU_STAGE_CAPTURE 3
  148437. #define RBU_STAGE_CKPT 4
  148438. #define RBU_STAGE_DONE 5
  148439. #define RBU_CREATE_STATE \
  148440. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  148441. typedef struct RbuFrame RbuFrame;
  148442. typedef struct RbuObjIter RbuObjIter;
  148443. typedef struct RbuState RbuState;
  148444. typedef struct rbu_vfs rbu_vfs;
  148445. typedef struct rbu_file rbu_file;
  148446. typedef struct RbuUpdateStmt RbuUpdateStmt;
  148447. #if !defined(SQLITE_AMALGAMATION)
  148448. typedef unsigned int u32;
  148449. typedef unsigned char u8;
  148450. typedef sqlite3_int64 i64;
  148451. #endif
  148452. /*
  148453. ** These values must match the values defined in wal.c for the equivalent
  148454. ** locks. These are not magic numbers as they are part of the SQLite file
  148455. ** format.
  148456. */
  148457. #define WAL_LOCK_WRITE 0
  148458. #define WAL_LOCK_CKPT 1
  148459. #define WAL_LOCK_READ0 3
  148460. /*
  148461. ** A structure to store values read from the rbu_state table in memory.
  148462. */
  148463. struct RbuState {
  148464. int eStage;
  148465. char *zTbl;
  148466. char *zIdx;
  148467. i64 iWalCksum;
  148468. int nRow;
  148469. i64 nProgress;
  148470. u32 iCookie;
  148471. i64 iOalSz;
  148472. };
  148473. struct RbuUpdateStmt {
  148474. char *zMask; /* Copy of update mask used with pUpdate */
  148475. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  148476. RbuUpdateStmt *pNext;
  148477. };
  148478. /*
  148479. ** An iterator of this type is used to iterate through all objects in
  148480. ** the target database that require updating. For each such table, the
  148481. ** iterator visits, in order:
  148482. **
  148483. ** * the table itself,
  148484. ** * each index of the table (zero or more points to visit), and
  148485. ** * a special "cleanup table" state.
  148486. **
  148487. ** abIndexed:
  148488. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  148489. ** it points to an array of flags nTblCol elements in size. The flag is
  148490. ** set for each column that is either a part of the PK or a part of an
  148491. ** index. Or clear otherwise.
  148492. **
  148493. */
  148494. struct RbuObjIter {
  148495. sqlite3_stmt *pTblIter; /* Iterate through tables */
  148496. sqlite3_stmt *pIdxIter; /* Index iterator */
  148497. int nTblCol; /* Size of azTblCol[] array */
  148498. char **azTblCol; /* Array of unquoted target column names */
  148499. char **azTblType; /* Array of target column types */
  148500. int *aiSrcOrder; /* src table col -> target table col */
  148501. u8 *abTblPk; /* Array of flags, set on target PK columns */
  148502. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  148503. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  148504. int eType; /* Table type - an RBU_PK_XXX value */
  148505. /* Output variables. zTbl==0 implies EOF. */
  148506. int bCleanup; /* True in "cleanup" state */
  148507. const char *zTbl; /* Name of target db table */
  148508. const char *zDataTbl; /* Name of rbu db table (or null) */
  148509. const char *zIdx; /* Name of target db index (or null) */
  148510. int iTnum; /* Root page of current object */
  148511. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  148512. int bUnique; /* Current index is unique */
  148513. /* Statements created by rbuObjIterPrepareAll() */
  148514. int nCol; /* Number of columns in current object */
  148515. sqlite3_stmt *pSelect; /* Source data */
  148516. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  148517. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  148518. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  148519. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  148520. RbuUpdateStmt *pRbuUpdate;
  148521. };
  148522. /*
  148523. ** Values for RbuObjIter.eType
  148524. **
  148525. ** 0: Table does not exist (error)
  148526. ** 1: Table has an implicit rowid.
  148527. ** 2: Table has an explicit IPK column.
  148528. ** 3: Table has an external PK index.
  148529. ** 4: Table is WITHOUT ROWID.
  148530. ** 5: Table is a virtual table.
  148531. */
  148532. #define RBU_PK_NOTABLE 0
  148533. #define RBU_PK_NONE 1
  148534. #define RBU_PK_IPK 2
  148535. #define RBU_PK_EXTERNAL 3
  148536. #define RBU_PK_WITHOUT_ROWID 4
  148537. #define RBU_PK_VTAB 5
  148538. /*
  148539. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  148540. ** one of the following operations.
  148541. */
  148542. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  148543. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  148544. #define RBU_IDX_DELETE 3 /* Delete a row from an aux. index b-tree */
  148545. #define RBU_IDX_INSERT 4 /* Insert on an aux. index b-tree */
  148546. #define RBU_UPDATE 5 /* Update a row in a main table b-tree */
  148547. /*
  148548. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  148549. ** file should be copied to page iDbPage of the database file.
  148550. */
  148551. struct RbuFrame {
  148552. u32 iDbPage;
  148553. u32 iWalFrame;
  148554. };
  148555. /*
  148556. ** RBU handle.
  148557. */
  148558. struct sqlite3rbu {
  148559. int eStage; /* Value of RBU_STATE_STAGE field */
  148560. sqlite3 *dbMain; /* target database handle */
  148561. sqlite3 *dbRbu; /* rbu database handle */
  148562. char *zTarget; /* Path to target db */
  148563. char *zRbu; /* Path to rbu db */
  148564. char *zState; /* Path to state db (or NULL if zRbu) */
  148565. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  148566. int rc; /* Value returned by last rbu_step() call */
  148567. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  148568. int nStep; /* Rows processed for current object */
  148569. int nProgress; /* Rows processed for all objects */
  148570. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  148571. const char *zVfsName; /* Name of automatically created rbu vfs */
  148572. rbu_file *pTargetFd; /* File handle open on target db */
  148573. i64 iOalSz;
  148574. /* The following state variables are used as part of the incremental
  148575. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  148576. ** function rbuSetupCheckpoint() for details. */
  148577. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  148578. u32 mLock;
  148579. int nFrame; /* Entries in aFrame[] array */
  148580. int nFrameAlloc; /* Allocated size of aFrame[] array */
  148581. RbuFrame *aFrame;
  148582. int pgsz;
  148583. u8 *aBuf;
  148584. i64 iWalCksum;
  148585. };
  148586. /*
  148587. ** An rbu VFS is implemented using an instance of this structure.
  148588. */
  148589. struct rbu_vfs {
  148590. sqlite3_vfs base; /* rbu VFS shim methods */
  148591. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  148592. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  148593. rbu_file *pMain; /* Linked list of main db files */
  148594. };
  148595. /*
  148596. ** Each file opened by an rbu VFS is represented by an instance of
  148597. ** the following structure.
  148598. */
  148599. struct rbu_file {
  148600. sqlite3_file base; /* sqlite3_file methods */
  148601. sqlite3_file *pReal; /* Underlying file handle */
  148602. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  148603. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  148604. int openFlags; /* Flags this file was opened with */
  148605. u32 iCookie; /* Cookie value for main db files */
  148606. u8 iWriteVer; /* "write-version" value for main db files */
  148607. int nShm; /* Number of entries in apShm[] array */
  148608. char **apShm; /* Array of mmap'd *-shm regions */
  148609. char *zDel; /* Delete this when closing file */
  148610. const char *zWal; /* Wal filename for this main db file */
  148611. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  148612. rbu_file *pMainNext; /* Next MAIN_DB file */
  148613. };
  148614. /*************************************************************************
  148615. ** The following three functions, found below:
  148616. **
  148617. ** rbuDeltaGetInt()
  148618. ** rbuDeltaChecksum()
  148619. ** rbuDeltaApply()
  148620. **
  148621. ** are lifted from the fossil source code (http://fossil-scm.org). They
  148622. ** are used to implement the scalar SQL function rbu_fossil_delta().
  148623. */
  148624. /*
  148625. ** Read bytes from *pz and convert them into a positive integer. When
  148626. ** finished, leave *pz pointing to the first character past the end of
  148627. ** the integer. The *pLen parameter holds the length of the string
  148628. ** in *pz and is decremented once for each character in the integer.
  148629. */
  148630. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  148631. static const signed char zValue[] = {
  148632. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  148633. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  148634. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  148635. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  148636. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  148637. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  148638. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  148639. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  148640. };
  148641. unsigned int v = 0;
  148642. int c;
  148643. unsigned char *z = (unsigned char*)*pz;
  148644. unsigned char *zStart = z;
  148645. while( (c = zValue[0x7f&*(z++)])>=0 ){
  148646. v = (v<<6) + c;
  148647. }
  148648. z--;
  148649. *pLen -= z - zStart;
  148650. *pz = (char*)z;
  148651. return v;
  148652. }
  148653. /*
  148654. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  148655. */
  148656. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  148657. const unsigned char *z = (const unsigned char *)zIn;
  148658. unsigned sum0 = 0;
  148659. unsigned sum1 = 0;
  148660. unsigned sum2 = 0;
  148661. unsigned sum3 = 0;
  148662. while(N >= 16){
  148663. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  148664. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  148665. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  148666. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  148667. z += 16;
  148668. N -= 16;
  148669. }
  148670. while(N >= 4){
  148671. sum0 += z[0];
  148672. sum1 += z[1];
  148673. sum2 += z[2];
  148674. sum3 += z[3];
  148675. z += 4;
  148676. N -= 4;
  148677. }
  148678. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  148679. switch(N){
  148680. case 3: sum3 += (z[2] << 8);
  148681. case 2: sum3 += (z[1] << 16);
  148682. case 1: sum3 += (z[0] << 24);
  148683. default: ;
  148684. }
  148685. return sum3;
  148686. }
  148687. /*
  148688. ** Apply a delta.
  148689. **
  148690. ** The output buffer should be big enough to hold the whole output
  148691. ** file and a NUL terminator at the end. The delta_output_size()
  148692. ** routine will determine this size for you.
  148693. **
  148694. ** The delta string should be null-terminated. But the delta string
  148695. ** may contain embedded NUL characters (if the input and output are
  148696. ** binary files) so we also have to pass in the length of the delta in
  148697. ** the lenDelta parameter.
  148698. **
  148699. ** This function returns the size of the output file in bytes (excluding
  148700. ** the final NUL terminator character). Except, if the delta string is
  148701. ** malformed or intended for use with a source file other than zSrc,
  148702. ** then this routine returns -1.
  148703. **
  148704. ** Refer to the delta_create() documentation above for a description
  148705. ** of the delta file format.
  148706. */
  148707. static int rbuDeltaApply(
  148708. const char *zSrc, /* The source or pattern file */
  148709. int lenSrc, /* Length of the source file */
  148710. const char *zDelta, /* Delta to apply to the pattern */
  148711. int lenDelta, /* Length of the delta */
  148712. char *zOut /* Write the output into this preallocated buffer */
  148713. ){
  148714. unsigned int limit;
  148715. unsigned int total = 0;
  148716. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  148717. char *zOrigOut = zOut;
  148718. #endif
  148719. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  148720. if( *zDelta!='\n' ){
  148721. /* ERROR: size integer not terminated by "\n" */
  148722. return -1;
  148723. }
  148724. zDelta++; lenDelta--;
  148725. while( *zDelta && lenDelta>0 ){
  148726. unsigned int cnt, ofst;
  148727. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  148728. switch( zDelta[0] ){
  148729. case '@': {
  148730. zDelta++; lenDelta--;
  148731. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  148732. if( lenDelta>0 && zDelta[0]!=',' ){
  148733. /* ERROR: copy command not terminated by ',' */
  148734. return -1;
  148735. }
  148736. zDelta++; lenDelta--;
  148737. total += cnt;
  148738. if( total>limit ){
  148739. /* ERROR: copy exceeds output file size */
  148740. return -1;
  148741. }
  148742. if( (int)(ofst+cnt) > lenSrc ){
  148743. /* ERROR: copy extends past end of input */
  148744. return -1;
  148745. }
  148746. memcpy(zOut, &zSrc[ofst], cnt);
  148747. zOut += cnt;
  148748. break;
  148749. }
  148750. case ':': {
  148751. zDelta++; lenDelta--;
  148752. total += cnt;
  148753. if( total>limit ){
  148754. /* ERROR: insert command gives an output larger than predicted */
  148755. return -1;
  148756. }
  148757. if( (int)cnt>lenDelta ){
  148758. /* ERROR: insert count exceeds size of delta */
  148759. return -1;
  148760. }
  148761. memcpy(zOut, zDelta, cnt);
  148762. zOut += cnt;
  148763. zDelta += cnt;
  148764. lenDelta -= cnt;
  148765. break;
  148766. }
  148767. case ';': {
  148768. zDelta++; lenDelta--;
  148769. zOut[0] = 0;
  148770. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  148771. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  148772. /* ERROR: bad checksum */
  148773. return -1;
  148774. }
  148775. #endif
  148776. if( total!=limit ){
  148777. /* ERROR: generated size does not match predicted size */
  148778. return -1;
  148779. }
  148780. return total;
  148781. }
  148782. default: {
  148783. /* ERROR: unknown delta operator */
  148784. return -1;
  148785. }
  148786. }
  148787. }
  148788. /* ERROR: unterminated delta */
  148789. return -1;
  148790. }
  148791. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  148792. int size;
  148793. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  148794. if( *zDelta!='\n' ){
  148795. /* ERROR: size integer not terminated by "\n" */
  148796. return -1;
  148797. }
  148798. return size;
  148799. }
  148800. /*
  148801. ** End of code taken from fossil.
  148802. *************************************************************************/
  148803. /*
  148804. ** Implementation of SQL scalar function rbu_fossil_delta().
  148805. **
  148806. ** This function applies a fossil delta patch to a blob. Exactly two
  148807. ** arguments must be passed to this function. The first is the blob to
  148808. ** patch and the second the patch to apply. If no error occurs, this
  148809. ** function returns the patched blob.
  148810. */
  148811. static void rbuFossilDeltaFunc(
  148812. sqlite3_context *context,
  148813. int argc,
  148814. sqlite3_value **argv
  148815. ){
  148816. const char *aDelta;
  148817. int nDelta;
  148818. const char *aOrig;
  148819. int nOrig;
  148820. int nOut;
  148821. int nOut2;
  148822. char *aOut;
  148823. assert( argc==2 );
  148824. nOrig = sqlite3_value_bytes(argv[0]);
  148825. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  148826. nDelta = sqlite3_value_bytes(argv[1]);
  148827. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  148828. /* Figure out the size of the output */
  148829. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  148830. if( nOut<0 ){
  148831. sqlite3_result_error(context, "corrupt fossil delta", -1);
  148832. return;
  148833. }
  148834. aOut = sqlite3_malloc(nOut+1);
  148835. if( aOut==0 ){
  148836. sqlite3_result_error_nomem(context);
  148837. }else{
  148838. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  148839. if( nOut2!=nOut ){
  148840. sqlite3_result_error(context, "corrupt fossil delta", -1);
  148841. }else{
  148842. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  148843. }
  148844. }
  148845. }
  148846. /*
  148847. ** Prepare the SQL statement in buffer zSql against database handle db.
  148848. ** If successful, set *ppStmt to point to the new statement and return
  148849. ** SQLITE_OK.
  148850. **
  148851. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  148852. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  148853. ** point to a buffer containing an error message. It is the responsibility
  148854. ** of the caller to (eventually) free this buffer using sqlite3_free().
  148855. */
  148856. static int prepareAndCollectError(
  148857. sqlite3 *db,
  148858. sqlite3_stmt **ppStmt,
  148859. char **pzErrmsg,
  148860. const char *zSql
  148861. ){
  148862. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  148863. if( rc!=SQLITE_OK ){
  148864. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148865. *ppStmt = 0;
  148866. }
  148867. return rc;
  148868. }
  148869. /*
  148870. ** Reset the SQL statement passed as the first argument. Return a copy
  148871. ** of the value returned by sqlite3_reset().
  148872. **
  148873. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  148874. ** containing an error message. It is the responsibility of the caller
  148875. ** to eventually free this buffer using sqlite3_free().
  148876. */
  148877. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  148878. int rc = sqlite3_reset(pStmt);
  148879. if( rc!=SQLITE_OK ){
  148880. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  148881. }
  148882. return rc;
  148883. }
  148884. /*
  148885. ** Unless it is NULL, argument zSql points to a buffer allocated using
  148886. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  148887. ** statement against database db and frees the buffer. If statement
  148888. ** compilation is successful, *ppStmt is set to point to the new statement
  148889. ** handle and SQLITE_OK is returned.
  148890. **
  148891. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  148892. ** returned. In this case, *pzErrmsg may also be set to point to an error
  148893. ** message. It is the responsibility of the caller to free this error message
  148894. ** buffer using sqlite3_free().
  148895. **
  148896. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  148897. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  148898. */
  148899. static int prepareFreeAndCollectError(
  148900. sqlite3 *db,
  148901. sqlite3_stmt **ppStmt,
  148902. char **pzErrmsg,
  148903. char *zSql
  148904. ){
  148905. int rc;
  148906. assert( *pzErrmsg==0 );
  148907. if( zSql==0 ){
  148908. rc = SQLITE_NOMEM;
  148909. *ppStmt = 0;
  148910. }else{
  148911. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  148912. sqlite3_free(zSql);
  148913. }
  148914. return rc;
  148915. }
  148916. /*
  148917. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  148918. ** by an earlier call to rbuObjIterCacheTableInfo().
  148919. */
  148920. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  148921. int i;
  148922. for(i=0; i<pIter->nTblCol; i++){
  148923. sqlite3_free(pIter->azTblCol[i]);
  148924. sqlite3_free(pIter->azTblType[i]);
  148925. }
  148926. sqlite3_free(pIter->azTblCol);
  148927. pIter->azTblCol = 0;
  148928. pIter->azTblType = 0;
  148929. pIter->aiSrcOrder = 0;
  148930. pIter->abTblPk = 0;
  148931. pIter->abNotNull = 0;
  148932. pIter->nTblCol = 0;
  148933. pIter->eType = 0; /* Invalid value */
  148934. }
  148935. /*
  148936. ** Finalize all statements and free all allocations that are specific to
  148937. ** the current object (table/index pair).
  148938. */
  148939. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  148940. RbuUpdateStmt *pUp;
  148941. sqlite3_finalize(pIter->pSelect);
  148942. sqlite3_finalize(pIter->pInsert);
  148943. sqlite3_finalize(pIter->pDelete);
  148944. sqlite3_finalize(pIter->pTmpInsert);
  148945. pUp = pIter->pRbuUpdate;
  148946. while( pUp ){
  148947. RbuUpdateStmt *pTmp = pUp->pNext;
  148948. sqlite3_finalize(pUp->pUpdate);
  148949. sqlite3_free(pUp);
  148950. pUp = pTmp;
  148951. }
  148952. pIter->pSelect = 0;
  148953. pIter->pInsert = 0;
  148954. pIter->pDelete = 0;
  148955. pIter->pRbuUpdate = 0;
  148956. pIter->pTmpInsert = 0;
  148957. pIter->nCol = 0;
  148958. }
  148959. /*
  148960. ** Clean up any resources allocated as part of the iterator object passed
  148961. ** as the only argument.
  148962. */
  148963. static void rbuObjIterFinalize(RbuObjIter *pIter){
  148964. rbuObjIterClearStatements(pIter);
  148965. sqlite3_finalize(pIter->pTblIter);
  148966. sqlite3_finalize(pIter->pIdxIter);
  148967. rbuObjIterFreeCols(pIter);
  148968. memset(pIter, 0, sizeof(RbuObjIter));
  148969. }
  148970. /*
  148971. ** Advance the iterator to the next position.
  148972. **
  148973. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  148974. ** pointing to the next entry. Otherwise, an error code and message is
  148975. ** left in the RBU handle passed as the first argument. A copy of the
  148976. ** error code is returned.
  148977. */
  148978. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  148979. int rc = p->rc;
  148980. if( rc==SQLITE_OK ){
  148981. /* Free any SQLite statements used while processing the previous object */
  148982. rbuObjIterClearStatements(pIter);
  148983. if( pIter->zIdx==0 ){
  148984. rc = sqlite3_exec(p->dbMain,
  148985. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  148986. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  148987. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  148988. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  148989. , 0, 0, &p->zErrmsg
  148990. );
  148991. }
  148992. if( rc==SQLITE_OK ){
  148993. if( pIter->bCleanup ){
  148994. rbuObjIterFreeCols(pIter);
  148995. pIter->bCleanup = 0;
  148996. rc = sqlite3_step(pIter->pTblIter);
  148997. if( rc!=SQLITE_ROW ){
  148998. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  148999. pIter->zTbl = 0;
  149000. }else{
  149001. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  149002. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  149003. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  149004. }
  149005. }else{
  149006. if( pIter->zIdx==0 ){
  149007. sqlite3_stmt *pIdx = pIter->pIdxIter;
  149008. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  149009. }
  149010. if( rc==SQLITE_OK ){
  149011. rc = sqlite3_step(pIter->pIdxIter);
  149012. if( rc!=SQLITE_ROW ){
  149013. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  149014. pIter->bCleanup = 1;
  149015. pIter->zIdx = 0;
  149016. }else{
  149017. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  149018. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  149019. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  149020. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  149021. }
  149022. }
  149023. }
  149024. }
  149025. }
  149026. if( rc!=SQLITE_OK ){
  149027. rbuObjIterFinalize(pIter);
  149028. p->rc = rc;
  149029. }
  149030. return rc;
  149031. }
  149032. /*
  149033. ** The implementation of the rbu_target_name() SQL function. This function
  149034. ** accepts one argument - the name of a table in the RBU database. If the
  149035. ** table name matches the pattern:
  149036. **
  149037. ** data[0-9]_<name>
  149038. **
  149039. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  149040. ** Otherwise, if the only argument does not match the above pattern, an SQL
  149041. ** NULL is returned.
  149042. **
  149043. ** "data_t1" -> "t1"
  149044. ** "data0123_t2" -> "t2"
  149045. ** "dataAB_t3" -> NULL
  149046. */
  149047. static void rbuTargetNameFunc(
  149048. sqlite3_context *context,
  149049. int argc,
  149050. sqlite3_value **argv
  149051. ){
  149052. const char *zIn;
  149053. assert( argc==1 );
  149054. zIn = (const char*)sqlite3_value_text(argv[0]);
  149055. if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  149056. int i;
  149057. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  149058. if( zIn[i]=='_' && zIn[i+1] ){
  149059. sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
  149060. }
  149061. }
  149062. }
  149063. /*
  149064. ** Initialize the iterator structure passed as the second argument.
  149065. **
  149066. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  149067. ** pointing to the first entry. Otherwise, an error code and message is
  149068. ** left in the RBU handle passed as the first argument. A copy of the
  149069. ** error code is returned.
  149070. */
  149071. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  149072. int rc;
  149073. memset(pIter, 0, sizeof(RbuObjIter));
  149074. rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  149075. "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
  149076. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  149077. "ORDER BY name"
  149078. );
  149079. if( rc==SQLITE_OK ){
  149080. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  149081. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  149082. " FROM main.sqlite_master "
  149083. " WHERE type='index' AND tbl_name = ?"
  149084. );
  149085. }
  149086. pIter->bCleanup = 1;
  149087. p->rc = rc;
  149088. return rbuObjIterNext(p, pIter);
  149089. }
  149090. /*
  149091. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  149092. ** an error code is stored in the RBU handle passed as the first argument.
  149093. **
  149094. ** If an error has already occurred (p->rc is already set to something other
  149095. ** than SQLITE_OK), then this function returns NULL without modifying the
  149096. ** stored error code. In this case it still calls sqlite3_free() on any
  149097. ** printf() parameters associated with %z conversions.
  149098. */
  149099. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  149100. char *zSql = 0;
  149101. va_list ap;
  149102. va_start(ap, zFmt);
  149103. zSql = sqlite3_vmprintf(zFmt, ap);
  149104. if( p->rc==SQLITE_OK ){
  149105. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  149106. }else{
  149107. sqlite3_free(zSql);
  149108. zSql = 0;
  149109. }
  149110. va_end(ap);
  149111. return zSql;
  149112. }
  149113. /*
  149114. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  149115. ** arguments are the usual subsitution values. This function performs
  149116. ** the printf() style substitutions and executes the result as an SQL
  149117. ** statement on the RBU handles database.
  149118. **
  149119. ** If an error occurs, an error code and error message is stored in the
  149120. ** RBU handle. If an error has already occurred when this function is
  149121. ** called, it is a no-op.
  149122. */
  149123. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  149124. va_list ap;
  149125. char *zSql;
  149126. va_start(ap, zFmt);
  149127. zSql = sqlite3_vmprintf(zFmt, ap);
  149128. if( p->rc==SQLITE_OK ){
  149129. if( zSql==0 ){
  149130. p->rc = SQLITE_NOMEM;
  149131. }else{
  149132. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  149133. }
  149134. }
  149135. sqlite3_free(zSql);
  149136. va_end(ap);
  149137. return p->rc;
  149138. }
  149139. /*
  149140. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  149141. ** bytes.
  149142. **
  149143. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  149144. ** error code in the rbu handle passed as the first argument. Or, if an
  149145. ** error has already occurred when this function is called, return NULL
  149146. ** immediately without attempting the allocation or modifying the stored
  149147. ** error code.
  149148. */
  149149. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  149150. void *pRet = 0;
  149151. if( p->rc==SQLITE_OK ){
  149152. assert( nByte>0 );
  149153. pRet = sqlite3_malloc(nByte);
  149154. if( pRet==0 ){
  149155. p->rc = SQLITE_NOMEM;
  149156. }else{
  149157. memset(pRet, 0, nByte);
  149158. }
  149159. }
  149160. return pRet;
  149161. }
  149162. /*
  149163. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  149164. ** there is room for at least nCol elements. If an OOM occurs, store an
  149165. ** error code in the RBU handle passed as the first argument.
  149166. */
  149167. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  149168. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  149169. char **azNew;
  149170. azNew = (char**)rbuMalloc(p, nByte);
  149171. if( azNew ){
  149172. pIter->azTblCol = azNew;
  149173. pIter->azTblType = &azNew[nCol];
  149174. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  149175. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  149176. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  149177. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  149178. }
  149179. }
  149180. /*
  149181. ** The first argument must be a nul-terminated string. This function
  149182. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  149183. ** It is the responsibility of the caller to eventually free this memory
  149184. ** using sqlite3_free().
  149185. **
  149186. ** If an OOM condition is encountered when attempting to allocate memory,
  149187. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  149188. ** if the allocation succeeds, (*pRc) is left unchanged.
  149189. */
  149190. static char *rbuStrndup(const char *zStr, int *pRc){
  149191. char *zRet = 0;
  149192. assert( *pRc==SQLITE_OK );
  149193. if( zStr ){
  149194. int nCopy = strlen(zStr) + 1;
  149195. zRet = (char*)sqlite3_malloc(nCopy);
  149196. if( zRet ){
  149197. memcpy(zRet, zStr, nCopy);
  149198. }else{
  149199. *pRc = SQLITE_NOMEM;
  149200. }
  149201. }
  149202. return zRet;
  149203. }
  149204. /*
  149205. ** Finalize the statement passed as the second argument.
  149206. **
  149207. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  149208. ** rbu handle error code is not already set, set the error code and error
  149209. ** message accordingly.
  149210. */
  149211. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  149212. sqlite3 *db = sqlite3_db_handle(pStmt);
  149213. int rc = sqlite3_finalize(pStmt);
  149214. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  149215. p->rc = rc;
  149216. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  149217. }
  149218. }
  149219. /* Determine the type of a table.
  149220. **
  149221. ** peType is of type (int*), a pointer to an output parameter of type
  149222. ** (int). This call sets the output parameter as follows, depending
  149223. ** on the type of the table specified by parameters dbName and zTbl.
  149224. **
  149225. ** RBU_PK_NOTABLE: No such table.
  149226. ** RBU_PK_NONE: Table has an implicit rowid.
  149227. ** RBU_PK_IPK: Table has an explicit IPK column.
  149228. ** RBU_PK_EXTERNAL: Table has an external PK index.
  149229. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  149230. ** RBU_PK_VTAB: Table is a virtual table.
  149231. **
  149232. ** Argument *piPk is also of type (int*), and also points to an output
  149233. ** parameter. Unless the table has an external primary key index
  149234. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  149235. ** if the table does have an external primary key index, then *piPk
  149236. ** is set to the root page number of the primary key index before
  149237. ** returning.
  149238. **
  149239. ** ALGORITHM:
  149240. **
  149241. ** if( no entry exists in sqlite_master ){
  149242. ** return RBU_PK_NOTABLE
  149243. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  149244. ** return RBU_PK_VTAB
  149245. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  149246. ** if( the index that is the pk exists in sqlite_master ){
  149247. ** *piPK = rootpage of that index.
  149248. ** return RBU_PK_EXTERNAL
  149249. ** }else{
  149250. ** return RBU_PK_WITHOUT_ROWID
  149251. ** }
  149252. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  149253. ** return RBU_PK_IPK
  149254. ** }else{
  149255. ** return RBU_PK_NONE
  149256. ** }
  149257. */
  149258. static void rbuTableType(
  149259. sqlite3rbu *p,
  149260. const char *zTab,
  149261. int *peType,
  149262. int *piTnum,
  149263. int *piPk
  149264. ){
  149265. /*
  149266. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  149267. ** 1) PRAGMA index_list = ?
  149268. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  149269. ** 3) PRAGMA table_info = ?
  149270. */
  149271. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  149272. *peType = RBU_PK_NOTABLE;
  149273. *piPk = 0;
  149274. assert( p->rc==SQLITE_OK );
  149275. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  149276. sqlite3_mprintf(
  149277. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  149278. " FROM sqlite_master"
  149279. " WHERE name=%Q", zTab
  149280. ));
  149281. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  149282. /* Either an error, or no such table. */
  149283. goto rbuTableType_end;
  149284. }
  149285. if( sqlite3_column_int(aStmt[0], 0) ){
  149286. *peType = RBU_PK_VTAB; /* virtual table */
  149287. goto rbuTableType_end;
  149288. }
  149289. *piTnum = sqlite3_column_int(aStmt[0], 1);
  149290. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  149291. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  149292. );
  149293. if( p->rc ) goto rbuTableType_end;
  149294. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  149295. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  149296. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  149297. if( zOrig && zIdx && zOrig[0]=='p' ){
  149298. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  149299. sqlite3_mprintf(
  149300. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  149301. ));
  149302. if( p->rc==SQLITE_OK ){
  149303. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  149304. *piPk = sqlite3_column_int(aStmt[2], 0);
  149305. *peType = RBU_PK_EXTERNAL;
  149306. }else{
  149307. *peType = RBU_PK_WITHOUT_ROWID;
  149308. }
  149309. }
  149310. goto rbuTableType_end;
  149311. }
  149312. }
  149313. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  149314. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  149315. );
  149316. if( p->rc==SQLITE_OK ){
  149317. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  149318. if( sqlite3_column_int(aStmt[3],5)>0 ){
  149319. *peType = RBU_PK_IPK; /* explicit IPK column */
  149320. goto rbuTableType_end;
  149321. }
  149322. }
  149323. *peType = RBU_PK_NONE;
  149324. }
  149325. rbuTableType_end: {
  149326. unsigned int i;
  149327. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  149328. rbuFinalize(p, aStmt[i]);
  149329. }
  149330. }
  149331. }
  149332. /*
  149333. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  149334. ** the pIter->abIndexed[] array.
  149335. */
  149336. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  149337. sqlite3_stmt *pList = 0;
  149338. int bIndex = 0;
  149339. if( p->rc==SQLITE_OK ){
  149340. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  149341. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  149342. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  149343. );
  149344. }
  149345. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  149346. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  149347. sqlite3_stmt *pXInfo = 0;
  149348. if( zIdx==0 ) break;
  149349. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  149350. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  149351. );
  149352. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  149353. int iCid = sqlite3_column_int(pXInfo, 1);
  149354. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  149355. }
  149356. rbuFinalize(p, pXInfo);
  149357. bIndex = 1;
  149358. }
  149359. rbuFinalize(p, pList);
  149360. if( bIndex==0 ) pIter->abIndexed = 0;
  149361. }
  149362. /*
  149363. ** If they are not already populated, populate the pIter->azTblCol[],
  149364. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  149365. ** the table (not index) that the iterator currently points to.
  149366. **
  149367. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  149368. ** an error does occur, an error code and error message are also left in
  149369. ** the RBU handle.
  149370. */
  149371. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  149372. if( pIter->azTblCol==0 ){
  149373. sqlite3_stmt *pStmt = 0;
  149374. int nCol = 0;
  149375. int i; /* for() loop iterator variable */
  149376. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  149377. int iOrder = 0;
  149378. int iTnum = 0;
  149379. /* Figure out the type of table this step will deal with. */
  149380. assert( pIter->eType==0 );
  149381. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  149382. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  149383. p->rc = SQLITE_ERROR;
  149384. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  149385. }
  149386. if( p->rc ) return p->rc;
  149387. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  149388. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  149389. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  149390. || pIter->eType==RBU_PK_VTAB
  149391. );
  149392. /* Populate the azTblCol[] and nTblCol variables based on the columns
  149393. ** of the input table. Ignore any input table columns that begin with
  149394. ** "rbu_". */
  149395. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  149396. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  149397. );
  149398. if( p->rc==SQLITE_OK ){
  149399. nCol = sqlite3_column_count(pStmt);
  149400. rbuAllocateIterArrays(p, pIter, nCol);
  149401. }
  149402. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  149403. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  149404. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  149405. char *zCopy = rbuStrndup(zName, &p->rc);
  149406. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  149407. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  149408. }
  149409. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  149410. bRbuRowid = 1;
  149411. }
  149412. }
  149413. sqlite3_finalize(pStmt);
  149414. pStmt = 0;
  149415. if( p->rc==SQLITE_OK
  149416. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  149417. ){
  149418. p->rc = SQLITE_ERROR;
  149419. p->zErrmsg = sqlite3_mprintf(
  149420. "table %q %s rbu_rowid column", pIter->zDataTbl,
  149421. (bRbuRowid ? "may not have" : "requires")
  149422. );
  149423. }
  149424. /* Check that all non-HIDDEN columns in the destination table are also
  149425. ** present in the input table. Populate the abTblPk[], azTblType[] and
  149426. ** aiTblOrder[] arrays at the same time. */
  149427. if( p->rc==SQLITE_OK ){
  149428. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  149429. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  149430. );
  149431. }
  149432. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  149433. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  149434. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  149435. for(i=iOrder; i<pIter->nTblCol; i++){
  149436. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  149437. }
  149438. if( i==pIter->nTblCol ){
  149439. p->rc = SQLITE_ERROR;
  149440. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  149441. pIter->zDataTbl, zName
  149442. );
  149443. }else{
  149444. int iPk = sqlite3_column_int(pStmt, 5);
  149445. int bNotNull = sqlite3_column_int(pStmt, 3);
  149446. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  149447. if( i!=iOrder ){
  149448. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  149449. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  149450. }
  149451. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  149452. pIter->abTblPk[iOrder] = (iPk!=0);
  149453. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  149454. iOrder++;
  149455. }
  149456. }
  149457. rbuFinalize(p, pStmt);
  149458. rbuObjIterCacheIndexedCols(p, pIter);
  149459. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  149460. }
  149461. return p->rc;
  149462. }
  149463. /*
  149464. ** This function constructs and returns a pointer to a nul-terminated
  149465. ** string containing some SQL clause or list based on one or more of the
  149466. ** column names currently stored in the pIter->azTblCol[] array.
  149467. */
  149468. static char *rbuObjIterGetCollist(
  149469. sqlite3rbu *p, /* RBU object */
  149470. RbuObjIter *pIter /* Object iterator for column names */
  149471. ){
  149472. char *zList = 0;
  149473. const char *zSep = "";
  149474. int i;
  149475. for(i=0; i<pIter->nTblCol; i++){
  149476. const char *z = pIter->azTblCol[i];
  149477. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  149478. zSep = ", ";
  149479. }
  149480. return zList;
  149481. }
  149482. /*
  149483. ** This function is used to create a SELECT list (the list of SQL
  149484. ** expressions that follows a SELECT keyword) for a SELECT statement
  149485. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  149486. ** index object currently indicated by the iterator object passed as the
  149487. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  149488. ** to obtain the required information.
  149489. **
  149490. ** If the index is of the following form:
  149491. **
  149492. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  149493. **
  149494. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  149495. ** "ipk", the returned string is:
  149496. **
  149497. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  149498. **
  149499. ** As well as the returned string, three other malloc'd strings are
  149500. ** returned via output parameters. As follows:
  149501. **
  149502. ** pzImposterCols: ...
  149503. ** pzImposterPk: ...
  149504. ** pzWhere: ...
  149505. */
  149506. static char *rbuObjIterGetIndexCols(
  149507. sqlite3rbu *p, /* RBU object */
  149508. RbuObjIter *pIter, /* Object iterator for column names */
  149509. char **pzImposterCols, /* OUT: Columns for imposter table */
  149510. char **pzImposterPk, /* OUT: Imposter PK clause */
  149511. char **pzWhere, /* OUT: WHERE clause */
  149512. int *pnBind /* OUT: Trbul number of columns */
  149513. ){
  149514. int rc = p->rc; /* Error code */
  149515. int rc2; /* sqlite3_finalize() return code */
  149516. char *zRet = 0; /* String to return */
  149517. char *zImpCols = 0; /* String to return via *pzImposterCols */
  149518. char *zImpPK = 0; /* String to return via *pzImposterPK */
  149519. char *zWhere = 0; /* String to return via *pzWhere */
  149520. int nBind = 0; /* Value to return via *pnBind */
  149521. const char *zCom = ""; /* Set to ", " later on */
  149522. const char *zAnd = ""; /* Set to " AND " later on */
  149523. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  149524. if( rc==SQLITE_OK ){
  149525. assert( p->zErrmsg==0 );
  149526. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  149527. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  149528. );
  149529. }
  149530. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  149531. int iCid = sqlite3_column_int(pXInfo, 1);
  149532. int bDesc = sqlite3_column_int(pXInfo, 3);
  149533. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  149534. const char *zCol;
  149535. const char *zType;
  149536. if( iCid<0 ){
  149537. /* An integer primary key. If the table has an explicit IPK, use
  149538. ** its name. Otherwise, use "rbu_rowid". */
  149539. if( pIter->eType==RBU_PK_IPK ){
  149540. int i;
  149541. for(i=0; pIter->abTblPk[i]==0; i++);
  149542. assert( i<pIter->nTblCol );
  149543. zCol = pIter->azTblCol[i];
  149544. }else{
  149545. zCol = "rbu_rowid";
  149546. }
  149547. zType = "INTEGER";
  149548. }else{
  149549. zCol = pIter->azTblCol[iCid];
  149550. zType = pIter->azTblType[iCid];
  149551. }
  149552. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  149553. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  149554. const char *zOrder = (bDesc ? " DESC" : "");
  149555. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  149556. zImpPK, zCom, nBind, zCol, zOrder
  149557. );
  149558. }
  149559. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  149560. zImpCols, zCom, nBind, zCol, zType, zCollate
  149561. );
  149562. zWhere = sqlite3_mprintf(
  149563. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  149564. );
  149565. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  149566. zCom = ", ";
  149567. zAnd = " AND ";
  149568. nBind++;
  149569. }
  149570. rc2 = sqlite3_finalize(pXInfo);
  149571. if( rc==SQLITE_OK ) rc = rc2;
  149572. if( rc!=SQLITE_OK ){
  149573. sqlite3_free(zRet);
  149574. sqlite3_free(zImpCols);
  149575. sqlite3_free(zImpPK);
  149576. sqlite3_free(zWhere);
  149577. zRet = 0;
  149578. zImpCols = 0;
  149579. zImpPK = 0;
  149580. zWhere = 0;
  149581. p->rc = rc;
  149582. }
  149583. *pzImposterCols = zImpCols;
  149584. *pzImposterPk = zImpPK;
  149585. *pzWhere = zWhere;
  149586. *pnBind = nBind;
  149587. return zRet;
  149588. }
  149589. /*
  149590. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  149591. ** paramter is passed "old", return a string of the form:
  149592. **
  149593. ** "old.a, old.b, old.b"
  149594. **
  149595. ** With the column names escaped.
  149596. **
  149597. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  149598. ** the text ", old._rowid_" to the returned value.
  149599. */
  149600. static char *rbuObjIterGetOldlist(
  149601. sqlite3rbu *p,
  149602. RbuObjIter *pIter,
  149603. const char *zObj
  149604. ){
  149605. char *zList = 0;
  149606. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  149607. const char *zS = "";
  149608. int i;
  149609. for(i=0; i<pIter->nTblCol; i++){
  149610. if( pIter->abIndexed[i] ){
  149611. const char *zCol = pIter->azTblCol[i];
  149612. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  149613. }else{
  149614. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  149615. }
  149616. zS = ", ";
  149617. if( zList==0 ){
  149618. p->rc = SQLITE_NOMEM;
  149619. break;
  149620. }
  149621. }
  149622. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  149623. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  149624. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  149625. }
  149626. }
  149627. return zList;
  149628. }
  149629. /*
  149630. ** Return an expression that can be used in a WHERE clause to match the
  149631. ** primary key of the current table. For example, if the table is:
  149632. **
  149633. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  149634. **
  149635. ** Return the string:
  149636. **
  149637. ** "b = ?1 AND c = ?2"
  149638. */
  149639. static char *rbuObjIterGetWhere(
  149640. sqlite3rbu *p,
  149641. RbuObjIter *pIter
  149642. ){
  149643. char *zList = 0;
  149644. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  149645. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  149646. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  149647. const char *zSep = "";
  149648. int i;
  149649. for(i=0; i<pIter->nTblCol; i++){
  149650. if( pIter->abTblPk[i] ){
  149651. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  149652. zSep = " AND ";
  149653. }
  149654. }
  149655. zList = rbuMPrintf(p,
  149656. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  149657. );
  149658. }else{
  149659. const char *zSep = "";
  149660. int i;
  149661. for(i=0; i<pIter->nTblCol; i++){
  149662. if( pIter->abTblPk[i] ){
  149663. const char *zCol = pIter->azTblCol[i];
  149664. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  149665. zSep = " AND ";
  149666. }
  149667. }
  149668. }
  149669. return zList;
  149670. }
  149671. /*
  149672. ** The SELECT statement iterating through the keys for the current object
  149673. ** (p->objiter.pSelect) currently points to a valid row. However, there
  149674. ** is something wrong with the rbu_control value in the rbu_control value
  149675. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  149676. ** of the RBU handle to something reflecting this.
  149677. */
  149678. static void rbuBadControlError(sqlite3rbu *p){
  149679. p->rc = SQLITE_ERROR;
  149680. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  149681. }
  149682. /*
  149683. ** Return a nul-terminated string containing the comma separated list of
  149684. ** assignments that should be included following the "SET" keyword of
  149685. ** an UPDATE statement used to update the table object that the iterator
  149686. ** passed as the second argument currently points to if the rbu_control
  149687. ** column of the data_xxx table entry is set to zMask.
  149688. **
  149689. ** The memory for the returned string is obtained from sqlite3_malloc().
  149690. ** It is the responsibility of the caller to eventually free it using
  149691. ** sqlite3_free().
  149692. **
  149693. ** If an OOM error is encountered when allocating space for the new
  149694. ** string, an error code is left in the rbu handle passed as the first
  149695. ** argument and NULL is returned. Or, if an error has already occurred
  149696. ** when this function is called, NULL is returned immediately, without
  149697. ** attempting the allocation or modifying the stored error code.
  149698. */
  149699. static char *rbuObjIterGetSetlist(
  149700. sqlite3rbu *p,
  149701. RbuObjIter *pIter,
  149702. const char *zMask
  149703. ){
  149704. char *zList = 0;
  149705. if( p->rc==SQLITE_OK ){
  149706. int i;
  149707. if( (int)strlen(zMask)!=pIter->nTblCol ){
  149708. rbuBadControlError(p);
  149709. }else{
  149710. const char *zSep = "";
  149711. for(i=0; i<pIter->nTblCol; i++){
  149712. char c = zMask[pIter->aiSrcOrder[i]];
  149713. if( c=='x' ){
  149714. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  149715. zList, zSep, pIter->azTblCol[i], i+1
  149716. );
  149717. zSep = ", ";
  149718. }
  149719. else if( c=='d' ){
  149720. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  149721. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  149722. );
  149723. zSep = ", ";
  149724. }
  149725. else if( c=='f' ){
  149726. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  149727. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  149728. );
  149729. zSep = ", ";
  149730. }
  149731. }
  149732. }
  149733. }
  149734. return zList;
  149735. }
  149736. /*
  149737. ** Return a nul-terminated string consisting of nByte comma separated
  149738. ** "?" expressions. For example, if nByte is 3, return a pointer to
  149739. ** a buffer containing the string "?,?,?".
  149740. **
  149741. ** The memory for the returned string is obtained from sqlite3_malloc().
  149742. ** It is the responsibility of the caller to eventually free it using
  149743. ** sqlite3_free().
  149744. **
  149745. ** If an OOM error is encountered when allocating space for the new
  149746. ** string, an error code is left in the rbu handle passed as the first
  149747. ** argument and NULL is returned. Or, if an error has already occurred
  149748. ** when this function is called, NULL is returned immediately, without
  149749. ** attempting the allocation or modifying the stored error code.
  149750. */
  149751. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  149752. char *zRet = 0;
  149753. int nByte = nBind*2 + 1;
  149754. zRet = (char*)rbuMalloc(p, nByte);
  149755. if( zRet ){
  149756. int i;
  149757. for(i=0; i<nBind; i++){
  149758. zRet[i*2] = '?';
  149759. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  149760. }
  149761. }
  149762. return zRet;
  149763. }
  149764. /*
  149765. ** The iterator currently points to a table (not index) of type
  149766. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  149767. ** declaration for the corresponding imposter table. For example,
  149768. ** if the iterator points to a table created as:
  149769. **
  149770. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  149771. **
  149772. ** this function returns:
  149773. **
  149774. ** PRIMARY KEY("b", "a" DESC)
  149775. */
  149776. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  149777. char *z = 0;
  149778. assert( pIter->zIdx==0 );
  149779. if( p->rc==SQLITE_OK ){
  149780. const char *zSep = "PRIMARY KEY(";
  149781. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  149782. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  149783. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  149784. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  149785. );
  149786. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  149787. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  149788. if( zOrig && strcmp(zOrig, "pk")==0 ){
  149789. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  149790. if( zIdx ){
  149791. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  149792. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  149793. );
  149794. }
  149795. break;
  149796. }
  149797. }
  149798. rbuFinalize(p, pXList);
  149799. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  149800. if( sqlite3_column_int(pXInfo, 5) ){
  149801. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  149802. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  149803. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  149804. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  149805. zSep = ", ";
  149806. }
  149807. }
  149808. z = rbuMPrintf(p, "%z)", z);
  149809. rbuFinalize(p, pXInfo);
  149810. }
  149811. return z;
  149812. }
  149813. /*
  149814. ** This function creates the second imposter table used when writing to
  149815. ** a table b-tree where the table has an external primary key. If the
  149816. ** iterator passed as the second argument does not currently point to
  149817. ** a table (not index) with an external primary key, this function is a
  149818. ** no-op.
  149819. **
  149820. ** Assuming the iterator does point to a table with an external PK, this
  149821. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  149822. ** used to access that PK index. For example, if the target table is
  149823. ** declared as follows:
  149824. **
  149825. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  149826. **
  149827. ** then the imposter table schema is:
  149828. **
  149829. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  149830. **
  149831. */
  149832. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  149833. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  149834. int tnum = pIter->iPkTnum; /* Root page of PK index */
  149835. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  149836. const char *zIdx = 0; /* Name of PK index */
  149837. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  149838. const char *zComma = "";
  149839. char *zCols = 0; /* Used to build up list of table cols */
  149840. char *zPk = 0; /* Used to build up table PK declaration */
  149841. /* Figure out the name of the primary key index for the current table.
  149842. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  149843. ** zIdx to point to a nul-terminated string containing this name. */
  149844. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  149845. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  149846. );
  149847. if( p->rc==SQLITE_OK ){
  149848. sqlite3_bind_int(pQuery, 1, tnum);
  149849. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  149850. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  149851. }
  149852. }
  149853. if( zIdx ){
  149854. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  149855. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  149856. );
  149857. }
  149858. rbuFinalize(p, pQuery);
  149859. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  149860. int bKey = sqlite3_column_int(pXInfo, 5);
  149861. if( bKey ){
  149862. int iCid = sqlite3_column_int(pXInfo, 1);
  149863. int bDesc = sqlite3_column_int(pXInfo, 3);
  149864. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  149865. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  149866. iCid, pIter->azTblType[iCid], zCollate
  149867. );
  149868. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  149869. zComma = ", ";
  149870. }
  149871. }
  149872. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  149873. rbuFinalize(p, pXInfo);
  149874. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  149875. rbuMPrintfExec(p, p->dbMain,
  149876. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  149877. zCols, zPk
  149878. );
  149879. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  149880. }
  149881. }
  149882. /*
  149883. ** If an error has already occurred when this function is called, it
  149884. ** immediately returns zero (without doing any work). Or, if an error
  149885. ** occurs during the execution of this function, it sets the error code
  149886. ** in the sqlite3rbu object indicated by the first argument and returns
  149887. ** zero.
  149888. **
  149889. ** The iterator passed as the second argument is guaranteed to point to
  149890. ** a table (not an index) when this function is called. This function
  149891. ** attempts to create any imposter table required to write to the main
  149892. ** table b-tree of the table before returning. Non-zero is returned if
  149893. ** an imposter table are created, or zero otherwise.
  149894. **
  149895. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  149896. ** virtual tables are written to directly. The imposter table has the
  149897. ** same schema as the actual target table (less any UNIQUE constraints).
  149898. ** More precisely, the "same schema" means the same columns, types,
  149899. ** collation sequences. For tables that do not have an external PRIMARY
  149900. ** KEY, it also means the same PRIMARY KEY declaration.
  149901. */
  149902. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  149903. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  149904. int tnum = pIter->iTnum;
  149905. const char *zComma = "";
  149906. char *zSql = 0;
  149907. int iCol;
  149908. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  149909. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  149910. const char *zPk = "";
  149911. const char *zCol = pIter->azTblCol[iCol];
  149912. const char *zColl = 0;
  149913. p->rc = sqlite3_table_column_metadata(
  149914. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  149915. );
  149916. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  149917. /* If the target table column is an "INTEGER PRIMARY KEY", add
  149918. ** "PRIMARY KEY" to the imposter table column declaration. */
  149919. zPk = "PRIMARY KEY ";
  149920. }
  149921. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  149922. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  149923. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  149924. );
  149925. zComma = ", ";
  149926. }
  149927. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  149928. char *zPk = rbuWithoutRowidPK(p, pIter);
  149929. if( zPk ){
  149930. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  149931. }
  149932. }
  149933. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  149934. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  149935. pIter->zTbl, zSql,
  149936. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  149937. );
  149938. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  149939. }
  149940. }
  149941. /*
  149942. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  149943. ** Specifically a statement of the form:
  149944. **
  149945. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  149946. **
  149947. ** The number of bound variables is equal to the number of columns in
  149948. ** the target table, plus one (for the rbu_control column), plus one more
  149949. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  149950. ** virtual table.
  149951. */
  149952. static void rbuObjIterPrepareTmpInsert(
  149953. sqlite3rbu *p,
  149954. RbuObjIter *pIter,
  149955. const char *zCollist,
  149956. const char *zRbuRowid
  149957. ){
  149958. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  149959. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  149960. if( zBind ){
  149961. assert( pIter->pTmpInsert==0 );
  149962. p->rc = prepareFreeAndCollectError(
  149963. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  149964. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  149965. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  149966. ));
  149967. }
  149968. }
  149969. static void rbuTmpInsertFunc(
  149970. sqlite3_context *pCtx,
  149971. int nVal,
  149972. sqlite3_value **apVal
  149973. ){
  149974. sqlite3rbu *p = sqlite3_user_data(pCtx);
  149975. int rc = SQLITE_OK;
  149976. int i;
  149977. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  149978. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  149979. }
  149980. if( rc==SQLITE_OK ){
  149981. sqlite3_step(p->objiter.pTmpInsert);
  149982. rc = sqlite3_reset(p->objiter.pTmpInsert);
  149983. }
  149984. if( rc!=SQLITE_OK ){
  149985. sqlite3_result_error_code(pCtx, rc);
  149986. }
  149987. }
  149988. /*
  149989. ** Ensure that the SQLite statement handles required to update the
  149990. ** target database object currently indicated by the iterator passed
  149991. ** as the second argument are available.
  149992. */
  149993. static int rbuObjIterPrepareAll(
  149994. sqlite3rbu *p,
  149995. RbuObjIter *pIter,
  149996. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  149997. ){
  149998. assert( pIter->bCleanup==0 );
  149999. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  150000. const int tnum = pIter->iTnum;
  150001. char *zCollist = 0; /* List of indexed columns */
  150002. char **pz = &p->zErrmsg;
  150003. const char *zIdx = pIter->zIdx;
  150004. char *zLimit = 0;
  150005. if( nOffset ){
  150006. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  150007. if( !zLimit ) p->rc = SQLITE_NOMEM;
  150008. }
  150009. if( zIdx ){
  150010. const char *zTbl = pIter->zTbl;
  150011. char *zImposterCols = 0; /* Columns for imposter table */
  150012. char *zImposterPK = 0; /* Primary key declaration for imposter */
  150013. char *zWhere = 0; /* WHERE clause on PK columns */
  150014. char *zBind = 0;
  150015. int nBind = 0;
  150016. assert( pIter->eType!=RBU_PK_VTAB );
  150017. zCollist = rbuObjIterGetIndexCols(
  150018. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  150019. );
  150020. zBind = rbuObjIterGetBindlist(p, nBind);
  150021. /* Create the imposter table used to write to this index. */
  150022. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  150023. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  150024. rbuMPrintfExec(p, p->dbMain,
  150025. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  150026. zTbl, zImposterCols, zImposterPK
  150027. );
  150028. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  150029. /* Create the statement to insert index entries */
  150030. pIter->nCol = nBind;
  150031. if( p->rc==SQLITE_OK ){
  150032. p->rc = prepareFreeAndCollectError(
  150033. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  150034. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  150035. );
  150036. }
  150037. /* And to delete index entries */
  150038. if( p->rc==SQLITE_OK ){
  150039. p->rc = prepareFreeAndCollectError(
  150040. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  150041. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  150042. );
  150043. }
  150044. /* Create the SELECT statement to read keys in sorted order */
  150045. if( p->rc==SQLITE_OK ){
  150046. char *zSql;
  150047. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  150048. zSql = sqlite3_mprintf(
  150049. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  150050. zCollist, p->zStateDb, pIter->zDataTbl,
  150051. zCollist, zLimit
  150052. );
  150053. }else{
  150054. zSql = sqlite3_mprintf(
  150055. "SELECT %s, rbu_control FROM '%q' "
  150056. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  150057. "UNION ALL "
  150058. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  150059. "ORDER BY %s%s",
  150060. zCollist, pIter->zDataTbl,
  150061. zCollist, p->zStateDb, pIter->zDataTbl,
  150062. zCollist, zLimit
  150063. );
  150064. }
  150065. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  150066. }
  150067. sqlite3_free(zImposterCols);
  150068. sqlite3_free(zImposterPK);
  150069. sqlite3_free(zWhere);
  150070. sqlite3_free(zBind);
  150071. }else{
  150072. int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
  150073. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  150074. const char *zWrite; /* Imposter table name */
  150075. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  150076. char *zWhere = rbuObjIterGetWhere(p, pIter);
  150077. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  150078. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  150079. zCollist = rbuObjIterGetCollist(p, pIter);
  150080. pIter->nCol = pIter->nTblCol;
  150081. /* Create the imposter table or tables (if required). */
  150082. rbuCreateImposterTable(p, pIter);
  150083. rbuCreateImposterTable2(p, pIter);
  150084. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  150085. /* Create the INSERT statement to write to the target PK b-tree */
  150086. if( p->rc==SQLITE_OK ){
  150087. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  150088. sqlite3_mprintf(
  150089. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  150090. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  150091. )
  150092. );
  150093. }
  150094. /* Create the DELETE statement to write to the target PK b-tree */
  150095. if( p->rc==SQLITE_OK ){
  150096. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  150097. sqlite3_mprintf(
  150098. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  150099. )
  150100. );
  150101. }
  150102. if( pIter->abIndexed ){
  150103. const char *zRbuRowid = "";
  150104. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  150105. zRbuRowid = ", rbu_rowid";
  150106. }
  150107. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  150108. rbuMPrintfExec(p, p->dbRbu,
  150109. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  150110. "SELECT *%s FROM '%q' WHERE 0;"
  150111. , p->zStateDb, pIter->zDataTbl
  150112. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  150113. , pIter->zDataTbl
  150114. );
  150115. rbuMPrintfExec(p, p->dbMain,
  150116. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  150117. "BEGIN "
  150118. " SELECT rbu_tmp_insert(2, %s);"
  150119. "END;"
  150120. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  150121. "BEGIN "
  150122. " SELECT rbu_tmp_insert(2, %s);"
  150123. "END;"
  150124. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  150125. "BEGIN "
  150126. " SELECT rbu_tmp_insert(3, %s);"
  150127. "END;",
  150128. zWrite, zTbl, zOldlist,
  150129. zWrite, zTbl, zOldlist,
  150130. zWrite, zTbl, zNewlist
  150131. );
  150132. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  150133. rbuMPrintfExec(p, p->dbMain,
  150134. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  150135. "BEGIN "
  150136. " SELECT rbu_tmp_insert(0, %s);"
  150137. "END;",
  150138. zWrite, zTbl, zNewlist
  150139. );
  150140. }
  150141. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  150142. }
  150143. /* Create the SELECT statement to read keys from data_xxx */
  150144. if( p->rc==SQLITE_OK ){
  150145. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  150146. sqlite3_mprintf(
  150147. "SELECT %s, rbu_control%s FROM '%q'%s",
  150148. zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
  150149. pIter->zDataTbl, zLimit
  150150. )
  150151. );
  150152. }
  150153. sqlite3_free(zWhere);
  150154. sqlite3_free(zOldlist);
  150155. sqlite3_free(zNewlist);
  150156. sqlite3_free(zBindings);
  150157. }
  150158. sqlite3_free(zCollist);
  150159. sqlite3_free(zLimit);
  150160. }
  150161. return p->rc;
  150162. }
  150163. /*
  150164. ** Set output variable *ppStmt to point to an UPDATE statement that may
  150165. ** be used to update the imposter table for the main table b-tree of the
  150166. ** table object that pIter currently points to, assuming that the
  150167. ** rbu_control column of the data_xyz table contains zMask.
  150168. **
  150169. ** If the zMask string does not specify any columns to update, then this
  150170. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  150171. */
  150172. static int rbuGetUpdateStmt(
  150173. sqlite3rbu *p, /* RBU handle */
  150174. RbuObjIter *pIter, /* Object iterator */
  150175. const char *zMask, /* rbu_control value ('x.x.') */
  150176. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  150177. ){
  150178. RbuUpdateStmt **pp;
  150179. RbuUpdateStmt *pUp = 0;
  150180. int nUp = 0;
  150181. /* In case an error occurs */
  150182. *ppStmt = 0;
  150183. /* Search for an existing statement. If one is found, shift it to the front
  150184. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  150185. ** to the number of statements currently in the cache and pUp to the
  150186. ** last object in the list. */
  150187. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  150188. pUp = *pp;
  150189. if( strcmp(pUp->zMask, zMask)==0 ){
  150190. *pp = pUp->pNext;
  150191. pUp->pNext = pIter->pRbuUpdate;
  150192. pIter->pRbuUpdate = pUp;
  150193. *ppStmt = pUp->pUpdate;
  150194. return SQLITE_OK;
  150195. }
  150196. nUp++;
  150197. }
  150198. assert( pUp==0 || pUp->pNext==0 );
  150199. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  150200. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  150201. *pp = 0;
  150202. sqlite3_finalize(pUp->pUpdate);
  150203. pUp->pUpdate = 0;
  150204. }else{
  150205. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  150206. }
  150207. if( pUp ){
  150208. char *zWhere = rbuObjIterGetWhere(p, pIter);
  150209. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  150210. char *zUpdate = 0;
  150211. pUp->zMask = (char*)&pUp[1];
  150212. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  150213. pUp->pNext = pIter->pRbuUpdate;
  150214. pIter->pRbuUpdate = pUp;
  150215. if( zSet ){
  150216. const char *zPrefix = "";
  150217. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  150218. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  150219. zPrefix, pIter->zTbl, zSet, zWhere
  150220. );
  150221. p->rc = prepareFreeAndCollectError(
  150222. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  150223. );
  150224. *ppStmt = pUp->pUpdate;
  150225. }
  150226. sqlite3_free(zWhere);
  150227. sqlite3_free(zSet);
  150228. }
  150229. return p->rc;
  150230. }
  150231. static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
  150232. sqlite3 *db = 0;
  150233. if( p->rc==SQLITE_OK ){
  150234. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  150235. p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
  150236. if( p->rc ){
  150237. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  150238. sqlite3_close(db);
  150239. db = 0;
  150240. }
  150241. }
  150242. return db;
  150243. }
  150244. /*
  150245. ** Open the database handle and attach the RBU database as "rbu". If an
  150246. ** error occurs, leave an error code and message in the RBU handle.
  150247. */
  150248. static void rbuOpenDatabase(sqlite3rbu *p){
  150249. assert( p->rc==SQLITE_OK );
  150250. assert( p->dbMain==0 && p->dbRbu==0 );
  150251. p->eStage = 0;
  150252. p->dbMain = rbuOpenDbhandle(p, p->zTarget);
  150253. p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
  150254. /* If using separate RBU and state databases, attach the state database to
  150255. ** the RBU db handle now. */
  150256. if( p->zState ){
  150257. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  150258. memcpy(p->zStateDb, "stat", 4);
  150259. }else{
  150260. memcpy(p->zStateDb, "main", 4);
  150261. }
  150262. if( p->rc==SQLITE_OK ){
  150263. p->rc = sqlite3_create_function(p->dbMain,
  150264. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  150265. );
  150266. }
  150267. if( p->rc==SQLITE_OK ){
  150268. p->rc = sqlite3_create_function(p->dbMain,
  150269. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  150270. );
  150271. }
  150272. if( p->rc==SQLITE_OK ){
  150273. p->rc = sqlite3_create_function(p->dbRbu,
  150274. "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  150275. );
  150276. }
  150277. if( p->rc==SQLITE_OK ){
  150278. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  150279. }
  150280. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  150281. /* Mark the database file just opened as an RBU target database. If
  150282. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  150283. ** This is an error. */
  150284. if( p->rc==SQLITE_OK ){
  150285. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  150286. }
  150287. if( p->rc==SQLITE_NOTFOUND ){
  150288. p->rc = SQLITE_ERROR;
  150289. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  150290. }
  150291. }
  150292. /*
  150293. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  150294. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  150295. **
  150296. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  150297. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  150298. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  150299. ** three characters, then shorten the suffix on z[] to be the last three
  150300. ** characters of the original suffix.
  150301. **
  150302. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  150303. ** do the suffix shortening regardless of URI parameter.
  150304. **
  150305. ** Examples:
  150306. **
  150307. ** test.db-journal => test.nal
  150308. ** test.db-wal => test.wal
  150309. ** test.db-shm => test.shm
  150310. ** test.db-mj7f3319fa => test.9fa
  150311. */
  150312. static void rbuFileSuffix3(const char *zBase, char *z){
  150313. #ifdef SQLITE_ENABLE_8_3_NAMES
  150314. #if SQLITE_ENABLE_8_3_NAMES<2
  150315. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  150316. #endif
  150317. {
  150318. int i, sz;
  150319. sz = sqlite3Strlen30(z);
  150320. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  150321. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  150322. }
  150323. #endif
  150324. }
  150325. /*
  150326. ** Return the current wal-index header checksum for the target database
  150327. ** as a 64-bit integer.
  150328. **
  150329. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  150330. ** blob starting at byte offset 40.
  150331. */
  150332. static i64 rbuShmChecksum(sqlite3rbu *p){
  150333. i64 iRet = 0;
  150334. if( p->rc==SQLITE_OK ){
  150335. sqlite3_file *pDb = p->pTargetFd->pReal;
  150336. u32 volatile *ptr;
  150337. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  150338. if( p->rc==SQLITE_OK ){
  150339. iRet = ((i64)ptr[10] << 32) + ptr[11];
  150340. }
  150341. }
  150342. return iRet;
  150343. }
  150344. /*
  150345. ** This function is called as part of initializing or reinitializing an
  150346. ** incremental checkpoint.
  150347. **
  150348. ** It populates the sqlite3rbu.aFrame[] array with the set of
  150349. ** (wal frame -> db page) copy operations required to checkpoint the
  150350. ** current wal file, and obtains the set of shm locks required to safely
  150351. ** perform the copy operations directly on the file-system.
  150352. **
  150353. ** If argument pState is not NULL, then the incremental checkpoint is
  150354. ** being resumed. In this case, if the checksum of the wal-index-header
  150355. ** following recovery is not the same as the checksum saved in the RbuState
  150356. ** object, then the rbu handle is set to DONE state. This occurs if some
  150357. ** other client appends a transaction to the wal file in the middle of
  150358. ** an incremental checkpoint.
  150359. */
  150360. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  150361. /* If pState is NULL, then the wal file may not have been opened and
  150362. ** recovered. Running a read-statement here to ensure that doing so
  150363. ** does not interfere with the "capture" process below. */
  150364. if( pState==0 ){
  150365. p->eStage = 0;
  150366. if( p->rc==SQLITE_OK ){
  150367. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  150368. }
  150369. }
  150370. /* Assuming no error has occurred, run a "restart" checkpoint with the
  150371. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  150372. ** special behaviour in the rbu VFS:
  150373. **
  150374. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  150375. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  150376. ** proceed with running a passive checkpoint instead of failing).
  150377. **
  150378. ** * Attempts to read from the *-wal file or write to the database file
  150379. ** do not perform any IO. Instead, the frame/page combinations that
  150380. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  150381. ** array.
  150382. **
  150383. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  150384. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  150385. ** no-ops. These locks will not be released until the connection
  150386. ** is closed.
  150387. **
  150388. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  150389. ** error.
  150390. **
  150391. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  150392. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  150393. ** array populated with a set of (frame -> page) mappings. Because the
  150394. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  150395. ** data from the wal file into the database file according to the
  150396. ** contents of aFrame[].
  150397. */
  150398. if( p->rc==SQLITE_OK ){
  150399. int rc2;
  150400. p->eStage = RBU_STAGE_CAPTURE;
  150401. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  150402. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  150403. }
  150404. if( p->rc==SQLITE_OK ){
  150405. p->eStage = RBU_STAGE_CKPT;
  150406. p->nStep = (pState ? pState->nRow : 0);
  150407. p->aBuf = rbuMalloc(p, p->pgsz);
  150408. p->iWalCksum = rbuShmChecksum(p);
  150409. }
  150410. if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
  150411. p->rc = SQLITE_DONE;
  150412. p->eStage = RBU_STAGE_DONE;
  150413. }
  150414. }
  150415. /*
  150416. ** Called when iAmt bytes are read from offset iOff of the wal file while
  150417. ** the rbu object is in capture mode. Record the frame number of the frame
  150418. ** being read in the aFrame[] array.
  150419. */
  150420. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  150421. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  150422. u32 iFrame;
  150423. if( pRbu->mLock!=mReq ){
  150424. pRbu->rc = SQLITE_BUSY;
  150425. return SQLITE_INTERNAL;
  150426. }
  150427. pRbu->pgsz = iAmt;
  150428. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  150429. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  150430. RbuFrame *aNew;
  150431. aNew = (RbuFrame*)sqlite3_realloc(pRbu->aFrame, nNew * sizeof(RbuFrame));
  150432. if( aNew==0 ) return SQLITE_NOMEM;
  150433. pRbu->aFrame = aNew;
  150434. pRbu->nFrameAlloc = nNew;
  150435. }
  150436. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  150437. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  150438. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  150439. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  150440. pRbu->nFrame++;
  150441. return SQLITE_OK;
  150442. }
  150443. /*
  150444. ** Called when a page of data is written to offset iOff of the database
  150445. ** file while the rbu handle is in capture mode. Record the page number
  150446. ** of the page being written in the aFrame[] array.
  150447. */
  150448. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  150449. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  150450. return SQLITE_OK;
  150451. }
  150452. /*
  150453. ** This is called as part of an incremental checkpoint operation. Copy
  150454. ** a single frame of data from the wal file into the database file, as
  150455. ** indicated by the RbuFrame object.
  150456. */
  150457. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  150458. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  150459. sqlite3_file *pDb = p->pTargetFd->pReal;
  150460. i64 iOff;
  150461. assert( p->rc==SQLITE_OK );
  150462. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  150463. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  150464. if( p->rc ) return;
  150465. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  150466. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  150467. }
  150468. /*
  150469. ** Take an EXCLUSIVE lock on the database file.
  150470. */
  150471. static void rbuLockDatabase(sqlite3rbu *p){
  150472. sqlite3_file *pReal = p->pTargetFd->pReal;
  150473. assert( p->rc==SQLITE_OK );
  150474. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  150475. if( p->rc==SQLITE_OK ){
  150476. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  150477. }
  150478. }
  150479. #if defined(_WIN32_WCE)
  150480. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  150481. int nChar;
  150482. LPWSTR zWideFilename;
  150483. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  150484. if( nChar==0 ){
  150485. return 0;
  150486. }
  150487. zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
  150488. if( zWideFilename==0 ){
  150489. return 0;
  150490. }
  150491. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  150492. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  150493. nChar);
  150494. if( nChar==0 ){
  150495. sqlite3_free(zWideFilename);
  150496. zWideFilename = 0;
  150497. }
  150498. return zWideFilename;
  150499. }
  150500. #endif
  150501. /*
  150502. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  150503. ** on the database file. This proc moves the *-oal file to the *-wal path,
  150504. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  150505. ** If an error occurs, leave an error code and error message in the rbu
  150506. ** handle.
  150507. */
  150508. static void rbuMoveOalFile(sqlite3rbu *p){
  150509. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  150510. char *zWal = sqlite3_mprintf("%s-wal", zBase);
  150511. char *zOal = sqlite3_mprintf("%s-oal", zBase);
  150512. assert( p->eStage==RBU_STAGE_MOVE );
  150513. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  150514. if( zWal==0 || zOal==0 ){
  150515. p->rc = SQLITE_NOMEM;
  150516. }else{
  150517. /* Move the *-oal file to *-wal. At this point connection p->db is
  150518. ** holding a SHARED lock on the target database file (because it is
  150519. ** in WAL mode). So no other connection may be writing the db.
  150520. **
  150521. ** In order to ensure that there are no database readers, an EXCLUSIVE
  150522. ** lock is obtained here before the *-oal is moved to *-wal.
  150523. */
  150524. rbuLockDatabase(p);
  150525. if( p->rc==SQLITE_OK ){
  150526. rbuFileSuffix3(zBase, zWal);
  150527. rbuFileSuffix3(zBase, zOal);
  150528. /* Re-open the databases. */
  150529. rbuObjIterFinalize(&p->objiter);
  150530. sqlite3_close(p->dbMain);
  150531. sqlite3_close(p->dbRbu);
  150532. p->dbMain = 0;
  150533. p->dbRbu = 0;
  150534. #if defined(_WIN32_WCE)
  150535. {
  150536. LPWSTR zWideOal;
  150537. LPWSTR zWideWal;
  150538. zWideOal = rbuWinUtf8ToUnicode(zOal);
  150539. if( zWideOal ){
  150540. zWideWal = rbuWinUtf8ToUnicode(zWal);
  150541. if( zWideWal ){
  150542. if( MoveFileW(zWideOal, zWideWal) ){
  150543. p->rc = SQLITE_OK;
  150544. }else{
  150545. p->rc = SQLITE_IOERR;
  150546. }
  150547. sqlite3_free(zWideWal);
  150548. }else{
  150549. p->rc = SQLITE_IOERR_NOMEM;
  150550. }
  150551. sqlite3_free(zWideOal);
  150552. }else{
  150553. p->rc = SQLITE_IOERR_NOMEM;
  150554. }
  150555. }
  150556. #else
  150557. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  150558. #endif
  150559. if( p->rc==SQLITE_OK ){
  150560. rbuOpenDatabase(p);
  150561. rbuSetupCheckpoint(p, 0);
  150562. }
  150563. }
  150564. }
  150565. sqlite3_free(zWal);
  150566. sqlite3_free(zOal);
  150567. }
  150568. /*
  150569. ** The SELECT statement iterating through the keys for the current object
  150570. ** (p->objiter.pSelect) currently points to a valid row. This function
  150571. ** determines the type of operation requested by this row and returns
  150572. ** one of the following values to indicate the result:
  150573. **
  150574. ** * RBU_INSERT
  150575. ** * RBU_DELETE
  150576. ** * RBU_IDX_DELETE
  150577. ** * RBU_UPDATE
  150578. **
  150579. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  150580. ** point to the text value indicating the columns to update.
  150581. **
  150582. ** If the rbu_control field contains an invalid value, an error code and
  150583. ** message are left in the RBU handle and zero returned.
  150584. */
  150585. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  150586. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  150587. int res = 0; /* Return value */
  150588. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  150589. case SQLITE_INTEGER: {
  150590. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  150591. if( iVal==0 ){
  150592. res = RBU_INSERT;
  150593. }else if( iVal==1 ){
  150594. res = RBU_DELETE;
  150595. }else if( iVal==2 ){
  150596. res = RBU_IDX_DELETE;
  150597. }else if( iVal==3 ){
  150598. res = RBU_IDX_INSERT;
  150599. }
  150600. break;
  150601. }
  150602. case SQLITE_TEXT: {
  150603. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  150604. if( z==0 ){
  150605. p->rc = SQLITE_NOMEM;
  150606. }else{
  150607. *pzMask = (const char*)z;
  150608. }
  150609. res = RBU_UPDATE;
  150610. break;
  150611. }
  150612. default:
  150613. break;
  150614. }
  150615. if( res==0 ){
  150616. rbuBadControlError(p);
  150617. }
  150618. return res;
  150619. }
  150620. #ifdef SQLITE_DEBUG
  150621. /*
  150622. ** Assert that column iCol of statement pStmt is named zName.
  150623. */
  150624. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  150625. const char *zCol = sqlite3_column_name(pStmt, iCol);
  150626. assert( 0==sqlite3_stricmp(zName, zCol) );
  150627. }
  150628. #else
  150629. # define assertColumnName(x,y,z)
  150630. #endif
  150631. /*
  150632. ** This function does the work for an sqlite3rbu_step() call.
  150633. **
  150634. ** The object-iterator (p->objiter) currently points to a valid object,
  150635. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  150636. ** input row. Perform whatever processing is required and return.
  150637. **
  150638. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  150639. ** and message is left in the RBU handle and a copy of the error code
  150640. ** returned.
  150641. */
  150642. static int rbuStep(sqlite3rbu *p){
  150643. RbuObjIter *pIter = &p->objiter;
  150644. const char *zMask = 0;
  150645. int i;
  150646. int eType = rbuStepType(p, &zMask);
  150647. if( eType ){
  150648. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  150649. if( pIter->zIdx==0 && eType==RBU_IDX_DELETE ){
  150650. rbuBadControlError(p);
  150651. }
  150652. else if(
  150653. eType==RBU_INSERT
  150654. || eType==RBU_DELETE
  150655. || eType==RBU_IDX_DELETE
  150656. || eType==RBU_IDX_INSERT
  150657. ){
  150658. sqlite3_value *pVal;
  150659. sqlite3_stmt *pWriter;
  150660. assert( eType!=RBU_UPDATE );
  150661. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  150662. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  150663. pWriter = pIter->pDelete;
  150664. }else{
  150665. pWriter = pIter->pInsert;
  150666. }
  150667. for(i=0; i<pIter->nCol; i++){
  150668. /* If this is an INSERT into a table b-tree and the table has an
  150669. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  150670. ** to write a NULL into the IPK column. That is not permitted. */
  150671. if( eType==RBU_INSERT
  150672. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  150673. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  150674. ){
  150675. p->rc = SQLITE_MISMATCH;
  150676. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  150677. goto step_out;
  150678. }
  150679. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  150680. continue;
  150681. }
  150682. pVal = sqlite3_column_value(pIter->pSelect, i);
  150683. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  150684. if( p->rc ) goto step_out;
  150685. }
  150686. if( pIter->zIdx==0
  150687. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  150688. ){
  150689. /* For a virtual table, or a table with no primary key, the
  150690. ** SELECT statement is:
  150691. **
  150692. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  150693. **
  150694. ** Hence column_value(pIter->nCol+1).
  150695. */
  150696. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  150697. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  150698. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  150699. }
  150700. if( p->rc==SQLITE_OK ){
  150701. sqlite3_step(pWriter);
  150702. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  150703. }
  150704. }else{
  150705. sqlite3_value *pVal;
  150706. sqlite3_stmt *pUpdate = 0;
  150707. assert( eType==RBU_UPDATE );
  150708. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  150709. if( pUpdate ){
  150710. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  150711. char c = zMask[pIter->aiSrcOrder[i]];
  150712. pVal = sqlite3_column_value(pIter->pSelect, i);
  150713. if( pIter->abTblPk[i] || c!='.' ){
  150714. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  150715. }
  150716. }
  150717. if( p->rc==SQLITE_OK
  150718. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  150719. ){
  150720. /* Bind the rbu_rowid value to column _rowid_ */
  150721. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  150722. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  150723. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  150724. }
  150725. if( p->rc==SQLITE_OK ){
  150726. sqlite3_step(pUpdate);
  150727. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  150728. }
  150729. }
  150730. }
  150731. }
  150732. step_out:
  150733. return p->rc;
  150734. }
  150735. /*
  150736. ** Increment the schema cookie of the main database opened by p->dbMain.
  150737. */
  150738. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  150739. if( p->rc==SQLITE_OK ){
  150740. int iCookie = 1000000;
  150741. sqlite3_stmt *pStmt;
  150742. p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  150743. "PRAGMA schema_version"
  150744. );
  150745. if( p->rc==SQLITE_OK ){
  150746. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  150747. ** is already a transaction open, so the prepared statement cannot
  150748. ** throw an SQLITE_SCHEMA exception. The only database page the
  150749. ** statement reads is page 1, which is guaranteed to be in the cache.
  150750. ** And no memory allocations are required. */
  150751. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  150752. iCookie = sqlite3_column_int(pStmt, 0);
  150753. }
  150754. rbuFinalize(p, pStmt);
  150755. }
  150756. if( p->rc==SQLITE_OK ){
  150757. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  150758. }
  150759. }
  150760. }
  150761. /*
  150762. ** Update the contents of the rbu_state table within the rbu database. The
  150763. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  150764. ** are determined by inspecting the rbu handle passed as the first argument.
  150765. */
  150766. static void rbuSaveState(sqlite3rbu *p, int eStage){
  150767. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  150768. sqlite3_stmt *pInsert = 0;
  150769. int rc;
  150770. assert( p->zErrmsg==0 );
  150771. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  150772. sqlite3_mprintf(
  150773. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  150774. "(%d, %d), "
  150775. "(%d, %Q), "
  150776. "(%d, %Q), "
  150777. "(%d, %d), "
  150778. "(%d, %d), "
  150779. "(%d, %lld), "
  150780. "(%d, %lld), "
  150781. "(%d, %lld) ",
  150782. p->zStateDb,
  150783. RBU_STATE_STAGE, eStage,
  150784. RBU_STATE_TBL, p->objiter.zTbl,
  150785. RBU_STATE_IDX, p->objiter.zIdx,
  150786. RBU_STATE_ROW, p->nStep,
  150787. RBU_STATE_PROGRESS, p->nProgress,
  150788. RBU_STATE_CKPT, p->iWalCksum,
  150789. RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
  150790. RBU_STATE_OALSZ, p->iOalSz
  150791. )
  150792. );
  150793. assert( pInsert==0 || rc==SQLITE_OK );
  150794. if( rc==SQLITE_OK ){
  150795. sqlite3_step(pInsert);
  150796. rc = sqlite3_finalize(pInsert);
  150797. }
  150798. if( rc!=SQLITE_OK ) p->rc = rc;
  150799. }
  150800. }
  150801. /*
  150802. ** Step the RBU object.
  150803. */
  150804. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
  150805. if( p ){
  150806. switch( p->eStage ){
  150807. case RBU_STAGE_OAL: {
  150808. RbuObjIter *pIter = &p->objiter;
  150809. while( p->rc==SQLITE_OK && pIter->zTbl ){
  150810. if( pIter->bCleanup ){
  150811. /* Clean up the rbu_tmp_xxx table for the previous table. It
  150812. ** cannot be dropped as there are currently active SQL statements.
  150813. ** But the contents can be deleted. */
  150814. if( pIter->abIndexed ){
  150815. rbuMPrintfExec(p, p->dbRbu,
  150816. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  150817. );
  150818. }
  150819. }else{
  150820. rbuObjIterPrepareAll(p, pIter, 0);
  150821. /* Advance to the next row to process. */
  150822. if( p->rc==SQLITE_OK ){
  150823. int rc = sqlite3_step(pIter->pSelect);
  150824. if( rc==SQLITE_ROW ){
  150825. p->nProgress++;
  150826. p->nStep++;
  150827. return rbuStep(p);
  150828. }
  150829. p->rc = sqlite3_reset(pIter->pSelect);
  150830. p->nStep = 0;
  150831. }
  150832. }
  150833. rbuObjIterNext(p, pIter);
  150834. }
  150835. if( p->rc==SQLITE_OK ){
  150836. assert( pIter->zTbl==0 );
  150837. rbuSaveState(p, RBU_STAGE_MOVE);
  150838. rbuIncrSchemaCookie(p);
  150839. if( p->rc==SQLITE_OK ){
  150840. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  150841. }
  150842. if( p->rc==SQLITE_OK ){
  150843. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  150844. }
  150845. p->eStage = RBU_STAGE_MOVE;
  150846. }
  150847. break;
  150848. }
  150849. case RBU_STAGE_MOVE: {
  150850. if( p->rc==SQLITE_OK ){
  150851. rbuMoveOalFile(p);
  150852. p->nProgress++;
  150853. }
  150854. break;
  150855. }
  150856. case RBU_STAGE_CKPT: {
  150857. if( p->rc==SQLITE_OK ){
  150858. if( p->nStep>=p->nFrame ){
  150859. sqlite3_file *pDb = p->pTargetFd->pReal;
  150860. /* Sync the db file */
  150861. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  150862. /* Update nBackfill */
  150863. if( p->rc==SQLITE_OK ){
  150864. void volatile *ptr;
  150865. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  150866. if( p->rc==SQLITE_OK ){
  150867. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  150868. }
  150869. }
  150870. if( p->rc==SQLITE_OK ){
  150871. p->eStage = RBU_STAGE_DONE;
  150872. p->rc = SQLITE_DONE;
  150873. }
  150874. }else{
  150875. RbuFrame *pFrame = &p->aFrame[p->nStep];
  150876. rbuCheckpointFrame(p, pFrame);
  150877. p->nStep++;
  150878. }
  150879. p->nProgress++;
  150880. }
  150881. break;
  150882. }
  150883. default:
  150884. break;
  150885. }
  150886. return p->rc;
  150887. }else{
  150888. return SQLITE_NOMEM;
  150889. }
  150890. }
  150891. /*
  150892. ** Free an RbuState object allocated by rbuLoadState().
  150893. */
  150894. static void rbuFreeState(RbuState *p){
  150895. if( p ){
  150896. sqlite3_free(p->zTbl);
  150897. sqlite3_free(p->zIdx);
  150898. sqlite3_free(p);
  150899. }
  150900. }
  150901. /*
  150902. ** Allocate an RbuState object and load the contents of the rbu_state
  150903. ** table into it. Return a pointer to the new object. It is the
  150904. ** responsibility of the caller to eventually free the object using
  150905. ** sqlite3_free().
  150906. **
  150907. ** If an error occurs, leave an error code and message in the rbu handle
  150908. ** and return NULL.
  150909. */
  150910. static RbuState *rbuLoadState(sqlite3rbu *p){
  150911. RbuState *pRet = 0;
  150912. sqlite3_stmt *pStmt = 0;
  150913. int rc;
  150914. int rc2;
  150915. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  150916. if( pRet==0 ) return 0;
  150917. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  150918. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  150919. );
  150920. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  150921. switch( sqlite3_column_int(pStmt, 0) ){
  150922. case RBU_STATE_STAGE:
  150923. pRet->eStage = sqlite3_column_int(pStmt, 1);
  150924. if( pRet->eStage!=RBU_STAGE_OAL
  150925. && pRet->eStage!=RBU_STAGE_MOVE
  150926. && pRet->eStage!=RBU_STAGE_CKPT
  150927. ){
  150928. p->rc = SQLITE_CORRUPT;
  150929. }
  150930. break;
  150931. case RBU_STATE_TBL:
  150932. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  150933. break;
  150934. case RBU_STATE_IDX:
  150935. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  150936. break;
  150937. case RBU_STATE_ROW:
  150938. pRet->nRow = sqlite3_column_int(pStmt, 1);
  150939. break;
  150940. case RBU_STATE_PROGRESS:
  150941. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  150942. break;
  150943. case RBU_STATE_CKPT:
  150944. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  150945. break;
  150946. case RBU_STATE_COOKIE:
  150947. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  150948. break;
  150949. case RBU_STATE_OALSZ:
  150950. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  150951. break;
  150952. default:
  150953. rc = SQLITE_CORRUPT;
  150954. break;
  150955. }
  150956. }
  150957. rc2 = sqlite3_finalize(pStmt);
  150958. if( rc==SQLITE_OK ) rc = rc2;
  150959. p->rc = rc;
  150960. return pRet;
  150961. }
  150962. /*
  150963. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  150964. ** otherwise. Either or both argument may be NULL. Two NULL values are
  150965. ** considered equal, and NULL is considered distinct from all other values.
  150966. */
  150967. static int rbuStrCompare(const char *z1, const char *z2){
  150968. if( z1==0 && z2==0 ) return 0;
  150969. if( z1==0 || z2==0 ) return 1;
  150970. return (sqlite3_stricmp(z1, z2)!=0);
  150971. }
  150972. /*
  150973. ** This function is called as part of sqlite3rbu_open() when initializing
  150974. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  150975. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  150976. ** things so that the next call to sqlite3rbu_step() continues on from
  150977. ** where the previous rbu handle left off.
  150978. **
  150979. ** If an error occurs, an error code and error message are left in the
  150980. ** rbu handle passed as the first argument.
  150981. */
  150982. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  150983. assert( p->rc==SQLITE_OK );
  150984. if( pState->zTbl ){
  150985. RbuObjIter *pIter = &p->objiter;
  150986. int rc = SQLITE_OK;
  150987. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  150988. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  150989. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  150990. )){
  150991. rc = rbuObjIterNext(p, pIter);
  150992. }
  150993. if( rc==SQLITE_OK && !pIter->zTbl ){
  150994. rc = SQLITE_ERROR;
  150995. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  150996. }
  150997. if( rc==SQLITE_OK ){
  150998. p->nStep = pState->nRow;
  150999. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  151000. }
  151001. p->rc = rc;
  151002. }
  151003. }
  151004. /*
  151005. ** If there is a "*-oal" file in the file-system corresponding to the
  151006. ** target database in the file-system, delete it. If an error occurs,
  151007. ** leave an error code and error message in the rbu handle.
  151008. */
  151009. static void rbuDeleteOalFile(sqlite3rbu *p){
  151010. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  151011. if( zOal ){
  151012. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  151013. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  151014. pVfs->xDelete(pVfs, zOal, 0);
  151015. sqlite3_free(zOal);
  151016. }
  151017. }
  151018. /*
  151019. ** Allocate a private rbu VFS for the rbu handle passed as the only
  151020. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  151021. ** specified a URI with a vfs=? option in place of a target database
  151022. ** file name.
  151023. */
  151024. static void rbuCreateVfs(sqlite3rbu *p){
  151025. int rnd;
  151026. char zRnd[64];
  151027. assert( p->rc==SQLITE_OK );
  151028. sqlite3_randomness(sizeof(int), (void*)&rnd);
  151029. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  151030. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  151031. if( p->rc==SQLITE_OK ){
  151032. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  151033. assert( pVfs );
  151034. p->zVfsName = pVfs->zName;
  151035. }
  151036. }
  151037. /*
  151038. ** Destroy the private VFS created for the rbu handle passed as the only
  151039. ** argument by an earlier call to rbuCreateVfs().
  151040. */
  151041. static void rbuDeleteVfs(sqlite3rbu *p){
  151042. if( p->zVfsName ){
  151043. sqlite3rbu_destroy_vfs(p->zVfsName);
  151044. p->zVfsName = 0;
  151045. }
  151046. }
  151047. /*
  151048. ** Open and return a new RBU handle.
  151049. */
  151050. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  151051. const char *zTarget,
  151052. const char *zRbu,
  151053. const char *zState
  151054. ){
  151055. sqlite3rbu *p;
  151056. int nTarget = strlen(zTarget);
  151057. int nRbu = strlen(zRbu);
  151058. int nState = zState ? strlen(zState) : 0;
  151059. p = (sqlite3rbu*)sqlite3_malloc(sizeof(sqlite3rbu)+nTarget+1+nRbu+1+nState+1);
  151060. if( p ){
  151061. RbuState *pState = 0;
  151062. /* Create the custom VFS. */
  151063. memset(p, 0, sizeof(sqlite3rbu));
  151064. rbuCreateVfs(p);
  151065. /* Open the target database */
  151066. if( p->rc==SQLITE_OK ){
  151067. p->zTarget = (char*)&p[1];
  151068. memcpy(p->zTarget, zTarget, nTarget+1);
  151069. p->zRbu = &p->zTarget[nTarget+1];
  151070. memcpy(p->zRbu, zRbu, nRbu+1);
  151071. if( zState ){
  151072. p->zState = &p->zRbu[nRbu+1];
  151073. memcpy(p->zState, zState, nState+1);
  151074. }
  151075. rbuOpenDatabase(p);
  151076. }
  151077. /* If it has not already been created, create the rbu_state table */
  151078. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  151079. if( p->rc==SQLITE_OK ){
  151080. pState = rbuLoadState(p);
  151081. assert( pState || p->rc!=SQLITE_OK );
  151082. if( p->rc==SQLITE_OK ){
  151083. if( pState->eStage==0 ){
  151084. rbuDeleteOalFile(p);
  151085. p->eStage = RBU_STAGE_OAL;
  151086. }else{
  151087. p->eStage = pState->eStage;
  151088. }
  151089. p->nProgress = pState->nProgress;
  151090. p->iOalSz = pState->iOalSz;
  151091. }
  151092. }
  151093. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  151094. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  151095. if( p->eStage==RBU_STAGE_OAL ){
  151096. p->rc = SQLITE_ERROR;
  151097. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  151098. }else if( p->eStage==RBU_STAGE_MOVE ){
  151099. p->eStage = RBU_STAGE_CKPT;
  151100. p->nStep = 0;
  151101. }
  151102. }
  151103. if( p->rc==SQLITE_OK
  151104. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  151105. && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
  151106. ){
  151107. /* At this point (pTargetFd->iCookie) contains the value of the
  151108. ** change-counter cookie (the thing that gets incremented when a
  151109. ** transaction is committed in rollback mode) currently stored on
  151110. ** page 1 of the database file. */
  151111. p->rc = SQLITE_BUSY;
  151112. p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
  151113. }
  151114. if( p->rc==SQLITE_OK ){
  151115. if( p->eStage==RBU_STAGE_OAL ){
  151116. sqlite3 *db = p->dbMain;
  151117. /* Open transactions both databases. The *-oal file is opened or
  151118. ** created at this point. */
  151119. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  151120. if( p->rc==SQLITE_OK ){
  151121. p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  151122. }
  151123. /* Check if the main database is a zipvfs db. If it is, set the upper
  151124. ** level pager to use "journal_mode=off". This prevents it from
  151125. ** generating a large journal using a temp file. */
  151126. if( p->rc==SQLITE_OK ){
  151127. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  151128. if( frc==SQLITE_OK ){
  151129. p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  151130. }
  151131. }
  151132. /* Point the object iterator at the first object */
  151133. if( p->rc==SQLITE_OK ){
  151134. p->rc = rbuObjIterFirst(p, &p->objiter);
  151135. }
  151136. /* If the RBU database contains no data_xxx tables, declare the RBU
  151137. ** update finished. */
  151138. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  151139. p->rc = SQLITE_DONE;
  151140. }
  151141. if( p->rc==SQLITE_OK ){
  151142. rbuSetupOal(p, pState);
  151143. }
  151144. }else if( p->eStage==RBU_STAGE_MOVE ){
  151145. /* no-op */
  151146. }else if( p->eStage==RBU_STAGE_CKPT ){
  151147. rbuSetupCheckpoint(p, pState);
  151148. }else if( p->eStage==RBU_STAGE_DONE ){
  151149. p->rc = SQLITE_DONE;
  151150. }else{
  151151. p->rc = SQLITE_CORRUPT;
  151152. }
  151153. }
  151154. rbuFreeState(pState);
  151155. }
  151156. return p;
  151157. }
  151158. /*
  151159. ** Return the database handle used by pRbu.
  151160. */
  151161. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  151162. sqlite3 *db = 0;
  151163. if( pRbu ){
  151164. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  151165. }
  151166. return db;
  151167. }
  151168. /*
  151169. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  151170. ** then edit any error message string so as to remove all occurrences of
  151171. ** the pattern "rbu_imp_[0-9]*".
  151172. */
  151173. static void rbuEditErrmsg(sqlite3rbu *p){
  151174. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  151175. int i;
  151176. int nErrmsg = strlen(p->zErrmsg);
  151177. for(i=0; i<(nErrmsg-8); i++){
  151178. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  151179. int nDel = 8;
  151180. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  151181. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  151182. nErrmsg -= nDel;
  151183. }
  151184. }
  151185. }
  151186. }
  151187. /*
  151188. ** Close the RBU handle.
  151189. */
  151190. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  151191. int rc;
  151192. if( p ){
  151193. /* Commit the transaction to the *-oal file. */
  151194. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  151195. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  151196. }
  151197. rbuSaveState(p, p->eStage);
  151198. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  151199. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  151200. }
  151201. /* Close any open statement handles. */
  151202. rbuObjIterFinalize(&p->objiter);
  151203. /* Close the open database handle and VFS object. */
  151204. sqlite3_close(p->dbMain);
  151205. sqlite3_close(p->dbRbu);
  151206. rbuDeleteVfs(p);
  151207. sqlite3_free(p->aBuf);
  151208. sqlite3_free(p->aFrame);
  151209. rbuEditErrmsg(p);
  151210. rc = p->rc;
  151211. *pzErrmsg = p->zErrmsg;
  151212. sqlite3_free(p);
  151213. }else{
  151214. rc = SQLITE_NOMEM;
  151215. *pzErrmsg = 0;
  151216. }
  151217. return rc;
  151218. }
  151219. /*
  151220. ** Return the total number of key-value operations (inserts, deletes or
  151221. ** updates) that have been performed on the target database since the
  151222. ** current RBU update was started.
  151223. */
  151224. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
  151225. return pRbu->nProgress;
  151226. }
  151227. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
  151228. int rc = p->rc;
  151229. if( rc==SQLITE_DONE ) return SQLITE_OK;
  151230. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  151231. if( p->eStage==RBU_STAGE_OAL ){
  151232. assert( rc!=SQLITE_DONE );
  151233. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  151234. }
  151235. p->rc = rc;
  151236. rbuSaveState(p, p->eStage);
  151237. rc = p->rc;
  151238. if( p->eStage==RBU_STAGE_OAL ){
  151239. assert( rc!=SQLITE_DONE );
  151240. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  151241. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  151242. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  151243. }
  151244. p->rc = rc;
  151245. return rc;
  151246. }
  151247. /**************************************************************************
  151248. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  151249. ** of a standard VFS in the following ways:
  151250. **
  151251. ** 1. Whenever the first page of a main database file is read or
  151252. ** written, the value of the change-counter cookie is stored in
  151253. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  151254. ** database header field is stored in rbu_file.iWriteVer. This ensures
  151255. ** that the values are always trustworthy within an open transaction.
  151256. **
  151257. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  151258. ** member variable of the associated database file descriptor is set
  151259. ** to point to the new file. A mutex protected linked list of all main
  151260. ** db fds opened using a particular RBU VFS is maintained at
  151261. ** rbu_vfs.pMain to facilitate this.
  151262. **
  151263. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  151264. ** object can be marked as the target database of an RBU update. This
  151265. ** turns on the following extra special behaviour:
  151266. **
  151267. ** 3a. If xAccess() is called to check if there exists a *-wal file
  151268. ** associated with an RBU target database currently in RBU_STAGE_OAL
  151269. ** stage (preparing the *-oal file), the following special handling
  151270. ** applies:
  151271. **
  151272. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  151273. ** target database may not be in wal mode already.
  151274. **
  151275. ** * if the *-wal file does not exist, set the output parameter to
  151276. ** non-zero (to tell SQLite that it does exist) anyway.
  151277. **
  151278. ** Then, when xOpen() is called to open the *-wal file associated with
  151279. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  151280. ** file, the rbu vfs opens the corresponding *-oal file instead.
  151281. **
  151282. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  151283. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  151284. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  151285. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  151286. ** because assert() statements in some VFS implementations fail if
  151287. ** xShmLock() is called before xShmMap().
  151288. **
  151289. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  151290. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  151291. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  151292. ** from automatically checkpointing a *-wal (or *-oal) file from within
  151293. ** sqlite3_close().
  151294. **
  151295. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  151296. ** all xWrite() calls on the target database file perform no IO.
  151297. ** Instead the frame and page numbers that would be read and written
  151298. ** are recorded. Additionally, successful attempts to obtain exclusive
  151299. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  151300. ** database file are recorded. xShmLock() calls to unlock the same
  151301. ** locks are no-ops (so that once obtained, these locks are never
  151302. ** relinquished). Finally, calls to xSync() on the target database
  151303. ** file fail with SQLITE_INTERNAL errors.
  151304. */
  151305. static void rbuUnlockShm(rbu_file *p){
  151306. if( p->pRbu ){
  151307. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  151308. int i;
  151309. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  151310. if( (1<<i) & p->pRbu->mLock ){
  151311. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  151312. }
  151313. }
  151314. p->pRbu->mLock = 0;
  151315. }
  151316. }
  151317. /*
  151318. ** Close an rbu file.
  151319. */
  151320. static int rbuVfsClose(sqlite3_file *pFile){
  151321. rbu_file *p = (rbu_file*)pFile;
  151322. int rc;
  151323. int i;
  151324. /* Free the contents of the apShm[] array. And the array itself. */
  151325. for(i=0; i<p->nShm; i++){
  151326. sqlite3_free(p->apShm[i]);
  151327. }
  151328. sqlite3_free(p->apShm);
  151329. p->apShm = 0;
  151330. sqlite3_free(p->zDel);
  151331. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  151332. rbu_file **pp;
  151333. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  151334. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  151335. *pp = p->pMainNext;
  151336. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  151337. rbuUnlockShm(p);
  151338. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  151339. }
  151340. /* Close the underlying file handle */
  151341. rc = p->pReal->pMethods->xClose(p->pReal);
  151342. return rc;
  151343. }
  151344. /*
  151345. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  151346. ** passed as the only argument.
  151347. */
  151348. static u32 rbuGetU32(u8 *aBuf){
  151349. return ((u32)aBuf[0] << 24)
  151350. + ((u32)aBuf[1] << 16)
  151351. + ((u32)aBuf[2] << 8)
  151352. + ((u32)aBuf[3]);
  151353. }
  151354. /*
  151355. ** Read data from an rbuVfs-file.
  151356. */
  151357. static int rbuVfsRead(
  151358. sqlite3_file *pFile,
  151359. void *zBuf,
  151360. int iAmt,
  151361. sqlite_int64 iOfst
  151362. ){
  151363. rbu_file *p = (rbu_file*)pFile;
  151364. sqlite3rbu *pRbu = p->pRbu;
  151365. int rc;
  151366. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  151367. assert( p->openFlags & SQLITE_OPEN_WAL );
  151368. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  151369. }else{
  151370. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  151371. && (p->openFlags & SQLITE_OPEN_WAL)
  151372. && iOfst>=pRbu->iOalSz
  151373. ){
  151374. rc = SQLITE_OK;
  151375. memset(zBuf, 0, iAmt);
  151376. }else{
  151377. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  151378. }
  151379. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  151380. /* These look like magic numbers. But they are stable, as they are part
  151381. ** of the definition of the SQLite file format, which may not change. */
  151382. u8 *pBuf = (u8*)zBuf;
  151383. p->iCookie = rbuGetU32(&pBuf[24]);
  151384. p->iWriteVer = pBuf[19];
  151385. }
  151386. }
  151387. return rc;
  151388. }
  151389. /*
  151390. ** Write data to an rbuVfs-file.
  151391. */
  151392. static int rbuVfsWrite(
  151393. sqlite3_file *pFile,
  151394. const void *zBuf,
  151395. int iAmt,
  151396. sqlite_int64 iOfst
  151397. ){
  151398. rbu_file *p = (rbu_file*)pFile;
  151399. sqlite3rbu *pRbu = p->pRbu;
  151400. int rc;
  151401. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  151402. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  151403. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  151404. }else{
  151405. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  151406. && (p->openFlags & SQLITE_OPEN_WAL)
  151407. && iOfst>=pRbu->iOalSz
  151408. ){
  151409. pRbu->iOalSz = iAmt + iOfst;
  151410. }
  151411. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  151412. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  151413. /* These look like magic numbers. But they are stable, as they are part
  151414. ** of the definition of the SQLite file format, which may not change. */
  151415. u8 *pBuf = (u8*)zBuf;
  151416. p->iCookie = rbuGetU32(&pBuf[24]);
  151417. p->iWriteVer = pBuf[19];
  151418. }
  151419. }
  151420. return rc;
  151421. }
  151422. /*
  151423. ** Truncate an rbuVfs-file.
  151424. */
  151425. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  151426. rbu_file *p = (rbu_file*)pFile;
  151427. return p->pReal->pMethods->xTruncate(p->pReal, size);
  151428. }
  151429. /*
  151430. ** Sync an rbuVfs-file.
  151431. */
  151432. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  151433. rbu_file *p = (rbu_file *)pFile;
  151434. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  151435. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  151436. return SQLITE_INTERNAL;
  151437. }
  151438. return SQLITE_OK;
  151439. }
  151440. return p->pReal->pMethods->xSync(p->pReal, flags);
  151441. }
  151442. /*
  151443. ** Return the current file-size of an rbuVfs-file.
  151444. */
  151445. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  151446. rbu_file *p = (rbu_file *)pFile;
  151447. return p->pReal->pMethods->xFileSize(p->pReal, pSize);
  151448. }
  151449. /*
  151450. ** Lock an rbuVfs-file.
  151451. */
  151452. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  151453. rbu_file *p = (rbu_file*)pFile;
  151454. sqlite3rbu *pRbu = p->pRbu;
  151455. int rc = SQLITE_OK;
  151456. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  151457. if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
  151458. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  151459. ** prevents it from checkpointing the database from sqlite3_close(). */
  151460. rc = SQLITE_BUSY;
  151461. }else{
  151462. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  151463. }
  151464. return rc;
  151465. }
  151466. /*
  151467. ** Unlock an rbuVfs-file.
  151468. */
  151469. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  151470. rbu_file *p = (rbu_file *)pFile;
  151471. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  151472. }
  151473. /*
  151474. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  151475. */
  151476. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  151477. rbu_file *p = (rbu_file *)pFile;
  151478. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  151479. }
  151480. /*
  151481. ** File control method. For custom operations on an rbuVfs-file.
  151482. */
  151483. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  151484. rbu_file *p = (rbu_file *)pFile;
  151485. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  151486. int rc;
  151487. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  151488. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  151489. );
  151490. if( op==SQLITE_FCNTL_RBU ){
  151491. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  151492. /* First try to find another RBU vfs lower down in the vfs stack. If
  151493. ** one is found, this vfs will operate in pass-through mode. The lower
  151494. ** level vfs will do the special RBU handling. */
  151495. rc = xControl(p->pReal, op, pArg);
  151496. if( rc==SQLITE_NOTFOUND ){
  151497. /* Now search for a zipvfs instance lower down in the VFS stack. If
  151498. ** one is found, this is an error. */
  151499. void *dummy = 0;
  151500. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  151501. if( rc==SQLITE_OK ){
  151502. rc = SQLITE_ERROR;
  151503. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  151504. }else if( rc==SQLITE_NOTFOUND ){
  151505. pRbu->pTargetFd = p;
  151506. p->pRbu = pRbu;
  151507. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  151508. rc = SQLITE_OK;
  151509. }
  151510. }
  151511. return rc;
  151512. }
  151513. rc = xControl(p->pReal, op, pArg);
  151514. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  151515. rbu_vfs *pRbuVfs = p->pRbuVfs;
  151516. char *zIn = *(char**)pArg;
  151517. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  151518. *(char**)pArg = zOut;
  151519. if( zOut==0 ) rc = SQLITE_NOMEM;
  151520. }
  151521. return rc;
  151522. }
  151523. /*
  151524. ** Return the sector-size in bytes for an rbuVfs-file.
  151525. */
  151526. static int rbuVfsSectorSize(sqlite3_file *pFile){
  151527. rbu_file *p = (rbu_file *)pFile;
  151528. return p->pReal->pMethods->xSectorSize(p->pReal);
  151529. }
  151530. /*
  151531. ** Return the device characteristic flags supported by an rbuVfs-file.
  151532. */
  151533. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  151534. rbu_file *p = (rbu_file *)pFile;
  151535. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  151536. }
  151537. /*
  151538. ** Take or release a shared-memory lock.
  151539. */
  151540. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  151541. rbu_file *p = (rbu_file*)pFile;
  151542. sqlite3rbu *pRbu = p->pRbu;
  151543. int rc = SQLITE_OK;
  151544. #ifdef SQLITE_AMALGAMATION
  151545. assert( WAL_CKPT_LOCK==1 );
  151546. #endif
  151547. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  151548. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  151549. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  151550. ** taking this lock also prevents any checkpoints from occurring.
  151551. ** todo: really, it's not clear why this might occur, as
  151552. ** wal_autocheckpoint ought to be turned off. */
  151553. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  151554. }else{
  151555. int bCapture = 0;
  151556. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  151557. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  151558. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  151559. ){
  151560. bCapture = 1;
  151561. }
  151562. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  151563. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  151564. if( bCapture && rc==SQLITE_OK ){
  151565. pRbu->mLock |= (1 << ofst);
  151566. }
  151567. }
  151568. }
  151569. return rc;
  151570. }
  151571. /*
  151572. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  151573. */
  151574. static int rbuVfsShmMap(
  151575. sqlite3_file *pFile,
  151576. int iRegion,
  151577. int szRegion,
  151578. int isWrite,
  151579. void volatile **pp
  151580. ){
  151581. rbu_file *p = (rbu_file*)pFile;
  151582. int rc = SQLITE_OK;
  151583. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  151584. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  151585. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  151586. ** instead of a file on disk. */
  151587. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  151588. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  151589. if( iRegion<=p->nShm ){
  151590. int nByte = (iRegion+1) * sizeof(char*);
  151591. char **apNew = (char**)sqlite3_realloc(p->apShm, nByte);
  151592. if( apNew==0 ){
  151593. rc = SQLITE_NOMEM;
  151594. }else{
  151595. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  151596. p->apShm = apNew;
  151597. p->nShm = iRegion+1;
  151598. }
  151599. }
  151600. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  151601. char *pNew = (char*)sqlite3_malloc(szRegion);
  151602. if( pNew==0 ){
  151603. rc = SQLITE_NOMEM;
  151604. }else{
  151605. memset(pNew, 0, szRegion);
  151606. p->apShm[iRegion] = pNew;
  151607. }
  151608. }
  151609. if( rc==SQLITE_OK ){
  151610. *pp = p->apShm[iRegion];
  151611. }else{
  151612. *pp = 0;
  151613. }
  151614. }else{
  151615. assert( p->apShm==0 );
  151616. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  151617. }
  151618. return rc;
  151619. }
  151620. /*
  151621. ** Memory barrier.
  151622. */
  151623. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  151624. rbu_file *p = (rbu_file *)pFile;
  151625. p->pReal->pMethods->xShmBarrier(p->pReal);
  151626. }
  151627. /*
  151628. ** The xShmUnmap method.
  151629. */
  151630. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  151631. rbu_file *p = (rbu_file*)pFile;
  151632. int rc = SQLITE_OK;
  151633. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  151634. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  151635. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  151636. /* no-op */
  151637. }else{
  151638. /* Release the checkpointer and writer locks */
  151639. rbuUnlockShm(p);
  151640. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  151641. }
  151642. return rc;
  151643. }
  151644. /*
  151645. ** Given that zWal points to a buffer containing a wal file name passed to
  151646. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  151647. ** file-handle opened by the same database connection on the corresponding
  151648. ** database file.
  151649. */
  151650. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  151651. rbu_file *pDb;
  151652. sqlite3_mutex_enter(pRbuVfs->mutex);
  151653. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext);
  151654. sqlite3_mutex_leave(pRbuVfs->mutex);
  151655. return pDb;
  151656. }
  151657. /*
  151658. ** Open an rbu file handle.
  151659. */
  151660. static int rbuVfsOpen(
  151661. sqlite3_vfs *pVfs,
  151662. const char *zName,
  151663. sqlite3_file *pFile,
  151664. int flags,
  151665. int *pOutFlags
  151666. ){
  151667. static sqlite3_io_methods rbuvfs_io_methods = {
  151668. 2, /* iVersion */
  151669. rbuVfsClose, /* xClose */
  151670. rbuVfsRead, /* xRead */
  151671. rbuVfsWrite, /* xWrite */
  151672. rbuVfsTruncate, /* xTruncate */
  151673. rbuVfsSync, /* xSync */
  151674. rbuVfsFileSize, /* xFileSize */
  151675. rbuVfsLock, /* xLock */
  151676. rbuVfsUnlock, /* xUnlock */
  151677. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  151678. rbuVfsFileControl, /* xFileControl */
  151679. rbuVfsSectorSize, /* xSectorSize */
  151680. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  151681. rbuVfsShmMap, /* xShmMap */
  151682. rbuVfsShmLock, /* xShmLock */
  151683. rbuVfsShmBarrier, /* xShmBarrier */
  151684. rbuVfsShmUnmap, /* xShmUnmap */
  151685. 0, 0 /* xFetch, xUnfetch */
  151686. };
  151687. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  151688. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  151689. rbu_file *pFd = (rbu_file *)pFile;
  151690. int rc = SQLITE_OK;
  151691. const char *zOpen = zName;
  151692. memset(pFd, 0, sizeof(rbu_file));
  151693. pFd->pReal = (sqlite3_file*)&pFd[1];
  151694. pFd->pRbuVfs = pRbuVfs;
  151695. pFd->openFlags = flags;
  151696. if( zName ){
  151697. if( flags & SQLITE_OPEN_MAIN_DB ){
  151698. /* A main database has just been opened. The following block sets
  151699. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  151700. ** the name of the *-wal file this db connection will use. SQLite
  151701. ** happens to pass a pointer to this buffer when using xAccess()
  151702. ** or xOpen() to operate on the *-wal file. */
  151703. int n = strlen(zName);
  151704. const char *z = &zName[n];
  151705. if( flags & SQLITE_OPEN_URI ){
  151706. int odd = 0;
  151707. while( 1 ){
  151708. if( z[0]==0 ){
  151709. odd = 1 - odd;
  151710. if( odd && z[1]==0 ) break;
  151711. }
  151712. z++;
  151713. }
  151714. z += 2;
  151715. }else{
  151716. while( *z==0 ) z++;
  151717. }
  151718. z += (n + 8 + 1);
  151719. pFd->zWal = z;
  151720. }
  151721. else if( flags & SQLITE_OPEN_WAL ){
  151722. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  151723. if( pDb ){
  151724. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  151725. /* This call is to open a *-wal file. Intead, open the *-oal. This
  151726. ** code ensures that the string passed to xOpen() is terminated by a
  151727. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  151728. ** parameter from it. */
  151729. int nCopy = strlen(zName);
  151730. char *zCopy = sqlite3_malloc(nCopy+2);
  151731. if( zCopy ){
  151732. memcpy(zCopy, zName, nCopy);
  151733. zCopy[nCopy-3] = 'o';
  151734. zCopy[nCopy] = '\0';
  151735. zCopy[nCopy+1] = '\0';
  151736. zOpen = (const char*)(pFd->zDel = zCopy);
  151737. }else{
  151738. rc = SQLITE_NOMEM;
  151739. }
  151740. pFd->pRbu = pDb->pRbu;
  151741. }
  151742. pDb->pWalFd = pFd;
  151743. }
  151744. }
  151745. }
  151746. if( rc==SQLITE_OK ){
  151747. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
  151748. }
  151749. if( pFd->pReal->pMethods ){
  151750. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  151751. ** pointer and, if the file is a main database file, link it into the
  151752. ** mutex protected linked list of all such files. */
  151753. pFile->pMethods = &rbuvfs_io_methods;
  151754. if( flags & SQLITE_OPEN_MAIN_DB ){
  151755. sqlite3_mutex_enter(pRbuVfs->mutex);
  151756. pFd->pMainNext = pRbuVfs->pMain;
  151757. pRbuVfs->pMain = pFd;
  151758. sqlite3_mutex_leave(pRbuVfs->mutex);
  151759. }
  151760. }else{
  151761. sqlite3_free(pFd->zDel);
  151762. }
  151763. return rc;
  151764. }
  151765. /*
  151766. ** Delete the file located at zPath.
  151767. */
  151768. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  151769. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151770. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  151771. }
  151772. /*
  151773. ** Test for access permissions. Return true if the requested permission
  151774. ** is available, or false otherwise.
  151775. */
  151776. static int rbuVfsAccess(
  151777. sqlite3_vfs *pVfs,
  151778. const char *zPath,
  151779. int flags,
  151780. int *pResOut
  151781. ){
  151782. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  151783. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  151784. int rc;
  151785. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  151786. /* If this call is to check if a *-wal file associated with an RBU target
  151787. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  151788. ** the following special handling is activated:
  151789. **
  151790. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  151791. ** ensures that the RBU extension never tries to update a database
  151792. ** in wal mode, even if the first page of the database file has
  151793. ** been damaged.
  151794. **
  151795. ** b) if the *-wal file does not exist, claim that it does anyway,
  151796. ** causing SQLite to call xOpen() to open it. This call will also
  151797. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  151798. ** file opened instead.
  151799. */
  151800. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  151801. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  151802. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  151803. if( *pResOut ){
  151804. rc = SQLITE_CANTOPEN;
  151805. }else{
  151806. *pResOut = 1;
  151807. }
  151808. }
  151809. }
  151810. return rc;
  151811. }
  151812. /*
  151813. ** Populate buffer zOut with the full canonical pathname corresponding
  151814. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  151815. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  151816. */
  151817. static int rbuVfsFullPathname(
  151818. sqlite3_vfs *pVfs,
  151819. const char *zPath,
  151820. int nOut,
  151821. char *zOut
  151822. ){
  151823. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151824. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  151825. }
  151826. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  151827. /*
  151828. ** Open the dynamic library located at zPath and return a handle.
  151829. */
  151830. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  151831. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151832. return pRealVfs->xDlOpen(pRealVfs, zPath);
  151833. }
  151834. /*
  151835. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  151836. ** utf-8 string describing the most recent error encountered associated
  151837. ** with dynamic libraries.
  151838. */
  151839. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  151840. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151841. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  151842. }
  151843. /*
  151844. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  151845. */
  151846. static void (*rbuVfsDlSym(
  151847. sqlite3_vfs *pVfs,
  151848. void *pArg,
  151849. const char *zSym
  151850. ))(void){
  151851. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151852. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  151853. }
  151854. /*
  151855. ** Close the dynamic library handle pHandle.
  151856. */
  151857. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  151858. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151859. pRealVfs->xDlClose(pRealVfs, pHandle);
  151860. }
  151861. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  151862. /*
  151863. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  151864. ** random data.
  151865. */
  151866. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  151867. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151868. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  151869. }
  151870. /*
  151871. ** Sleep for nMicro microseconds. Return the number of microseconds
  151872. ** actually slept.
  151873. */
  151874. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  151875. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151876. return pRealVfs->xSleep(pRealVfs, nMicro);
  151877. }
  151878. /*
  151879. ** Return the current time as a Julian Day number in *pTimeOut.
  151880. */
  151881. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  151882. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  151883. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  151884. }
  151885. /*
  151886. ** No-op.
  151887. */
  151888. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  151889. return 0;
  151890. }
  151891. /*
  151892. ** Deregister and destroy an RBU vfs created by an earlier call to
  151893. ** sqlite3rbu_create_vfs().
  151894. */
  151895. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
  151896. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  151897. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  151898. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  151899. sqlite3_vfs_unregister(pVfs);
  151900. sqlite3_free(pVfs);
  151901. }
  151902. }
  151903. /*
  151904. ** Create an RBU VFS named zName that accesses the underlying file-system
  151905. ** via existing VFS zParent. The new object is registered as a non-default
  151906. ** VFS with SQLite before returning.
  151907. */
  151908. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  151909. /* Template for VFS */
  151910. static sqlite3_vfs vfs_template = {
  151911. 1, /* iVersion */
  151912. 0, /* szOsFile */
  151913. 0, /* mxPathname */
  151914. 0, /* pNext */
  151915. 0, /* zName */
  151916. 0, /* pAppData */
  151917. rbuVfsOpen, /* xOpen */
  151918. rbuVfsDelete, /* xDelete */
  151919. rbuVfsAccess, /* xAccess */
  151920. rbuVfsFullPathname, /* xFullPathname */
  151921. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  151922. rbuVfsDlOpen, /* xDlOpen */
  151923. rbuVfsDlError, /* xDlError */
  151924. rbuVfsDlSym, /* xDlSym */
  151925. rbuVfsDlClose, /* xDlClose */
  151926. #else
  151927. 0, 0, 0, 0,
  151928. #endif
  151929. rbuVfsRandomness, /* xRandomness */
  151930. rbuVfsSleep, /* xSleep */
  151931. rbuVfsCurrentTime, /* xCurrentTime */
  151932. rbuVfsGetLastError, /* xGetLastError */
  151933. 0, /* xCurrentTimeInt64 (version 2) */
  151934. 0, 0, 0 /* Unimplemented version 3 methods */
  151935. };
  151936. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  151937. int nName;
  151938. int rc = SQLITE_OK;
  151939. int nByte;
  151940. nName = strlen(zName);
  151941. nByte = sizeof(rbu_vfs) + nName + 1;
  151942. pNew = (rbu_vfs*)sqlite3_malloc(nByte);
  151943. if( pNew==0 ){
  151944. rc = SQLITE_NOMEM;
  151945. }else{
  151946. sqlite3_vfs *pParent; /* Parent VFS */
  151947. memset(pNew, 0, nByte);
  151948. pParent = sqlite3_vfs_find(zParent);
  151949. if( pParent==0 ){
  151950. rc = SQLITE_NOTFOUND;
  151951. }else{
  151952. char *zSpace;
  151953. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  151954. pNew->base.mxPathname = pParent->mxPathname;
  151955. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  151956. pNew->pRealVfs = pParent;
  151957. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  151958. memcpy(zSpace, zName, nName);
  151959. /* Allocate the mutex and register the new VFS (not as the default) */
  151960. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  151961. if( pNew->mutex==0 ){
  151962. rc = SQLITE_NOMEM;
  151963. }else{
  151964. rc = sqlite3_vfs_register(&pNew->base, 0);
  151965. }
  151966. }
  151967. if( rc!=SQLITE_OK ){
  151968. sqlite3_mutex_free(pNew->mutex);
  151969. sqlite3_free(pNew);
  151970. }
  151971. }
  151972. return rc;
  151973. }
  151974. /**************************************************************************/
  151975. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  151976. /************** End of sqlite3rbu.c ******************************************/
  151977. /************** Begin file dbstat.c ******************************************/
  151978. /*
  151979. ** 2010 July 12
  151980. **
  151981. ** The author disclaims copyright to this source code. In place of
  151982. ** a legal notice, here is a blessing:
  151983. **
  151984. ** May you do good and not evil.
  151985. ** May you find forgiveness for yourself and forgive others.
  151986. ** May you share freely, never taking more than you give.
  151987. **
  151988. ******************************************************************************
  151989. **
  151990. ** This file contains an implementation of the "dbstat" virtual table.
  151991. **
  151992. ** The dbstat virtual table is used to extract low-level formatting
  151993. ** information from an SQLite database in order to implement the
  151994. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  151995. ** for an example implementation.
  151996. **
  151997. ** Additional information is available on the "dbstat.html" page of the
  151998. ** official SQLite documentation.
  151999. */
  152000. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  152001. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  152002. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  152003. /*
  152004. ** Page paths:
  152005. **
  152006. ** The value of the 'path' column describes the path taken from the
  152007. ** root-node of the b-tree structure to each page. The value of the
  152008. ** root-node path is '/'.
  152009. **
  152010. ** The value of the path for the left-most child page of the root of
  152011. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  152012. ** so the pages to the left have smaller keys than the pages to the right.)
  152013. ** The next to left-most child of the root page is
  152014. ** '/001', and so on, each sibling page identified by a 3-digit hex
  152015. ** value. The children of the 451st left-most sibling have paths such
  152016. ** as '/1c2/000/, '/1c2/001/' etc.
  152017. **
  152018. ** Overflow pages are specified by appending a '+' character and a
  152019. ** six-digit hexadecimal value to the path to the cell they are linked
  152020. ** from. For example, the three overflow pages in a chain linked from
  152021. ** the left-most cell of the 450th child of the root page are identified
  152022. ** by the paths:
  152023. **
  152024. ** '/1c2/000+000000' // First page in overflow chain
  152025. ** '/1c2/000+000001' // Second page in overflow chain
  152026. ** '/1c2/000+000002' // Third page in overflow chain
  152027. **
  152028. ** If the paths are sorted using the BINARY collation sequence, then
  152029. ** the overflow pages associated with a cell will appear earlier in the
  152030. ** sort-order than its child page:
  152031. **
  152032. ** '/1c2/000/' // Left-most child of 451st child of root
  152033. */
  152034. #define VTAB_SCHEMA \
  152035. "CREATE TABLE xx( " \
  152036. " name STRING, /* Name of table or index */" \
  152037. " path INTEGER, /* Path to page from root */" \
  152038. " pageno INTEGER, /* Page number */" \
  152039. " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
  152040. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  152041. " payload INTEGER, /* Bytes of payload on this page */" \
  152042. " unused INTEGER, /* Bytes of unused space on this page */" \
  152043. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  152044. " pgoffset INTEGER, /* Offset of page in file */" \
  152045. " pgsize INTEGER, /* Size of the page */" \
  152046. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  152047. ");"
  152048. typedef struct StatTable StatTable;
  152049. typedef struct StatCursor StatCursor;
  152050. typedef struct StatPage StatPage;
  152051. typedef struct StatCell StatCell;
  152052. struct StatCell {
  152053. int nLocal; /* Bytes of local payload */
  152054. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  152055. int nOvfl; /* Entries in aOvfl[] */
  152056. u32 *aOvfl; /* Array of overflow page numbers */
  152057. int nLastOvfl; /* Bytes of payload on final overflow page */
  152058. int iOvfl; /* Iterates through aOvfl[] */
  152059. };
  152060. struct StatPage {
  152061. u32 iPgno;
  152062. DbPage *pPg;
  152063. int iCell;
  152064. char *zPath; /* Path to this page */
  152065. /* Variables populated by statDecodePage(): */
  152066. u8 flags; /* Copy of flags byte */
  152067. int nCell; /* Number of cells on page */
  152068. int nUnused; /* Number of unused bytes on page */
  152069. StatCell *aCell; /* Array of parsed cells */
  152070. u32 iRightChildPg; /* Right-child page number (or 0) */
  152071. int nMxPayload; /* Largest payload of any cell on this page */
  152072. };
  152073. struct StatCursor {
  152074. sqlite3_vtab_cursor base;
  152075. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  152076. int isEof; /* After pStmt has returned SQLITE_DONE */
  152077. int iDb; /* Schema used for this query */
  152078. StatPage aPage[32];
  152079. int iPage; /* Current entry in aPage[] */
  152080. /* Values to return. */
  152081. char *zName; /* Value of 'name' column */
  152082. char *zPath; /* Value of 'path' column */
  152083. u32 iPageno; /* Value of 'pageno' column */
  152084. char *zPagetype; /* Value of 'pagetype' column */
  152085. int nCell; /* Value of 'ncell' column */
  152086. int nPayload; /* Value of 'payload' column */
  152087. int nUnused; /* Value of 'unused' column */
  152088. int nMxPayload; /* Value of 'mx_payload' column */
  152089. i64 iOffset; /* Value of 'pgOffset' column */
  152090. int szPage; /* Value of 'pgSize' column */
  152091. };
  152092. struct StatTable {
  152093. sqlite3_vtab base;
  152094. sqlite3 *db;
  152095. int iDb; /* Index of database to analyze */
  152096. };
  152097. #ifndef get2byte
  152098. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  152099. #endif
  152100. /*
  152101. ** Connect to or create a statvfs virtual table.
  152102. */
  152103. static int statConnect(
  152104. sqlite3 *db,
  152105. void *pAux,
  152106. int argc, const char *const*argv,
  152107. sqlite3_vtab **ppVtab,
  152108. char **pzErr
  152109. ){
  152110. StatTable *pTab = 0;
  152111. int rc = SQLITE_OK;
  152112. int iDb;
  152113. if( argc>=4 ){
  152114. iDb = sqlite3FindDbName(db, argv[3]);
  152115. if( iDb<0 ){
  152116. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  152117. return SQLITE_ERROR;
  152118. }
  152119. }else{
  152120. iDb = 0;
  152121. }
  152122. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  152123. if( rc==SQLITE_OK ){
  152124. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  152125. if( pTab==0 ) rc = SQLITE_NOMEM;
  152126. }
  152127. assert( rc==SQLITE_OK || pTab==0 );
  152128. if( rc==SQLITE_OK ){
  152129. memset(pTab, 0, sizeof(StatTable));
  152130. pTab->db = db;
  152131. pTab->iDb = iDb;
  152132. }
  152133. *ppVtab = (sqlite3_vtab*)pTab;
  152134. return rc;
  152135. }
  152136. /*
  152137. ** Disconnect from or destroy a statvfs virtual table.
  152138. */
  152139. static int statDisconnect(sqlite3_vtab *pVtab){
  152140. sqlite3_free(pVtab);
  152141. return SQLITE_OK;
  152142. }
  152143. /*
  152144. ** There is no "best-index". This virtual table always does a linear
  152145. ** scan. However, a schema=? constraint should cause this table to
  152146. ** operate on a different database schema, so check for it.
  152147. **
  152148. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  152149. */
  152150. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  152151. int i;
  152152. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  152153. /* Look for a valid schema=? constraint. If found, change the idxNum to
  152154. ** 1 and request the value of that constraint be sent to xFilter. And
  152155. ** lower the cost estimate to encourage the constrained version to be
  152156. ** used.
  152157. */
  152158. for(i=0; i<pIdxInfo->nConstraint; i++){
  152159. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  152160. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  152161. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  152162. pIdxInfo->idxNum = 1;
  152163. pIdxInfo->estimatedCost = 1.0;
  152164. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  152165. pIdxInfo->aConstraintUsage[i].omit = 1;
  152166. break;
  152167. }
  152168. /* Records are always returned in ascending order of (name, path).
  152169. ** If this will satisfy the client, set the orderByConsumed flag so that
  152170. ** SQLite does not do an external sort.
  152171. */
  152172. if( ( pIdxInfo->nOrderBy==1
  152173. && pIdxInfo->aOrderBy[0].iColumn==0
  152174. && pIdxInfo->aOrderBy[0].desc==0
  152175. ) ||
  152176. ( pIdxInfo->nOrderBy==2
  152177. && pIdxInfo->aOrderBy[0].iColumn==0
  152178. && pIdxInfo->aOrderBy[0].desc==0
  152179. && pIdxInfo->aOrderBy[1].iColumn==1
  152180. && pIdxInfo->aOrderBy[1].desc==0
  152181. )
  152182. ){
  152183. pIdxInfo->orderByConsumed = 1;
  152184. }
  152185. return SQLITE_OK;
  152186. }
  152187. /*
  152188. ** Open a new statvfs cursor.
  152189. */
  152190. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  152191. StatTable *pTab = (StatTable *)pVTab;
  152192. StatCursor *pCsr;
  152193. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  152194. if( pCsr==0 ){
  152195. return SQLITE_NOMEM;
  152196. }else{
  152197. memset(pCsr, 0, sizeof(StatCursor));
  152198. pCsr->base.pVtab = pVTab;
  152199. pCsr->iDb = pTab->iDb;
  152200. }
  152201. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  152202. return SQLITE_OK;
  152203. }
  152204. static void statClearPage(StatPage *p){
  152205. int i;
  152206. if( p->aCell ){
  152207. for(i=0; i<p->nCell; i++){
  152208. sqlite3_free(p->aCell[i].aOvfl);
  152209. }
  152210. sqlite3_free(p->aCell);
  152211. }
  152212. sqlite3PagerUnref(p->pPg);
  152213. sqlite3_free(p->zPath);
  152214. memset(p, 0, sizeof(StatPage));
  152215. }
  152216. static void statResetCsr(StatCursor *pCsr){
  152217. int i;
  152218. sqlite3_reset(pCsr->pStmt);
  152219. for(i=0; i<ArraySize(pCsr->aPage); i++){
  152220. statClearPage(&pCsr->aPage[i]);
  152221. }
  152222. pCsr->iPage = 0;
  152223. sqlite3_free(pCsr->zPath);
  152224. pCsr->zPath = 0;
  152225. pCsr->isEof = 0;
  152226. }
  152227. /*
  152228. ** Close a statvfs cursor.
  152229. */
  152230. static int statClose(sqlite3_vtab_cursor *pCursor){
  152231. StatCursor *pCsr = (StatCursor *)pCursor;
  152232. statResetCsr(pCsr);
  152233. sqlite3_finalize(pCsr->pStmt);
  152234. sqlite3_free(pCsr);
  152235. return SQLITE_OK;
  152236. }
  152237. static void getLocalPayload(
  152238. int nUsable, /* Usable bytes per page */
  152239. u8 flags, /* Page flags */
  152240. int nTotal, /* Total record (payload) size */
  152241. int *pnLocal /* OUT: Bytes stored locally */
  152242. ){
  152243. int nLocal;
  152244. int nMinLocal;
  152245. int nMaxLocal;
  152246. if( flags==0x0D ){ /* Table leaf node */
  152247. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  152248. nMaxLocal = nUsable - 35;
  152249. }else{ /* Index interior and leaf nodes */
  152250. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  152251. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  152252. }
  152253. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  152254. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  152255. *pnLocal = nLocal;
  152256. }
  152257. static int statDecodePage(Btree *pBt, StatPage *p){
  152258. int nUnused;
  152259. int iOff;
  152260. int nHdr;
  152261. int isLeaf;
  152262. int szPage;
  152263. u8 *aData = sqlite3PagerGetData(p->pPg);
  152264. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  152265. p->flags = aHdr[0];
  152266. p->nCell = get2byte(&aHdr[3]);
  152267. p->nMxPayload = 0;
  152268. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  152269. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  152270. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  152271. nUnused += (int)aHdr[7];
  152272. iOff = get2byte(&aHdr[1]);
  152273. while( iOff ){
  152274. nUnused += get2byte(&aData[iOff+2]);
  152275. iOff = get2byte(&aData[iOff]);
  152276. }
  152277. p->nUnused = nUnused;
  152278. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  152279. szPage = sqlite3BtreeGetPageSize(pBt);
  152280. if( p->nCell ){
  152281. int i; /* Used to iterate through cells */
  152282. int nUsable; /* Usable bytes per page */
  152283. sqlite3BtreeEnter(pBt);
  152284. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  152285. sqlite3BtreeLeave(pBt);
  152286. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  152287. if( p->aCell==0 ) return SQLITE_NOMEM;
  152288. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  152289. for(i=0; i<p->nCell; i++){
  152290. StatCell *pCell = &p->aCell[i];
  152291. iOff = get2byte(&aData[nHdr+i*2]);
  152292. if( !isLeaf ){
  152293. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  152294. iOff += 4;
  152295. }
  152296. if( p->flags==0x05 ){
  152297. /* A table interior node. nPayload==0. */
  152298. }else{
  152299. u32 nPayload; /* Bytes of payload total (local+overflow) */
  152300. int nLocal; /* Bytes of payload stored locally */
  152301. iOff += getVarint32(&aData[iOff], nPayload);
  152302. if( p->flags==0x0D ){
  152303. u64 dummy;
  152304. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  152305. }
  152306. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  152307. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  152308. pCell->nLocal = nLocal;
  152309. assert( nLocal>=0 );
  152310. assert( nPayload>=(u32)nLocal );
  152311. assert( nLocal<=(nUsable-35) );
  152312. if( nPayload>(u32)nLocal ){
  152313. int j;
  152314. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  152315. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  152316. pCell->nOvfl = nOvfl;
  152317. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  152318. if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
  152319. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  152320. for(j=1; j<nOvfl; j++){
  152321. int rc;
  152322. u32 iPrev = pCell->aOvfl[j-1];
  152323. DbPage *pPg = 0;
  152324. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
  152325. if( rc!=SQLITE_OK ){
  152326. assert( pPg==0 );
  152327. return rc;
  152328. }
  152329. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  152330. sqlite3PagerUnref(pPg);
  152331. }
  152332. }
  152333. }
  152334. }
  152335. }
  152336. return SQLITE_OK;
  152337. }
  152338. /*
  152339. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  152340. ** the current value of pCsr->iPageno.
  152341. */
  152342. static void statSizeAndOffset(StatCursor *pCsr){
  152343. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  152344. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  152345. Pager *pPager = sqlite3BtreePager(pBt);
  152346. sqlite3_file *fd;
  152347. sqlite3_int64 x[2];
  152348. /* The default page size and offset */
  152349. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  152350. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  152351. /* If connected to a ZIPVFS backend, override the page size and
  152352. ** offset with actual values obtained from ZIPVFS.
  152353. */
  152354. fd = sqlite3PagerFile(pPager);
  152355. x[0] = pCsr->iPageno;
  152356. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  152357. pCsr->iOffset = x[0];
  152358. pCsr->szPage = (int)x[1];
  152359. }
  152360. }
  152361. /*
  152362. ** Move a statvfs cursor to the next entry in the file.
  152363. */
  152364. static int statNext(sqlite3_vtab_cursor *pCursor){
  152365. int rc;
  152366. int nPayload;
  152367. char *z;
  152368. StatCursor *pCsr = (StatCursor *)pCursor;
  152369. StatTable *pTab = (StatTable *)pCursor->pVtab;
  152370. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  152371. Pager *pPager = sqlite3BtreePager(pBt);
  152372. sqlite3_free(pCsr->zPath);
  152373. pCsr->zPath = 0;
  152374. statNextRestart:
  152375. if( pCsr->aPage[0].pPg==0 ){
  152376. rc = sqlite3_step(pCsr->pStmt);
  152377. if( rc==SQLITE_ROW ){
  152378. int nPage;
  152379. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  152380. sqlite3PagerPagecount(pPager, &nPage);
  152381. if( nPage==0 ){
  152382. pCsr->isEof = 1;
  152383. return sqlite3_reset(pCsr->pStmt);
  152384. }
  152385. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
  152386. pCsr->aPage[0].iPgno = iRoot;
  152387. pCsr->aPage[0].iCell = 0;
  152388. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  152389. pCsr->iPage = 0;
  152390. if( z==0 ) rc = SQLITE_NOMEM;
  152391. }else{
  152392. pCsr->isEof = 1;
  152393. return sqlite3_reset(pCsr->pStmt);
  152394. }
  152395. }else{
  152396. /* Page p itself has already been visited. */
  152397. StatPage *p = &pCsr->aPage[pCsr->iPage];
  152398. while( p->iCell<p->nCell ){
  152399. StatCell *pCell = &p->aCell[p->iCell];
  152400. if( pCell->iOvfl<pCell->nOvfl ){
  152401. int nUsable;
  152402. sqlite3BtreeEnter(pBt);
  152403. nUsable = sqlite3BtreeGetPageSize(pBt) -
  152404. sqlite3BtreeGetReserveNoMutex(pBt);
  152405. sqlite3BtreeLeave(pBt);
  152406. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  152407. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  152408. pCsr->zPagetype = "overflow";
  152409. pCsr->nCell = 0;
  152410. pCsr->nMxPayload = 0;
  152411. pCsr->zPath = z = sqlite3_mprintf(
  152412. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  152413. );
  152414. if( pCell->iOvfl<pCell->nOvfl-1 ){
  152415. pCsr->nUnused = 0;
  152416. pCsr->nPayload = nUsable - 4;
  152417. }else{
  152418. pCsr->nPayload = pCell->nLastOvfl;
  152419. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  152420. }
  152421. pCell->iOvfl++;
  152422. statSizeAndOffset(pCsr);
  152423. return z==0 ? SQLITE_NOMEM : SQLITE_OK;
  152424. }
  152425. if( p->iRightChildPg ) break;
  152426. p->iCell++;
  152427. }
  152428. if( !p->iRightChildPg || p->iCell>p->nCell ){
  152429. statClearPage(p);
  152430. if( pCsr->iPage==0 ) return statNext(pCursor);
  152431. pCsr->iPage--;
  152432. goto statNextRestart; /* Tail recursion */
  152433. }
  152434. pCsr->iPage++;
  152435. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  152436. if( p->iCell==p->nCell ){
  152437. p[1].iPgno = p->iRightChildPg;
  152438. }else{
  152439. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  152440. }
  152441. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
  152442. p[1].iCell = 0;
  152443. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  152444. p->iCell++;
  152445. if( z==0 ) rc = SQLITE_NOMEM;
  152446. }
  152447. /* Populate the StatCursor fields with the values to be returned
  152448. ** by the xColumn() and xRowid() methods.
  152449. */
  152450. if( rc==SQLITE_OK ){
  152451. int i;
  152452. StatPage *p = &pCsr->aPage[pCsr->iPage];
  152453. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  152454. pCsr->iPageno = p->iPgno;
  152455. rc = statDecodePage(pBt, p);
  152456. if( rc==SQLITE_OK ){
  152457. statSizeAndOffset(pCsr);
  152458. switch( p->flags ){
  152459. case 0x05: /* table internal */
  152460. case 0x02: /* index internal */
  152461. pCsr->zPagetype = "internal";
  152462. break;
  152463. case 0x0D: /* table leaf */
  152464. case 0x0A: /* index leaf */
  152465. pCsr->zPagetype = "leaf";
  152466. break;
  152467. default:
  152468. pCsr->zPagetype = "corrupted";
  152469. break;
  152470. }
  152471. pCsr->nCell = p->nCell;
  152472. pCsr->nUnused = p->nUnused;
  152473. pCsr->nMxPayload = p->nMxPayload;
  152474. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  152475. if( z==0 ) rc = SQLITE_NOMEM;
  152476. nPayload = 0;
  152477. for(i=0; i<p->nCell; i++){
  152478. nPayload += p->aCell[i].nLocal;
  152479. }
  152480. pCsr->nPayload = nPayload;
  152481. }
  152482. }
  152483. return rc;
  152484. }
  152485. static int statEof(sqlite3_vtab_cursor *pCursor){
  152486. StatCursor *pCsr = (StatCursor *)pCursor;
  152487. return pCsr->isEof;
  152488. }
  152489. static int statFilter(
  152490. sqlite3_vtab_cursor *pCursor,
  152491. int idxNum, const char *idxStr,
  152492. int argc, sqlite3_value **argv
  152493. ){
  152494. StatCursor *pCsr = (StatCursor *)pCursor;
  152495. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  152496. char *zSql;
  152497. int rc = SQLITE_OK;
  152498. char *zMaster;
  152499. if( idxNum==1 ){
  152500. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  152501. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  152502. if( pCsr->iDb<0 ){
  152503. sqlite3_free(pCursor->pVtab->zErrMsg);
  152504. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  152505. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  152506. }
  152507. }else{
  152508. pCsr->iDb = pTab->iDb;
  152509. }
  152510. statResetCsr(pCsr);
  152511. sqlite3_finalize(pCsr->pStmt);
  152512. pCsr->pStmt = 0;
  152513. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  152514. zSql = sqlite3_mprintf(
  152515. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  152516. " UNION ALL "
  152517. "SELECT name, rootpage, type"
  152518. " FROM \"%w\".%s WHERE rootpage!=0"
  152519. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
  152520. if( zSql==0 ){
  152521. return SQLITE_NOMEM;
  152522. }else{
  152523. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  152524. sqlite3_free(zSql);
  152525. }
  152526. if( rc==SQLITE_OK ){
  152527. rc = statNext(pCursor);
  152528. }
  152529. return rc;
  152530. }
  152531. static int statColumn(
  152532. sqlite3_vtab_cursor *pCursor,
  152533. sqlite3_context *ctx,
  152534. int i
  152535. ){
  152536. StatCursor *pCsr = (StatCursor *)pCursor;
  152537. switch( i ){
  152538. case 0: /* name */
  152539. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  152540. break;
  152541. case 1: /* path */
  152542. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  152543. break;
  152544. case 2: /* pageno */
  152545. sqlite3_result_int64(ctx, pCsr->iPageno);
  152546. break;
  152547. case 3: /* pagetype */
  152548. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  152549. break;
  152550. case 4: /* ncell */
  152551. sqlite3_result_int(ctx, pCsr->nCell);
  152552. break;
  152553. case 5: /* payload */
  152554. sqlite3_result_int(ctx, pCsr->nPayload);
  152555. break;
  152556. case 6: /* unused */
  152557. sqlite3_result_int(ctx, pCsr->nUnused);
  152558. break;
  152559. case 7: /* mx_payload */
  152560. sqlite3_result_int(ctx, pCsr->nMxPayload);
  152561. break;
  152562. case 8: /* pgoffset */
  152563. sqlite3_result_int64(ctx, pCsr->iOffset);
  152564. break;
  152565. case 9: /* pgsize */
  152566. sqlite3_result_int(ctx, pCsr->szPage);
  152567. break;
  152568. default: { /* schema */
  152569. sqlite3 *db = sqlite3_context_db_handle(ctx);
  152570. int iDb = pCsr->iDb;
  152571. sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
  152572. break;
  152573. }
  152574. }
  152575. return SQLITE_OK;
  152576. }
  152577. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  152578. StatCursor *pCsr = (StatCursor *)pCursor;
  152579. *pRowid = pCsr->iPageno;
  152580. return SQLITE_OK;
  152581. }
  152582. /*
  152583. ** Invoke this routine to register the "dbstat" virtual table module
  152584. */
  152585. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  152586. static sqlite3_module dbstat_module = {
  152587. 0, /* iVersion */
  152588. statConnect, /* xCreate */
  152589. statConnect, /* xConnect */
  152590. statBestIndex, /* xBestIndex */
  152591. statDisconnect, /* xDisconnect */
  152592. statDisconnect, /* xDestroy */
  152593. statOpen, /* xOpen - open a cursor */
  152594. statClose, /* xClose - close a cursor */
  152595. statFilter, /* xFilter - configure scan constraints */
  152596. statNext, /* xNext - advance a cursor */
  152597. statEof, /* xEof - check for end of scan */
  152598. statColumn, /* xColumn - read data */
  152599. statRowid, /* xRowid - read data */
  152600. 0, /* xUpdate */
  152601. 0, /* xBegin */
  152602. 0, /* xSync */
  152603. 0, /* xCommit */
  152604. 0, /* xRollback */
  152605. 0, /* xFindMethod */
  152606. 0, /* xRename */
  152607. };
  152608. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  152609. }
  152610. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  152611. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  152612. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  152613. /************** End of dbstat.c **********************************************/
  152614. /************** Begin file json1.c *******************************************/
  152615. /*
  152616. ** 2015-08-12
  152617. **
  152618. ** The author disclaims copyright to this source code. In place of
  152619. ** a legal notice, here is a blessing:
  152620. **
  152621. ** May you do good and not evil.
  152622. ** May you find forgiveness for yourself and forgive others.
  152623. ** May you share freely, never taking more than you give.
  152624. **
  152625. ******************************************************************************
  152626. **
  152627. ** This SQLite extension implements JSON functions. The interface is
  152628. ** modeled after MySQL JSON functions:
  152629. **
  152630. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  152631. **
  152632. ** For the time being, all JSON is stored as pure text. (We might add
  152633. ** a JSONB type in the future which stores a binary encoding of JSON in
  152634. ** a BLOB, but there is no support for JSONB in the current implementation.
  152635. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  152636. ** how JSONB might improve on that.)
  152637. */
  152638. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  152639. #if !defined(_SQLITEINT_H_)
  152640. /* #include "sqlite3ext.h" */
  152641. #endif
  152642. SQLITE_EXTENSION_INIT1
  152643. /* #include <assert.h> */
  152644. /* #include <string.h> */
  152645. /* #include <stdlib.h> */
  152646. /* #include <stdarg.h> */
  152647. #define UNUSED_PARAM(X) (void)(X)
  152648. #ifndef LARGEST_INT64
  152649. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  152650. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  152651. #endif
  152652. /*
  152653. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  152654. ** to pass signed char values.
  152655. */
  152656. #ifdef sqlite3Isdigit
  152657. /* Use the SQLite core versions if this routine is part of the
  152658. ** SQLite amalgamation */
  152659. # define safe_isdigit(x) sqlite3Isdigit(x)
  152660. # define safe_isalnum(x) sqlite3Isalnum(x)
  152661. #else
  152662. /* Use the standard library for separate compilation */
  152663. #include <ctype.h> /* amalgamator: keep */
  152664. # define safe_isdigit(x) isdigit((unsigned char)(x))
  152665. # define safe_isalnum(x) isalnum((unsigned char)(x))
  152666. #endif
  152667. /*
  152668. ** Growing our own isspace() routine this way is twice as fast as
  152669. ** the library isspace() function, resulting in a 7% overall performance
  152670. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  152671. */
  152672. static const char jsonIsSpace[] = {
  152673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  152674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152675. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  152689. };
  152690. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  152691. #ifndef SQLITE_AMALGAMATION
  152692. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  152693. ** but the definitions need to be repeated for separate compilation. */
  152694. typedef sqlite3_uint64 u64;
  152695. typedef unsigned int u32;
  152696. typedef unsigned char u8;
  152697. #endif
  152698. /* Objects */
  152699. typedef struct JsonString JsonString;
  152700. typedef struct JsonNode JsonNode;
  152701. typedef struct JsonParse JsonParse;
  152702. /* An instance of this object represents a JSON string
  152703. ** under construction. Really, this is a generic string accumulator
  152704. ** that can be and is used to create strings other than JSON.
  152705. */
  152706. struct JsonString {
  152707. sqlite3_context *pCtx; /* Function context - put error messages here */
  152708. char *zBuf; /* Append JSON content here */
  152709. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  152710. u64 nUsed; /* Bytes of zBuf[] currently used */
  152711. u8 bStatic; /* True if zBuf is static space */
  152712. u8 bErr; /* True if an error has been encountered */
  152713. char zSpace[100]; /* Initial static space */
  152714. };
  152715. /* JSON type values
  152716. */
  152717. #define JSON_NULL 0
  152718. #define JSON_TRUE 1
  152719. #define JSON_FALSE 2
  152720. #define JSON_INT 3
  152721. #define JSON_REAL 4
  152722. #define JSON_STRING 5
  152723. #define JSON_ARRAY 6
  152724. #define JSON_OBJECT 7
  152725. /* The "subtype" set for JSON values */
  152726. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  152727. /*
  152728. ** Names of the various JSON types:
  152729. */
  152730. static const char * const jsonType[] = {
  152731. "null", "true", "false", "integer", "real", "text", "array", "object"
  152732. };
  152733. /* Bit values for the JsonNode.jnFlag field
  152734. */
  152735. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  152736. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  152737. #define JNODE_REMOVE 0x04 /* Do not output */
  152738. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
  152739. #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
  152740. #define JNODE_LABEL 0x20 /* Is a label of an object */
  152741. /* A single node of parsed JSON
  152742. */
  152743. struct JsonNode {
  152744. u8 eType; /* One of the JSON_ type values */
  152745. u8 jnFlags; /* JNODE flags */
  152746. u8 iVal; /* Replacement value when JNODE_REPLACE */
  152747. u32 n; /* Bytes of content, or number of sub-nodes */
  152748. union {
  152749. const char *zJContent; /* Content for INT, REAL, and STRING */
  152750. u32 iAppend; /* More terms for ARRAY and OBJECT */
  152751. u32 iKey; /* Key for ARRAY objects in json_tree() */
  152752. } u;
  152753. };
  152754. /* A completely parsed JSON string
  152755. */
  152756. struct JsonParse {
  152757. u32 nNode; /* Number of slots of aNode[] used */
  152758. u32 nAlloc; /* Number of slots of aNode[] allocated */
  152759. JsonNode *aNode; /* Array of nodes containing the parse */
  152760. const char *zJson; /* Original JSON string */
  152761. u32 *aUp; /* Index of parent of each node */
  152762. u8 oom; /* Set to true if out of memory */
  152763. u8 nErr; /* Number of errors seen */
  152764. };
  152765. /**************************************************************************
  152766. ** Utility routines for dealing with JsonString objects
  152767. **************************************************************************/
  152768. /* Set the JsonString object to an empty string
  152769. */
  152770. static void jsonZero(JsonString *p){
  152771. p->zBuf = p->zSpace;
  152772. p->nAlloc = sizeof(p->zSpace);
  152773. p->nUsed = 0;
  152774. p->bStatic = 1;
  152775. }
  152776. /* Initialize the JsonString object
  152777. */
  152778. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  152779. p->pCtx = pCtx;
  152780. p->bErr = 0;
  152781. jsonZero(p);
  152782. }
  152783. /* Free all allocated memory and reset the JsonString object back to its
  152784. ** initial state.
  152785. */
  152786. static void jsonReset(JsonString *p){
  152787. if( !p->bStatic ) sqlite3_free(p->zBuf);
  152788. jsonZero(p);
  152789. }
  152790. /* Report an out-of-memory (OOM) condition
  152791. */
  152792. static void jsonOom(JsonString *p){
  152793. p->bErr = 1;
  152794. sqlite3_result_error_nomem(p->pCtx);
  152795. jsonReset(p);
  152796. }
  152797. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  152798. ** Return zero on success. Return non-zero on an OOM error
  152799. */
  152800. static int jsonGrow(JsonString *p, u32 N){
  152801. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  152802. char *zNew;
  152803. if( p->bStatic ){
  152804. if( p->bErr ) return 1;
  152805. zNew = sqlite3_malloc64(nTotal);
  152806. if( zNew==0 ){
  152807. jsonOom(p);
  152808. return SQLITE_NOMEM;
  152809. }
  152810. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  152811. p->zBuf = zNew;
  152812. p->bStatic = 0;
  152813. }else{
  152814. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  152815. if( zNew==0 ){
  152816. jsonOom(p);
  152817. return SQLITE_NOMEM;
  152818. }
  152819. p->zBuf = zNew;
  152820. }
  152821. p->nAlloc = nTotal;
  152822. return SQLITE_OK;
  152823. }
  152824. /* Append N bytes from zIn onto the end of the JsonString string.
  152825. */
  152826. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  152827. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  152828. memcpy(p->zBuf+p->nUsed, zIn, N);
  152829. p->nUsed += N;
  152830. }
  152831. /* Append formatted text (not to exceed N bytes) to the JsonString.
  152832. */
  152833. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  152834. va_list ap;
  152835. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  152836. va_start(ap, zFormat);
  152837. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  152838. va_end(ap);
  152839. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  152840. }
  152841. /* Append a single character
  152842. */
  152843. static void jsonAppendChar(JsonString *p, char c){
  152844. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  152845. p->zBuf[p->nUsed++] = c;
  152846. }
  152847. /* Append a comma separator to the output buffer, if the previous
  152848. ** character is not '[' or '{'.
  152849. */
  152850. static void jsonAppendSeparator(JsonString *p){
  152851. char c;
  152852. if( p->nUsed==0 ) return;
  152853. c = p->zBuf[p->nUsed-1];
  152854. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  152855. }
  152856. /* Append the N-byte string in zIn to the end of the JsonString string
  152857. ** under construction. Enclose the string in "..." and escape
  152858. ** any double-quotes or backslash characters contained within the
  152859. ** string.
  152860. */
  152861. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  152862. u32 i;
  152863. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  152864. p->zBuf[p->nUsed++] = '"';
  152865. for(i=0; i<N; i++){
  152866. char c = zIn[i];
  152867. if( c=='"' || c=='\\' ){
  152868. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  152869. p->zBuf[p->nUsed++] = '\\';
  152870. }
  152871. p->zBuf[p->nUsed++] = c;
  152872. }
  152873. p->zBuf[p->nUsed++] = '"';
  152874. assert( p->nUsed<p->nAlloc );
  152875. }
  152876. /*
  152877. ** Append a function parameter value to the JSON string under
  152878. ** construction.
  152879. */
  152880. static void jsonAppendValue(
  152881. JsonString *p, /* Append to this JSON string */
  152882. sqlite3_value *pValue /* Value to append */
  152883. ){
  152884. switch( sqlite3_value_type(pValue) ){
  152885. case SQLITE_NULL: {
  152886. jsonAppendRaw(p, "null", 4);
  152887. break;
  152888. }
  152889. case SQLITE_INTEGER:
  152890. case SQLITE_FLOAT: {
  152891. const char *z = (const char*)sqlite3_value_text(pValue);
  152892. u32 n = (u32)sqlite3_value_bytes(pValue);
  152893. jsonAppendRaw(p, z, n);
  152894. break;
  152895. }
  152896. case SQLITE_TEXT: {
  152897. const char *z = (const char*)sqlite3_value_text(pValue);
  152898. u32 n = (u32)sqlite3_value_bytes(pValue);
  152899. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  152900. jsonAppendRaw(p, z, n);
  152901. }else{
  152902. jsonAppendString(p, z, n);
  152903. }
  152904. break;
  152905. }
  152906. default: {
  152907. if( p->bErr==0 ){
  152908. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  152909. p->bErr = 1;
  152910. jsonReset(p);
  152911. }
  152912. break;
  152913. }
  152914. }
  152915. }
  152916. /* Make the JSON in p the result of the SQL function.
  152917. */
  152918. static void jsonResult(JsonString *p){
  152919. if( p->bErr==0 ){
  152920. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  152921. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  152922. SQLITE_UTF8);
  152923. jsonZero(p);
  152924. }
  152925. assert( p->bStatic );
  152926. }
  152927. /**************************************************************************
  152928. ** Utility routines for dealing with JsonNode and JsonParse objects
  152929. **************************************************************************/
  152930. /*
  152931. ** Return the number of consecutive JsonNode slots need to represent
  152932. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  152933. ** OBJECT types, the number might be larger.
  152934. **
  152935. ** Appended elements are not counted. The value returned is the number
  152936. ** by which the JsonNode counter should increment in order to go to the
  152937. ** next peer value.
  152938. */
  152939. static u32 jsonNodeSize(JsonNode *pNode){
  152940. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  152941. }
  152942. /*
  152943. ** Reclaim all memory allocated by a JsonParse object. But do not
  152944. ** delete the JsonParse object itself.
  152945. */
  152946. static void jsonParseReset(JsonParse *pParse){
  152947. sqlite3_free(pParse->aNode);
  152948. pParse->aNode = 0;
  152949. pParse->nNode = 0;
  152950. pParse->nAlloc = 0;
  152951. sqlite3_free(pParse->aUp);
  152952. pParse->aUp = 0;
  152953. }
  152954. /*
  152955. ** Convert the JsonNode pNode into a pure JSON string and
  152956. ** append to pOut. Subsubstructure is also included. Return
  152957. ** the number of JsonNode objects that are encoded.
  152958. */
  152959. static void jsonRenderNode(
  152960. JsonNode *pNode, /* The node to render */
  152961. JsonString *pOut, /* Write JSON here */
  152962. sqlite3_value **aReplace /* Replacement values */
  152963. ){
  152964. switch( pNode->eType ){
  152965. default: {
  152966. assert( pNode->eType==JSON_NULL );
  152967. jsonAppendRaw(pOut, "null", 4);
  152968. break;
  152969. }
  152970. case JSON_TRUE: {
  152971. jsonAppendRaw(pOut, "true", 4);
  152972. break;
  152973. }
  152974. case JSON_FALSE: {
  152975. jsonAppendRaw(pOut, "false", 5);
  152976. break;
  152977. }
  152978. case JSON_STRING: {
  152979. if( pNode->jnFlags & JNODE_RAW ){
  152980. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  152981. break;
  152982. }
  152983. /* Fall through into the next case */
  152984. }
  152985. case JSON_REAL:
  152986. case JSON_INT: {
  152987. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  152988. break;
  152989. }
  152990. case JSON_ARRAY: {
  152991. u32 j = 1;
  152992. jsonAppendChar(pOut, '[');
  152993. for(;;){
  152994. while( j<=pNode->n ){
  152995. if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
  152996. if( pNode[j].jnFlags & JNODE_REPLACE ){
  152997. jsonAppendSeparator(pOut);
  152998. jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
  152999. }
  153000. }else{
  153001. jsonAppendSeparator(pOut);
  153002. jsonRenderNode(&pNode[j], pOut, aReplace);
  153003. }
  153004. j += jsonNodeSize(&pNode[j]);
  153005. }
  153006. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  153007. pNode = &pNode[pNode->u.iAppend];
  153008. j = 1;
  153009. }
  153010. jsonAppendChar(pOut, ']');
  153011. break;
  153012. }
  153013. case JSON_OBJECT: {
  153014. u32 j = 1;
  153015. jsonAppendChar(pOut, '{');
  153016. for(;;){
  153017. while( j<=pNode->n ){
  153018. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  153019. jsonAppendSeparator(pOut);
  153020. jsonRenderNode(&pNode[j], pOut, aReplace);
  153021. jsonAppendChar(pOut, ':');
  153022. if( pNode[j+1].jnFlags & JNODE_REPLACE ){
  153023. jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
  153024. }else{
  153025. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  153026. }
  153027. }
  153028. j += 1 + jsonNodeSize(&pNode[j+1]);
  153029. }
  153030. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  153031. pNode = &pNode[pNode->u.iAppend];
  153032. j = 1;
  153033. }
  153034. jsonAppendChar(pOut, '}');
  153035. break;
  153036. }
  153037. }
  153038. }
  153039. /*
  153040. ** Return a JsonNode and all its descendents as a JSON string.
  153041. */
  153042. static void jsonReturnJson(
  153043. JsonNode *pNode, /* Node to return */
  153044. sqlite3_context *pCtx, /* Return value for this function */
  153045. sqlite3_value **aReplace /* Array of replacement values */
  153046. ){
  153047. JsonString s;
  153048. jsonInit(&s, pCtx);
  153049. jsonRenderNode(pNode, &s, aReplace);
  153050. jsonResult(&s);
  153051. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  153052. }
  153053. /*
  153054. ** Make the JsonNode the return value of the function.
  153055. */
  153056. static void jsonReturn(
  153057. JsonNode *pNode, /* Node to return */
  153058. sqlite3_context *pCtx, /* Return value for this function */
  153059. sqlite3_value **aReplace /* Array of replacement values */
  153060. ){
  153061. switch( pNode->eType ){
  153062. default: {
  153063. assert( pNode->eType==JSON_NULL );
  153064. sqlite3_result_null(pCtx);
  153065. break;
  153066. }
  153067. case JSON_TRUE: {
  153068. sqlite3_result_int(pCtx, 1);
  153069. break;
  153070. }
  153071. case JSON_FALSE: {
  153072. sqlite3_result_int(pCtx, 0);
  153073. break;
  153074. }
  153075. case JSON_INT: {
  153076. sqlite3_int64 i = 0;
  153077. const char *z = pNode->u.zJContent;
  153078. if( z[0]=='-' ){ z++; }
  153079. while( z[0]>='0' && z[0]<='9' ){
  153080. unsigned v = *(z++) - '0';
  153081. if( i>=LARGEST_INT64/10 ){
  153082. if( i>LARGEST_INT64/10 ) goto int_as_real;
  153083. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  153084. if( v==9 ) goto int_as_real;
  153085. if( v==8 ){
  153086. if( pNode->u.zJContent[0]=='-' ){
  153087. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  153088. goto int_done;
  153089. }else{
  153090. goto int_as_real;
  153091. }
  153092. }
  153093. }
  153094. i = i*10 + v;
  153095. }
  153096. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  153097. sqlite3_result_int64(pCtx, i);
  153098. int_done:
  153099. break;
  153100. int_as_real: /* fall through to real */;
  153101. }
  153102. case JSON_REAL: {
  153103. double r;
  153104. #ifdef SQLITE_AMALGAMATION
  153105. const char *z = pNode->u.zJContent;
  153106. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  153107. #else
  153108. r = strtod(pNode->u.zJContent, 0);
  153109. #endif
  153110. sqlite3_result_double(pCtx, r);
  153111. break;
  153112. }
  153113. case JSON_STRING: {
  153114. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  153115. ** json_insert() and json_replace() and those routines do not
  153116. ** call jsonReturn() */
  153117. if( pNode->jnFlags & JNODE_RAW ){
  153118. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  153119. SQLITE_TRANSIENT);
  153120. }else
  153121. #endif
  153122. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  153123. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  153124. /* JSON formatted without any backslash-escapes */
  153125. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  153126. SQLITE_TRANSIENT);
  153127. }else{
  153128. /* Translate JSON formatted string into raw text */
  153129. u32 i;
  153130. u32 n = pNode->n;
  153131. const char *z = pNode->u.zJContent;
  153132. char *zOut;
  153133. u32 j;
  153134. zOut = sqlite3_malloc( n+1 );
  153135. if( zOut==0 ){
  153136. sqlite3_result_error_nomem(pCtx);
  153137. break;
  153138. }
  153139. for(i=1, j=0; i<n-1; i++){
  153140. char c = z[i];
  153141. if( c!='\\' ){
  153142. zOut[j++] = c;
  153143. }else{
  153144. c = z[++i];
  153145. if( c=='u' ){
  153146. u32 v = 0, k;
  153147. for(k=0; k<4 && i<n-2; i++, k++){
  153148. c = z[i+1];
  153149. if( c>='0' && c<='9' ) v = v*16 + c - '0';
  153150. else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
  153151. else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
  153152. else break;
  153153. }
  153154. if( v==0 ) break;
  153155. if( v<=0x7f ){
  153156. zOut[j++] = (char)v;
  153157. }else if( v<=0x7ff ){
  153158. zOut[j++] = (char)(0xc0 | (v>>6));
  153159. zOut[j++] = 0x80 | (v&0x3f);
  153160. }else{
  153161. zOut[j++] = (char)(0xe0 | (v>>12));
  153162. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  153163. zOut[j++] = 0x80 | (v&0x3f);
  153164. }
  153165. }else{
  153166. if( c=='b' ){
  153167. c = '\b';
  153168. }else if( c=='f' ){
  153169. c = '\f';
  153170. }else if( c=='n' ){
  153171. c = '\n';
  153172. }else if( c=='r' ){
  153173. c = '\r';
  153174. }else if( c=='t' ){
  153175. c = '\t';
  153176. }
  153177. zOut[j++] = c;
  153178. }
  153179. }
  153180. }
  153181. zOut[j] = 0;
  153182. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  153183. }
  153184. break;
  153185. }
  153186. case JSON_ARRAY:
  153187. case JSON_OBJECT: {
  153188. jsonReturnJson(pNode, pCtx, aReplace);
  153189. break;
  153190. }
  153191. }
  153192. }
  153193. /* Forward reference */
  153194. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  153195. /*
  153196. ** A macro to hint to the compiler that a function should not be
  153197. ** inlined.
  153198. */
  153199. #if defined(__GNUC__)
  153200. # define JSON_NOINLINE __attribute__((noinline))
  153201. #elif defined(_MSC_VER) && _MSC_VER>=1310
  153202. # define JSON_NOINLINE __declspec(noinline)
  153203. #else
  153204. # define JSON_NOINLINE
  153205. #endif
  153206. static JSON_NOINLINE int jsonParseAddNodeExpand(
  153207. JsonParse *pParse, /* Append the node to this object */
  153208. u32 eType, /* Node type */
  153209. u32 n, /* Content size or sub-node count */
  153210. const char *zContent /* Content */
  153211. ){
  153212. u32 nNew;
  153213. JsonNode *pNew;
  153214. assert( pParse->nNode>=pParse->nAlloc );
  153215. if( pParse->oom ) return -1;
  153216. nNew = pParse->nAlloc*2 + 10;
  153217. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  153218. if( pNew==0 ){
  153219. pParse->oom = 1;
  153220. return -1;
  153221. }
  153222. pParse->nAlloc = nNew;
  153223. pParse->aNode = pNew;
  153224. assert( pParse->nNode<pParse->nAlloc );
  153225. return jsonParseAddNode(pParse, eType, n, zContent);
  153226. }
  153227. /*
  153228. ** Create a new JsonNode instance based on the arguments and append that
  153229. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  153230. ** new node, or -1 if a memory allocation fails.
  153231. */
  153232. static int jsonParseAddNode(
  153233. JsonParse *pParse, /* Append the node to this object */
  153234. u32 eType, /* Node type */
  153235. u32 n, /* Content size or sub-node count */
  153236. const char *zContent /* Content */
  153237. ){
  153238. JsonNode *p;
  153239. if( pParse->nNode>=pParse->nAlloc ){
  153240. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  153241. }
  153242. p = &pParse->aNode[pParse->nNode];
  153243. p->eType = (u8)eType;
  153244. p->jnFlags = 0;
  153245. p->iVal = 0;
  153246. p->n = n;
  153247. p->u.zJContent = zContent;
  153248. return pParse->nNode++;
  153249. }
  153250. /*
  153251. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  153252. ** index of the first character past the end of the value parsed.
  153253. **
  153254. ** Return negative for a syntax error. Special cases: return -2 if the
  153255. ** first non-whitespace character is '}' and return -3 if the first
  153256. ** non-whitespace character is ']'.
  153257. */
  153258. static int jsonParseValue(JsonParse *pParse, u32 i){
  153259. char c;
  153260. u32 j;
  153261. int iThis;
  153262. int x;
  153263. JsonNode *pNode;
  153264. while( safe_isspace(pParse->zJson[i]) ){ i++; }
  153265. if( (c = pParse->zJson[i])=='{' ){
  153266. /* Parse object */
  153267. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  153268. if( iThis<0 ) return -1;
  153269. for(j=i+1;;j++){
  153270. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  153271. x = jsonParseValue(pParse, j);
  153272. if( x<0 ){
  153273. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  153274. return -1;
  153275. }
  153276. if( pParse->oom ) return -1;
  153277. pNode = &pParse->aNode[pParse->nNode-1];
  153278. if( pNode->eType!=JSON_STRING ) return -1;
  153279. pNode->jnFlags |= JNODE_LABEL;
  153280. j = x;
  153281. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  153282. if( pParse->zJson[j]!=':' ) return -1;
  153283. j++;
  153284. x = jsonParseValue(pParse, j);
  153285. if( x<0 ) return -1;
  153286. j = x;
  153287. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  153288. c = pParse->zJson[j];
  153289. if( c==',' ) continue;
  153290. if( c!='}' ) return -1;
  153291. break;
  153292. }
  153293. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  153294. return j+1;
  153295. }else if( c=='[' ){
  153296. /* Parse array */
  153297. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  153298. if( iThis<0 ) return -1;
  153299. for(j=i+1;;j++){
  153300. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  153301. x = jsonParseValue(pParse, j);
  153302. if( x<0 ){
  153303. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  153304. return -1;
  153305. }
  153306. j = x;
  153307. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  153308. c = pParse->zJson[j];
  153309. if( c==',' ) continue;
  153310. if( c!=']' ) return -1;
  153311. break;
  153312. }
  153313. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  153314. return j+1;
  153315. }else if( c=='"' ){
  153316. /* Parse string */
  153317. u8 jnFlags = 0;
  153318. j = i+1;
  153319. for(;;){
  153320. c = pParse->zJson[j];
  153321. if( c==0 ) return -1;
  153322. if( c=='\\' ){
  153323. c = pParse->zJson[++j];
  153324. if( c==0 ) return -1;
  153325. jnFlags = JNODE_ESCAPE;
  153326. }else if( c=='"' ){
  153327. break;
  153328. }
  153329. j++;
  153330. }
  153331. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
  153332. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  153333. return j+1;
  153334. }else if( c=='n'
  153335. && strncmp(pParse->zJson+i,"null",4)==0
  153336. && !safe_isalnum(pParse->zJson[i+4]) ){
  153337. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  153338. return i+4;
  153339. }else if( c=='t'
  153340. && strncmp(pParse->zJson+i,"true",4)==0
  153341. && !safe_isalnum(pParse->zJson[i+4]) ){
  153342. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  153343. return i+4;
  153344. }else if( c=='f'
  153345. && strncmp(pParse->zJson+i,"false",5)==0
  153346. && !safe_isalnum(pParse->zJson[i+5]) ){
  153347. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  153348. return i+5;
  153349. }else if( c=='-' || (c>='0' && c<='9') ){
  153350. /* Parse number */
  153351. u8 seenDP = 0;
  153352. u8 seenE = 0;
  153353. j = i+1;
  153354. for(;; j++){
  153355. c = pParse->zJson[j];
  153356. if( c>='0' && c<='9' ) continue;
  153357. if( c=='.' ){
  153358. if( pParse->zJson[j-1]=='-' ) return -1;
  153359. if( seenDP ) return -1;
  153360. seenDP = 1;
  153361. continue;
  153362. }
  153363. if( c=='e' || c=='E' ){
  153364. if( pParse->zJson[j-1]<'0' ) return -1;
  153365. if( seenE ) return -1;
  153366. seenDP = seenE = 1;
  153367. c = pParse->zJson[j+1];
  153368. if( c=='+' || c=='-' ){
  153369. j++;
  153370. c = pParse->zJson[j+1];
  153371. }
  153372. if( c<'0' || c>'9' ) return -1;
  153373. continue;
  153374. }
  153375. break;
  153376. }
  153377. if( pParse->zJson[j-1]<'0' ) return -1;
  153378. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  153379. j - i, &pParse->zJson[i]);
  153380. return j;
  153381. }else if( c=='}' ){
  153382. return -2; /* End of {...} */
  153383. }else if( c==']' ){
  153384. return -3; /* End of [...] */
  153385. }else if( c==0 ){
  153386. return 0; /* End of file */
  153387. }else{
  153388. return -1; /* Syntax error */
  153389. }
  153390. }
  153391. /*
  153392. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  153393. ** are any errors. If an error occurs, free all memory associated with
  153394. ** pParse.
  153395. **
  153396. ** pParse is uninitialized when this routine is called.
  153397. */
  153398. static int jsonParse(
  153399. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  153400. sqlite3_context *pCtx, /* Report errors here */
  153401. const char *zJson /* Input JSON text to be parsed */
  153402. ){
  153403. int i;
  153404. memset(pParse, 0, sizeof(*pParse));
  153405. if( zJson==0 ) return 1;
  153406. pParse->zJson = zJson;
  153407. i = jsonParseValue(pParse, 0);
  153408. if( pParse->oom ) i = -1;
  153409. if( i>0 ){
  153410. while( safe_isspace(zJson[i]) ) i++;
  153411. if( zJson[i] ) i = -1;
  153412. }
  153413. if( i<=0 ){
  153414. if( pCtx!=0 ){
  153415. if( pParse->oom ){
  153416. sqlite3_result_error_nomem(pCtx);
  153417. }else{
  153418. sqlite3_result_error(pCtx, "malformed JSON", -1);
  153419. }
  153420. }
  153421. jsonParseReset(pParse);
  153422. return 1;
  153423. }
  153424. return 0;
  153425. }
  153426. /* Mark node i of pParse as being a child of iParent. Call recursively
  153427. ** to fill in all the descendants of node i.
  153428. */
  153429. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  153430. JsonNode *pNode = &pParse->aNode[i];
  153431. u32 j;
  153432. pParse->aUp[i] = iParent;
  153433. switch( pNode->eType ){
  153434. case JSON_ARRAY: {
  153435. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  153436. jsonParseFillInParentage(pParse, i+j, i);
  153437. }
  153438. break;
  153439. }
  153440. case JSON_OBJECT: {
  153441. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  153442. pParse->aUp[i+j] = i;
  153443. jsonParseFillInParentage(pParse, i+j+1, i);
  153444. }
  153445. break;
  153446. }
  153447. default: {
  153448. break;
  153449. }
  153450. }
  153451. }
  153452. /*
  153453. ** Compute the parentage of all nodes in a completed parse.
  153454. */
  153455. static int jsonParseFindParents(JsonParse *pParse){
  153456. u32 *aUp;
  153457. assert( pParse->aUp==0 );
  153458. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  153459. if( aUp==0 ){
  153460. pParse->oom = 1;
  153461. return SQLITE_NOMEM;
  153462. }
  153463. jsonParseFillInParentage(pParse, 0, 0);
  153464. return SQLITE_OK;
  153465. }
  153466. /*
  153467. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  153468. ** a match.
  153469. */
  153470. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  153471. if( pNode->jnFlags & JNODE_RAW ){
  153472. if( pNode->n!=nKey ) return 0;
  153473. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  153474. }else{
  153475. if( pNode->n!=nKey+2 ) return 0;
  153476. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  153477. }
  153478. }
  153479. /* forward declaration */
  153480. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  153481. /*
  153482. ** Search along zPath to find the node specified. Return a pointer
  153483. ** to that node, or NULL if zPath is malformed or if there is no such
  153484. ** node.
  153485. **
  153486. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  153487. ** possible to do so and if no existing node corresponds to zPath. If
  153488. ** new nodes are appended *pApnd is set to 1.
  153489. */
  153490. static JsonNode *jsonLookupStep(
  153491. JsonParse *pParse, /* The JSON to search */
  153492. u32 iRoot, /* Begin the search at this node */
  153493. const char *zPath, /* The path to search */
  153494. int *pApnd, /* Append nodes to complete path if not NULL */
  153495. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  153496. ){
  153497. u32 i, j, nKey;
  153498. const char *zKey;
  153499. JsonNode *pRoot = &pParse->aNode[iRoot];
  153500. if( zPath[0]==0 ) return pRoot;
  153501. if( zPath[0]=='.' ){
  153502. if( pRoot->eType!=JSON_OBJECT ) return 0;
  153503. zPath++;
  153504. if( zPath[0]=='"' ){
  153505. zKey = zPath + 1;
  153506. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  153507. nKey = i-1;
  153508. if( zPath[i] ){
  153509. i++;
  153510. }else{
  153511. *pzErr = zPath;
  153512. return 0;
  153513. }
  153514. }else{
  153515. zKey = zPath;
  153516. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  153517. nKey = i;
  153518. }
  153519. if( nKey==0 ){
  153520. *pzErr = zPath;
  153521. return 0;
  153522. }
  153523. j = 1;
  153524. for(;;){
  153525. while( j<=pRoot->n ){
  153526. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  153527. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  153528. }
  153529. j++;
  153530. j += jsonNodeSize(&pRoot[j]);
  153531. }
  153532. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  153533. iRoot += pRoot->u.iAppend;
  153534. pRoot = &pParse->aNode[iRoot];
  153535. j = 1;
  153536. }
  153537. if( pApnd ){
  153538. u32 iStart, iLabel;
  153539. JsonNode *pNode;
  153540. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  153541. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  153542. zPath += i;
  153543. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  153544. if( pParse->oom ) return 0;
  153545. if( pNode ){
  153546. pRoot = &pParse->aNode[iRoot];
  153547. pRoot->u.iAppend = iStart - iRoot;
  153548. pRoot->jnFlags |= JNODE_APPEND;
  153549. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  153550. }
  153551. return pNode;
  153552. }
  153553. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  153554. if( pRoot->eType!=JSON_ARRAY ) return 0;
  153555. i = 0;
  153556. j = 1;
  153557. while( safe_isdigit(zPath[j]) ){
  153558. i = i*10 + zPath[j] - '0';
  153559. j++;
  153560. }
  153561. if( zPath[j]!=']' ){
  153562. *pzErr = zPath;
  153563. return 0;
  153564. }
  153565. zPath += j + 1;
  153566. j = 1;
  153567. for(;;){
  153568. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  153569. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  153570. j += jsonNodeSize(&pRoot[j]);
  153571. }
  153572. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  153573. iRoot += pRoot->u.iAppend;
  153574. pRoot = &pParse->aNode[iRoot];
  153575. j = 1;
  153576. }
  153577. if( j<=pRoot->n ){
  153578. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  153579. }
  153580. if( i==0 && pApnd ){
  153581. u32 iStart;
  153582. JsonNode *pNode;
  153583. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  153584. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  153585. if( pParse->oom ) return 0;
  153586. if( pNode ){
  153587. pRoot = &pParse->aNode[iRoot];
  153588. pRoot->u.iAppend = iStart - iRoot;
  153589. pRoot->jnFlags |= JNODE_APPEND;
  153590. }
  153591. return pNode;
  153592. }
  153593. }else{
  153594. *pzErr = zPath;
  153595. }
  153596. return 0;
  153597. }
  153598. /*
  153599. ** Append content to pParse that will complete zPath. Return a pointer
  153600. ** to the inserted node, or return NULL if the append fails.
  153601. */
  153602. static JsonNode *jsonLookupAppend(
  153603. JsonParse *pParse, /* Append content to the JSON parse */
  153604. const char *zPath, /* Description of content to append */
  153605. int *pApnd, /* Set this flag to 1 */
  153606. const char **pzErr /* Make this point to any syntax error */
  153607. ){
  153608. *pApnd = 1;
  153609. if( zPath[0]==0 ){
  153610. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  153611. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  153612. }
  153613. if( zPath[0]=='.' ){
  153614. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  153615. }else if( strncmp(zPath,"[0]",3)==0 ){
  153616. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  153617. }else{
  153618. return 0;
  153619. }
  153620. if( pParse->oom ) return 0;
  153621. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  153622. }
  153623. /*
  153624. ** Return the text of a syntax error message on a JSON path. Space is
  153625. ** obtained from sqlite3_malloc().
  153626. */
  153627. static char *jsonPathSyntaxError(const char *zErr){
  153628. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  153629. }
  153630. /*
  153631. ** Do a node lookup using zPath. Return a pointer to the node on success.
  153632. ** Return NULL if not found or if there is an error.
  153633. **
  153634. ** On an error, write an error message into pCtx and increment the
  153635. ** pParse->nErr counter.
  153636. **
  153637. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  153638. ** nodes are appended.
  153639. */
  153640. static JsonNode *jsonLookup(
  153641. JsonParse *pParse, /* The JSON to search */
  153642. const char *zPath, /* The path to search */
  153643. int *pApnd, /* Append nodes to complete path if not NULL */
  153644. sqlite3_context *pCtx /* Report errors here, if not NULL */
  153645. ){
  153646. const char *zErr = 0;
  153647. JsonNode *pNode = 0;
  153648. char *zMsg;
  153649. if( zPath==0 ) return 0;
  153650. if( zPath[0]!='$' ){
  153651. zErr = zPath;
  153652. goto lookup_err;
  153653. }
  153654. zPath++;
  153655. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  153656. if( zErr==0 ) return pNode;
  153657. lookup_err:
  153658. pParse->nErr++;
  153659. assert( zErr!=0 && pCtx!=0 );
  153660. zMsg = jsonPathSyntaxError(zErr);
  153661. if( zMsg ){
  153662. sqlite3_result_error(pCtx, zMsg, -1);
  153663. sqlite3_free(zMsg);
  153664. }else{
  153665. sqlite3_result_error_nomem(pCtx);
  153666. }
  153667. return 0;
  153668. }
  153669. /*
  153670. ** Report the wrong number of arguments for json_insert(), json_replace()
  153671. ** or json_set().
  153672. */
  153673. static void jsonWrongNumArgs(
  153674. sqlite3_context *pCtx,
  153675. const char *zFuncName
  153676. ){
  153677. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  153678. zFuncName);
  153679. sqlite3_result_error(pCtx, zMsg, -1);
  153680. sqlite3_free(zMsg);
  153681. }
  153682. /****************************************************************************
  153683. ** SQL functions used for testing and debugging
  153684. ****************************************************************************/
  153685. #ifdef SQLITE_DEBUG
  153686. /*
  153687. ** The json_parse(JSON) function returns a string which describes
  153688. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  153689. ** well-formed.
  153690. */
  153691. static void jsonParseFunc(
  153692. sqlite3_context *ctx,
  153693. int argc,
  153694. sqlite3_value **argv
  153695. ){
  153696. JsonString s; /* Output string - not real JSON */
  153697. JsonParse x; /* The parse */
  153698. u32 i;
  153699. assert( argc==1 );
  153700. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153701. jsonParseFindParents(&x);
  153702. jsonInit(&s, ctx);
  153703. for(i=0; i<x.nNode; i++){
  153704. const char *zType;
  153705. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  153706. assert( x.aNode[i].eType==JSON_STRING );
  153707. zType = "label";
  153708. }else{
  153709. zType = jsonType[x.aNode[i].eType];
  153710. }
  153711. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  153712. i, zType, x.aNode[i].n, x.aUp[i]);
  153713. if( x.aNode[i].u.zJContent!=0 ){
  153714. jsonAppendRaw(&s, " ", 1);
  153715. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  153716. }
  153717. jsonAppendRaw(&s, "\n", 1);
  153718. }
  153719. jsonParseReset(&x);
  153720. jsonResult(&s);
  153721. }
  153722. /*
  153723. ** The json_test1(JSON) function return true (1) if the input is JSON
  153724. ** text generated by another json function. It returns (0) if the input
  153725. ** is not known to be JSON.
  153726. */
  153727. static void jsonTest1Func(
  153728. sqlite3_context *ctx,
  153729. int argc,
  153730. sqlite3_value **argv
  153731. ){
  153732. UNUSED_PARAM(argc);
  153733. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  153734. }
  153735. #endif /* SQLITE_DEBUG */
  153736. /****************************************************************************
  153737. ** SQL function implementations
  153738. ****************************************************************************/
  153739. /*
  153740. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  153741. ** array that contains all values given in arguments. Or if any argument
  153742. ** is a BLOB, throw an error.
  153743. */
  153744. static void jsonArrayFunc(
  153745. sqlite3_context *ctx,
  153746. int argc,
  153747. sqlite3_value **argv
  153748. ){
  153749. int i;
  153750. JsonString jx;
  153751. jsonInit(&jx, ctx);
  153752. jsonAppendChar(&jx, '[');
  153753. for(i=0; i<argc; i++){
  153754. jsonAppendSeparator(&jx);
  153755. jsonAppendValue(&jx, argv[i]);
  153756. }
  153757. jsonAppendChar(&jx, ']');
  153758. jsonResult(&jx);
  153759. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  153760. }
  153761. /*
  153762. ** json_array_length(JSON)
  153763. ** json_array_length(JSON, PATH)
  153764. **
  153765. ** Return the number of elements in the top-level JSON array.
  153766. ** Return 0 if the input is not a well-formed JSON array.
  153767. */
  153768. static void jsonArrayLengthFunc(
  153769. sqlite3_context *ctx,
  153770. int argc,
  153771. sqlite3_value **argv
  153772. ){
  153773. JsonParse x; /* The parse */
  153774. sqlite3_int64 n = 0;
  153775. u32 i;
  153776. JsonNode *pNode;
  153777. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153778. assert( x.nNode );
  153779. if( argc==2 ){
  153780. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  153781. pNode = jsonLookup(&x, zPath, 0, ctx);
  153782. }else{
  153783. pNode = x.aNode;
  153784. }
  153785. if( pNode==0 ){
  153786. x.nErr = 1;
  153787. }else if( pNode->eType==JSON_ARRAY ){
  153788. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  153789. for(i=1; i<=pNode->n; n++){
  153790. i += jsonNodeSize(&pNode[i]);
  153791. }
  153792. }
  153793. if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
  153794. jsonParseReset(&x);
  153795. }
  153796. /*
  153797. ** json_extract(JSON, PATH, ...)
  153798. **
  153799. ** Return the element described by PATH. Return NULL if there is no
  153800. ** PATH element. If there are multiple PATHs, then return a JSON array
  153801. ** with the result from each path. Throw an error if the JSON or any PATH
  153802. ** is malformed.
  153803. */
  153804. static void jsonExtractFunc(
  153805. sqlite3_context *ctx,
  153806. int argc,
  153807. sqlite3_value **argv
  153808. ){
  153809. JsonParse x; /* The parse */
  153810. JsonNode *pNode;
  153811. const char *zPath;
  153812. JsonString jx;
  153813. int i;
  153814. if( argc<2 ) return;
  153815. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153816. jsonInit(&jx, ctx);
  153817. jsonAppendChar(&jx, '[');
  153818. for(i=1; i<argc; i++){
  153819. zPath = (const char*)sqlite3_value_text(argv[i]);
  153820. pNode = jsonLookup(&x, zPath, 0, ctx);
  153821. if( x.nErr ) break;
  153822. if( argc>2 ){
  153823. jsonAppendSeparator(&jx);
  153824. if( pNode ){
  153825. jsonRenderNode(pNode, &jx, 0);
  153826. }else{
  153827. jsonAppendRaw(&jx, "null", 4);
  153828. }
  153829. }else if( pNode ){
  153830. jsonReturn(pNode, ctx, 0);
  153831. }
  153832. }
  153833. if( argc>2 && i==argc ){
  153834. jsonAppendChar(&jx, ']');
  153835. jsonResult(&jx);
  153836. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  153837. }
  153838. jsonReset(&jx);
  153839. jsonParseReset(&x);
  153840. }
  153841. /*
  153842. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  153843. ** object that contains all name/value given in arguments. Or if any name
  153844. ** is not a string or if any value is a BLOB, throw an error.
  153845. */
  153846. static void jsonObjectFunc(
  153847. sqlite3_context *ctx,
  153848. int argc,
  153849. sqlite3_value **argv
  153850. ){
  153851. int i;
  153852. JsonString jx;
  153853. const char *z;
  153854. u32 n;
  153855. if( argc&1 ){
  153856. sqlite3_result_error(ctx, "json_object() requires an even number "
  153857. "of arguments", -1);
  153858. return;
  153859. }
  153860. jsonInit(&jx, ctx);
  153861. jsonAppendChar(&jx, '{');
  153862. for(i=0; i<argc; i+=2){
  153863. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  153864. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  153865. jsonReset(&jx);
  153866. return;
  153867. }
  153868. jsonAppendSeparator(&jx);
  153869. z = (const char*)sqlite3_value_text(argv[i]);
  153870. n = (u32)sqlite3_value_bytes(argv[i]);
  153871. jsonAppendString(&jx, z, n);
  153872. jsonAppendChar(&jx, ':');
  153873. jsonAppendValue(&jx, argv[i+1]);
  153874. }
  153875. jsonAppendChar(&jx, '}');
  153876. jsonResult(&jx);
  153877. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  153878. }
  153879. /*
  153880. ** json_remove(JSON, PATH, ...)
  153881. **
  153882. ** Remove the named elements from JSON and return the result. malformed
  153883. ** JSON or PATH arguments result in an error.
  153884. */
  153885. static void jsonRemoveFunc(
  153886. sqlite3_context *ctx,
  153887. int argc,
  153888. sqlite3_value **argv
  153889. ){
  153890. JsonParse x; /* The parse */
  153891. JsonNode *pNode;
  153892. const char *zPath;
  153893. u32 i;
  153894. if( argc<1 ) return;
  153895. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153896. assert( x.nNode );
  153897. for(i=1; i<(u32)argc; i++){
  153898. zPath = (const char*)sqlite3_value_text(argv[i]);
  153899. if( zPath==0 ) goto remove_done;
  153900. pNode = jsonLookup(&x, zPath, 0, ctx);
  153901. if( x.nErr ) goto remove_done;
  153902. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  153903. }
  153904. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  153905. jsonReturnJson(x.aNode, ctx, 0);
  153906. }
  153907. remove_done:
  153908. jsonParseReset(&x);
  153909. }
  153910. /*
  153911. ** json_replace(JSON, PATH, VALUE, ...)
  153912. **
  153913. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  153914. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  153915. */
  153916. static void jsonReplaceFunc(
  153917. sqlite3_context *ctx,
  153918. int argc,
  153919. sqlite3_value **argv
  153920. ){
  153921. JsonParse x; /* The parse */
  153922. JsonNode *pNode;
  153923. const char *zPath;
  153924. u32 i;
  153925. if( argc<1 ) return;
  153926. if( (argc&1)==0 ) {
  153927. jsonWrongNumArgs(ctx, "replace");
  153928. return;
  153929. }
  153930. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153931. assert( x.nNode );
  153932. for(i=1; i<(u32)argc; i+=2){
  153933. zPath = (const char*)sqlite3_value_text(argv[i]);
  153934. pNode = jsonLookup(&x, zPath, 0, ctx);
  153935. if( x.nErr ) goto replace_err;
  153936. if( pNode ){
  153937. pNode->jnFlags |= (u8)JNODE_REPLACE;
  153938. pNode->iVal = (u8)(i+1);
  153939. }
  153940. }
  153941. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  153942. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  153943. }else{
  153944. jsonReturnJson(x.aNode, ctx, argv);
  153945. }
  153946. replace_err:
  153947. jsonParseReset(&x);
  153948. }
  153949. /*
  153950. ** json_set(JSON, PATH, VALUE, ...)
  153951. **
  153952. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  153953. ** exist. Overwrite existing values that do exist.
  153954. ** If JSON or PATH is malformed, throw an error.
  153955. **
  153956. ** json_insert(JSON, PATH, VALUE, ...)
  153957. **
  153958. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  153959. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  153960. */
  153961. static void jsonSetFunc(
  153962. sqlite3_context *ctx,
  153963. int argc,
  153964. sqlite3_value **argv
  153965. ){
  153966. JsonParse x; /* The parse */
  153967. JsonNode *pNode;
  153968. const char *zPath;
  153969. u32 i;
  153970. int bApnd;
  153971. int bIsSet = *(int*)sqlite3_user_data(ctx);
  153972. if( argc<1 ) return;
  153973. if( (argc&1)==0 ) {
  153974. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  153975. return;
  153976. }
  153977. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  153978. assert( x.nNode );
  153979. for(i=1; i<(u32)argc; i+=2){
  153980. zPath = (const char*)sqlite3_value_text(argv[i]);
  153981. bApnd = 0;
  153982. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  153983. if( x.oom ){
  153984. sqlite3_result_error_nomem(ctx);
  153985. goto jsonSetDone;
  153986. }else if( x.nErr ){
  153987. goto jsonSetDone;
  153988. }else if( pNode && (bApnd || bIsSet) ){
  153989. pNode->jnFlags |= (u8)JNODE_REPLACE;
  153990. pNode->iVal = (u8)(i+1);
  153991. }
  153992. }
  153993. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  153994. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  153995. }else{
  153996. jsonReturnJson(x.aNode, ctx, argv);
  153997. }
  153998. jsonSetDone:
  153999. jsonParseReset(&x);
  154000. }
  154001. /*
  154002. ** json_type(JSON)
  154003. ** json_type(JSON, PATH)
  154004. **
  154005. ** Return the top-level "type" of a JSON string. Throw an error if
  154006. ** either the JSON or PATH inputs are not well-formed.
  154007. */
  154008. static void jsonTypeFunc(
  154009. sqlite3_context *ctx,
  154010. int argc,
  154011. sqlite3_value **argv
  154012. ){
  154013. JsonParse x; /* The parse */
  154014. const char *zPath;
  154015. JsonNode *pNode;
  154016. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  154017. assert( x.nNode );
  154018. if( argc==2 ){
  154019. zPath = (const char*)sqlite3_value_text(argv[1]);
  154020. pNode = jsonLookup(&x, zPath, 0, ctx);
  154021. }else{
  154022. pNode = x.aNode;
  154023. }
  154024. if( pNode ){
  154025. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  154026. }
  154027. jsonParseReset(&x);
  154028. }
  154029. /*
  154030. ** json_valid(JSON)
  154031. **
  154032. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  154033. ** Return 0 otherwise.
  154034. */
  154035. static void jsonValidFunc(
  154036. sqlite3_context *ctx,
  154037. int argc,
  154038. sqlite3_value **argv
  154039. ){
  154040. JsonParse x; /* The parse */
  154041. int rc = 0;
  154042. UNUSED_PARAM(argc);
  154043. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  154044. rc = 1;
  154045. }
  154046. jsonParseReset(&x);
  154047. sqlite3_result_int(ctx, rc);
  154048. }
  154049. #ifndef SQLITE_OMIT_VIRTUALTABLE
  154050. /****************************************************************************
  154051. ** The json_each virtual table
  154052. ****************************************************************************/
  154053. typedef struct JsonEachCursor JsonEachCursor;
  154054. struct JsonEachCursor {
  154055. sqlite3_vtab_cursor base; /* Base class - must be first */
  154056. u32 iRowid; /* The rowid */
  154057. u32 iBegin; /* The first node of the scan */
  154058. u32 i; /* Index in sParse.aNode[] of current row */
  154059. u32 iEnd; /* EOF when i equals or exceeds this value */
  154060. u8 eType; /* Type of top-level element */
  154061. u8 bRecursive; /* True for json_tree(). False for json_each() */
  154062. char *zJson; /* Input JSON */
  154063. char *zRoot; /* Path by which to filter zJson */
  154064. JsonParse sParse; /* Parse of the input JSON */
  154065. };
  154066. /* Constructor for the json_each virtual table */
  154067. static int jsonEachConnect(
  154068. sqlite3 *db,
  154069. void *pAux,
  154070. int argc, const char *const*argv,
  154071. sqlite3_vtab **ppVtab,
  154072. char **pzErr
  154073. ){
  154074. sqlite3_vtab *pNew;
  154075. int rc;
  154076. /* Column numbers */
  154077. #define JEACH_KEY 0
  154078. #define JEACH_VALUE 1
  154079. #define JEACH_TYPE 2
  154080. #define JEACH_ATOM 3
  154081. #define JEACH_ID 4
  154082. #define JEACH_PARENT 5
  154083. #define JEACH_FULLKEY 6
  154084. #define JEACH_PATH 7
  154085. #define JEACH_JSON 8
  154086. #define JEACH_ROOT 9
  154087. UNUSED_PARAM(pzErr);
  154088. UNUSED_PARAM(argv);
  154089. UNUSED_PARAM(argc);
  154090. UNUSED_PARAM(pAux);
  154091. rc = sqlite3_declare_vtab(db,
  154092. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  154093. "json HIDDEN,root HIDDEN)");
  154094. if( rc==SQLITE_OK ){
  154095. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  154096. if( pNew==0 ) return SQLITE_NOMEM;
  154097. memset(pNew, 0, sizeof(*pNew));
  154098. }
  154099. return rc;
  154100. }
  154101. /* destructor for json_each virtual table */
  154102. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  154103. sqlite3_free(pVtab);
  154104. return SQLITE_OK;
  154105. }
  154106. /* constructor for a JsonEachCursor object for json_each(). */
  154107. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  154108. JsonEachCursor *pCur;
  154109. UNUSED_PARAM(p);
  154110. pCur = sqlite3_malloc( sizeof(*pCur) );
  154111. if( pCur==0 ) return SQLITE_NOMEM;
  154112. memset(pCur, 0, sizeof(*pCur));
  154113. *ppCursor = &pCur->base;
  154114. return SQLITE_OK;
  154115. }
  154116. /* constructor for a JsonEachCursor object for json_tree(). */
  154117. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  154118. int rc = jsonEachOpenEach(p, ppCursor);
  154119. if( rc==SQLITE_OK ){
  154120. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  154121. pCur->bRecursive = 1;
  154122. }
  154123. return rc;
  154124. }
  154125. /* Reset a JsonEachCursor back to its original state. Free any memory
  154126. ** held. */
  154127. static void jsonEachCursorReset(JsonEachCursor *p){
  154128. sqlite3_free(p->zJson);
  154129. sqlite3_free(p->zRoot);
  154130. jsonParseReset(&p->sParse);
  154131. p->iRowid = 0;
  154132. p->i = 0;
  154133. p->iEnd = 0;
  154134. p->eType = 0;
  154135. p->zJson = 0;
  154136. p->zRoot = 0;
  154137. }
  154138. /* Destructor for a jsonEachCursor object */
  154139. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  154140. JsonEachCursor *p = (JsonEachCursor*)cur;
  154141. jsonEachCursorReset(p);
  154142. sqlite3_free(cur);
  154143. return SQLITE_OK;
  154144. }
  154145. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  154146. ** of the JSON object */
  154147. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  154148. JsonEachCursor *p = (JsonEachCursor*)cur;
  154149. return p->i >= p->iEnd;
  154150. }
  154151. /* Advance the cursor to the next element for json_tree() */
  154152. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  154153. JsonEachCursor *p = (JsonEachCursor*)cur;
  154154. if( p->bRecursive ){
  154155. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  154156. p->i++;
  154157. p->iRowid++;
  154158. if( p->i<p->iEnd ){
  154159. u32 iUp = p->sParse.aUp[p->i];
  154160. JsonNode *pUp = &p->sParse.aNode[iUp];
  154161. p->eType = pUp->eType;
  154162. if( pUp->eType==JSON_ARRAY ){
  154163. if( iUp==p->i-1 ){
  154164. pUp->u.iKey = 0;
  154165. }else{
  154166. pUp->u.iKey++;
  154167. }
  154168. }
  154169. }
  154170. }else{
  154171. switch( p->eType ){
  154172. case JSON_ARRAY: {
  154173. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  154174. p->iRowid++;
  154175. break;
  154176. }
  154177. case JSON_OBJECT: {
  154178. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  154179. p->iRowid++;
  154180. break;
  154181. }
  154182. default: {
  154183. p->i = p->iEnd;
  154184. break;
  154185. }
  154186. }
  154187. }
  154188. return SQLITE_OK;
  154189. }
  154190. /* Append the name of the path for element i to pStr
  154191. */
  154192. static void jsonEachComputePath(
  154193. JsonEachCursor *p, /* The cursor */
  154194. JsonString *pStr, /* Write the path here */
  154195. u32 i /* Path to this element */
  154196. ){
  154197. JsonNode *pNode, *pUp;
  154198. u32 iUp;
  154199. if( i==0 ){
  154200. jsonAppendChar(pStr, '$');
  154201. return;
  154202. }
  154203. iUp = p->sParse.aUp[i];
  154204. jsonEachComputePath(p, pStr, iUp);
  154205. pNode = &p->sParse.aNode[i];
  154206. pUp = &p->sParse.aNode[iUp];
  154207. if( pUp->eType==JSON_ARRAY ){
  154208. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  154209. }else{
  154210. assert( pUp->eType==JSON_OBJECT );
  154211. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  154212. assert( pNode->eType==JSON_STRING );
  154213. assert( pNode->jnFlags & JNODE_LABEL );
  154214. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  154215. }
  154216. }
  154217. /* Return the value of a column */
  154218. static int jsonEachColumn(
  154219. sqlite3_vtab_cursor *cur, /* The cursor */
  154220. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  154221. int i /* Which column to return */
  154222. ){
  154223. JsonEachCursor *p = (JsonEachCursor*)cur;
  154224. JsonNode *pThis = &p->sParse.aNode[p->i];
  154225. switch( i ){
  154226. case JEACH_KEY: {
  154227. if( p->i==0 ) break;
  154228. if( p->eType==JSON_OBJECT ){
  154229. jsonReturn(pThis, ctx, 0);
  154230. }else if( p->eType==JSON_ARRAY ){
  154231. u32 iKey;
  154232. if( p->bRecursive ){
  154233. if( p->iRowid==0 ) break;
  154234. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  154235. }else{
  154236. iKey = p->iRowid;
  154237. }
  154238. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  154239. }
  154240. break;
  154241. }
  154242. case JEACH_VALUE: {
  154243. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  154244. jsonReturn(pThis, ctx, 0);
  154245. break;
  154246. }
  154247. case JEACH_TYPE: {
  154248. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  154249. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  154250. break;
  154251. }
  154252. case JEACH_ATOM: {
  154253. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  154254. if( pThis->eType>=JSON_ARRAY ) break;
  154255. jsonReturn(pThis, ctx, 0);
  154256. break;
  154257. }
  154258. case JEACH_ID: {
  154259. sqlite3_result_int64(ctx,
  154260. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  154261. break;
  154262. }
  154263. case JEACH_PARENT: {
  154264. if( p->i>p->iBegin && p->bRecursive ){
  154265. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  154266. }
  154267. break;
  154268. }
  154269. case JEACH_FULLKEY: {
  154270. JsonString x;
  154271. jsonInit(&x, ctx);
  154272. if( p->bRecursive ){
  154273. jsonEachComputePath(p, &x, p->i);
  154274. }else{
  154275. if( p->zRoot ){
  154276. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  154277. }else{
  154278. jsonAppendChar(&x, '$');
  154279. }
  154280. if( p->eType==JSON_ARRAY ){
  154281. jsonPrintf(30, &x, "[%d]", p->iRowid);
  154282. }else{
  154283. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  154284. }
  154285. }
  154286. jsonResult(&x);
  154287. break;
  154288. }
  154289. case JEACH_PATH: {
  154290. if( p->bRecursive ){
  154291. JsonString x;
  154292. jsonInit(&x, ctx);
  154293. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  154294. jsonResult(&x);
  154295. break;
  154296. }
  154297. /* For json_each() path and root are the same so fall through
  154298. ** into the root case */
  154299. }
  154300. case JEACH_ROOT: {
  154301. const char *zRoot = p->zRoot;
  154302. if( zRoot==0 ) zRoot = "$";
  154303. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  154304. break;
  154305. }
  154306. case JEACH_JSON: {
  154307. assert( i==JEACH_JSON );
  154308. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  154309. break;
  154310. }
  154311. }
  154312. return SQLITE_OK;
  154313. }
  154314. /* Return the current rowid value */
  154315. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  154316. JsonEachCursor *p = (JsonEachCursor*)cur;
  154317. *pRowid = p->iRowid;
  154318. return SQLITE_OK;
  154319. }
  154320. /* The query strategy is to look for an equality constraint on the json
  154321. ** column. Without such a constraint, the table cannot operate. idxNum is
  154322. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  154323. ** and 0 otherwise.
  154324. */
  154325. static int jsonEachBestIndex(
  154326. sqlite3_vtab *tab,
  154327. sqlite3_index_info *pIdxInfo
  154328. ){
  154329. int i;
  154330. int jsonIdx = -1;
  154331. int rootIdx = -1;
  154332. const struct sqlite3_index_constraint *pConstraint;
  154333. UNUSED_PARAM(tab);
  154334. pConstraint = pIdxInfo->aConstraint;
  154335. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  154336. if( pConstraint->usable==0 ) continue;
  154337. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  154338. switch( pConstraint->iColumn ){
  154339. case JEACH_JSON: jsonIdx = i; break;
  154340. case JEACH_ROOT: rootIdx = i; break;
  154341. default: /* no-op */ break;
  154342. }
  154343. }
  154344. if( jsonIdx<0 ){
  154345. pIdxInfo->idxNum = 0;
  154346. pIdxInfo->estimatedCost = 1e99;
  154347. }else{
  154348. pIdxInfo->estimatedCost = 1.0;
  154349. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  154350. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  154351. if( rootIdx<0 ){
  154352. pIdxInfo->idxNum = 1;
  154353. }else{
  154354. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  154355. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  154356. pIdxInfo->idxNum = 3;
  154357. }
  154358. }
  154359. return SQLITE_OK;
  154360. }
  154361. /* Start a search on a new JSON string */
  154362. static int jsonEachFilter(
  154363. sqlite3_vtab_cursor *cur,
  154364. int idxNum, const char *idxStr,
  154365. int argc, sqlite3_value **argv
  154366. ){
  154367. JsonEachCursor *p = (JsonEachCursor*)cur;
  154368. const char *z;
  154369. const char *zRoot = 0;
  154370. sqlite3_int64 n;
  154371. UNUSED_PARAM(idxStr);
  154372. UNUSED_PARAM(argc);
  154373. jsonEachCursorReset(p);
  154374. if( idxNum==0 ) return SQLITE_OK;
  154375. z = (const char*)sqlite3_value_text(argv[0]);
  154376. if( z==0 ) return SQLITE_OK;
  154377. n = sqlite3_value_bytes(argv[0]);
  154378. p->zJson = sqlite3_malloc64( n+1 );
  154379. if( p->zJson==0 ) return SQLITE_NOMEM;
  154380. memcpy(p->zJson, z, (size_t)n+1);
  154381. if( jsonParse(&p->sParse, 0, p->zJson) ){
  154382. int rc = SQLITE_NOMEM;
  154383. if( p->sParse.oom==0 ){
  154384. sqlite3_free(cur->pVtab->zErrMsg);
  154385. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  154386. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  154387. }
  154388. jsonEachCursorReset(p);
  154389. return rc;
  154390. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  154391. jsonEachCursorReset(p);
  154392. return SQLITE_NOMEM;
  154393. }else{
  154394. JsonNode *pNode = 0;
  154395. if( idxNum==3 ){
  154396. const char *zErr = 0;
  154397. zRoot = (const char*)sqlite3_value_text(argv[1]);
  154398. if( zRoot==0 ) return SQLITE_OK;
  154399. n = sqlite3_value_bytes(argv[1]);
  154400. p->zRoot = sqlite3_malloc64( n+1 );
  154401. if( p->zRoot==0 ) return SQLITE_NOMEM;
  154402. memcpy(p->zRoot, zRoot, (size_t)n+1);
  154403. if( zRoot[0]!='$' ){
  154404. zErr = zRoot;
  154405. }else{
  154406. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  154407. }
  154408. if( zErr ){
  154409. sqlite3_free(cur->pVtab->zErrMsg);
  154410. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  154411. jsonEachCursorReset(p);
  154412. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  154413. }else if( pNode==0 ){
  154414. return SQLITE_OK;
  154415. }
  154416. }else{
  154417. pNode = p->sParse.aNode;
  154418. }
  154419. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  154420. p->eType = pNode->eType;
  154421. if( p->eType>=JSON_ARRAY ){
  154422. pNode->u.iKey = 0;
  154423. p->iEnd = p->i + pNode->n + 1;
  154424. if( p->bRecursive ){
  154425. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  154426. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  154427. p->i--;
  154428. }
  154429. }else{
  154430. p->i++;
  154431. }
  154432. }else{
  154433. p->iEnd = p->i+1;
  154434. }
  154435. }
  154436. return SQLITE_OK;
  154437. }
  154438. /* The methods of the json_each virtual table */
  154439. static sqlite3_module jsonEachModule = {
  154440. 0, /* iVersion */
  154441. 0, /* xCreate */
  154442. jsonEachConnect, /* xConnect */
  154443. jsonEachBestIndex, /* xBestIndex */
  154444. jsonEachDisconnect, /* xDisconnect */
  154445. 0, /* xDestroy */
  154446. jsonEachOpenEach, /* xOpen - open a cursor */
  154447. jsonEachClose, /* xClose - close a cursor */
  154448. jsonEachFilter, /* xFilter - configure scan constraints */
  154449. jsonEachNext, /* xNext - advance a cursor */
  154450. jsonEachEof, /* xEof - check for end of scan */
  154451. jsonEachColumn, /* xColumn - read data */
  154452. jsonEachRowid, /* xRowid - read data */
  154453. 0, /* xUpdate */
  154454. 0, /* xBegin */
  154455. 0, /* xSync */
  154456. 0, /* xCommit */
  154457. 0, /* xRollback */
  154458. 0, /* xFindMethod */
  154459. 0, /* xRename */
  154460. 0, /* xSavepoint */
  154461. 0, /* xRelease */
  154462. 0 /* xRollbackTo */
  154463. };
  154464. /* The methods of the json_tree virtual table. */
  154465. static sqlite3_module jsonTreeModule = {
  154466. 0, /* iVersion */
  154467. 0, /* xCreate */
  154468. jsonEachConnect, /* xConnect */
  154469. jsonEachBestIndex, /* xBestIndex */
  154470. jsonEachDisconnect, /* xDisconnect */
  154471. 0, /* xDestroy */
  154472. jsonEachOpenTree, /* xOpen - open a cursor */
  154473. jsonEachClose, /* xClose - close a cursor */
  154474. jsonEachFilter, /* xFilter - configure scan constraints */
  154475. jsonEachNext, /* xNext - advance a cursor */
  154476. jsonEachEof, /* xEof - check for end of scan */
  154477. jsonEachColumn, /* xColumn - read data */
  154478. jsonEachRowid, /* xRowid - read data */
  154479. 0, /* xUpdate */
  154480. 0, /* xBegin */
  154481. 0, /* xSync */
  154482. 0, /* xCommit */
  154483. 0, /* xRollback */
  154484. 0, /* xFindMethod */
  154485. 0, /* xRename */
  154486. 0, /* xSavepoint */
  154487. 0, /* xRelease */
  154488. 0 /* xRollbackTo */
  154489. };
  154490. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  154491. /****************************************************************************
  154492. ** The following routines are the only publically visible identifiers in this
  154493. ** file. Call the following routines in order to register the various SQL
  154494. ** functions and the virtual table implemented by this file.
  154495. ****************************************************************************/
  154496. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  154497. int rc = SQLITE_OK;
  154498. unsigned int i;
  154499. static const struct {
  154500. const char *zName;
  154501. int nArg;
  154502. int flag;
  154503. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  154504. } aFunc[] = {
  154505. { "json", 1, 0, jsonRemoveFunc },
  154506. { "json_array", -1, 0, jsonArrayFunc },
  154507. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  154508. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  154509. { "json_extract", -1, 0, jsonExtractFunc },
  154510. { "json_insert", -1, 0, jsonSetFunc },
  154511. { "json_object", -1, 0, jsonObjectFunc },
  154512. { "json_remove", -1, 0, jsonRemoveFunc },
  154513. { "json_replace", -1, 0, jsonReplaceFunc },
  154514. { "json_set", -1, 1, jsonSetFunc },
  154515. { "json_type", 1, 0, jsonTypeFunc },
  154516. { "json_type", 2, 0, jsonTypeFunc },
  154517. { "json_valid", 1, 0, jsonValidFunc },
  154518. #if SQLITE_DEBUG
  154519. /* DEBUG and TESTING functions */
  154520. { "json_parse", 1, 0, jsonParseFunc },
  154521. { "json_test1", 1, 0, jsonTest1Func },
  154522. #endif
  154523. };
  154524. #ifndef SQLITE_OMIT_VIRTUALTABLE
  154525. static const struct {
  154526. const char *zName;
  154527. sqlite3_module *pModule;
  154528. } aMod[] = {
  154529. { "json_each", &jsonEachModule },
  154530. { "json_tree", &jsonTreeModule },
  154531. };
  154532. #endif
  154533. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  154534. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  154535. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  154536. (void*)&aFunc[i].flag,
  154537. aFunc[i].xFunc, 0, 0);
  154538. }
  154539. #ifndef SQLITE_OMIT_VIRTUALTABLE
  154540. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  154541. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  154542. }
  154543. #endif
  154544. return rc;
  154545. }
  154546. #ifndef SQLITE_CORE
  154547. #ifdef _WIN32
  154548. __declspec(dllexport)
  154549. #endif
  154550. SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
  154551. sqlite3 *db,
  154552. char **pzErrMsg,
  154553. const sqlite3_api_routines *pApi
  154554. ){
  154555. SQLITE_EXTENSION_INIT2(pApi);
  154556. (void)pzErrMsg; /* Unused parameter */
  154557. return sqlite3Json1Init(db);
  154558. }
  154559. #endif
  154560. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  154561. /************** End of json1.c ***********************************************/
  154562. /************** Begin file fts5.c ********************************************/
  154563. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  154564. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  154565. # define NDEBUG 1
  154566. #endif
  154567. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  154568. # undef NDEBUG
  154569. #endif
  154570. /*
  154571. ** 2014 May 31
  154572. **
  154573. ** The author disclaims copyright to this source code. In place of
  154574. ** a legal notice, here is a blessing:
  154575. **
  154576. ** May you do good and not evil.
  154577. ** May you find forgiveness for yourself and forgive others.
  154578. ** May you share freely, never taking more than you give.
  154579. **
  154580. ******************************************************************************
  154581. **
  154582. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  154583. ** FTS5 may be extended with:
  154584. **
  154585. ** * custom tokenizers, and
  154586. ** * custom auxiliary functions.
  154587. */
  154588. #ifndef _FTS5_H
  154589. #define _FTS5_H
  154590. /* #include "sqlite3.h" */
  154591. #if 0
  154592. extern "C" {
  154593. #endif
  154594. /*************************************************************************
  154595. ** CUSTOM AUXILIARY FUNCTIONS
  154596. **
  154597. ** Virtual table implementations may overload SQL functions by implementing
  154598. ** the sqlite3_module.xFindFunction() method.
  154599. */
  154600. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  154601. typedef struct Fts5Context Fts5Context;
  154602. typedef struct Fts5PhraseIter Fts5PhraseIter;
  154603. typedef void (*fts5_extension_function)(
  154604. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  154605. Fts5Context *pFts, /* First arg to pass to pApi functions */
  154606. sqlite3_context *pCtx, /* Context for returning result/error */
  154607. int nVal, /* Number of values in apVal[] array */
  154608. sqlite3_value **apVal /* Array of trailing arguments */
  154609. );
  154610. struct Fts5PhraseIter {
  154611. const unsigned char *a;
  154612. const unsigned char *b;
  154613. };
  154614. /*
  154615. ** EXTENSION API FUNCTIONS
  154616. **
  154617. ** xUserData(pFts):
  154618. ** Return a copy of the context pointer the extension function was
  154619. ** registered with.
  154620. **
  154621. ** xColumnTotalSize(pFts, iCol, pnToken):
  154622. ** If parameter iCol is less than zero, set output variable *pnToken
  154623. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  154624. ** non-negative but less than the number of columns in the table, return
  154625. ** the total number of tokens in column iCol, considering all rows in
  154626. ** the FTS5 table.
  154627. **
  154628. ** If parameter iCol is greater than or equal to the number of columns
  154629. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  154630. ** an OOM condition or IO error), an appropriate SQLite error code is
  154631. ** returned.
  154632. **
  154633. ** xColumnCount(pFts):
  154634. ** Return the number of columns in the table.
  154635. **
  154636. ** xColumnSize(pFts, iCol, pnToken):
  154637. ** If parameter iCol is less than zero, set output variable *pnToken
  154638. ** to the total number of tokens in the current row. Or, if iCol is
  154639. ** non-negative but less than the number of columns in the table, set
  154640. ** *pnToken to the number of tokens in column iCol of the current row.
  154641. **
  154642. ** If parameter iCol is greater than or equal to the number of columns
  154643. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  154644. ** an OOM condition or IO error), an appropriate SQLite error code is
  154645. ** returned.
  154646. **
  154647. ** xColumnText:
  154648. ** This function attempts to retrieve the text of column iCol of the
  154649. ** current document. If successful, (*pz) is set to point to a buffer
  154650. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  154651. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  154652. ** if an error occurs, an SQLite error code is returned and the final values
  154653. ** of (*pz) and (*pn) are undefined.
  154654. **
  154655. ** xPhraseCount:
  154656. ** Returns the number of phrases in the current query expression.
  154657. **
  154658. ** xPhraseSize:
  154659. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  154660. ** are numbered starting from zero.
  154661. **
  154662. ** xInstCount:
  154663. ** Set *pnInst to the total number of occurrences of all phrases within
  154664. ** the query within the current row. Return SQLITE_OK if successful, or
  154665. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  154666. **
  154667. ** xInst:
  154668. ** Query for the details of phrase match iIdx within the current row.
  154669. ** Phrase matches are numbered starting from zero, so the iIdx argument
  154670. ** should be greater than or equal to zero and smaller than the value
  154671. ** output by xInstCount().
  154672. **
  154673. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  154674. ** if an error occurs.
  154675. **
  154676. ** xRowid:
  154677. ** Returns the rowid of the current row.
  154678. **
  154679. ** xTokenize:
  154680. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  154681. **
  154682. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  154683. ** This API function is used to query the FTS table for phrase iPhrase
  154684. ** of the current query. Specifically, a query equivalent to:
  154685. **
  154686. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  154687. **
  154688. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  154689. ** current query is executed. For each row visited, the callback function
  154690. ** passed as the fourth argument is invoked. The context and API objects
  154691. ** passed to the callback function may be used to access the properties of
  154692. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  154693. ** passed as the third argument to pUserData.
  154694. **
  154695. ** If the callback function returns any value other than SQLITE_OK, the
  154696. ** query is abandoned and the xQueryPhrase function returns immediately.
  154697. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  154698. ** Otherwise, the error code is propagated upwards.
  154699. **
  154700. ** If the query runs to completion without incident, SQLITE_OK is returned.
  154701. ** Or, if some error occurs before the query completes or is aborted by
  154702. ** the callback, an SQLite error code is returned.
  154703. **
  154704. **
  154705. ** xSetAuxdata(pFts5, pAux, xDelete)
  154706. **
  154707. ** Save the pointer passed as the second argument as the extension functions
  154708. ** "auxiliary data". The pointer may then be retrieved by the current or any
  154709. ** future invocation of the same fts5 extension function made as part of
  154710. ** of the same MATCH query using the xGetAuxdata() API.
  154711. **
  154712. ** Each extension function is allocated a single auxiliary data slot for
  154713. ** each FTS query (MATCH expression). If the extension function is invoked
  154714. ** more than once for a single FTS query, then all invocations share a
  154715. ** single auxiliary data context.
  154716. **
  154717. ** If there is already an auxiliary data pointer when this function is
  154718. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  154719. ** was specified along with the original pointer, it is invoked at this
  154720. ** point.
  154721. **
  154722. ** The xDelete callback, if one is specified, is also invoked on the
  154723. ** auxiliary data pointer after the FTS5 query has finished.
  154724. **
  154725. ** If an error (e.g. an OOM condition) occurs within this function, an
  154726. ** the auxiliary data is set to NULL and an error code returned. If the
  154727. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  154728. ** pointer before returning.
  154729. **
  154730. **
  154731. ** xGetAuxdata(pFts5, bClear)
  154732. **
  154733. ** Returns the current auxiliary data pointer for the fts5 extension
  154734. ** function. See the xSetAuxdata() method for details.
  154735. **
  154736. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  154737. ** (set to NULL) before this function returns. In this case the xDelete,
  154738. ** if any, is not invoked.
  154739. **
  154740. **
  154741. ** xRowCount(pFts5, pnRow)
  154742. **
  154743. ** This function is used to retrieve the total number of rows in the table.
  154744. ** In other words, the same value that would be returned by:
  154745. **
  154746. ** SELECT count(*) FROM ftstable;
  154747. **
  154748. ** xPhraseFirst()
  154749. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  154750. ** method, to iterate through all instances of a single query phrase within
  154751. ** the current row. This is the same information as is accessible via the
  154752. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  154753. ** to use, this API may be faster under some circumstances. To iterate
  154754. ** through instances of phrase iPhrase, use the following code:
  154755. **
  154756. ** Fts5PhraseIter iter;
  154757. ** int iCol, iOff;
  154758. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  154759. ** iOff>=0;
  154760. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  154761. ** ){
  154762. ** // An instance of phrase iPhrase at offset iOff of column iCol
  154763. ** }
  154764. **
  154765. ** The Fts5PhraseIter structure is defined above. Applications should not
  154766. ** modify this structure directly - it should only be used as shown above
  154767. ** with the xPhraseFirst() and xPhraseNext() API methods.
  154768. **
  154769. ** xPhraseNext()
  154770. ** See xPhraseFirst above.
  154771. */
  154772. struct Fts5ExtensionApi {
  154773. int iVersion; /* Currently always set to 1 */
  154774. void *(*xUserData)(Fts5Context*);
  154775. int (*xColumnCount)(Fts5Context*);
  154776. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  154777. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  154778. int (*xTokenize)(Fts5Context*,
  154779. const char *pText, int nText, /* Text to tokenize */
  154780. void *pCtx, /* Context passed to xToken() */
  154781. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  154782. );
  154783. int (*xPhraseCount)(Fts5Context*);
  154784. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  154785. int (*xInstCount)(Fts5Context*, int *pnInst);
  154786. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  154787. sqlite3_int64 (*xRowid)(Fts5Context*);
  154788. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  154789. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  154790. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  154791. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  154792. );
  154793. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  154794. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  154795. void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  154796. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  154797. };
  154798. /*
  154799. ** CUSTOM AUXILIARY FUNCTIONS
  154800. *************************************************************************/
  154801. /*************************************************************************
  154802. ** CUSTOM TOKENIZERS
  154803. **
  154804. ** Applications may also register custom tokenizer types. A tokenizer
  154805. ** is registered by providing fts5 with a populated instance of the
  154806. ** following structure. All structure methods must be defined, setting
  154807. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  154808. ** behaviour. The structure methods are expected to function as follows:
  154809. **
  154810. ** xCreate:
  154811. ** This function is used to allocate and inititalize a tokenizer instance.
  154812. ** A tokenizer instance is required to actually tokenize text.
  154813. **
  154814. ** The first argument passed to this function is a copy of the (void*)
  154815. ** pointer provided by the application when the fts5_tokenizer object
  154816. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  154817. ** The second and third arguments are an array of nul-terminated strings
  154818. ** containing the tokenizer arguments, if any, specified following the
  154819. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  154820. ** to create the FTS5 table.
  154821. **
  154822. ** The final argument is an output variable. If successful, (*ppOut)
  154823. ** should be set to point to the new tokenizer handle and SQLITE_OK
  154824. ** returned. If an error occurs, some value other than SQLITE_OK should
  154825. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  154826. ** is undefined.
  154827. **
  154828. ** xDelete:
  154829. ** This function is invoked to delete a tokenizer handle previously
  154830. ** allocated using xCreate(). Fts5 guarantees that this function will
  154831. ** be invoked exactly once for each successful call to xCreate().
  154832. **
  154833. ** xTokenize:
  154834. ** This function is expected to tokenize the nText byte string indicated
  154835. ** by argument pText. pText may or may not be nul-terminated. The first
  154836. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  154837. ** returned by an earlier call to xCreate().
  154838. **
  154839. ** The second argument indicates the reason that FTS5 is requesting
  154840. ** tokenization of the supplied text. This is always one of the following
  154841. ** four values:
  154842. **
  154843. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  154844. ** or removed from the FTS table. The tokenizer is being invoked to
  154845. ** determine the set of tokens to add to (or delete from) the
  154846. ** FTS index.
  154847. **
  154848. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  154849. ** against the FTS index. The tokenizer is being called to tokenize
  154850. ** a bareword or quoted string specified as part of the query.
  154851. **
  154852. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  154853. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  154854. ** followed by a "*" character, indicating that the last token
  154855. ** returned by the tokenizer will be treated as a token prefix.
  154856. **
  154857. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  154858. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  154859. ** function. Or an fts5_api.xColumnSize() request made by the same
  154860. ** on a columnsize=0 database.
  154861. ** </ul>
  154862. **
  154863. ** For each token in the input string, the supplied callback xToken() must
  154864. ** be invoked. The first argument to it should be a copy of the pointer
  154865. ** passed as the second argument to xTokenize(). The third and fourth
  154866. ** arguments are a pointer to a buffer containing the token text, and the
  154867. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  154868. ** of the first byte of and first byte immediately following the text from
  154869. ** which the token is derived within the input.
  154870. **
  154871. ** The second argument passed to the xToken() callback ("tflags") should
  154872. ** normally be set to 0. The exception is if the tokenizer supports
  154873. ** synonyms. In this case see the discussion below for details.
  154874. **
  154875. ** FTS5 assumes the xToken() callback is invoked for each token in the
  154876. ** order that they occur within the input text.
  154877. **
  154878. ** If an xToken() callback returns any value other than SQLITE_OK, then
  154879. ** the tokenization should be abandoned and the xTokenize() method should
  154880. ** immediately return a copy of the xToken() return value. Or, if the
  154881. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  154882. ** if an error occurs with the xTokenize() implementation itself, it
  154883. ** may abandon the tokenization and return any error code other than
  154884. ** SQLITE_OK or SQLITE_DONE.
  154885. **
  154886. ** SYNONYM SUPPORT
  154887. **
  154888. ** Custom tokenizers may also support synonyms. Consider a case in which a
  154889. ** user wishes to query for a phrase such as "first place". Using the
  154890. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  154891. ** of "first place" within the document set, but not alternative forms
  154892. ** such as "1st place". In some applications, it would be better to match
  154893. ** all instances of "first place" or "1st place" regardless of which form
  154894. ** the user specified in the MATCH query text.
  154895. **
  154896. ** There are several ways to approach this in FTS5:
  154897. **
  154898. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  154899. ** In the above example, this means that the tokenizer returns the
  154900. ** same token for inputs "first" and "1st". Say that token is in
  154901. ** fact "first", so that when the user inserts the document "I won
  154902. ** 1st place" entries are added to the index for tokens "i", "won",
  154903. ** "first" and "place". If the user then queries for '1st + place',
  154904. ** the tokenizer substitutes "first" for "1st" and the query works
  154905. ** as expected.
  154906. **
  154907. ** <li> By adding multiple synonyms for a single term to the FTS index.
  154908. ** In this case, when tokenizing query text, the tokenizer may
  154909. ** provide multiple synonyms for a single term within the document.
  154910. ** FTS5 then queries the index for each synonym individually. For
  154911. ** example, faced with the query:
  154912. **
  154913. ** <codeblock>
  154914. ** ... MATCH 'first place'</codeblock>
  154915. **
  154916. ** the tokenizer offers both "1st" and "first" as synonyms for the
  154917. ** first token in the MATCH query and FTS5 effectively runs a query
  154918. ** similar to:
  154919. **
  154920. ** <codeblock>
  154921. ** ... MATCH '(first OR 1st) place'</codeblock>
  154922. **
  154923. ** except that, for the purposes of auxiliary functions, the query
  154924. ** still appears to contain just two phrases - "(first OR 1st)"
  154925. ** being treated as a single phrase.
  154926. **
  154927. ** <li> By adding multiple synonyms for a single term to the FTS index.
  154928. ** Using this method, when tokenizing document text, the tokenizer
  154929. ** provides multiple synonyms for each token. So that when a
  154930. ** document such as "I won first place" is tokenized, entries are
  154931. ** added to the FTS index for "i", "won", "first", "1st" and
  154932. ** "place".
  154933. **
  154934. ** This way, even if the tokenizer does not provide synonyms
  154935. ** when tokenizing query text (it should not - to do would be
  154936. ** inefficient), it doesn't matter if the user queries for
  154937. ** 'first + place' or '1st + place', as there are entires in the
  154938. ** FTS index corresponding to both forms of the first token.
  154939. ** </ol>
  154940. **
  154941. ** Whether it is parsing document or query text, any call to xToken that
  154942. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  154943. ** is considered to supply a synonym for the previous token. For example,
  154944. ** when parsing the document "I won first place", a tokenizer that supports
  154945. ** synonyms would call xToken() 5 times, as follows:
  154946. **
  154947. ** <codeblock>
  154948. ** xToken(pCtx, 0, "i", 1, 0, 1);
  154949. ** xToken(pCtx, 0, "won", 3, 2, 5);
  154950. ** xToken(pCtx, 0, "first", 5, 6, 11);
  154951. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  154952. ** xToken(pCtx, 0, "place", 5, 12, 17);
  154953. **</codeblock>
  154954. **
  154955. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  154956. ** xToken() is called. Multiple synonyms may be specified for a single token
  154957. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  154958. ** There is no limit to the number of synonyms that may be provided for a
  154959. ** single token.
  154960. **
  154961. ** In many cases, method (1) above is the best approach. It does not add
  154962. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  154963. ** so it is efficient in terms of disk space and query speed. However, it
  154964. ** does not support prefix queries very well. If, as suggested above, the
  154965. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  154966. **
  154967. ** <codeblock>
  154968. ** ... MATCH '1s*'</codeblock>
  154969. **
  154970. ** will not match documents that contain the token "1st" (as the tokenizer
  154971. ** will probably not map "1s" to any prefix of "first").
  154972. **
  154973. ** For full prefix support, method (3) may be preferred. In this case,
  154974. ** because the index contains entries for both "first" and "1st", prefix
  154975. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  154976. ** extra entries are added to the FTS index, this method uses more space
  154977. ** within the database.
  154978. **
  154979. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  154980. ** a query such as '1s*' will match documents that contain the literal
  154981. ** token "1st", but not "first" (assuming the tokenizer is not able to
  154982. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  154983. ** will match against "1st" and "first". This method does not require
  154984. ** extra disk space, as no extra entries are added to the FTS index.
  154985. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  154986. ** as separate queries of the FTS index are required for each synonym.
  154987. **
  154988. ** When using methods (2) or (3), it is important that the tokenizer only
  154989. ** provide synonyms when tokenizing document text (method (2)) or query
  154990. ** text (method (3)), not both. Doing so will not cause any errors, but is
  154991. ** inefficient.
  154992. */
  154993. typedef struct Fts5Tokenizer Fts5Tokenizer;
  154994. typedef struct fts5_tokenizer fts5_tokenizer;
  154995. struct fts5_tokenizer {
  154996. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  154997. void (*xDelete)(Fts5Tokenizer*);
  154998. int (*xTokenize)(Fts5Tokenizer*,
  154999. void *pCtx,
  155000. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  155001. const char *pText, int nText,
  155002. int (*xToken)(
  155003. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  155004. int tflags, /* Mask of FTS5_TOKEN_* flags */
  155005. const char *pToken, /* Pointer to buffer containing token */
  155006. int nToken, /* Size of token in bytes */
  155007. int iStart, /* Byte offset of token within input text */
  155008. int iEnd /* Byte offset of end of token within input text */
  155009. )
  155010. );
  155011. };
  155012. /* Flags that may be passed as the third argument to xTokenize() */
  155013. #define FTS5_TOKENIZE_QUERY 0x0001
  155014. #define FTS5_TOKENIZE_PREFIX 0x0002
  155015. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  155016. #define FTS5_TOKENIZE_AUX 0x0008
  155017. /* Flags that may be passed by the tokenizer implementation back to FTS5
  155018. ** as the third argument to the supplied xToken callback. */
  155019. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  155020. /*
  155021. ** END OF CUSTOM TOKENIZERS
  155022. *************************************************************************/
  155023. /*************************************************************************
  155024. ** FTS5 EXTENSION REGISTRATION API
  155025. */
  155026. typedef struct fts5_api fts5_api;
  155027. struct fts5_api {
  155028. int iVersion; /* Currently always set to 2 */
  155029. /* Create a new tokenizer */
  155030. int (*xCreateTokenizer)(
  155031. fts5_api *pApi,
  155032. const char *zName,
  155033. void *pContext,
  155034. fts5_tokenizer *pTokenizer,
  155035. void (*xDestroy)(void*)
  155036. );
  155037. /* Find an existing tokenizer */
  155038. int (*xFindTokenizer)(
  155039. fts5_api *pApi,
  155040. const char *zName,
  155041. void **ppContext,
  155042. fts5_tokenizer *pTokenizer
  155043. );
  155044. /* Create a new auxiliary function */
  155045. int (*xCreateFunction)(
  155046. fts5_api *pApi,
  155047. const char *zName,
  155048. void *pContext,
  155049. fts5_extension_function xFunction,
  155050. void (*xDestroy)(void*)
  155051. );
  155052. };
  155053. /*
  155054. ** END OF REGISTRATION API
  155055. *************************************************************************/
  155056. #if 0
  155057. } /* end of the 'extern "C"' block */
  155058. #endif
  155059. #endif /* _FTS5_H */
  155060. /*
  155061. ** 2014 May 31
  155062. **
  155063. ** The author disclaims copyright to this source code. In place of
  155064. ** a legal notice, here is a blessing:
  155065. **
  155066. ** May you do good and not evil.
  155067. ** May you find forgiveness for yourself and forgive others.
  155068. ** May you share freely, never taking more than you give.
  155069. **
  155070. ******************************************************************************
  155071. **
  155072. */
  155073. #ifndef _FTS5INT_H
  155074. #define _FTS5INT_H
  155075. /* #include "sqlite3ext.h" */
  155076. SQLITE_EXTENSION_INIT1
  155077. /* #include <string.h> */
  155078. /* #include <assert.h> */
  155079. #ifndef SQLITE_AMALGAMATION
  155080. typedef unsigned char u8;
  155081. typedef unsigned int u32;
  155082. typedef unsigned short u16;
  155083. typedef sqlite3_int64 i64;
  155084. typedef sqlite3_uint64 u64;
  155085. #define ArraySize(x) (sizeof(x) / sizeof(x[0]))
  155086. #define testcase(x)
  155087. #define ALWAYS(x) 1
  155088. #define NEVER(x) 0
  155089. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  155090. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  155091. /*
  155092. ** Constants for the largest and smallest possible 64-bit signed integers.
  155093. */
  155094. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  155095. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  155096. #endif
  155097. /*
  155098. ** Maximum number of prefix indexes on single FTS5 table. This must be
  155099. ** less than 32. If it is set to anything large than that, an #error
  155100. ** directive in fts5_index.c will cause the build to fail.
  155101. */
  155102. #define FTS5_MAX_PREFIX_INDEXES 31
  155103. #define FTS5_DEFAULT_NEARDIST 10
  155104. #define FTS5_DEFAULT_RANK "bm25"
  155105. /* Name of rank and rowid columns */
  155106. #define FTS5_RANK_NAME "rank"
  155107. #define FTS5_ROWID_NAME "rowid"
  155108. #ifdef SQLITE_DEBUG
  155109. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  155110. static int sqlite3Fts5Corrupt(void);
  155111. #else
  155112. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  155113. #endif
  155114. /*
  155115. ** The assert_nc() macro is similar to the assert() macro, except that it
  155116. ** is used for assert() conditions that are true only if it can be
  155117. ** guranteed that the database is not corrupt.
  155118. */
  155119. #ifdef SQLITE_DEBUG
  155120. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  155121. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  155122. #else
  155123. # define assert_nc(x) assert(x)
  155124. #endif
  155125. typedef struct Fts5Global Fts5Global;
  155126. typedef struct Fts5Colset Fts5Colset;
  155127. /* If a NEAR() clump or phrase may only match a specific set of columns,
  155128. ** then an object of the following type is used to record the set of columns.
  155129. ** Each entry in the aiCol[] array is a column that may be matched.
  155130. **
  155131. ** This object is used by fts5_expr.c and fts5_index.c.
  155132. */
  155133. struct Fts5Colset {
  155134. int nCol;
  155135. int aiCol[1];
  155136. };
  155137. /**************************************************************************
  155138. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  155139. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  155140. */
  155141. typedef struct Fts5Config Fts5Config;
  155142. /*
  155143. ** An instance of the following structure encodes all information that can
  155144. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  155145. **
  155146. ** And all information loaded from the %_config table.
  155147. **
  155148. ** nAutomerge:
  155149. ** The minimum number of segments that an auto-merge operation should
  155150. ** attempt to merge together. A value of 1 sets the object to use the
  155151. ** compile time default. Zero disables auto-merge altogether.
  155152. **
  155153. ** zContent:
  155154. **
  155155. ** zContentRowid:
  155156. ** The value of the content_rowid= option, if one was specified. Or
  155157. ** the string "rowid" otherwise. This text is not quoted - if it is
  155158. ** used as part of an SQL statement it needs to be quoted appropriately.
  155159. **
  155160. ** zContentExprlist:
  155161. **
  155162. ** pzErrmsg:
  155163. ** This exists in order to allow the fts5_index.c module to return a
  155164. ** decent error message if it encounters a file-format version it does
  155165. ** not understand.
  155166. **
  155167. ** bColumnsize:
  155168. ** True if the %_docsize table is created.
  155169. **
  155170. ** bPrefixIndex:
  155171. ** This is only used for debugging. If set to false, any prefix indexes
  155172. ** are ignored. This value is configured using:
  155173. **
  155174. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  155175. **
  155176. */
  155177. struct Fts5Config {
  155178. sqlite3 *db; /* Database handle */
  155179. char *zDb; /* Database holding FTS index (e.g. "main") */
  155180. char *zName; /* Name of FTS index */
  155181. int nCol; /* Number of columns */
  155182. char **azCol; /* Column names */
  155183. u8 *abUnindexed; /* True for unindexed columns */
  155184. int nPrefix; /* Number of prefix indexes */
  155185. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  155186. int eContent; /* An FTS5_CONTENT value */
  155187. char *zContent; /* content table */
  155188. char *zContentRowid; /* "content_rowid=" option value */
  155189. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  155190. char *zContentExprlist;
  155191. Fts5Tokenizer *pTok;
  155192. fts5_tokenizer *pTokApi;
  155193. /* Values loaded from the %_config table */
  155194. int iCookie; /* Incremented when %_config is modified */
  155195. int pgsz; /* Approximate page size used in %_data */
  155196. int nAutomerge; /* 'automerge' setting */
  155197. int nCrisisMerge; /* Maximum allowed segments per level */
  155198. char *zRank; /* Name of rank function */
  155199. char *zRankArgs; /* Arguments to rank function */
  155200. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  155201. char **pzErrmsg;
  155202. #ifdef SQLITE_DEBUG
  155203. int bPrefixIndex; /* True to use prefix-indexes */
  155204. #endif
  155205. };
  155206. /* Current expected value of %_config table 'version' field */
  155207. #define FTS5_CURRENT_VERSION 4
  155208. #define FTS5_CONTENT_NORMAL 0
  155209. #define FTS5_CONTENT_NONE 1
  155210. #define FTS5_CONTENT_EXTERNAL 2
  155211. static int sqlite3Fts5ConfigParse(
  155212. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  155213. );
  155214. static void sqlite3Fts5ConfigFree(Fts5Config*);
  155215. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  155216. static int sqlite3Fts5Tokenize(
  155217. Fts5Config *pConfig, /* FTS5 Configuration object */
  155218. int flags, /* FTS5_TOKENIZE_* flags */
  155219. const char *pText, int nText, /* Text to tokenize */
  155220. void *pCtx, /* Context passed to xToken() */
  155221. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  155222. );
  155223. static void sqlite3Fts5Dequote(char *z);
  155224. /* Load the contents of the %_config table */
  155225. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  155226. /* Set the value of a single config attribute */
  155227. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  155228. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  155229. /*
  155230. ** End of interface to code in fts5_config.c.
  155231. **************************************************************************/
  155232. /**************************************************************************
  155233. ** Interface to code in fts5_buffer.c.
  155234. */
  155235. /*
  155236. ** Buffer object for the incremental building of string data.
  155237. */
  155238. typedef struct Fts5Buffer Fts5Buffer;
  155239. struct Fts5Buffer {
  155240. u8 *p;
  155241. int n;
  155242. int nSpace;
  155243. };
  155244. static int sqlite3Fts5BufferGrow(int*, Fts5Buffer*, int);
  155245. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  155246. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, int, const u8*);
  155247. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  155248. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  155249. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  155250. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  155251. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  155252. static void sqlite3Fts5BufferAppend32(int*, Fts5Buffer*, int);
  155253. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  155254. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  155255. #define fts5BufferGrow(a,b,c) sqlite3Fts5BufferGrow(a,b,c)
  155256. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  155257. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  155258. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  155259. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  155260. #define fts5BufferAppend32(a,b,c) sqlite3Fts5BufferAppend32(a,b,c)
  155261. /* Write and decode big-endian 32-bit integer values */
  155262. static void sqlite3Fts5Put32(u8*, int);
  155263. static int sqlite3Fts5Get32(const u8*);
  155264. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  155265. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  155266. typedef struct Fts5PoslistReader Fts5PoslistReader;
  155267. struct Fts5PoslistReader {
  155268. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  155269. const u8 *a; /* Position list to iterate through */
  155270. int n; /* Size of buffer at a[] in bytes */
  155271. int i; /* Current offset in a[] */
  155272. u8 bFlag; /* For client use (any custom purpose) */
  155273. /* Output variables */
  155274. u8 bEof; /* Set to true at EOF */
  155275. i64 iPos; /* (iCol<<32) + iPos */
  155276. };
  155277. static int sqlite3Fts5PoslistReaderInit(
  155278. const u8 *a, int n, /* Poslist buffer to iterate through */
  155279. Fts5PoslistReader *pIter /* Iterator object to initialize */
  155280. );
  155281. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  155282. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  155283. struct Fts5PoslistWriter {
  155284. i64 iPrev;
  155285. };
  155286. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  155287. static int sqlite3Fts5PoslistNext64(
  155288. const u8 *a, int n, /* Buffer containing poslist */
  155289. int *pi, /* IN/OUT: Offset within a[] */
  155290. i64 *piOff /* IN/OUT: Current offset */
  155291. );
  155292. /* Malloc utility */
  155293. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  155294. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  155295. /* Character set tests (like isspace(), isalpha() etc.) */
  155296. static int sqlite3Fts5IsBareword(char t);
  155297. /*
  155298. ** End of interface to code in fts5_buffer.c.
  155299. **************************************************************************/
  155300. /**************************************************************************
  155301. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  155302. ** to access the data stored in the %_data table.
  155303. */
  155304. typedef struct Fts5Index Fts5Index;
  155305. typedef struct Fts5IndexIter Fts5IndexIter;
  155306. /*
  155307. ** Values used as part of the flags argument passed to IndexQuery().
  155308. */
  155309. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  155310. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  155311. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  155312. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  155313. /*
  155314. ** Create/destroy an Fts5Index object.
  155315. */
  155316. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  155317. static int sqlite3Fts5IndexClose(Fts5Index *p);
  155318. /*
  155319. ** for(
  155320. ** sqlite3Fts5IndexQuery(p, "token", 5, 0, 0, &pIter);
  155321. ** 0==sqlite3Fts5IterEof(pIter);
  155322. ** sqlite3Fts5IterNext(pIter)
  155323. ** ){
  155324. ** i64 iRowid = sqlite3Fts5IterRowid(pIter);
  155325. ** }
  155326. */
  155327. /*
  155328. ** Open a new iterator to iterate though all rowids that match the
  155329. ** specified token or token prefix.
  155330. */
  155331. static int sqlite3Fts5IndexQuery(
  155332. Fts5Index *p, /* FTS index to query */
  155333. const char *pToken, int nToken, /* Token (or prefix) to query for */
  155334. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  155335. Fts5Colset *pColset, /* Match these columns only */
  155336. Fts5IndexIter **ppIter /* OUT: New iterator object */
  155337. );
  155338. /*
  155339. ** The various operations on open token or token prefix iterators opened
  155340. ** using sqlite3Fts5IndexQuery().
  155341. */
  155342. static int sqlite3Fts5IterEof(Fts5IndexIter*);
  155343. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  155344. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  155345. static i64 sqlite3Fts5IterRowid(Fts5IndexIter*);
  155346. static int sqlite3Fts5IterPoslist(Fts5IndexIter*,Fts5Colset*, const u8**, int*, i64*);
  155347. static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf);
  155348. /*
  155349. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  155350. */
  155351. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  155352. /*
  155353. ** This interface is used by the fts5vocab module.
  155354. */
  155355. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  155356. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  155357. /*
  155358. ** Insert or remove data to or from the index. Each time a document is
  155359. ** added to or removed from the index, this function is called one or more
  155360. ** times.
  155361. **
  155362. ** For an insert, it must be called once for each token in the new document.
  155363. ** If the operation is a delete, it must be called (at least) once for each
  155364. ** unique token in the document with an iCol value less than zero. The iPos
  155365. ** argument is ignored for a delete.
  155366. */
  155367. static int sqlite3Fts5IndexWrite(
  155368. Fts5Index *p, /* Index to write to */
  155369. int iCol, /* Column token appears in (-ve -> delete) */
  155370. int iPos, /* Position of token within column */
  155371. const char *pToken, int nToken /* Token to add or remove to or from index */
  155372. );
  155373. /*
  155374. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  155375. ** document iDocid.
  155376. */
  155377. static int sqlite3Fts5IndexBeginWrite(
  155378. Fts5Index *p, /* Index to write to */
  155379. int bDelete, /* True if current operation is a delete */
  155380. i64 iDocid /* Docid to add or remove data from */
  155381. );
  155382. /*
  155383. ** Flush any data stored in the in-memory hash tables to the database.
  155384. ** If the bCommit flag is true, also close any open blob handles.
  155385. */
  155386. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
  155387. /*
  155388. ** Discard any data stored in the in-memory hash tables. Do not write it
  155389. ** to the database. Additionally, assume that the contents of the %_data
  155390. ** table may have changed on disk. So any in-memory caches of %_data
  155391. ** records must be invalidated.
  155392. */
  155393. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  155394. /*
  155395. ** Get or set the "averages" values.
  155396. */
  155397. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  155398. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  155399. /*
  155400. ** Functions called by the storage module as part of integrity-check.
  155401. */
  155402. static u64 sqlite3Fts5IndexCksum(Fts5Config*,i64,int,int,const char*,int);
  155403. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  155404. /*
  155405. ** Called during virtual module initialization to register UDF
  155406. ** fts5_decode() with SQLite
  155407. */
  155408. static int sqlite3Fts5IndexInit(sqlite3*);
  155409. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  155410. /*
  155411. ** Return the total number of entries read from the %_data table by
  155412. ** this connection since it was created.
  155413. */
  155414. static int sqlite3Fts5IndexReads(Fts5Index *p);
  155415. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  155416. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  155417. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  155418. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  155419. /*
  155420. ** End of interface to code in fts5_index.c.
  155421. **************************************************************************/
  155422. /**************************************************************************
  155423. ** Interface to code in fts5_varint.c.
  155424. */
  155425. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  155426. static int sqlite3Fts5GetVarintLen(u32 iVal);
  155427. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  155428. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  155429. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  155430. #define fts5GetVarint sqlite3Fts5GetVarint
  155431. #define fts5FastGetVarint32(a, iOff, nVal) { \
  155432. nVal = (a)[iOff++]; \
  155433. if( nVal & 0x80 ){ \
  155434. iOff--; \
  155435. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  155436. } \
  155437. }
  155438. /*
  155439. ** End of interface to code in fts5_varint.c.
  155440. **************************************************************************/
  155441. /**************************************************************************
  155442. ** Interface to code in fts5.c.
  155443. */
  155444. static int sqlite3Fts5GetTokenizer(
  155445. Fts5Global*,
  155446. const char **azArg,
  155447. int nArg,
  155448. Fts5Tokenizer**,
  155449. fts5_tokenizer**,
  155450. char **pzErr
  155451. );
  155452. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, int*);
  155453. /*
  155454. ** End of interface to code in fts5.c.
  155455. **************************************************************************/
  155456. /**************************************************************************
  155457. ** Interface to code in fts5_hash.c.
  155458. */
  155459. typedef struct Fts5Hash Fts5Hash;
  155460. /*
  155461. ** Create a hash table, free a hash table.
  155462. */
  155463. static int sqlite3Fts5HashNew(Fts5Hash**, int *pnSize);
  155464. static void sqlite3Fts5HashFree(Fts5Hash*);
  155465. static int sqlite3Fts5HashWrite(
  155466. Fts5Hash*,
  155467. i64 iRowid, /* Rowid for this entry */
  155468. int iCol, /* Column token appears in (-ve -> delete) */
  155469. int iPos, /* Position of token within column */
  155470. char bByte,
  155471. const char *pToken, int nToken /* Token to add or remove to or from index */
  155472. );
  155473. /*
  155474. ** Empty (but do not delete) a hash table.
  155475. */
  155476. static void sqlite3Fts5HashClear(Fts5Hash*);
  155477. static int sqlite3Fts5HashQuery(
  155478. Fts5Hash*, /* Hash table to query */
  155479. const char *pTerm, int nTerm, /* Query term */
  155480. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  155481. int *pnDoclist /* OUT: Size of doclist in bytes */
  155482. );
  155483. static int sqlite3Fts5HashScanInit(
  155484. Fts5Hash*, /* Hash table to query */
  155485. const char *pTerm, int nTerm /* Query prefix */
  155486. );
  155487. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  155488. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  155489. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  155490. const char **pzTerm, /* OUT: term (nul-terminated) */
  155491. const u8 **ppDoclist, /* OUT: pointer to doclist */
  155492. int *pnDoclist /* OUT: size of doclist in bytes */
  155493. );
  155494. /*
  155495. ** End of interface to code in fts5_hash.c.
  155496. **************************************************************************/
  155497. /**************************************************************************
  155498. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  155499. ** code to access the data stored in the %_content and %_docsize tables.
  155500. */
  155501. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  155502. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  155503. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  155504. typedef struct Fts5Storage Fts5Storage;
  155505. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  155506. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  155507. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  155508. static int sqlite3Fts5DropAll(Fts5Config*);
  155509. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  155510. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64);
  155511. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  155512. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  155513. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  155514. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  155515. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  155516. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  155517. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  155518. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  155519. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
  155520. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  155521. static int sqlite3Fts5StorageConfigValue(
  155522. Fts5Storage *p, const char*, sqlite3_value*, int
  155523. );
  155524. static int sqlite3Fts5StorageSpecialDelete(Fts5Storage *p, i64 iDel, sqlite3_value**);
  155525. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  155526. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  155527. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  155528. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  155529. /*
  155530. ** End of interface to code in fts5_storage.c.
  155531. **************************************************************************/
  155532. /**************************************************************************
  155533. ** Interface to code in fts5_expr.c.
  155534. */
  155535. typedef struct Fts5Expr Fts5Expr;
  155536. typedef struct Fts5ExprNode Fts5ExprNode;
  155537. typedef struct Fts5Parse Fts5Parse;
  155538. typedef struct Fts5Token Fts5Token;
  155539. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  155540. typedef struct Fts5ExprNearset Fts5ExprNearset;
  155541. struct Fts5Token {
  155542. const char *p; /* Token text (not NULL terminated) */
  155543. int n; /* Size of buffer p in bytes */
  155544. };
  155545. /* Parse a MATCH expression. */
  155546. static int sqlite3Fts5ExprNew(
  155547. Fts5Config *pConfig,
  155548. const char *zExpr,
  155549. Fts5Expr **ppNew,
  155550. char **pzErr
  155551. );
  155552. /*
  155553. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  155554. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  155555. ** rc = sqlite3Fts5ExprNext(pExpr)
  155556. ** ){
  155557. ** // The document with rowid iRowid matches the expression!
  155558. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  155559. ** }
  155560. */
  155561. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  155562. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  155563. static int sqlite3Fts5ExprEof(Fts5Expr*);
  155564. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  155565. static void sqlite3Fts5ExprFree(Fts5Expr*);
  155566. /* Called during startup to register a UDF with SQLite */
  155567. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  155568. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  155569. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  155570. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  155571. static int sqlite3Fts5ExprClonePhrase(Fts5Config*, Fts5Expr*, int, Fts5Expr**);
  155572. /*******************************************
  155573. ** The fts5_expr.c API above this point is used by the other hand-written
  155574. ** C code in this module. The interfaces below this point are called by
  155575. ** the parser code in fts5parse.y. */
  155576. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  155577. static Fts5ExprNode *sqlite3Fts5ParseNode(
  155578. Fts5Parse *pParse,
  155579. int eType,
  155580. Fts5ExprNode *pLeft,
  155581. Fts5ExprNode *pRight,
  155582. Fts5ExprNearset *pNear
  155583. );
  155584. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  155585. Fts5Parse *pParse,
  155586. Fts5ExprPhrase *pPhrase,
  155587. Fts5Token *pToken,
  155588. int bPrefix
  155589. );
  155590. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  155591. Fts5Parse*,
  155592. Fts5ExprNearset*,
  155593. Fts5ExprPhrase*
  155594. );
  155595. static Fts5Colset *sqlite3Fts5ParseColset(
  155596. Fts5Parse*,
  155597. Fts5Colset*,
  155598. Fts5Token *
  155599. );
  155600. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  155601. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  155602. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  155603. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  155604. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
  155605. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  155606. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  155607. /*
  155608. ** End of interface to code in fts5_expr.c.
  155609. **************************************************************************/
  155610. /**************************************************************************
  155611. ** Interface to code in fts5_aux.c.
  155612. */
  155613. static int sqlite3Fts5AuxInit(fts5_api*);
  155614. /*
  155615. ** End of interface to code in fts5_aux.c.
  155616. **************************************************************************/
  155617. /**************************************************************************
  155618. ** Interface to code in fts5_tokenizer.c.
  155619. */
  155620. static int sqlite3Fts5TokenizerInit(fts5_api*);
  155621. /*
  155622. ** End of interface to code in fts5_tokenizer.c.
  155623. **************************************************************************/
  155624. /**************************************************************************
  155625. ** Interface to code in fts5_vocab.c.
  155626. */
  155627. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  155628. /*
  155629. ** End of interface to code in fts5_vocab.c.
  155630. **************************************************************************/
  155631. /**************************************************************************
  155632. ** Interface to automatically generated code in fts5_unicode2.c.
  155633. */
  155634. static int sqlite3Fts5UnicodeIsalnum(int c);
  155635. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  155636. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  155637. /*
  155638. ** End of interface to code in fts5_unicode2.c.
  155639. **************************************************************************/
  155640. #endif
  155641. #define FTS5_OR 1
  155642. #define FTS5_AND 2
  155643. #define FTS5_NOT 3
  155644. #define FTS5_TERM 4
  155645. #define FTS5_COLON 5
  155646. #define FTS5_LP 6
  155647. #define FTS5_RP 7
  155648. #define FTS5_LCP 8
  155649. #define FTS5_RCP 9
  155650. #define FTS5_STRING 10
  155651. #define FTS5_COMMA 11
  155652. #define FTS5_PLUS 12
  155653. #define FTS5_STAR 13
  155654. /* Driver template for the LEMON parser generator.
  155655. ** The author disclaims copyright to this source code.
  155656. **
  155657. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  155658. ** The only modifications are the addition of a couple of NEVER()
  155659. ** macros to disable tests that are needed in the case of a general
  155660. ** LALR(1) grammar but which are always false in the
  155661. ** specific grammar used by SQLite.
  155662. */
  155663. /* First off, code is included that follows the "include" declaration
  155664. ** in the input grammar file. */
  155665. /* #include <stdio.h> */
  155666. /*
  155667. ** Disable all error recovery processing in the parser push-down
  155668. ** automaton.
  155669. */
  155670. #define fts5YYNOERRORRECOVERY 1
  155671. /*
  155672. ** Make fts5yytestcase() the same as testcase()
  155673. */
  155674. #define fts5yytestcase(X) testcase(X)
  155675. /* Next is all token values, in a form suitable for use by makeheaders.
  155676. ** This section will be null unless lemon is run with the -m switch.
  155677. */
  155678. /*
  155679. ** These constants (all generated automatically by the parser generator)
  155680. ** specify the various kinds of tokens (terminals) that the parser
  155681. ** understands.
  155682. **
  155683. ** Each symbol here is a terminal symbol in the grammar.
  155684. */
  155685. /* Make sure the INTERFACE macro is defined.
  155686. */
  155687. #ifndef INTERFACE
  155688. # define INTERFACE 1
  155689. #endif
  155690. /* The next thing included is series of defines which control
  155691. ** various aspects of the generated parser.
  155692. ** fts5YYCODETYPE is the data type used for storing terminal
  155693. ** and nonterminal numbers. "unsigned char" is
  155694. ** used if there are fewer than 250 terminals
  155695. ** and nonterminals. "int" is used otherwise.
  155696. ** fts5YYNOCODE is a number of type fts5YYCODETYPE which corresponds
  155697. ** to no legal terminal or nonterminal number. This
  155698. ** number is used to fill in empty slots of the hash
  155699. ** table.
  155700. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  155701. ** have fall-back values which should be used if the
  155702. ** original value of the token will not parse.
  155703. ** fts5YYACTIONTYPE is the data type used for storing terminal
  155704. ** and nonterminal numbers. "unsigned char" is
  155705. ** used if there are fewer than 250 rules and
  155706. ** states combined. "int" is used otherwise.
  155707. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor tokens given
  155708. ** directly to the parser from the tokenizer.
  155709. ** fts5YYMINORTYPE is the data type used for all minor tokens.
  155710. ** This is typically a union of many types, one of
  155711. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  155712. ** for base tokens is called "fts5yy0".
  155713. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  155714. ** zero the stack is dynamically sized using realloc()
  155715. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  155716. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  155717. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  155718. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  155719. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  155720. ** defined, then do no error processing.
  155721. ** fts5YYNSTATE the combined number of states.
  155722. ** fts5YYNRULE the number of rules in the grammar
  155723. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  155724. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  155725. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  155726. ** fts5YY_MIN_REDUCE Maximum value for reduce actions
  155727. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  155728. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  155729. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  155730. */
  155731. #define fts5YYCODETYPE unsigned char
  155732. #define fts5YYNOCODE 27
  155733. #define fts5YYACTIONTYPE unsigned char
  155734. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  155735. typedef union {
  155736. int fts5yyinit;
  155737. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  155738. Fts5Colset* fts5yy3;
  155739. Fts5ExprPhrase* fts5yy11;
  155740. Fts5ExprNode* fts5yy18;
  155741. int fts5yy20;
  155742. Fts5ExprNearset* fts5yy26;
  155743. } fts5YYMINORTYPE;
  155744. #ifndef fts5YYSTACKDEPTH
  155745. #define fts5YYSTACKDEPTH 100
  155746. #endif
  155747. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  155748. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  155749. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  155750. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  155751. #define fts5YYNSTATE 26
  155752. #define fts5YYNRULE 24
  155753. #define fts5YY_MAX_SHIFT 25
  155754. #define fts5YY_MIN_SHIFTREDUCE 40
  155755. #define fts5YY_MAX_SHIFTREDUCE 63
  155756. #define fts5YY_MIN_REDUCE 64
  155757. #define fts5YY_MAX_REDUCE 87
  155758. #define fts5YY_ERROR_ACTION 88
  155759. #define fts5YY_ACCEPT_ACTION 89
  155760. #define fts5YY_NO_ACTION 90
  155761. /* The fts5yyzerominor constant is used to initialize instances of
  155762. ** fts5YYMINORTYPE objects to zero. */
  155763. static const fts5YYMINORTYPE fts5yyzerominor = { 0 };
  155764. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  155765. ** otherwise.
  155766. **
  155767. ** Applications can choose to define fts5yytestcase() in the %include section
  155768. ** to a macro that can assist in verifying code coverage. For production
  155769. ** code the fts5yytestcase() macro should be turned off. But it is useful
  155770. ** for testing.
  155771. */
  155772. #ifndef fts5yytestcase
  155773. # define fts5yytestcase(X)
  155774. #endif
  155775. /* Next are the tables used to determine what action to take based on the
  155776. ** current state and lookahead token. These tables are used to implement
  155777. ** functions that take a state number and lookahead value and return an
  155778. ** action integer.
  155779. **
  155780. ** Suppose the action integer is N. Then the action is determined as
  155781. ** follows
  155782. **
  155783. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  155784. ** token onto the stack and goto state N.
  155785. **
  155786. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  155787. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  155788. **
  155789. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  155790. ** and fts5YY_MAX_REDUCE
  155791. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  155792. **
  155793. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  155794. **
  155795. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  155796. ** slots in the fts5yy_action[] table.
  155797. **
  155798. ** The action table is constructed as a single large table named fts5yy_action[].
  155799. ** Given state S and lookahead X, the action is computed as
  155800. **
  155801. ** fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  155802. **
  155803. ** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
  155804. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
  155805. ** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
  155806. ** and that fts5yy_default[S] should be used instead.
  155807. **
  155808. ** The formula above is for computing the action when the lookahead is
  155809. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  155810. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  155811. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  155812. ** fts5YY_SHIFT_USE_DFLT.
  155813. **
  155814. ** The following are the tables generated in this section:
  155815. **
  155816. ** fts5yy_action[] A single table containing all actions.
  155817. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  155818. ** fts5yy_action. Used to detect hash collisions.
  155819. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  155820. ** shifting terminals.
  155821. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  155822. ** shifting non-terminals after a reduce.
  155823. ** fts5yy_default[] Default action for each state.
  155824. */
  155825. #define fts5YY_ACTTAB_COUNT (78)
  155826. static const fts5YYACTIONTYPE fts5yy_action[] = {
  155827. /* 0 */ 89, 15, 46, 5, 48, 24, 12, 19, 23, 14,
  155828. /* 10 */ 46, 5, 48, 24, 20, 21, 23, 43, 46, 5,
  155829. /* 20 */ 48, 24, 6, 18, 23, 17, 46, 5, 48, 24,
  155830. /* 30 */ 75, 7, 23, 25, 46, 5, 48, 24, 62, 47,
  155831. /* 40 */ 23, 48, 24, 7, 11, 23, 9, 3, 4, 2,
  155832. /* 50 */ 62, 50, 52, 44, 64, 3, 4, 2, 49, 4,
  155833. /* 60 */ 2, 1, 23, 11, 16, 9, 12, 2, 10, 61,
  155834. /* 70 */ 53, 59, 62, 60, 22, 13, 55, 8,
  155835. };
  155836. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  155837. /* 0 */ 15, 16, 17, 18, 19, 20, 10, 11, 23, 16,
  155838. /* 10 */ 17, 18, 19, 20, 23, 24, 23, 16, 17, 18,
  155839. /* 20 */ 19, 20, 22, 23, 23, 16, 17, 18, 19, 20,
  155840. /* 30 */ 5, 6, 23, 16, 17, 18, 19, 20, 13, 17,
  155841. /* 40 */ 23, 19, 20, 6, 8, 23, 10, 1, 2, 3,
  155842. /* 50 */ 13, 9, 10, 7, 0, 1, 2, 3, 19, 2,
  155843. /* 60 */ 3, 6, 23, 8, 21, 10, 10, 3, 10, 25,
  155844. /* 70 */ 10, 10, 13, 25, 12, 10, 7, 5,
  155845. };
  155846. #define fts5YY_SHIFT_USE_DFLT (-5)
  155847. #define fts5YY_SHIFT_COUNT (25)
  155848. #define fts5YY_SHIFT_MIN (-4)
  155849. #define fts5YY_SHIFT_MAX (72)
  155850. static const signed char fts5yy_shift_ofst[] = {
  155851. /* 0 */ 55, 55, 55, 55, 55, 36, -4, 56, 58, 25,
  155852. /* 10 */ 37, 60, 59, 59, 46, 54, 42, 57, 62, 61,
  155853. /* 20 */ 62, 69, 65, 62, 72, 64,
  155854. };
  155855. #define fts5YY_REDUCE_USE_DFLT (-16)
  155856. #define fts5YY_REDUCE_COUNT (13)
  155857. #define fts5YY_REDUCE_MIN (-15)
  155858. #define fts5YY_REDUCE_MAX (48)
  155859. static const signed char fts5yy_reduce_ofst[] = {
  155860. /* 0 */ -15, -7, 1, 9, 17, 22, -9, 0, 39, 44,
  155861. /* 10 */ 44, 43, 44, 48,
  155862. };
  155863. static const fts5YYACTIONTYPE fts5yy_default[] = {
  155864. /* 0 */ 88, 88, 88, 88, 88, 69, 82, 88, 88, 87,
  155865. /* 10 */ 87, 88, 87, 87, 88, 88, 88, 66, 80, 88,
  155866. /* 20 */ 81, 88, 88, 78, 88, 65,
  155867. };
  155868. /* The next table maps tokens into fallback tokens. If a construct
  155869. ** like the following:
  155870. **
  155871. ** %fallback ID X Y Z.
  155872. **
  155873. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  155874. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  155875. ** but it does not parse, the type of the token is changed to ID and
  155876. ** the parse is retried before an error is thrown.
  155877. */
  155878. #ifdef fts5YYFALLBACK
  155879. static const fts5YYCODETYPE fts5yyFallback[] = {
  155880. };
  155881. #endif /* fts5YYFALLBACK */
  155882. /* The following structure represents a single element of the
  155883. ** parser's stack. Information stored includes:
  155884. **
  155885. ** + The state number for the parser at this level of the stack.
  155886. **
  155887. ** + The value of the token stored at this level of the stack.
  155888. ** (In other words, the "major" token.)
  155889. **
  155890. ** + The semantic value stored at this level of the stack. This is
  155891. ** the information used by the action routines in the grammar.
  155892. ** It is sometimes called the "minor" token.
  155893. **
  155894. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  155895. ** actually contains the reduce action for the second half of the
  155896. ** SHIFTREDUCE.
  155897. */
  155898. struct fts5yyStackEntry {
  155899. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  155900. fts5YYCODETYPE major; /* The major token value. This is the code
  155901. ** number for the token at this stack level */
  155902. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  155903. ** is the value of the token */
  155904. };
  155905. typedef struct fts5yyStackEntry fts5yyStackEntry;
  155906. /* The state of the parser is completely contained in an instance of
  155907. ** the following structure */
  155908. struct fts5yyParser {
  155909. int fts5yyidx; /* Index of top element in stack */
  155910. #ifdef fts5YYTRACKMAXSTACKDEPTH
  155911. int fts5yyidxMax; /* Maximum value of fts5yyidx */
  155912. #endif
  155913. int fts5yyerrcnt; /* Shifts left before out of the error */
  155914. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  155915. #if fts5YYSTACKDEPTH<=0
  155916. int fts5yystksz; /* Current side of the stack */
  155917. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  155918. #else
  155919. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  155920. #endif
  155921. };
  155922. typedef struct fts5yyParser fts5yyParser;
  155923. #ifndef NDEBUG
  155924. /* #include <stdio.h> */
  155925. static FILE *fts5yyTraceFILE = 0;
  155926. static char *fts5yyTracePrompt = 0;
  155927. #endif /* NDEBUG */
  155928. #ifndef NDEBUG
  155929. /*
  155930. ** Turn parser tracing on by giving a stream to which to write the trace
  155931. ** and a prompt to preface each trace message. Tracing is turned off
  155932. ** by making either argument NULL
  155933. **
  155934. ** Inputs:
  155935. ** <ul>
  155936. ** <li> A FILE* to which trace output should be written.
  155937. ** If NULL, then tracing is turned off.
  155938. ** <li> A prefix string written at the beginning of every
  155939. ** line of trace output. If NULL, then tracing is
  155940. ** turned off.
  155941. ** </ul>
  155942. **
  155943. ** Outputs:
  155944. ** None.
  155945. */
  155946. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  155947. fts5yyTraceFILE = TraceFILE;
  155948. fts5yyTracePrompt = zTracePrompt;
  155949. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  155950. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  155951. }
  155952. #endif /* NDEBUG */
  155953. #ifndef NDEBUG
  155954. /* For tracing shifts, the names of all terminals and nonterminals
  155955. ** are required. The following table supplies these names */
  155956. static const char *const fts5yyTokenName[] = {
  155957. "$", "OR", "AND", "NOT",
  155958. "TERM", "COLON", "LP", "RP",
  155959. "LCP", "RCP", "STRING", "COMMA",
  155960. "PLUS", "STAR", "error", "input",
  155961. "expr", "cnearset", "exprlist", "nearset",
  155962. "colset", "colsetlist", "nearphrases", "phrase",
  155963. "neardist_opt", "star_opt",
  155964. };
  155965. #endif /* NDEBUG */
  155966. #ifndef NDEBUG
  155967. /* For tracing reduce actions, the names of all rules are required.
  155968. */
  155969. static const char *const fts5yyRuleName[] = {
  155970. /* 0 */ "input ::= expr",
  155971. /* 1 */ "expr ::= expr AND expr",
  155972. /* 2 */ "expr ::= expr OR expr",
  155973. /* 3 */ "expr ::= expr NOT expr",
  155974. /* 4 */ "expr ::= LP expr RP",
  155975. /* 5 */ "expr ::= exprlist",
  155976. /* 6 */ "exprlist ::= cnearset",
  155977. /* 7 */ "exprlist ::= exprlist cnearset",
  155978. /* 8 */ "cnearset ::= nearset",
  155979. /* 9 */ "cnearset ::= colset COLON nearset",
  155980. /* 10 */ "colset ::= LCP colsetlist RCP",
  155981. /* 11 */ "colset ::= STRING",
  155982. /* 12 */ "colsetlist ::= colsetlist STRING",
  155983. /* 13 */ "colsetlist ::= STRING",
  155984. /* 14 */ "nearset ::= phrase",
  155985. /* 15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  155986. /* 16 */ "nearphrases ::= phrase",
  155987. /* 17 */ "nearphrases ::= nearphrases phrase",
  155988. /* 18 */ "neardist_opt ::=",
  155989. /* 19 */ "neardist_opt ::= COMMA STRING",
  155990. /* 20 */ "phrase ::= phrase PLUS STRING star_opt",
  155991. /* 21 */ "phrase ::= STRING star_opt",
  155992. /* 22 */ "star_opt ::= STAR",
  155993. /* 23 */ "star_opt ::=",
  155994. };
  155995. #endif /* NDEBUG */
  155996. #if fts5YYSTACKDEPTH<=0
  155997. /*
  155998. ** Try to increase the size of the parser stack.
  155999. */
  156000. static void fts5yyGrowStack(fts5yyParser *p){
  156001. int newSize;
  156002. fts5yyStackEntry *pNew;
  156003. newSize = p->fts5yystksz*2 + 100;
  156004. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  156005. if( pNew ){
  156006. p->fts5yystack = pNew;
  156007. p->fts5yystksz = newSize;
  156008. #ifndef NDEBUG
  156009. if( fts5yyTraceFILE ){
  156010. fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
  156011. fts5yyTracePrompt, p->fts5yystksz);
  156012. }
  156013. #endif
  156014. }
  156015. }
  156016. #endif
  156017. /*
  156018. ** This function allocates a new parser.
  156019. ** The only argument is a pointer to a function which works like
  156020. ** malloc.
  156021. **
  156022. ** Inputs:
  156023. ** A pointer to the function used to allocate memory.
  156024. **
  156025. ** Outputs:
  156026. ** A pointer to a parser. This pointer is used in subsequent calls
  156027. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  156028. */
  156029. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)){
  156030. fts5yyParser *pParser;
  156031. pParser = (fts5yyParser*)(*mallocProc)( (u64)sizeof(fts5yyParser) );
  156032. if( pParser ){
  156033. pParser->fts5yyidx = -1;
  156034. #ifdef fts5YYTRACKMAXSTACKDEPTH
  156035. pParser->fts5yyidxMax = 0;
  156036. #endif
  156037. #if fts5YYSTACKDEPTH<=0
  156038. pParser->fts5yystack = NULL;
  156039. pParser->fts5yystksz = 0;
  156040. fts5yyGrowStack(pParser);
  156041. #endif
  156042. }
  156043. return pParser;
  156044. }
  156045. /* The following function deletes the value associated with a
  156046. ** symbol. The symbol can be either a terminal or nonterminal.
  156047. ** "fts5yymajor" is the symbol code, and "fts5yypminor" is a pointer to
  156048. ** the value.
  156049. */
  156050. static void fts5yy_destructor(
  156051. fts5yyParser *fts5yypParser, /* The parser */
  156052. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  156053. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  156054. ){
  156055. sqlite3Fts5ParserARG_FETCH;
  156056. switch( fts5yymajor ){
  156057. /* Here is inserted the actions which take place when a
  156058. ** terminal or non-terminal is destroyed. This can happen
  156059. ** when the symbol is popped from the stack during a
  156060. ** reduce or during error processing or when a parser is
  156061. ** being destroyed before it is finished parsing.
  156062. **
  156063. ** Note: during a reduce, the only symbols destroyed are those
  156064. ** which appear on the RHS of the rule, but which are not used
  156065. ** inside the C code.
  156066. */
  156067. case 15: /* input */
  156068. {
  156069. (void)pParse;
  156070. }
  156071. break;
  156072. case 16: /* expr */
  156073. case 17: /* cnearset */
  156074. case 18: /* exprlist */
  156075. {
  156076. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
  156077. }
  156078. break;
  156079. case 19: /* nearset */
  156080. case 22: /* nearphrases */
  156081. {
  156082. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
  156083. }
  156084. break;
  156085. case 20: /* colset */
  156086. case 21: /* colsetlist */
  156087. {
  156088. sqlite3_free((fts5yypminor->fts5yy3));
  156089. }
  156090. break;
  156091. case 23: /* phrase */
  156092. {
  156093. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
  156094. }
  156095. break;
  156096. default: break; /* If no destructor action specified: do nothing */
  156097. }
  156098. }
  156099. /*
  156100. ** Pop the parser's stack once.
  156101. **
  156102. ** If there is a destructor routine associated with the token which
  156103. ** is popped from the stack, then call it.
  156104. **
  156105. ** Return the major token number for the symbol popped.
  156106. */
  156107. static int fts5yy_pop_parser_stack(fts5yyParser *pParser){
  156108. fts5YYCODETYPE fts5yymajor;
  156109. fts5yyStackEntry *fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx];
  156110. /* There is no mechanism by which the parser stack can be popped below
  156111. ** empty in SQLite. */
  156112. assert( pParser->fts5yyidx>=0 );
  156113. #ifndef NDEBUG
  156114. if( fts5yyTraceFILE && pParser->fts5yyidx>=0 ){
  156115. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  156116. fts5yyTracePrompt,
  156117. fts5yyTokenName[fts5yytos->major]);
  156118. }
  156119. #endif
  156120. fts5yymajor = fts5yytos->major;
  156121. fts5yy_destructor(pParser, fts5yymajor, &fts5yytos->minor);
  156122. pParser->fts5yyidx--;
  156123. return fts5yymajor;
  156124. }
  156125. /*
  156126. ** Deallocate and destroy a parser. Destructors are all called for
  156127. ** all stack elements before shutting the parser down.
  156128. **
  156129. ** Inputs:
  156130. ** <ul>
  156131. ** <li> A pointer to the parser. This should be a pointer
  156132. ** obtained from sqlite3Fts5ParserAlloc.
  156133. ** <li> A pointer to a function used to reclaim memory obtained
  156134. ** from malloc.
  156135. ** </ul>
  156136. */
  156137. static void sqlite3Fts5ParserFree(
  156138. void *p, /* The parser to be deleted */
  156139. void (*freeProc)(void*) /* Function used to reclaim memory */
  156140. ){
  156141. fts5yyParser *pParser = (fts5yyParser*)p;
  156142. /* In SQLite, we never try to destroy a parser that was not successfully
  156143. ** created in the first place. */
  156144. if( NEVER(pParser==0) ) return;
  156145. while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
  156146. #if fts5YYSTACKDEPTH<=0
  156147. free(pParser->fts5yystack);
  156148. #endif
  156149. (*freeProc)((void*)pParser);
  156150. }
  156151. /*
  156152. ** Return the peak depth of the stack for a parser.
  156153. */
  156154. #ifdef fts5YYTRACKMAXSTACKDEPTH
  156155. static int sqlite3Fts5ParserStackPeak(void *p){
  156156. fts5yyParser *pParser = (fts5yyParser*)p;
  156157. return pParser->fts5yyidxMax;
  156158. }
  156159. #endif
  156160. /*
  156161. ** Find the appropriate action for a parser given the terminal
  156162. ** look-ahead token iLookAhead.
  156163. **
  156164. ** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
  156165. ** independent of the look-ahead. If it is, return the action, otherwise
  156166. ** return fts5YY_NO_ACTION.
  156167. */
  156168. static int fts5yy_find_shift_action(
  156169. fts5yyParser *pParser, /* The parser */
  156170. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  156171. ){
  156172. int i;
  156173. int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
  156174. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  156175. assert( stateno <= fts5YY_SHIFT_COUNT );
  156176. i = fts5yy_shift_ofst[stateno];
  156177. if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
  156178. assert( iLookAhead!=fts5YYNOCODE );
  156179. i += iLookAhead;
  156180. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  156181. if( iLookAhead>0 ){
  156182. #ifdef fts5YYFALLBACK
  156183. fts5YYCODETYPE iFallback; /* Fallback token */
  156184. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  156185. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  156186. #ifndef NDEBUG
  156187. if( fts5yyTraceFILE ){
  156188. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  156189. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  156190. }
  156191. #endif
  156192. return fts5yy_find_shift_action(pParser, iFallback);
  156193. }
  156194. #endif
  156195. #ifdef fts5YYWILDCARD
  156196. {
  156197. int j = i - iLookAhead + fts5YYWILDCARD;
  156198. if(
  156199. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  156200. j>=0 &&
  156201. #endif
  156202. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  156203. j<fts5YY_ACTTAB_COUNT &&
  156204. #endif
  156205. fts5yy_lookahead[j]==fts5YYWILDCARD
  156206. ){
  156207. #ifndef NDEBUG
  156208. if( fts5yyTraceFILE ){
  156209. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  156210. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[fts5YYWILDCARD]);
  156211. }
  156212. #endif /* NDEBUG */
  156213. return fts5yy_action[j];
  156214. }
  156215. }
  156216. #endif /* fts5YYWILDCARD */
  156217. }
  156218. return fts5yy_default[stateno];
  156219. }else{
  156220. return fts5yy_action[i];
  156221. }
  156222. }
  156223. /*
  156224. ** Find the appropriate action for a parser given the non-terminal
  156225. ** look-ahead token iLookAhead.
  156226. **
  156227. ** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
  156228. ** independent of the look-ahead. If it is, return the action, otherwise
  156229. ** return fts5YY_NO_ACTION.
  156230. */
  156231. static int fts5yy_find_reduce_action(
  156232. int stateno, /* Current state number */
  156233. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  156234. ){
  156235. int i;
  156236. #ifdef fts5YYERRORSYMBOL
  156237. if( stateno>fts5YY_REDUCE_COUNT ){
  156238. return fts5yy_default[stateno];
  156239. }
  156240. #else
  156241. assert( stateno<=fts5YY_REDUCE_COUNT );
  156242. #endif
  156243. i = fts5yy_reduce_ofst[stateno];
  156244. assert( i!=fts5YY_REDUCE_USE_DFLT );
  156245. assert( iLookAhead!=fts5YYNOCODE );
  156246. i += iLookAhead;
  156247. #ifdef fts5YYERRORSYMBOL
  156248. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  156249. return fts5yy_default[stateno];
  156250. }
  156251. #else
  156252. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  156253. assert( fts5yy_lookahead[i]==iLookAhead );
  156254. #endif
  156255. return fts5yy_action[i];
  156256. }
  156257. /*
  156258. ** The following routine is called if the stack overflows.
  156259. */
  156260. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser, fts5YYMINORTYPE *fts5yypMinor){
  156261. sqlite3Fts5ParserARG_FETCH;
  156262. fts5yypParser->fts5yyidx--;
  156263. #ifndef NDEBUG
  156264. if( fts5yyTraceFILE ){
  156265. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  156266. }
  156267. #endif
  156268. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  156269. /* Here code is inserted which will execute if the parser
  156270. ** stack every overflows */
  156271. assert( 0 );
  156272. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  156273. }
  156274. /*
  156275. ** Print tracing information for a SHIFT action
  156276. */
  156277. #ifndef NDEBUG
  156278. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  156279. if( fts5yyTraceFILE ){
  156280. int i;
  156281. if( fts5yyNewState<fts5YYNSTATE ){
  156282. fprintf(fts5yyTraceFILE,"%sShift %d\n",fts5yyTracePrompt,fts5yyNewState);
  156283. fprintf(fts5yyTraceFILE,"%sStack:",fts5yyTracePrompt);
  156284. for(i=1; i<=fts5yypParser->fts5yyidx; i++)
  156285. fprintf(fts5yyTraceFILE," %s",fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
  156286. fprintf(fts5yyTraceFILE,"\n");
  156287. }else{
  156288. fprintf(fts5yyTraceFILE,"%sShift *\n",fts5yyTracePrompt);
  156289. }
  156290. }
  156291. }
  156292. #else
  156293. # define fts5yyTraceShift(X,Y)
  156294. #endif
  156295. /*
  156296. ** Perform a shift action. Return the number of errors.
  156297. */
  156298. static void fts5yy_shift(
  156299. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  156300. int fts5yyNewState, /* The new state to shift in */
  156301. int fts5yyMajor, /* The major token to shift in */
  156302. fts5YYMINORTYPE *fts5yypMinor /* Pointer to the minor token to shift in */
  156303. ){
  156304. fts5yyStackEntry *fts5yytos;
  156305. fts5yypParser->fts5yyidx++;
  156306. #ifdef fts5YYTRACKMAXSTACKDEPTH
  156307. if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
  156308. fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
  156309. }
  156310. #endif
  156311. #if fts5YYSTACKDEPTH>0
  156312. if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
  156313. fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
  156314. return;
  156315. }
  156316. #else
  156317. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  156318. fts5yyGrowStack(fts5yypParser);
  156319. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  156320. fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
  156321. return;
  156322. }
  156323. }
  156324. #endif
  156325. fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  156326. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  156327. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  156328. fts5yytos->minor = *fts5yypMinor;
  156329. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  156330. }
  156331. /* The following table contains information about every rule that
  156332. ** is used during the reduce.
  156333. */
  156334. static const struct {
  156335. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  156336. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  156337. } fts5yyRuleInfo[] = {
  156338. { 15, 1 },
  156339. { 16, 3 },
  156340. { 16, 3 },
  156341. { 16, 3 },
  156342. { 16, 3 },
  156343. { 16, 1 },
  156344. { 18, 1 },
  156345. { 18, 2 },
  156346. { 17, 1 },
  156347. { 17, 3 },
  156348. { 20, 3 },
  156349. { 20, 1 },
  156350. { 21, 2 },
  156351. { 21, 1 },
  156352. { 19, 1 },
  156353. { 19, 5 },
  156354. { 22, 1 },
  156355. { 22, 2 },
  156356. { 24, 0 },
  156357. { 24, 2 },
  156358. { 23, 4 },
  156359. { 23, 2 },
  156360. { 25, 1 },
  156361. { 25, 0 },
  156362. };
  156363. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  156364. /*
  156365. ** Perform a reduce action and the shift that must immediately
  156366. ** follow the reduce.
  156367. */
  156368. static void fts5yy_reduce(
  156369. fts5yyParser *fts5yypParser, /* The parser */
  156370. int fts5yyruleno /* Number of the rule by which to reduce */
  156371. ){
  156372. int fts5yygoto; /* The next state */
  156373. int fts5yyact; /* The next action */
  156374. fts5YYMINORTYPE fts5yygotominor; /* The LHS of the rule reduced */
  156375. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  156376. int fts5yysize; /* Amount to pop the stack */
  156377. sqlite3Fts5ParserARG_FETCH;
  156378. fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  156379. #ifndef NDEBUG
  156380. if( fts5yyTraceFILE && fts5yyruleno>=0
  156381. && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  156382. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  156383. fprintf(fts5yyTraceFILE, "%sReduce [%s] -> state %d.\n", fts5yyTracePrompt,
  156384. fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
  156385. }
  156386. #endif /* NDEBUG */
  156387. /* Silence complaints from purify about fts5yygotominor being uninitialized
  156388. ** in some cases when it is copied into the stack after the following
  156389. ** switch. fts5yygotominor is uninitialized when a rule reduces that does
  156390. ** not set the value of its left-hand side nonterminal. Leaving the
  156391. ** value of the nonterminal uninitialized is utterly harmless as long
  156392. ** as the value is never used. So really the only thing this code
  156393. ** accomplishes is to quieten purify.
  156394. **
  156395. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  156396. ** without this code, their parser segfaults. I'm not sure what there
  156397. ** parser is doing to make this happen. This is the second bug report
  156398. ** from wireshark this week. Clearly they are stressing Lemon in ways
  156399. ** that it has not been previously stressed... (SQLite ticket #2172)
  156400. */
  156401. /*memset(&fts5yygotominor, 0, sizeof(fts5yygotominor));*/
  156402. fts5yygotominor = fts5yyzerominor;
  156403. switch( fts5yyruleno ){
  156404. /* Beginning here are the reduction cases. A typical example
  156405. ** follows:
  156406. ** case 0:
  156407. ** #line <lineno> <grammarfile>
  156408. ** { ... } // User supplied code
  156409. ** #line <lineno> <thisfile>
  156410. ** break;
  156411. */
  156412. case 0: /* input ::= expr */
  156413. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
  156414. break;
  156415. case 1: /* expr ::= expr AND expr */
  156416. {
  156417. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  156418. }
  156419. break;
  156420. case 2: /* expr ::= expr OR expr */
  156421. {
  156422. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  156423. }
  156424. break;
  156425. case 3: /* expr ::= expr NOT expr */
  156426. {
  156427. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  156428. }
  156429. break;
  156430. case 4: /* expr ::= LP expr RP */
  156431. {fts5yygotominor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
  156432. break;
  156433. case 5: /* expr ::= exprlist */
  156434. case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
  156435. {fts5yygotominor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
  156436. break;
  156437. case 7: /* exprlist ::= exprlist cnearset */
  156438. {
  156439. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  156440. }
  156441. break;
  156442. case 8: /* cnearset ::= nearset */
  156443. {
  156444. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  156445. }
  156446. break;
  156447. case 9: /* cnearset ::= colset COLON nearset */
  156448. {
  156449. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
  156450. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  156451. }
  156452. break;
  156453. case 10: /* colset ::= LCP colsetlist RCP */
  156454. { fts5yygotominor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
  156455. break;
  156456. case 11: /* colset ::= STRING */
  156457. {
  156458. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  156459. }
  156460. break;
  156461. case 12: /* colsetlist ::= colsetlist STRING */
  156462. {
  156463. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
  156464. break;
  156465. case 13: /* colsetlist ::= STRING */
  156466. {
  156467. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  156468. }
  156469. break;
  156470. case 14: /* nearset ::= phrase */
  156471. { fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
  156472. break;
  156473. case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  156474. {
  156475. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  156476. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
  156477. fts5yygotominor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
  156478. }
  156479. break;
  156480. case 16: /* nearphrases ::= phrase */
  156481. {
  156482. fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
  156483. }
  156484. break;
  156485. case 17: /* nearphrases ::= nearphrases phrase */
  156486. {
  156487. fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
  156488. }
  156489. break;
  156490. case 18: /* neardist_opt ::= */
  156491. { fts5yygotominor.fts5yy0.p = 0; fts5yygotominor.fts5yy0.n = 0; }
  156492. break;
  156493. case 19: /* neardist_opt ::= COMMA STRING */
  156494. { fts5yygotominor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  156495. break;
  156496. case 20: /* phrase ::= phrase PLUS STRING star_opt */
  156497. {
  156498. fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  156499. }
  156500. break;
  156501. case 21: /* phrase ::= STRING star_opt */
  156502. {
  156503. fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  156504. }
  156505. break;
  156506. case 22: /* star_opt ::= STAR */
  156507. { fts5yygotominor.fts5yy20 = 1; }
  156508. break;
  156509. case 23: /* star_opt ::= */
  156510. { fts5yygotominor.fts5yy20 = 0; }
  156511. break;
  156512. default:
  156513. break;
  156514. };
  156515. assert( fts5yyruleno>=0 && fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  156516. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  156517. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  156518. fts5yypParser->fts5yyidx -= fts5yysize;
  156519. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  156520. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  156521. if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  156522. /* If the reduce action popped at least
  156523. ** one element off the stack, then we can push the new element back
  156524. ** onto the stack here, and skip the stack overflow test in fts5yy_shift().
  156525. ** That gives a significant speed improvement. */
  156526. if( fts5yysize ){
  156527. fts5yypParser->fts5yyidx++;
  156528. fts5yymsp -= fts5yysize-1;
  156529. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  156530. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  156531. fts5yymsp->minor = fts5yygotominor;
  156532. fts5yyTraceShift(fts5yypParser, fts5yyact);
  156533. }else{
  156534. fts5yy_shift(fts5yypParser,fts5yyact,fts5yygoto,&fts5yygotominor);
  156535. }
  156536. }else{
  156537. assert( fts5yyact == fts5YY_ACCEPT_ACTION );
  156538. fts5yy_accept(fts5yypParser);
  156539. }
  156540. }
  156541. /*
  156542. ** The following code executes when the parse fails
  156543. */
  156544. #ifndef fts5YYNOERRORRECOVERY
  156545. static void fts5yy_parse_failed(
  156546. fts5yyParser *fts5yypParser /* The parser */
  156547. ){
  156548. sqlite3Fts5ParserARG_FETCH;
  156549. #ifndef NDEBUG
  156550. if( fts5yyTraceFILE ){
  156551. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  156552. }
  156553. #endif
  156554. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  156555. /* Here code is inserted which will be executed whenever the
  156556. ** parser fails */
  156557. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  156558. }
  156559. #endif /* fts5YYNOERRORRECOVERY */
  156560. /*
  156561. ** The following code executes when a syntax error first occurs.
  156562. */
  156563. static void fts5yy_syntax_error(
  156564. fts5yyParser *fts5yypParser, /* The parser */
  156565. int fts5yymajor, /* The major type of the error token */
  156566. fts5YYMINORTYPE fts5yyminor /* The minor type of the error token */
  156567. ){
  156568. sqlite3Fts5ParserARG_FETCH;
  156569. #define FTS5TOKEN (fts5yyminor.fts5yy0)
  156570. sqlite3Fts5ParseError(
  156571. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  156572. );
  156573. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  156574. }
  156575. /*
  156576. ** The following is executed when the parser accepts
  156577. */
  156578. static void fts5yy_accept(
  156579. fts5yyParser *fts5yypParser /* The parser */
  156580. ){
  156581. sqlite3Fts5ParserARG_FETCH;
  156582. #ifndef NDEBUG
  156583. if( fts5yyTraceFILE ){
  156584. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  156585. }
  156586. #endif
  156587. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  156588. /* Here code is inserted which will be executed whenever the
  156589. ** parser accepts */
  156590. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  156591. }
  156592. /* The main parser program.
  156593. ** The first argument is a pointer to a structure obtained from
  156594. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  156595. ** The second argument is the major token number. The third is
  156596. ** the minor token. The fourth optional argument is whatever the
  156597. ** user wants (and specified in the grammar) and is available for
  156598. ** use by the action routines.
  156599. **
  156600. ** Inputs:
  156601. ** <ul>
  156602. ** <li> A pointer to the parser (an opaque structure.)
  156603. ** <li> The major token number.
  156604. ** <li> The minor token number.
  156605. ** <li> An option argument of a grammar-specified type.
  156606. ** </ul>
  156607. **
  156608. ** Outputs:
  156609. ** None.
  156610. */
  156611. static void sqlite3Fts5Parser(
  156612. void *fts5yyp, /* The parser */
  156613. int fts5yymajor, /* The major token code number */
  156614. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  156615. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  156616. ){
  156617. fts5YYMINORTYPE fts5yyminorunion;
  156618. int fts5yyact; /* The parser action. */
  156619. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  156620. int fts5yyendofinput; /* True if we are at the end of input */
  156621. #endif
  156622. #ifdef fts5YYERRORSYMBOL
  156623. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  156624. #endif
  156625. fts5yyParser *fts5yypParser; /* The parser */
  156626. /* (re)initialize the parser, if necessary */
  156627. fts5yypParser = (fts5yyParser*)fts5yyp;
  156628. if( fts5yypParser->fts5yyidx<0 ){
  156629. #if fts5YYSTACKDEPTH<=0
  156630. if( fts5yypParser->fts5yystksz <=0 ){
  156631. /*memset(&fts5yyminorunion, 0, sizeof(fts5yyminorunion));*/
  156632. fts5yyminorunion = fts5yyzerominor;
  156633. fts5yyStackOverflow(fts5yypParser, &fts5yyminorunion);
  156634. return;
  156635. }
  156636. #endif
  156637. fts5yypParser->fts5yyidx = 0;
  156638. fts5yypParser->fts5yyerrcnt = -1;
  156639. fts5yypParser->fts5yystack[0].stateno = 0;
  156640. fts5yypParser->fts5yystack[0].major = 0;
  156641. }
  156642. fts5yyminorunion.fts5yy0 = fts5yyminor;
  156643. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  156644. fts5yyendofinput = (fts5yymajor==0);
  156645. #endif
  156646. sqlite3Fts5ParserARG_STORE;
  156647. #ifndef NDEBUG
  156648. if( fts5yyTraceFILE ){
  156649. fprintf(fts5yyTraceFILE,"%sInput %s\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  156650. }
  156651. #endif
  156652. do{
  156653. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  156654. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  156655. if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  156656. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,&fts5yyminorunion);
  156657. fts5yypParser->fts5yyerrcnt--;
  156658. fts5yymajor = fts5YYNOCODE;
  156659. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  156660. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  156661. }else{
  156662. assert( fts5yyact == fts5YY_ERROR_ACTION );
  156663. #ifdef fts5YYERRORSYMBOL
  156664. int fts5yymx;
  156665. #endif
  156666. #ifndef NDEBUG
  156667. if( fts5yyTraceFILE ){
  156668. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  156669. }
  156670. #endif
  156671. #ifdef fts5YYERRORSYMBOL
  156672. /* A syntax error has occurred.
  156673. ** The response to an error depends upon whether or not the
  156674. ** grammar defines an error token "ERROR".
  156675. **
  156676. ** This is what we do if the grammar does define ERROR:
  156677. **
  156678. ** * Call the %syntax_error function.
  156679. **
  156680. ** * Begin popping the stack until we enter a state where
  156681. ** it is legal to shift the error symbol, then shift
  156682. ** the error symbol.
  156683. **
  156684. ** * Set the error count to three.
  156685. **
  156686. ** * Begin accepting and shifting new tokens. No new error
  156687. ** processing will occur until three tokens have been
  156688. ** shifted successfully.
  156689. **
  156690. */
  156691. if( fts5yypParser->fts5yyerrcnt<0 ){
  156692. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  156693. }
  156694. fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
  156695. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  156696. #ifndef NDEBUG
  156697. if( fts5yyTraceFILE ){
  156698. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  156699. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  156700. }
  156701. #endif
  156702. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  156703. fts5yymajor = fts5YYNOCODE;
  156704. }else{
  156705. while(
  156706. fts5yypParser->fts5yyidx >= 0 &&
  156707. fts5yymx != fts5YYERRORSYMBOL &&
  156708. (fts5yyact = fts5yy_find_reduce_action(
  156709. fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
  156710. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  156711. ){
  156712. fts5yy_pop_parser_stack(fts5yypParser);
  156713. }
  156714. if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
  156715. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  156716. fts5yy_parse_failed(fts5yypParser);
  156717. fts5yymajor = fts5YYNOCODE;
  156718. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  156719. fts5YYMINORTYPE u2;
  156720. u2.fts5YYERRSYMDT = 0;
  156721. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,&u2);
  156722. }
  156723. }
  156724. fts5yypParser->fts5yyerrcnt = 3;
  156725. fts5yyerrorhit = 1;
  156726. #elif defined(fts5YYNOERRORRECOVERY)
  156727. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  156728. ** do any kind of error recovery. Instead, simply invoke the syntax
  156729. ** error routine and continue going as if nothing had happened.
  156730. **
  156731. ** Applications can set this macro (for example inside %include) if
  156732. ** they intend to abandon the parse upon the first syntax error seen.
  156733. */
  156734. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  156735. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  156736. fts5yymajor = fts5YYNOCODE;
  156737. #else /* fts5YYERRORSYMBOL is not defined */
  156738. /* This is what we do if the grammar does not define ERROR:
  156739. **
  156740. ** * Report an error message, and throw away the input token.
  156741. **
  156742. ** * If the input token is $, then fail the parse.
  156743. **
  156744. ** As before, subsequent error messages are suppressed until
  156745. ** three input tokens have been successfully shifted.
  156746. */
  156747. if( fts5yypParser->fts5yyerrcnt<=0 ){
  156748. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  156749. }
  156750. fts5yypParser->fts5yyerrcnt = 3;
  156751. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  156752. if( fts5yyendofinput ){
  156753. fts5yy_parse_failed(fts5yypParser);
  156754. }
  156755. fts5yymajor = fts5YYNOCODE;
  156756. #endif
  156757. }
  156758. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
  156759. #ifndef NDEBUG
  156760. if( fts5yyTraceFILE ){
  156761. fprintf(fts5yyTraceFILE,"%sReturn\n",fts5yyTracePrompt);
  156762. }
  156763. #endif
  156764. return;
  156765. }
  156766. /*
  156767. ** 2014 May 31
  156768. **
  156769. ** The author disclaims copyright to this source code. In place of
  156770. ** a legal notice, here is a blessing:
  156771. **
  156772. ** May you do good and not evil.
  156773. ** May you find forgiveness for yourself and forgive others.
  156774. ** May you share freely, never taking more than you give.
  156775. **
  156776. ******************************************************************************
  156777. */
  156778. #include <math.h> /* amalgamator: keep */
  156779. /*
  156780. ** Object used to iterate through all "coalesced phrase instances" in
  156781. ** a single column of the current row. If the phrase instances in the
  156782. ** column being considered do not overlap, this object simply iterates
  156783. ** through them. Or, if they do overlap (share one or more tokens in
  156784. ** common), each set of overlapping instances is treated as a single
  156785. ** match. See documentation for the highlight() auxiliary function for
  156786. ** details.
  156787. **
  156788. ** Usage is:
  156789. **
  156790. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  156791. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  156792. ** rc = fts5CInstIterNext(&iter)
  156793. ** ){
  156794. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  156795. ** }
  156796. **
  156797. */
  156798. typedef struct CInstIter CInstIter;
  156799. struct CInstIter {
  156800. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  156801. Fts5Context *pFts; /* First arg to pass to pApi functions */
  156802. int iCol; /* Column to search */
  156803. int iInst; /* Next phrase instance index */
  156804. int nInst; /* Total number of phrase instances */
  156805. /* Output variables */
  156806. int iStart; /* First token in coalesced phrase instance */
  156807. int iEnd; /* Last token in coalesced phrase instance */
  156808. };
  156809. /*
  156810. ** Advance the iterator to the next coalesced phrase instance. Return
  156811. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  156812. */
  156813. static int fts5CInstIterNext(CInstIter *pIter){
  156814. int rc = SQLITE_OK;
  156815. pIter->iStart = -1;
  156816. pIter->iEnd = -1;
  156817. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  156818. int ip; int ic; int io;
  156819. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  156820. if( rc==SQLITE_OK ){
  156821. if( ic==pIter->iCol ){
  156822. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  156823. if( pIter->iStart<0 ){
  156824. pIter->iStart = io;
  156825. pIter->iEnd = iEnd;
  156826. }else if( io<=pIter->iEnd ){
  156827. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  156828. }else{
  156829. break;
  156830. }
  156831. }
  156832. pIter->iInst++;
  156833. }
  156834. }
  156835. return rc;
  156836. }
  156837. /*
  156838. ** Initialize the iterator object indicated by the final parameter to
  156839. ** iterate through coalesced phrase instances in column iCol.
  156840. */
  156841. static int fts5CInstIterInit(
  156842. const Fts5ExtensionApi *pApi,
  156843. Fts5Context *pFts,
  156844. int iCol,
  156845. CInstIter *pIter
  156846. ){
  156847. int rc;
  156848. memset(pIter, 0, sizeof(CInstIter));
  156849. pIter->pApi = pApi;
  156850. pIter->pFts = pFts;
  156851. pIter->iCol = iCol;
  156852. rc = pApi->xInstCount(pFts, &pIter->nInst);
  156853. if( rc==SQLITE_OK ){
  156854. rc = fts5CInstIterNext(pIter);
  156855. }
  156856. return rc;
  156857. }
  156858. /*************************************************************************
  156859. ** Start of highlight() implementation.
  156860. */
  156861. typedef struct HighlightContext HighlightContext;
  156862. struct HighlightContext {
  156863. CInstIter iter; /* Coalesced Instance Iterator */
  156864. int iPos; /* Current token offset in zIn[] */
  156865. int iRangeStart; /* First token to include */
  156866. int iRangeEnd; /* If non-zero, last token to include */
  156867. const char *zOpen; /* Opening highlight */
  156868. const char *zClose; /* Closing highlight */
  156869. const char *zIn; /* Input text */
  156870. int nIn; /* Size of input text in bytes */
  156871. int iOff; /* Current offset within zIn[] */
  156872. char *zOut; /* Output value */
  156873. };
  156874. /*
  156875. ** Append text to the HighlightContext output string - p->zOut. Argument
  156876. ** z points to a buffer containing n bytes of text to append. If n is
  156877. ** negative, everything up until the first '\0' is appended to the output.
  156878. **
  156879. ** If *pRc is set to any value other than SQLITE_OK when this function is
  156880. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  156881. ** *pRc is set to an error code before returning.
  156882. */
  156883. static void fts5HighlightAppend(
  156884. int *pRc,
  156885. HighlightContext *p,
  156886. const char *z, int n
  156887. ){
  156888. if( *pRc==SQLITE_OK ){
  156889. if( n<0 ) n = strlen(z);
  156890. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  156891. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  156892. }
  156893. }
  156894. /*
  156895. ** Tokenizer callback used by implementation of highlight() function.
  156896. */
  156897. static int fts5HighlightCb(
  156898. void *pContext, /* Pointer to HighlightContext object */
  156899. int tflags, /* Mask of FTS5_TOKEN_* flags */
  156900. const char *pToken, /* Buffer containing token */
  156901. int nToken, /* Size of token in bytes */
  156902. int iStartOff, /* Start offset of token */
  156903. int iEndOff /* End offset of token */
  156904. ){
  156905. HighlightContext *p = (HighlightContext*)pContext;
  156906. int rc = SQLITE_OK;
  156907. int iPos;
  156908. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  156909. iPos = p->iPos++;
  156910. if( p->iRangeEnd>0 ){
  156911. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  156912. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  156913. }
  156914. if( iPos==p->iter.iStart ){
  156915. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  156916. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  156917. p->iOff = iStartOff;
  156918. }
  156919. if( iPos==p->iter.iEnd ){
  156920. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  156921. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  156922. }
  156923. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  156924. fts5HighlightAppend(&rc, p, p->zClose, -1);
  156925. p->iOff = iEndOff;
  156926. if( rc==SQLITE_OK ){
  156927. rc = fts5CInstIterNext(&p->iter);
  156928. }
  156929. }
  156930. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  156931. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  156932. p->iOff = iEndOff;
  156933. if( iPos<p->iter.iEnd ){
  156934. fts5HighlightAppend(&rc, p, p->zClose, -1);
  156935. }
  156936. }
  156937. return rc;
  156938. }
  156939. /*
  156940. ** Implementation of highlight() function.
  156941. */
  156942. static void fts5HighlightFunction(
  156943. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  156944. Fts5Context *pFts, /* First arg to pass to pApi functions */
  156945. sqlite3_context *pCtx, /* Context for returning result/error */
  156946. int nVal, /* Number of values in apVal[] array */
  156947. sqlite3_value **apVal /* Array of trailing arguments */
  156948. ){
  156949. HighlightContext ctx;
  156950. int rc;
  156951. int iCol;
  156952. if( nVal!=3 ){
  156953. const char *zErr = "wrong number of arguments to function highlight()";
  156954. sqlite3_result_error(pCtx, zErr, -1);
  156955. return;
  156956. }
  156957. iCol = sqlite3_value_int(apVal[0]);
  156958. memset(&ctx, 0, sizeof(HighlightContext));
  156959. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  156960. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  156961. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  156962. if( ctx.zIn ){
  156963. if( rc==SQLITE_OK ){
  156964. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  156965. }
  156966. if( rc==SQLITE_OK ){
  156967. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  156968. }
  156969. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  156970. if( rc==SQLITE_OK ){
  156971. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  156972. }
  156973. sqlite3_free(ctx.zOut);
  156974. }
  156975. if( rc!=SQLITE_OK ){
  156976. sqlite3_result_error_code(pCtx, rc);
  156977. }
  156978. }
  156979. /*
  156980. ** End of highlight() implementation.
  156981. **************************************************************************/
  156982. /*
  156983. ** Implementation of snippet() function.
  156984. */
  156985. static void fts5SnippetFunction(
  156986. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  156987. Fts5Context *pFts, /* First arg to pass to pApi functions */
  156988. sqlite3_context *pCtx, /* Context for returning result/error */
  156989. int nVal, /* Number of values in apVal[] array */
  156990. sqlite3_value **apVal /* Array of trailing arguments */
  156991. ){
  156992. HighlightContext ctx;
  156993. int rc = SQLITE_OK; /* Return code */
  156994. int iCol; /* 1st argument to snippet() */
  156995. const char *zEllips; /* 4th argument to snippet() */
  156996. int nToken; /* 5th argument to snippet() */
  156997. int nInst = 0; /* Number of instance matches this row */
  156998. int i; /* Used to iterate through instances */
  156999. int nPhrase; /* Number of phrases in query */
  157000. unsigned char *aSeen; /* Array of "seen instance" flags */
  157001. int iBestCol; /* Column containing best snippet */
  157002. int iBestStart = 0; /* First token of best snippet */
  157003. int iBestLast; /* Last token of best snippet */
  157004. int nBestScore = 0; /* Score of best snippet */
  157005. int nColSize = 0; /* Total size of iBestCol in tokens */
  157006. if( nVal!=5 ){
  157007. const char *zErr = "wrong number of arguments to function snippet()";
  157008. sqlite3_result_error(pCtx, zErr, -1);
  157009. return;
  157010. }
  157011. memset(&ctx, 0, sizeof(HighlightContext));
  157012. iCol = sqlite3_value_int(apVal[0]);
  157013. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  157014. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  157015. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  157016. nToken = sqlite3_value_int(apVal[4]);
  157017. iBestLast = nToken-1;
  157018. iBestCol = (iCol>=0 ? iCol : 0);
  157019. nPhrase = pApi->xPhraseCount(pFts);
  157020. aSeen = sqlite3_malloc(nPhrase);
  157021. if( aSeen==0 ){
  157022. rc = SQLITE_NOMEM;
  157023. }
  157024. if( rc==SQLITE_OK ){
  157025. rc = pApi->xInstCount(pFts, &nInst);
  157026. }
  157027. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  157028. int ip, iSnippetCol, iStart;
  157029. memset(aSeen, 0, nPhrase);
  157030. rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
  157031. if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
  157032. int nScore = 1000;
  157033. int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
  157034. int j;
  157035. aSeen[ip] = 1;
  157036. for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
  157037. int ic; int io; int iFinal;
  157038. rc = pApi->xInst(pFts, j, &ip, &ic, &io);
  157039. iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
  157040. if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
  157041. nScore += aSeen[ip] ? 1000 : 1;
  157042. aSeen[ip] = 1;
  157043. if( iFinal>iLast ) iLast = iFinal;
  157044. }
  157045. }
  157046. if( rc==SQLITE_OK && nScore>nBestScore ){
  157047. iBestCol = iSnippetCol;
  157048. iBestStart = iStart;
  157049. iBestLast = iLast;
  157050. nBestScore = nScore;
  157051. }
  157052. }
  157053. }
  157054. if( rc==SQLITE_OK ){
  157055. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  157056. }
  157057. if( rc==SQLITE_OK ){
  157058. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  157059. }
  157060. if( ctx.zIn ){
  157061. if( rc==SQLITE_OK ){
  157062. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  157063. }
  157064. if( (iBestStart+nToken-1)>iBestLast ){
  157065. iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
  157066. }
  157067. if( iBestStart+nToken>nColSize ){
  157068. iBestStart = nColSize - nToken;
  157069. }
  157070. if( iBestStart<0 ) iBestStart = 0;
  157071. ctx.iRangeStart = iBestStart;
  157072. ctx.iRangeEnd = iBestStart + nToken - 1;
  157073. if( iBestStart>0 ){
  157074. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  157075. }
  157076. if( rc==SQLITE_OK ){
  157077. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  157078. }
  157079. if( ctx.iRangeEnd>=(nColSize-1) ){
  157080. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  157081. }else{
  157082. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  157083. }
  157084. if( rc==SQLITE_OK ){
  157085. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  157086. }else{
  157087. sqlite3_result_error_code(pCtx, rc);
  157088. }
  157089. sqlite3_free(ctx.zOut);
  157090. }
  157091. sqlite3_free(aSeen);
  157092. }
  157093. /************************************************************************/
  157094. /*
  157095. ** The first time the bm25() function is called for a query, an instance
  157096. ** of the following structure is allocated and populated.
  157097. */
  157098. typedef struct Fts5Bm25Data Fts5Bm25Data;
  157099. struct Fts5Bm25Data {
  157100. int nPhrase; /* Number of phrases in query */
  157101. double avgdl; /* Average number of tokens in each row */
  157102. double *aIDF; /* IDF for each phrase */
  157103. double *aFreq; /* Array used to calculate phrase freq. */
  157104. };
  157105. /*
  157106. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  157107. ** table matched by each individual phrase within the query.
  157108. */
  157109. static int fts5CountCb(
  157110. const Fts5ExtensionApi *pApi,
  157111. Fts5Context *pFts,
  157112. void *pUserData /* Pointer to sqlite3_int64 variable */
  157113. ){
  157114. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  157115. (*pn)++;
  157116. return SQLITE_OK;
  157117. }
  157118. /*
  157119. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  157120. ** If the object has not already been allocated, allocate and populate it
  157121. ** now.
  157122. */
  157123. static int fts5Bm25GetData(
  157124. const Fts5ExtensionApi *pApi,
  157125. Fts5Context *pFts,
  157126. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  157127. ){
  157128. int rc = SQLITE_OK; /* Return code */
  157129. Fts5Bm25Data *p; /* Object to return */
  157130. p = pApi->xGetAuxdata(pFts, 0);
  157131. if( p==0 ){
  157132. int nPhrase; /* Number of phrases in query */
  157133. sqlite3_int64 nRow = 0; /* Number of rows in table */
  157134. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  157135. int nByte; /* Bytes of space to allocate */
  157136. int i;
  157137. /* Allocate the Fts5Bm25Data object */
  157138. nPhrase = pApi->xPhraseCount(pFts);
  157139. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  157140. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  157141. if( p==0 ){
  157142. rc = SQLITE_NOMEM;
  157143. }else{
  157144. memset(p, 0, nByte);
  157145. p->nPhrase = nPhrase;
  157146. p->aIDF = (double*)&p[1];
  157147. p->aFreq = &p->aIDF[nPhrase];
  157148. }
  157149. /* Calculate the average document length for this FTS5 table */
  157150. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  157151. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  157152. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  157153. /* Calculate an IDF for each phrase in the query */
  157154. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  157155. sqlite3_int64 nHit = 0;
  157156. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  157157. if( rc==SQLITE_OK ){
  157158. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  157159. ** This is done using the standard BM25 formula as found on wikipedia:
  157160. **
  157161. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  157162. **
  157163. ** where "N" is the total number of documents in the set and nHit
  157164. ** is the number that contain at least one instance of the phrase
  157165. ** under consideration.
  157166. **
  157167. ** The problem with this is that if (N < 2*nHit), the IDF is
  157168. ** negative. Which is undesirable. So the mimimum allowable IDF is
  157169. ** (1e-6) - roughly the same as a term that appears in just over
  157170. ** half of set of 5,000,000 documents. */
  157171. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  157172. if( idf<=0.0 ) idf = 1e-6;
  157173. p->aIDF[i] = idf;
  157174. }
  157175. }
  157176. if( rc!=SQLITE_OK ){
  157177. sqlite3_free(p);
  157178. }else{
  157179. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  157180. }
  157181. if( rc!=SQLITE_OK ) p = 0;
  157182. }
  157183. *ppData = p;
  157184. return rc;
  157185. }
  157186. /*
  157187. ** Implementation of bm25() function.
  157188. */
  157189. static void fts5Bm25Function(
  157190. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  157191. Fts5Context *pFts, /* First arg to pass to pApi functions */
  157192. sqlite3_context *pCtx, /* Context for returning result/error */
  157193. int nVal, /* Number of values in apVal[] array */
  157194. sqlite3_value **apVal /* Array of trailing arguments */
  157195. ){
  157196. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  157197. const double b = 0.75; /* Constant "b" from BM25 formula */
  157198. int rc = SQLITE_OK; /* Error code */
  157199. double score = 0.0; /* SQL function return value */
  157200. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  157201. int i; /* Iterator variable */
  157202. int nInst = 0; /* Value returned by xInstCount() */
  157203. double D = 0.0; /* Total number of tokens in row */
  157204. double *aFreq = 0; /* Array of phrase freq. for current row */
  157205. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  157206. ** for each phrase in the query for the current row. */
  157207. rc = fts5Bm25GetData(pApi, pFts, &pData);
  157208. if( rc==SQLITE_OK ){
  157209. aFreq = pData->aFreq;
  157210. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  157211. rc = pApi->xInstCount(pFts, &nInst);
  157212. }
  157213. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  157214. int ip; int ic; int io;
  157215. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  157216. if( rc==SQLITE_OK ){
  157217. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  157218. aFreq[ip] += w;
  157219. }
  157220. }
  157221. /* Figure out the total size of the current row in tokens. */
  157222. if( rc==SQLITE_OK ){
  157223. int nTok;
  157224. rc = pApi->xColumnSize(pFts, -1, &nTok);
  157225. D = (double)nTok;
  157226. }
  157227. /* Determine the BM25 score for the current row. */
  157228. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  157229. score += pData->aIDF[i] * (
  157230. ( aFreq[i] * (k1 + 1.0) ) /
  157231. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  157232. );
  157233. }
  157234. /* If no error has occurred, return the calculated score. Otherwise,
  157235. ** throw an SQL exception. */
  157236. if( rc==SQLITE_OK ){
  157237. sqlite3_result_double(pCtx, -1.0 * score);
  157238. }else{
  157239. sqlite3_result_error_code(pCtx, rc);
  157240. }
  157241. }
  157242. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  157243. struct Builtin {
  157244. const char *zFunc; /* Function name (nul-terminated) */
  157245. void *pUserData; /* User-data pointer */
  157246. fts5_extension_function xFunc;/* Callback function */
  157247. void (*xDestroy)(void*); /* Destructor function */
  157248. } aBuiltin [] = {
  157249. { "snippet", 0, fts5SnippetFunction, 0 },
  157250. { "highlight", 0, fts5HighlightFunction, 0 },
  157251. { "bm25", 0, fts5Bm25Function, 0 },
  157252. };
  157253. int rc = SQLITE_OK; /* Return code */
  157254. int i; /* To iterate through builtin functions */
  157255. for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
  157256. rc = pApi->xCreateFunction(pApi,
  157257. aBuiltin[i].zFunc,
  157258. aBuiltin[i].pUserData,
  157259. aBuiltin[i].xFunc,
  157260. aBuiltin[i].xDestroy
  157261. );
  157262. }
  157263. return rc;
  157264. }
  157265. /*
  157266. ** 2014 May 31
  157267. **
  157268. ** The author disclaims copyright to this source code. In place of
  157269. ** a legal notice, here is a blessing:
  157270. **
  157271. ** May you do good and not evil.
  157272. ** May you find forgiveness for yourself and forgive others.
  157273. ** May you share freely, never taking more than you give.
  157274. **
  157275. ******************************************************************************
  157276. */
  157277. static int sqlite3Fts5BufferGrow(int *pRc, Fts5Buffer *pBuf, int nByte){
  157278. if( (pBuf->n + nByte) > pBuf->nSpace ){
  157279. u8 *pNew;
  157280. int nNew = pBuf->nSpace ? pBuf->nSpace*2 : 64;
  157281. /* A no-op if an error has already occurred */
  157282. if( *pRc ) return 1;
  157283. while( nNew<(pBuf->n + nByte) ){
  157284. nNew = nNew * 2;
  157285. }
  157286. pNew = sqlite3_realloc(pBuf->p, nNew);
  157287. if( pNew==0 ){
  157288. *pRc = SQLITE_NOMEM;
  157289. return 1;
  157290. }else{
  157291. pBuf->nSpace = nNew;
  157292. pBuf->p = pNew;
  157293. }
  157294. }
  157295. return 0;
  157296. }
  157297. /*
  157298. ** Encode value iVal as an SQLite varint and append it to the buffer object
  157299. ** pBuf. If an OOM error occurs, set the error code in p.
  157300. */
  157301. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  157302. if( sqlite3Fts5BufferGrow(pRc, pBuf, 9) ) return;
  157303. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  157304. }
  157305. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  157306. aBuf[0] = (iVal>>24) & 0x00FF;
  157307. aBuf[1] = (iVal>>16) & 0x00FF;
  157308. aBuf[2] = (iVal>> 8) & 0x00FF;
  157309. aBuf[3] = (iVal>> 0) & 0x00FF;
  157310. }
  157311. static int sqlite3Fts5Get32(const u8 *aBuf){
  157312. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  157313. }
  157314. static void sqlite3Fts5BufferAppend32(int *pRc, Fts5Buffer *pBuf, int iVal){
  157315. if( sqlite3Fts5BufferGrow(pRc, pBuf, 4) ) return;
  157316. sqlite3Fts5Put32(&pBuf->p[pBuf->n], iVal);
  157317. pBuf->n += 4;
  157318. }
  157319. /*
  157320. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  157321. ** the error code in p. If an error has already occurred when this function
  157322. ** is called, it is a no-op.
  157323. */
  157324. static void sqlite3Fts5BufferAppendBlob(
  157325. int *pRc,
  157326. Fts5Buffer *pBuf,
  157327. int nData,
  157328. const u8 *pData
  157329. ){
  157330. assert( *pRc || nData>=0 );
  157331. if( sqlite3Fts5BufferGrow(pRc, pBuf, nData) ) return;
  157332. memcpy(&pBuf->p[pBuf->n], pData, nData);
  157333. pBuf->n += nData;
  157334. }
  157335. /*
  157336. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  157337. ** ensures that the byte following the buffer data is set to 0x00, even
  157338. ** though this byte is not included in the pBuf->n count.
  157339. */
  157340. static void sqlite3Fts5BufferAppendString(
  157341. int *pRc,
  157342. Fts5Buffer *pBuf,
  157343. const char *zStr
  157344. ){
  157345. int nStr = strlen(zStr);
  157346. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  157347. pBuf->n--;
  157348. }
  157349. /*
  157350. ** Argument zFmt is a printf() style format string. This function performs
  157351. ** the printf() style processing, then appends the results to buffer pBuf.
  157352. **
  157353. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  157354. ** following the buffer data is set to 0x00, even though this byte is not
  157355. ** included in the pBuf->n count.
  157356. */
  157357. static void sqlite3Fts5BufferAppendPrintf(
  157358. int *pRc,
  157359. Fts5Buffer *pBuf,
  157360. char *zFmt, ...
  157361. ){
  157362. if( *pRc==SQLITE_OK ){
  157363. char *zTmp;
  157364. va_list ap;
  157365. va_start(ap, zFmt);
  157366. zTmp = sqlite3_vmprintf(zFmt, ap);
  157367. va_end(ap);
  157368. if( zTmp==0 ){
  157369. *pRc = SQLITE_NOMEM;
  157370. }else{
  157371. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  157372. sqlite3_free(zTmp);
  157373. }
  157374. }
  157375. }
  157376. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  157377. char *zRet = 0;
  157378. if( *pRc==SQLITE_OK ){
  157379. va_list ap;
  157380. va_start(ap, zFmt);
  157381. zRet = sqlite3_vmprintf(zFmt, ap);
  157382. va_end(ap);
  157383. if( zRet==0 ){
  157384. *pRc = SQLITE_NOMEM;
  157385. }
  157386. }
  157387. return zRet;
  157388. }
  157389. /*
  157390. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  157391. */
  157392. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  157393. sqlite3_free(pBuf->p);
  157394. memset(pBuf, 0, sizeof(Fts5Buffer));
  157395. }
  157396. /*
  157397. ** Zero the contents of the buffer object. But do not free the associated
  157398. ** memory allocation.
  157399. */
  157400. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  157401. pBuf->n = 0;
  157402. }
  157403. /*
  157404. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  157405. ** the error code in p. If an error has already occurred when this function
  157406. ** is called, it is a no-op.
  157407. */
  157408. static void sqlite3Fts5BufferSet(
  157409. int *pRc,
  157410. Fts5Buffer *pBuf,
  157411. int nData,
  157412. const u8 *pData
  157413. ){
  157414. pBuf->n = 0;
  157415. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  157416. }
  157417. static int sqlite3Fts5PoslistNext64(
  157418. const u8 *a, int n, /* Buffer containing poslist */
  157419. int *pi, /* IN/OUT: Offset within a[] */
  157420. i64 *piOff /* IN/OUT: Current offset */
  157421. ){
  157422. int i = *pi;
  157423. if( i>=n ){
  157424. /* EOF */
  157425. *piOff = -1;
  157426. return 1;
  157427. }else{
  157428. i64 iOff = *piOff;
  157429. int iVal;
  157430. fts5FastGetVarint32(a, i, iVal);
  157431. if( iVal==1 ){
  157432. fts5FastGetVarint32(a, i, iVal);
  157433. iOff = ((i64)iVal) << 32;
  157434. fts5FastGetVarint32(a, i, iVal);
  157435. }
  157436. *piOff = iOff + (iVal-2);
  157437. *pi = i;
  157438. return 0;
  157439. }
  157440. }
  157441. /*
  157442. ** Advance the iterator object passed as the only argument. Return true
  157443. ** if the iterator reaches EOF, or false otherwise.
  157444. */
  157445. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  157446. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  157447. pIter->bEof = 1;
  157448. }
  157449. return pIter->bEof;
  157450. }
  157451. static int sqlite3Fts5PoslistReaderInit(
  157452. const u8 *a, int n, /* Poslist buffer to iterate through */
  157453. Fts5PoslistReader *pIter /* Iterator object to initialize */
  157454. ){
  157455. memset(pIter, 0, sizeof(*pIter));
  157456. pIter->a = a;
  157457. pIter->n = n;
  157458. sqlite3Fts5PoslistReaderNext(pIter);
  157459. return pIter->bEof;
  157460. }
  157461. static int sqlite3Fts5PoslistWriterAppend(
  157462. Fts5Buffer *pBuf,
  157463. Fts5PoslistWriter *pWriter,
  157464. i64 iPos
  157465. ){
  157466. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  157467. int rc = SQLITE_OK;
  157468. if( 0==sqlite3Fts5BufferGrow(&rc, pBuf, 5+5+5) ){
  157469. if( (iPos & colmask) != (pWriter->iPrev & colmask) ){
  157470. pBuf->p[pBuf->n++] = 1;
  157471. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  157472. pWriter->iPrev = (iPos & colmask);
  157473. }
  157474. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-pWriter->iPrev)+2);
  157475. pWriter->iPrev = iPos;
  157476. }
  157477. return rc;
  157478. }
  157479. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  157480. void *pRet = 0;
  157481. if( *pRc==SQLITE_OK ){
  157482. pRet = sqlite3_malloc(nByte);
  157483. if( pRet==0 && nByte>0 ){
  157484. *pRc = SQLITE_NOMEM;
  157485. }else{
  157486. memset(pRet, 0, nByte);
  157487. }
  157488. }
  157489. return pRet;
  157490. }
  157491. /*
  157492. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  157493. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  157494. ** the length of the string is determined using strlen().
  157495. **
  157496. ** It is the responsibility of the caller to eventually free the returned
  157497. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  157498. */
  157499. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  157500. char *zRet = 0;
  157501. if( *pRc==SQLITE_OK ){
  157502. if( nIn<0 ){
  157503. nIn = strlen(pIn);
  157504. }
  157505. zRet = (char*)sqlite3_malloc(nIn+1);
  157506. if( zRet ){
  157507. memcpy(zRet, pIn, nIn);
  157508. zRet[nIn] = '\0';
  157509. }else{
  157510. *pRc = SQLITE_NOMEM;
  157511. }
  157512. }
  157513. return zRet;
  157514. }
  157515. /*
  157516. ** Return true if character 't' may be part of an FTS5 bareword, or false
  157517. ** otherwise. Characters that may be part of barewords:
  157518. **
  157519. ** * All non-ASCII characters,
  157520. ** * The 52 upper and lower case ASCII characters, and
  157521. ** * The 10 integer ASCII characters.
  157522. ** * The underscore character "_" (0x5F).
  157523. ** * The unicode "subsitute" character (0x1A).
  157524. */
  157525. static int sqlite3Fts5IsBareword(char t){
  157526. u8 aBareword[128] = {
  157527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  157528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  157529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  157530. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  157531. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  157532. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  157533. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  157534. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  157535. };
  157536. return (t & 0x80) || aBareword[(int)t];
  157537. }
  157538. /*
  157539. ** 2014 Jun 09
  157540. **
  157541. ** The author disclaims copyright to this source code. In place of
  157542. ** a legal notice, here is a blessing:
  157543. **
  157544. ** May you do good and not evil.
  157545. ** May you find forgiveness for yourself and forgive others.
  157546. ** May you share freely, never taking more than you give.
  157547. **
  157548. ******************************************************************************
  157549. **
  157550. ** This is an SQLite module implementing full-text search.
  157551. */
  157552. #define FTS5_DEFAULT_PAGE_SIZE 4050
  157553. #define FTS5_DEFAULT_AUTOMERGE 4
  157554. #define FTS5_DEFAULT_CRISISMERGE 16
  157555. /* Maximum allowed page size */
  157556. #define FTS5_MAX_PAGE_SIZE (128*1024)
  157557. static int fts5_iswhitespace(char x){
  157558. return (x==' ');
  157559. }
  157560. static int fts5_isopenquote(char x){
  157561. return (x=='"' || x=='\'' || x=='[' || x=='`');
  157562. }
  157563. /*
  157564. ** Argument pIn points to a character that is part of a nul-terminated
  157565. ** string. Return a pointer to the first character following *pIn in
  157566. ** the string that is not a white-space character.
  157567. */
  157568. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  157569. const char *p = pIn;
  157570. if( p ){
  157571. while( fts5_iswhitespace(*p) ){ p++; }
  157572. }
  157573. return p;
  157574. }
  157575. /*
  157576. ** Argument pIn points to a character that is part of a nul-terminated
  157577. ** string. Return a pointer to the first character following *pIn in
  157578. ** the string that is not a "bareword" character.
  157579. */
  157580. static const char *fts5ConfigSkipBareword(const char *pIn){
  157581. const char *p = pIn;
  157582. while ( sqlite3Fts5IsBareword(*p) ) p++;
  157583. if( p==pIn ) p = 0;
  157584. return p;
  157585. }
  157586. static int fts5_isdigit(char a){
  157587. return (a>='0' && a<='9');
  157588. }
  157589. static const char *fts5ConfigSkipLiteral(const char *pIn){
  157590. const char *p = pIn;
  157591. switch( *p ){
  157592. case 'n': case 'N':
  157593. if( sqlite3_strnicmp("null", p, 4)==0 ){
  157594. p = &p[4];
  157595. }else{
  157596. p = 0;
  157597. }
  157598. break;
  157599. case 'x': case 'X':
  157600. p++;
  157601. if( *p=='\'' ){
  157602. p++;
  157603. while( (*p>='a' && *p<='f')
  157604. || (*p>='A' && *p<='F')
  157605. || (*p>='0' && *p<='9')
  157606. ){
  157607. p++;
  157608. }
  157609. if( *p=='\'' && 0==((p-pIn)%2) ){
  157610. p++;
  157611. }else{
  157612. p = 0;
  157613. }
  157614. }else{
  157615. p = 0;
  157616. }
  157617. break;
  157618. case '\'':
  157619. p++;
  157620. while( p ){
  157621. if( *p=='\'' ){
  157622. p++;
  157623. if( *p!='\'' ) break;
  157624. }
  157625. p++;
  157626. if( *p==0 ) p = 0;
  157627. }
  157628. break;
  157629. default:
  157630. /* maybe a number */
  157631. if( *p=='+' || *p=='-' ) p++;
  157632. while( fts5_isdigit(*p) ) p++;
  157633. /* At this point, if the literal was an integer, the parse is
  157634. ** finished. Or, if it is a floating point value, it may continue
  157635. ** with either a decimal point or an 'E' character. */
  157636. if( *p=='.' && fts5_isdigit(p[1]) ){
  157637. p += 2;
  157638. while( fts5_isdigit(*p) ) p++;
  157639. }
  157640. if( p==pIn ) p = 0;
  157641. break;
  157642. }
  157643. return p;
  157644. }
  157645. /*
  157646. ** The first character of the string pointed to by argument z is guaranteed
  157647. ** to be an open-quote character (see function fts5_isopenquote()).
  157648. **
  157649. ** This function searches for the corresponding close-quote character within
  157650. ** the string and, if found, dequotes the string in place and adds a new
  157651. ** nul-terminator byte.
  157652. **
  157653. ** If the close-quote is found, the value returned is the byte offset of
  157654. ** the character immediately following it. Or, if the close-quote is not
  157655. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  157656. ** undefined state.
  157657. */
  157658. static int fts5Dequote(char *z){
  157659. char q;
  157660. int iIn = 1;
  157661. int iOut = 0;
  157662. q = z[0];
  157663. /* Set stack variable q to the close-quote character */
  157664. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  157665. if( q=='[' ) q = ']';
  157666. while( ALWAYS(z[iIn]) ){
  157667. if( z[iIn]==q ){
  157668. if( z[iIn+1]!=q ){
  157669. /* Character iIn was the close quote. */
  157670. iIn++;
  157671. break;
  157672. }else{
  157673. /* Character iIn and iIn+1 form an escaped quote character. Skip
  157674. ** the input cursor past both and copy a single quote character
  157675. ** to the output buffer. */
  157676. iIn += 2;
  157677. z[iOut++] = q;
  157678. }
  157679. }else{
  157680. z[iOut++] = z[iIn++];
  157681. }
  157682. }
  157683. z[iOut] = '\0';
  157684. return iIn;
  157685. }
  157686. /*
  157687. ** Convert an SQL-style quoted string into a normal string by removing
  157688. ** the quote characters. The conversion is done in-place. If the
  157689. ** input does not begin with a quote character, then this routine
  157690. ** is a no-op.
  157691. **
  157692. ** Examples:
  157693. **
  157694. ** "abc" becomes abc
  157695. ** 'xyz' becomes xyz
  157696. ** [pqr] becomes pqr
  157697. ** `mno` becomes mno
  157698. */
  157699. static void sqlite3Fts5Dequote(char *z){
  157700. char quote; /* Quote character (if any ) */
  157701. assert( 0==fts5_iswhitespace(z[0]) );
  157702. quote = z[0];
  157703. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  157704. fts5Dequote(z);
  157705. }
  157706. }
  157707. /*
  157708. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  157709. ** configuration object pConfig as appropriate.
  157710. **
  157711. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  157712. ** an error occurs, an SQLite error code is returned and an error message
  157713. ** may be left in *pzErr. It is the responsibility of the caller to
  157714. ** eventually free any such error message using sqlite3_free().
  157715. */
  157716. static int fts5ConfigParseSpecial(
  157717. Fts5Global *pGlobal,
  157718. Fts5Config *pConfig, /* Configuration object to update */
  157719. const char *zCmd, /* Special command to parse */
  157720. const char *zArg, /* Argument to parse */
  157721. char **pzErr /* OUT: Error message */
  157722. ){
  157723. int rc = SQLITE_OK;
  157724. int nCmd = strlen(zCmd);
  157725. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  157726. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  157727. const char *p;
  157728. if( pConfig->aPrefix ){
  157729. *pzErr = sqlite3_mprintf("multiple prefix=... directives");
  157730. rc = SQLITE_ERROR;
  157731. }else{
  157732. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  157733. }
  157734. p = zArg;
  157735. while( rc==SQLITE_OK && p[0] ){
  157736. int nPre = 0;
  157737. while( p[0]==' ' ) p++;
  157738. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  157739. nPre = nPre*10 + (p[0] - '0');
  157740. p++;
  157741. }
  157742. while( p[0]==' ' ) p++;
  157743. if( p[0]==',' ){
  157744. p++;
  157745. }else if( p[0] ){
  157746. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  157747. rc = SQLITE_ERROR;
  157748. }
  157749. if( rc==SQLITE_OK && (nPre==0 || nPre>=1000) ){
  157750. *pzErr = sqlite3_mprintf("prefix length out of range: %d", nPre);
  157751. rc = SQLITE_ERROR;
  157752. }
  157753. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  157754. pConfig->nPrefix++;
  157755. }
  157756. return rc;
  157757. }
  157758. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  157759. const char *p = (const char*)zArg;
  157760. int nArg = strlen(zArg) + 1;
  157761. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  157762. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  157763. char *pSpace = pDel;
  157764. if( azArg && pSpace ){
  157765. if( pConfig->pTok ){
  157766. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  157767. rc = SQLITE_ERROR;
  157768. }else{
  157769. for(nArg=0; p && *p; nArg++){
  157770. const char *p2 = fts5ConfigSkipWhitespace(p);
  157771. if( *p2=='\'' ){
  157772. p = fts5ConfigSkipLiteral(p2);
  157773. }else{
  157774. p = fts5ConfigSkipBareword(p2);
  157775. }
  157776. if( p ){
  157777. memcpy(pSpace, p2, p-p2);
  157778. azArg[nArg] = pSpace;
  157779. sqlite3Fts5Dequote(pSpace);
  157780. pSpace += (p - p2) + 1;
  157781. p = fts5ConfigSkipWhitespace(p);
  157782. }
  157783. }
  157784. if( p==0 ){
  157785. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  157786. rc = SQLITE_ERROR;
  157787. }else{
  157788. rc = sqlite3Fts5GetTokenizer(pGlobal,
  157789. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  157790. pzErr
  157791. );
  157792. }
  157793. }
  157794. }
  157795. sqlite3_free(azArg);
  157796. sqlite3_free(pDel);
  157797. return rc;
  157798. }
  157799. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  157800. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  157801. *pzErr = sqlite3_mprintf("multiple content=... directives");
  157802. rc = SQLITE_ERROR;
  157803. }else{
  157804. if( zArg[0] ){
  157805. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  157806. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  157807. }else{
  157808. pConfig->eContent = FTS5_CONTENT_NONE;
  157809. }
  157810. }
  157811. return rc;
  157812. }
  157813. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  157814. if( pConfig->zContentRowid ){
  157815. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  157816. rc = SQLITE_ERROR;
  157817. }else{
  157818. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  157819. }
  157820. return rc;
  157821. }
  157822. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  157823. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  157824. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  157825. rc = SQLITE_ERROR;
  157826. }else{
  157827. pConfig->bColumnsize = (zArg[0]=='1');
  157828. }
  157829. return rc;
  157830. }
  157831. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  157832. return SQLITE_ERROR;
  157833. }
  157834. /*
  157835. ** Allocate an instance of the default tokenizer ("simple") at
  157836. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  157837. ** code if an error occurs.
  157838. */
  157839. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  157840. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  157841. return sqlite3Fts5GetTokenizer(
  157842. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  157843. );
  157844. }
  157845. /*
  157846. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  157847. ** Return a pointer to the character immediately following the last in
  157848. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  157849. ** to find close-quote character).
  157850. **
  157851. ** Before returning, set pzOut to point to a new buffer containing a
  157852. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  157853. ** quoted, *pbQuoted is also set to 1 before returning.
  157854. **
  157855. ** If *pRc is other than SQLITE_OK when this function is called, it is
  157856. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  157857. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  157858. ** set if a parse error (failed to find close quote) occurs.
  157859. */
  157860. static const char *fts5ConfigGobbleWord(
  157861. int *pRc, /* IN/OUT: Error code */
  157862. const char *zIn, /* Buffer to gobble string/bareword from */
  157863. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  157864. int *pbQuoted /* OUT: Set to true if dequoting required */
  157865. ){
  157866. const char *zRet = 0;
  157867. int nIn = strlen(zIn);
  157868. char *zOut = sqlite3_malloc(nIn+1);
  157869. assert( *pRc==SQLITE_OK );
  157870. *pbQuoted = 0;
  157871. *pzOut = 0;
  157872. if( zOut==0 ){
  157873. *pRc = SQLITE_NOMEM;
  157874. }else{
  157875. memcpy(zOut, zIn, nIn+1);
  157876. if( fts5_isopenquote(zOut[0]) ){
  157877. int ii = fts5Dequote(zOut);
  157878. zRet = &zIn[ii];
  157879. *pbQuoted = 1;
  157880. }else{
  157881. zRet = fts5ConfigSkipBareword(zIn);
  157882. zOut[zRet-zIn] = '\0';
  157883. }
  157884. }
  157885. if( zRet==0 ){
  157886. sqlite3_free(zOut);
  157887. }else{
  157888. *pzOut = zOut;
  157889. }
  157890. return zRet;
  157891. }
  157892. static int fts5ConfigParseColumn(
  157893. Fts5Config *p,
  157894. char *zCol,
  157895. char *zArg,
  157896. char **pzErr
  157897. ){
  157898. int rc = SQLITE_OK;
  157899. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  157900. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  157901. ){
  157902. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  157903. rc = SQLITE_ERROR;
  157904. }else if( zArg ){
  157905. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  157906. p->abUnindexed[p->nCol] = 1;
  157907. }else{
  157908. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  157909. rc = SQLITE_ERROR;
  157910. }
  157911. }
  157912. p->azCol[p->nCol++] = zCol;
  157913. return rc;
  157914. }
  157915. /*
  157916. ** Populate the Fts5Config.zContentExprlist string.
  157917. */
  157918. static int fts5ConfigMakeExprlist(Fts5Config *p){
  157919. int i;
  157920. int rc = SQLITE_OK;
  157921. Fts5Buffer buf = {0, 0, 0};
  157922. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  157923. if( p->eContent!=FTS5_CONTENT_NONE ){
  157924. for(i=0; i<p->nCol; i++){
  157925. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  157926. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  157927. }else{
  157928. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  157929. }
  157930. }
  157931. }
  157932. assert( p->zContentExprlist==0 );
  157933. p->zContentExprlist = (char*)buf.p;
  157934. return rc;
  157935. }
  157936. /*
  157937. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  157938. ** or xConnect method of the virtual table. This function attempts to
  157939. ** allocate an instance of Fts5Config containing the results of parsing
  157940. ** those arguments.
  157941. **
  157942. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  157943. ** new Fts5Config object. If an error occurs, an SQLite error code is
  157944. ** returned, *ppOut is set to NULL and an error message may be left in
  157945. ** *pzErr. It is the responsibility of the caller to eventually free any
  157946. ** such error message using sqlite3_free().
  157947. */
  157948. static int sqlite3Fts5ConfigParse(
  157949. Fts5Global *pGlobal,
  157950. sqlite3 *db,
  157951. int nArg, /* Number of arguments */
  157952. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  157953. Fts5Config **ppOut, /* OUT: Results of parse */
  157954. char **pzErr /* OUT: Error message */
  157955. ){
  157956. int rc = SQLITE_OK; /* Return code */
  157957. Fts5Config *pRet; /* New object to return */
  157958. int i;
  157959. int nByte;
  157960. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  157961. if( pRet==0 ) return SQLITE_NOMEM;
  157962. memset(pRet, 0, sizeof(Fts5Config));
  157963. pRet->db = db;
  157964. pRet->iCookie = -1;
  157965. nByte = nArg * (sizeof(char*) + sizeof(u8));
  157966. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  157967. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  157968. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  157969. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  157970. pRet->bColumnsize = 1;
  157971. #ifdef SQLITE_DEBUG
  157972. pRet->bPrefixIndex = 1;
  157973. #endif
  157974. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  157975. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  157976. rc = SQLITE_ERROR;
  157977. }
  157978. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  157979. const char *zOrig = azArg[i];
  157980. const char *z;
  157981. char *zOne = 0;
  157982. char *zTwo = 0;
  157983. int bOption = 0;
  157984. int bMustBeCol = 0;
  157985. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  157986. z = fts5ConfigSkipWhitespace(z);
  157987. if( z && *z=='=' ){
  157988. bOption = 1;
  157989. z++;
  157990. if( bMustBeCol ) z = 0;
  157991. }
  157992. z = fts5ConfigSkipWhitespace(z);
  157993. if( z && z[0] ){
  157994. int bDummy;
  157995. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  157996. if( z && z[0] ) z = 0;
  157997. }
  157998. if( rc==SQLITE_OK ){
  157999. if( z==0 ){
  158000. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  158001. rc = SQLITE_ERROR;
  158002. }else{
  158003. if( bOption ){
  158004. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  158005. }else{
  158006. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  158007. zOne = 0;
  158008. }
  158009. }
  158010. }
  158011. sqlite3_free(zOne);
  158012. sqlite3_free(zTwo);
  158013. }
  158014. /* If a tokenizer= option was successfully parsed, the tokenizer has
  158015. ** already been allocated. Otherwise, allocate an instance of the default
  158016. ** tokenizer (unicode61) now. */
  158017. if( rc==SQLITE_OK && pRet->pTok==0 ){
  158018. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  158019. }
  158020. /* If no zContent option was specified, fill in the default values. */
  158021. if( rc==SQLITE_OK && pRet->zContent==0 ){
  158022. const char *zTail = 0;
  158023. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  158024. || pRet->eContent==FTS5_CONTENT_NONE
  158025. );
  158026. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  158027. zTail = "content";
  158028. }else if( pRet->bColumnsize ){
  158029. zTail = "docsize";
  158030. }
  158031. if( zTail ){
  158032. pRet->zContent = sqlite3Fts5Mprintf(
  158033. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  158034. );
  158035. }
  158036. }
  158037. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  158038. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  158039. }
  158040. /* Formulate the zContentExprlist text */
  158041. if( rc==SQLITE_OK ){
  158042. rc = fts5ConfigMakeExprlist(pRet);
  158043. }
  158044. if( rc!=SQLITE_OK ){
  158045. sqlite3Fts5ConfigFree(pRet);
  158046. *ppOut = 0;
  158047. }
  158048. return rc;
  158049. }
  158050. /*
  158051. ** Free the configuration object passed as the only argument.
  158052. */
  158053. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  158054. if( pConfig ){
  158055. int i;
  158056. if( pConfig->pTok ){
  158057. pConfig->pTokApi->xDelete(pConfig->pTok);
  158058. }
  158059. sqlite3_free(pConfig->zDb);
  158060. sqlite3_free(pConfig->zName);
  158061. for(i=0; i<pConfig->nCol; i++){
  158062. sqlite3_free(pConfig->azCol[i]);
  158063. }
  158064. sqlite3_free(pConfig->azCol);
  158065. sqlite3_free(pConfig->aPrefix);
  158066. sqlite3_free(pConfig->zRank);
  158067. sqlite3_free(pConfig->zRankArgs);
  158068. sqlite3_free(pConfig->zContent);
  158069. sqlite3_free(pConfig->zContentRowid);
  158070. sqlite3_free(pConfig->zContentExprlist);
  158071. sqlite3_free(pConfig);
  158072. }
  158073. }
  158074. /*
  158075. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  158076. ** object passed as the only argument. Return SQLITE_OK if successful, or
  158077. ** an SQLite error code if an error occurs.
  158078. */
  158079. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  158080. int i;
  158081. int rc = SQLITE_OK;
  158082. char *zSql;
  158083. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  158084. for(i=0; zSql && i<pConfig->nCol; i++){
  158085. const char *zSep = (i==0?"":", ");
  158086. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  158087. }
  158088. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  158089. zSql, pConfig->zName, FTS5_RANK_NAME
  158090. );
  158091. assert( zSql || rc==SQLITE_NOMEM );
  158092. if( zSql ){
  158093. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  158094. sqlite3_free(zSql);
  158095. }
  158096. return rc;
  158097. }
  158098. /*
  158099. ** Tokenize the text passed via the second and third arguments.
  158100. **
  158101. ** The callback is invoked once for each token in the input text. The
  158102. ** arguments passed to it are, in order:
  158103. **
  158104. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  158105. ** const char *pToken // Pointer to buffer containing token
  158106. ** int nToken // Size of token in bytes
  158107. ** int iStart // Byte offset of start of token within input text
  158108. ** int iEnd // Byte offset of end of token within input text
  158109. ** int iPos // Position of token in input (first token is 0)
  158110. **
  158111. ** If the callback returns a non-zero value the tokenization is abandoned
  158112. ** and no further callbacks are issued.
  158113. **
  158114. ** This function returns SQLITE_OK if successful or an SQLite error code
  158115. ** if an error occurs. If the tokenization was abandoned early because
  158116. ** the callback returned SQLITE_DONE, this is not an error and this function
  158117. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  158118. ** because the callback returned another non-zero value, it is assumed
  158119. ** to be an SQLite error code and returned to the caller.
  158120. */
  158121. static int sqlite3Fts5Tokenize(
  158122. Fts5Config *pConfig, /* FTS5 Configuration object */
  158123. int flags, /* FTS5_TOKENIZE_* flags */
  158124. const char *pText, int nText, /* Text to tokenize */
  158125. void *pCtx, /* Context passed to xToken() */
  158126. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  158127. ){
  158128. if( pText==0 ) return SQLITE_OK;
  158129. return pConfig->pTokApi->xTokenize(
  158130. pConfig->pTok, pCtx, flags, pText, nText, xToken
  158131. );
  158132. }
  158133. /*
  158134. ** Argument pIn points to the first character in what is expected to be
  158135. ** a comma-separated list of SQL literals followed by a ')' character.
  158136. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  158137. ** NULL to indicate a parse error.
  158138. */
  158139. static const char *fts5ConfigSkipArgs(const char *pIn){
  158140. const char *p = pIn;
  158141. while( 1 ){
  158142. p = fts5ConfigSkipWhitespace(p);
  158143. p = fts5ConfigSkipLiteral(p);
  158144. p = fts5ConfigSkipWhitespace(p);
  158145. if( p==0 || *p==')' ) break;
  158146. if( *p!=',' ){
  158147. p = 0;
  158148. break;
  158149. }
  158150. p++;
  158151. }
  158152. return p;
  158153. }
  158154. /*
  158155. ** Parameter zIn contains a rank() function specification. The format of
  158156. ** this is:
  158157. **
  158158. ** + Bareword (function name)
  158159. ** + Open parenthesis - "("
  158160. ** + Zero or more SQL literals in a comma separated list
  158161. ** + Close parenthesis - ")"
  158162. */
  158163. static int sqlite3Fts5ConfigParseRank(
  158164. const char *zIn, /* Input string */
  158165. char **pzRank, /* OUT: Rank function name */
  158166. char **pzRankArgs /* OUT: Rank function arguments */
  158167. ){
  158168. const char *p = zIn;
  158169. const char *pRank;
  158170. char *zRank = 0;
  158171. char *zRankArgs = 0;
  158172. int rc = SQLITE_OK;
  158173. *pzRank = 0;
  158174. *pzRankArgs = 0;
  158175. p = fts5ConfigSkipWhitespace(p);
  158176. pRank = p;
  158177. p = fts5ConfigSkipBareword(p);
  158178. if( p ){
  158179. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  158180. if( zRank ) memcpy(zRank, pRank, p-pRank);
  158181. }else{
  158182. rc = SQLITE_ERROR;
  158183. }
  158184. if( rc==SQLITE_OK ){
  158185. p = fts5ConfigSkipWhitespace(p);
  158186. if( *p!='(' ) rc = SQLITE_ERROR;
  158187. p++;
  158188. }
  158189. if( rc==SQLITE_OK ){
  158190. const char *pArgs;
  158191. p = fts5ConfigSkipWhitespace(p);
  158192. pArgs = p;
  158193. if( *p!=')' ){
  158194. p = fts5ConfigSkipArgs(p);
  158195. if( p==0 ){
  158196. rc = SQLITE_ERROR;
  158197. }else{
  158198. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  158199. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  158200. }
  158201. }
  158202. }
  158203. if( rc!=SQLITE_OK ){
  158204. sqlite3_free(zRank);
  158205. assert( zRankArgs==0 );
  158206. }else{
  158207. *pzRank = zRank;
  158208. *pzRankArgs = zRankArgs;
  158209. }
  158210. return rc;
  158211. }
  158212. static int sqlite3Fts5ConfigSetValue(
  158213. Fts5Config *pConfig,
  158214. const char *zKey,
  158215. sqlite3_value *pVal,
  158216. int *pbBadkey
  158217. ){
  158218. int rc = SQLITE_OK;
  158219. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  158220. int pgsz = 0;
  158221. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  158222. pgsz = sqlite3_value_int(pVal);
  158223. }
  158224. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  158225. *pbBadkey = 1;
  158226. }else{
  158227. pConfig->pgsz = pgsz;
  158228. }
  158229. }
  158230. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  158231. int nAutomerge = -1;
  158232. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  158233. nAutomerge = sqlite3_value_int(pVal);
  158234. }
  158235. if( nAutomerge<0 || nAutomerge>64 ){
  158236. *pbBadkey = 1;
  158237. }else{
  158238. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  158239. pConfig->nAutomerge = nAutomerge;
  158240. }
  158241. }
  158242. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  158243. int nCrisisMerge = -1;
  158244. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  158245. nCrisisMerge = sqlite3_value_int(pVal);
  158246. }
  158247. if( nCrisisMerge<0 ){
  158248. *pbBadkey = 1;
  158249. }else{
  158250. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  158251. pConfig->nCrisisMerge = nCrisisMerge;
  158252. }
  158253. }
  158254. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  158255. const char *zIn = (const char*)sqlite3_value_text(pVal);
  158256. char *zRank;
  158257. char *zRankArgs;
  158258. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  158259. if( rc==SQLITE_OK ){
  158260. sqlite3_free(pConfig->zRank);
  158261. sqlite3_free(pConfig->zRankArgs);
  158262. pConfig->zRank = zRank;
  158263. pConfig->zRankArgs = zRankArgs;
  158264. }else if( rc==SQLITE_ERROR ){
  158265. rc = SQLITE_OK;
  158266. *pbBadkey = 1;
  158267. }
  158268. }else{
  158269. *pbBadkey = 1;
  158270. }
  158271. return rc;
  158272. }
  158273. /*
  158274. ** Load the contents of the %_config table into memory.
  158275. */
  158276. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  158277. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  158278. char *zSql;
  158279. sqlite3_stmt *p = 0;
  158280. int rc = SQLITE_OK;
  158281. int iVersion = 0;
  158282. /* Set default values */
  158283. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  158284. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  158285. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  158286. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  158287. if( zSql ){
  158288. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  158289. sqlite3_free(zSql);
  158290. }
  158291. assert( rc==SQLITE_OK || p==0 );
  158292. if( rc==SQLITE_OK ){
  158293. while( SQLITE_ROW==sqlite3_step(p) ){
  158294. const char *zK = (const char*)sqlite3_column_text(p, 0);
  158295. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  158296. if( 0==sqlite3_stricmp(zK, "version") ){
  158297. iVersion = sqlite3_value_int(pVal);
  158298. }else{
  158299. int bDummy = 0;
  158300. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  158301. }
  158302. }
  158303. rc = sqlite3_finalize(p);
  158304. }
  158305. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  158306. rc = SQLITE_ERROR;
  158307. if( pConfig->pzErrmsg ){
  158308. assert( 0==*pConfig->pzErrmsg );
  158309. *pConfig->pzErrmsg = sqlite3_mprintf(
  158310. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  158311. iVersion, FTS5_CURRENT_VERSION
  158312. );
  158313. }
  158314. }
  158315. if( rc==SQLITE_OK ){
  158316. pConfig->iCookie = iCookie;
  158317. }
  158318. return rc;
  158319. }
  158320. /*
  158321. ** 2014 May 31
  158322. **
  158323. ** The author disclaims copyright to this source code. In place of
  158324. ** a legal notice, here is a blessing:
  158325. **
  158326. ** May you do good and not evil.
  158327. ** May you find forgiveness for yourself and forgive others.
  158328. ** May you share freely, never taking more than you give.
  158329. **
  158330. ******************************************************************************
  158331. **
  158332. */
  158333. /*
  158334. ** All token types in the generated fts5parse.h file are greater than 0.
  158335. */
  158336. #define FTS5_EOF 0
  158337. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  158338. typedef struct Fts5ExprTerm Fts5ExprTerm;
  158339. /*
  158340. ** Functions generated by lemon from fts5parse.y.
  158341. */
  158342. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  158343. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  158344. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  158345. #ifndef NDEBUG
  158346. /* #include <stdio.h> */
  158347. static void sqlite3Fts5ParserTrace(FILE*, char*);
  158348. #endif
  158349. struct Fts5Expr {
  158350. Fts5Index *pIndex;
  158351. Fts5ExprNode *pRoot;
  158352. int bDesc; /* Iterate in descending rowid order */
  158353. int nPhrase; /* Number of phrases in expression */
  158354. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  158355. };
  158356. /*
  158357. ** eType:
  158358. ** Expression node type. Always one of:
  158359. **
  158360. ** FTS5_AND (nChild, apChild valid)
  158361. ** FTS5_OR (nChild, apChild valid)
  158362. ** FTS5_NOT (nChild, apChild valid)
  158363. ** FTS5_STRING (pNear valid)
  158364. ** FTS5_TERM (pNear valid)
  158365. */
  158366. struct Fts5ExprNode {
  158367. int eType; /* Node type */
  158368. int bEof; /* True at EOF */
  158369. int bNomatch; /* True if entry is not a match */
  158370. i64 iRowid; /* Current rowid */
  158371. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  158372. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  158373. ** AND or OR nodes, it contains 2 or more entries. */
  158374. int nChild; /* Number of child nodes */
  158375. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  158376. };
  158377. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  158378. /*
  158379. ** An instance of the following structure represents a single search term
  158380. ** or term prefix.
  158381. */
  158382. struct Fts5ExprTerm {
  158383. int bPrefix; /* True for a prefix term */
  158384. char *zTerm; /* nul-terminated term */
  158385. Fts5IndexIter *pIter; /* Iterator for this term */
  158386. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  158387. };
  158388. /*
  158389. ** A phrase. One or more terms that must appear in a contiguous sequence
  158390. ** within a document for it to match.
  158391. */
  158392. struct Fts5ExprPhrase {
  158393. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  158394. Fts5Buffer poslist; /* Current position list */
  158395. int nTerm; /* Number of entries in aTerm[] */
  158396. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  158397. };
  158398. /*
  158399. ** One or more phrases that must appear within a certain token distance of
  158400. ** each other within each matching document.
  158401. */
  158402. struct Fts5ExprNearset {
  158403. int nNear; /* NEAR parameter */
  158404. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  158405. int nPhrase; /* Number of entries in aPhrase[] array */
  158406. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  158407. };
  158408. /*
  158409. ** Parse context.
  158410. */
  158411. struct Fts5Parse {
  158412. Fts5Config *pConfig;
  158413. char *zErr;
  158414. int rc;
  158415. int nPhrase; /* Size of apPhrase array */
  158416. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  158417. Fts5ExprNode *pExpr; /* Result of a successful parse */
  158418. };
  158419. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  158420. va_list ap;
  158421. va_start(ap, zFmt);
  158422. if( pParse->rc==SQLITE_OK ){
  158423. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  158424. pParse->rc = SQLITE_ERROR;
  158425. }
  158426. va_end(ap);
  158427. }
  158428. static int fts5ExprIsspace(char t){
  158429. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  158430. }
  158431. /*
  158432. ** Read the first token from the nul-terminated string at *pz.
  158433. */
  158434. static int fts5ExprGetToken(
  158435. Fts5Parse *pParse,
  158436. const char **pz, /* IN/OUT: Pointer into buffer */
  158437. Fts5Token *pToken
  158438. ){
  158439. const char *z = *pz;
  158440. int tok;
  158441. /* Skip past any whitespace */
  158442. while( fts5ExprIsspace(*z) ) z++;
  158443. pToken->p = z;
  158444. pToken->n = 1;
  158445. switch( *z ){
  158446. case '(': tok = FTS5_LP; break;
  158447. case ')': tok = FTS5_RP; break;
  158448. case '{': tok = FTS5_LCP; break;
  158449. case '}': tok = FTS5_RCP; break;
  158450. case ':': tok = FTS5_COLON; break;
  158451. case ',': tok = FTS5_COMMA; break;
  158452. case '+': tok = FTS5_PLUS; break;
  158453. case '*': tok = FTS5_STAR; break;
  158454. case '\0': tok = FTS5_EOF; break;
  158455. case '"': {
  158456. const char *z2;
  158457. tok = FTS5_STRING;
  158458. for(z2=&z[1]; 1; z2++){
  158459. if( z2[0]=='"' ){
  158460. z2++;
  158461. if( z2[0]!='"' ) break;
  158462. }
  158463. if( z2[0]=='\0' ){
  158464. sqlite3Fts5ParseError(pParse, "unterminated string");
  158465. return FTS5_EOF;
  158466. }
  158467. }
  158468. pToken->n = (z2 - z);
  158469. break;
  158470. }
  158471. default: {
  158472. const char *z2;
  158473. if( sqlite3Fts5IsBareword(z[0])==0 ){
  158474. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  158475. return FTS5_EOF;
  158476. }
  158477. tok = FTS5_STRING;
  158478. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  158479. pToken->n = (z2 - z);
  158480. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  158481. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  158482. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  158483. break;
  158484. }
  158485. }
  158486. *pz = &pToken->p[pToken->n];
  158487. return tok;
  158488. }
  158489. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  158490. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  158491. static int sqlite3Fts5ExprNew(
  158492. Fts5Config *pConfig, /* FTS5 Configuration */
  158493. const char *zExpr, /* Expression text */
  158494. Fts5Expr **ppNew,
  158495. char **pzErr
  158496. ){
  158497. Fts5Parse sParse;
  158498. Fts5Token token;
  158499. const char *z = zExpr;
  158500. int t; /* Next token type */
  158501. void *pEngine;
  158502. Fts5Expr *pNew;
  158503. *ppNew = 0;
  158504. *pzErr = 0;
  158505. memset(&sParse, 0, sizeof(sParse));
  158506. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  158507. if( pEngine==0 ){ return SQLITE_NOMEM; }
  158508. sParse.pConfig = pConfig;
  158509. do {
  158510. t = fts5ExprGetToken(&sParse, &z, &token);
  158511. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  158512. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  158513. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  158514. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  158515. if( sParse.rc==SQLITE_OK ){
  158516. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  158517. if( pNew==0 ){
  158518. sParse.rc = SQLITE_NOMEM;
  158519. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  158520. }else{
  158521. pNew->pRoot = sParse.pExpr;
  158522. pNew->pIndex = 0;
  158523. pNew->apExprPhrase = sParse.apPhrase;
  158524. pNew->nPhrase = sParse.nPhrase;
  158525. sParse.apPhrase = 0;
  158526. }
  158527. }
  158528. sqlite3_free(sParse.apPhrase);
  158529. *pzErr = sParse.zErr;
  158530. return sParse.rc;
  158531. }
  158532. /*
  158533. ** Free the expression node object passed as the only argument.
  158534. */
  158535. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  158536. if( p ){
  158537. int i;
  158538. for(i=0; i<p->nChild; i++){
  158539. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  158540. }
  158541. sqlite3Fts5ParseNearsetFree(p->pNear);
  158542. sqlite3_free(p);
  158543. }
  158544. }
  158545. /*
  158546. ** Free the expression object passed as the only argument.
  158547. */
  158548. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  158549. if( p ){
  158550. sqlite3Fts5ParseNodeFree(p->pRoot);
  158551. sqlite3_free(p->apExprPhrase);
  158552. sqlite3_free(p);
  158553. }
  158554. }
  158555. /*
  158556. ** Argument pTerm must be a synonym iterator. Return the current rowid
  158557. ** that it points to.
  158558. */
  158559. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  158560. i64 iRet = 0;
  158561. int bRetValid = 0;
  158562. Fts5ExprTerm *p;
  158563. assert( pTerm->pSynonym );
  158564. assert( bDesc==0 || bDesc==1 );
  158565. for(p=pTerm; p; p=p->pSynonym){
  158566. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  158567. i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
  158568. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  158569. iRet = iRowid;
  158570. bRetValid = 1;
  158571. }
  158572. }
  158573. }
  158574. if( pbEof && bRetValid==0 ) *pbEof = 1;
  158575. return iRet;
  158576. }
  158577. /*
  158578. ** Argument pTerm must be a synonym iterator.
  158579. */
  158580. static int fts5ExprSynonymPoslist(
  158581. Fts5ExprTerm *pTerm,
  158582. Fts5Colset *pColset,
  158583. i64 iRowid,
  158584. int *pbDel, /* OUT: Caller should sqlite3_free(*pa) */
  158585. u8 **pa, int *pn
  158586. ){
  158587. Fts5PoslistReader aStatic[4];
  158588. Fts5PoslistReader *aIter = aStatic;
  158589. int nIter = 0;
  158590. int nAlloc = 4;
  158591. int rc = SQLITE_OK;
  158592. Fts5ExprTerm *p;
  158593. assert( pTerm->pSynonym );
  158594. for(p=pTerm; p; p=p->pSynonym){
  158595. Fts5IndexIter *pIter = p->pIter;
  158596. if( sqlite3Fts5IterEof(pIter)==0 && sqlite3Fts5IterRowid(pIter)==iRowid ){
  158597. const u8 *a;
  158598. int n;
  158599. i64 dummy;
  158600. rc = sqlite3Fts5IterPoslist(pIter, pColset, &a, &n, &dummy);
  158601. if( rc!=SQLITE_OK ) goto synonym_poslist_out;
  158602. if( nIter==nAlloc ){
  158603. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  158604. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  158605. if( aNew==0 ){
  158606. rc = SQLITE_NOMEM;
  158607. goto synonym_poslist_out;
  158608. }
  158609. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  158610. nAlloc = nAlloc*2;
  158611. if( aIter!=aStatic ) sqlite3_free(aIter);
  158612. aIter = aNew;
  158613. }
  158614. sqlite3Fts5PoslistReaderInit(a, n, &aIter[nIter]);
  158615. assert( aIter[nIter].bEof==0 );
  158616. nIter++;
  158617. }
  158618. }
  158619. assert( *pbDel==0 );
  158620. if( nIter==1 ){
  158621. *pa = (u8*)aIter[0].a;
  158622. *pn = aIter[0].n;
  158623. }else{
  158624. Fts5PoslistWriter writer = {0};
  158625. Fts5Buffer buf = {0,0,0};
  158626. i64 iPrev = -1;
  158627. while( 1 ){
  158628. int i;
  158629. i64 iMin = FTS5_LARGEST_INT64;
  158630. for(i=0; i<nIter; i++){
  158631. if( aIter[i].bEof==0 ){
  158632. if( aIter[i].iPos==iPrev ){
  158633. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  158634. }
  158635. if( aIter[i].iPos<iMin ){
  158636. iMin = aIter[i].iPos;
  158637. }
  158638. }
  158639. }
  158640. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  158641. rc = sqlite3Fts5PoslistWriterAppend(&buf, &writer, iMin);
  158642. iPrev = iMin;
  158643. }
  158644. if( rc ){
  158645. sqlite3_free(buf.p);
  158646. }else{
  158647. *pa = buf.p;
  158648. *pn = buf.n;
  158649. *pbDel = 1;
  158650. }
  158651. }
  158652. synonym_poslist_out:
  158653. if( aIter!=aStatic ) sqlite3_free(aIter);
  158654. return rc;
  158655. }
  158656. /*
  158657. ** All individual term iterators in pPhrase are guaranteed to be valid and
  158658. ** pointing to the same rowid when this function is called. This function
  158659. ** checks if the current rowid really is a match, and if so populates
  158660. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  158661. ** is set to true if this is really a match, or false otherwise.
  158662. **
  158663. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  158664. ** otherwise. It is not considered an error code if the current rowid is
  158665. ** not a match.
  158666. */
  158667. static int fts5ExprPhraseIsMatch(
  158668. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  158669. Fts5Colset *pColset, /* Restrict matches to these columns */
  158670. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  158671. int *pbMatch /* OUT: Set to true if really a match */
  158672. ){
  158673. Fts5PoslistWriter writer = {0};
  158674. Fts5PoslistReader aStatic[4];
  158675. Fts5PoslistReader *aIter = aStatic;
  158676. int i;
  158677. int rc = SQLITE_OK;
  158678. fts5BufferZero(&pPhrase->poslist);
  158679. /* If the aStatic[] array is not large enough, allocate a large array
  158680. ** using sqlite3_malloc(). This approach could be improved upon. */
  158681. if( pPhrase->nTerm>(sizeof(aStatic) / sizeof(aStatic[0])) ){
  158682. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  158683. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  158684. if( !aIter ) return SQLITE_NOMEM;
  158685. }
  158686. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  158687. /* Initialize a term iterator for each term in the phrase */
  158688. for(i=0; i<pPhrase->nTerm; i++){
  158689. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  158690. i64 dummy;
  158691. int n = 0;
  158692. int bFlag = 0;
  158693. const u8 *a = 0;
  158694. if( pTerm->pSynonym ){
  158695. rc = fts5ExprSynonymPoslist(
  158696. pTerm, pColset, pNode->iRowid, &bFlag, (u8**)&a, &n
  158697. );
  158698. }else{
  158699. rc = sqlite3Fts5IterPoslist(pTerm->pIter, pColset, &a, &n, &dummy);
  158700. }
  158701. if( rc!=SQLITE_OK ) goto ismatch_out;
  158702. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  158703. aIter[i].bFlag = bFlag;
  158704. if( aIter[i].bEof ) goto ismatch_out;
  158705. }
  158706. while( 1 ){
  158707. int bMatch;
  158708. i64 iPos = aIter[0].iPos;
  158709. do {
  158710. bMatch = 1;
  158711. for(i=0; i<pPhrase->nTerm; i++){
  158712. Fts5PoslistReader *pPos = &aIter[i];
  158713. i64 iAdj = iPos + i;
  158714. if( pPos->iPos!=iAdj ){
  158715. bMatch = 0;
  158716. while( pPos->iPos<iAdj ){
  158717. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  158718. }
  158719. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  158720. }
  158721. }
  158722. }while( bMatch==0 );
  158723. /* Append position iPos to the output */
  158724. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  158725. if( rc!=SQLITE_OK ) goto ismatch_out;
  158726. for(i=0; i<pPhrase->nTerm; i++){
  158727. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  158728. }
  158729. }
  158730. ismatch_out:
  158731. *pbMatch = (pPhrase->poslist.n>0);
  158732. for(i=0; i<pPhrase->nTerm; i++){
  158733. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  158734. }
  158735. if( aIter!=aStatic ) sqlite3_free(aIter);
  158736. return rc;
  158737. }
  158738. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  158739. struct Fts5LookaheadReader {
  158740. const u8 *a; /* Buffer containing position list */
  158741. int n; /* Size of buffer a[] in bytes */
  158742. int i; /* Current offset in position list */
  158743. i64 iPos; /* Current position */
  158744. i64 iLookahead; /* Next position */
  158745. };
  158746. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  158747. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  158748. p->iPos = p->iLookahead;
  158749. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  158750. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  158751. }
  158752. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  158753. }
  158754. static int fts5LookaheadReaderInit(
  158755. const u8 *a, int n, /* Buffer to read position list from */
  158756. Fts5LookaheadReader *p /* Iterator object to initialize */
  158757. ){
  158758. memset(p, 0, sizeof(Fts5LookaheadReader));
  158759. p->a = a;
  158760. p->n = n;
  158761. fts5LookaheadReaderNext(p);
  158762. return fts5LookaheadReaderNext(p);
  158763. }
  158764. #if 0
  158765. static int fts5LookaheadReaderEof(Fts5LookaheadReader *p){
  158766. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  158767. }
  158768. #endif
  158769. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  158770. struct Fts5NearTrimmer {
  158771. Fts5LookaheadReader reader; /* Input iterator */
  158772. Fts5PoslistWriter writer; /* Writer context */
  158773. Fts5Buffer *pOut; /* Output poslist */
  158774. };
  158775. /*
  158776. ** The near-set object passed as the first argument contains more than
  158777. ** one phrase. All phrases currently point to the same row. The
  158778. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  158779. ** tests if the current row contains instances of each phrase sufficiently
  158780. ** close together to meet the NEAR constraint. Non-zero is returned if it
  158781. ** does, or zero otherwise.
  158782. **
  158783. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  158784. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  158785. ** occurs within this function (*pRc) is set accordingly before returning.
  158786. ** The return value is undefined in both these cases.
  158787. **
  158788. ** If no error occurs and non-zero (a match) is returned, the position-list
  158789. ** of each phrase object is edited to contain only those entries that
  158790. ** meet the constraint before returning.
  158791. */
  158792. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  158793. Fts5NearTrimmer aStatic[4];
  158794. Fts5NearTrimmer *a = aStatic;
  158795. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  158796. int i;
  158797. int rc = *pRc;
  158798. int bMatch;
  158799. assert( pNear->nPhrase>1 );
  158800. /* If the aStatic[] array is not large enough, allocate a large array
  158801. ** using sqlite3_malloc(). This approach could be improved upon. */
  158802. if( pNear->nPhrase>(sizeof(aStatic) / sizeof(aStatic[0])) ){
  158803. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  158804. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  158805. }else{
  158806. memset(aStatic, 0, sizeof(aStatic));
  158807. }
  158808. if( rc!=SQLITE_OK ){
  158809. *pRc = rc;
  158810. return 0;
  158811. }
  158812. /* Initialize a lookahead iterator for each phrase. After passing the
  158813. ** buffer and buffer size to the lookaside-reader init function, zero
  158814. ** the phrase poslist buffer. The new poslist for the phrase (containing
  158815. ** the same entries as the original with some entries removed on account
  158816. ** of the NEAR constraint) is written over the original even as it is
  158817. ** being read. This is safe as the entries for the new poslist are a
  158818. ** subset of the old, so it is not possible for data yet to be read to
  158819. ** be overwritten. */
  158820. for(i=0; i<pNear->nPhrase; i++){
  158821. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  158822. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  158823. pPoslist->n = 0;
  158824. a[i].pOut = pPoslist;
  158825. }
  158826. while( 1 ){
  158827. int iAdv;
  158828. i64 iMin;
  158829. i64 iMax;
  158830. /* This block advances the phrase iterators until they point to a set of
  158831. ** entries that together comprise a match. */
  158832. iMax = a[0].reader.iPos;
  158833. do {
  158834. bMatch = 1;
  158835. for(i=0; i<pNear->nPhrase; i++){
  158836. Fts5LookaheadReader *pPos = &a[i].reader;
  158837. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  158838. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  158839. bMatch = 0;
  158840. while( pPos->iPos<iMin ){
  158841. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  158842. }
  158843. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  158844. }
  158845. }
  158846. }while( bMatch==0 );
  158847. /* Add an entry to each output position list */
  158848. for(i=0; i<pNear->nPhrase; i++){
  158849. i64 iPos = a[i].reader.iPos;
  158850. Fts5PoslistWriter *pWriter = &a[i].writer;
  158851. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  158852. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  158853. }
  158854. }
  158855. iAdv = 0;
  158856. iMin = a[0].reader.iLookahead;
  158857. for(i=0; i<pNear->nPhrase; i++){
  158858. if( a[i].reader.iLookahead < iMin ){
  158859. iMin = a[i].reader.iLookahead;
  158860. iAdv = i;
  158861. }
  158862. }
  158863. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  158864. }
  158865. ismatch_out: {
  158866. int bRet = a[0].pOut->n>0;
  158867. *pRc = rc;
  158868. if( a!=aStatic ) sqlite3_free(a);
  158869. return bRet;
  158870. }
  158871. }
  158872. /*
  158873. ** Advance the first term iterator in the first phrase of pNear. Set output
  158874. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  158875. **
  158876. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  158877. ** occurs.
  158878. */
  158879. static int fts5ExprNearAdvanceFirst(
  158880. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  158881. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  158882. int bFromValid,
  158883. i64 iFrom
  158884. ){
  158885. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  158886. int rc = SQLITE_OK;
  158887. if( pTerm->pSynonym ){
  158888. int bEof = 1;
  158889. Fts5ExprTerm *p;
  158890. /* Find the firstest rowid any synonym points to. */
  158891. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  158892. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  158893. ** is valid - each iterator that points to a rowid before iFrom. */
  158894. for(p=pTerm; p; p=p->pSynonym){
  158895. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  158896. i64 ii = sqlite3Fts5IterRowid(p->pIter);
  158897. if( ii==iRowid
  158898. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  158899. ){
  158900. if( bFromValid ){
  158901. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  158902. }else{
  158903. rc = sqlite3Fts5IterNext(p->pIter);
  158904. }
  158905. if( rc!=SQLITE_OK ) break;
  158906. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  158907. bEof = 0;
  158908. }
  158909. }else{
  158910. bEof = 0;
  158911. }
  158912. }
  158913. }
  158914. /* Set the EOF flag if either all synonym iterators are at EOF or an
  158915. ** error has occurred. */
  158916. pNode->bEof = (rc || bEof);
  158917. }else{
  158918. Fts5IndexIter *pIter = pTerm->pIter;
  158919. assert( Fts5NodeIsString(pNode) );
  158920. if( bFromValid ){
  158921. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  158922. }else{
  158923. rc = sqlite3Fts5IterNext(pIter);
  158924. }
  158925. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  158926. }
  158927. return rc;
  158928. }
  158929. /*
  158930. ** Advance iterator pIter until it points to a value equal to or laster
  158931. ** than the initial value of *piLast. If this means the iterator points
  158932. ** to a value laster than *piLast, update *piLast to the new lastest value.
  158933. **
  158934. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  158935. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  158936. ** are set, return a non-zero value. Otherwise, return zero.
  158937. */
  158938. static int fts5ExprAdvanceto(
  158939. Fts5IndexIter *pIter, /* Iterator to advance */
  158940. int bDesc, /* True if iterator is "rowid DESC" */
  158941. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  158942. int *pRc, /* OUT: Error code */
  158943. int *pbEof /* OUT: Set to true if EOF */
  158944. ){
  158945. i64 iLast = *piLast;
  158946. i64 iRowid;
  158947. iRowid = sqlite3Fts5IterRowid(pIter);
  158948. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  158949. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  158950. if( rc || sqlite3Fts5IterEof(pIter) ){
  158951. *pRc = rc;
  158952. *pbEof = 1;
  158953. return 1;
  158954. }
  158955. iRowid = sqlite3Fts5IterRowid(pIter);
  158956. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  158957. }
  158958. *piLast = iRowid;
  158959. return 0;
  158960. }
  158961. static int fts5ExprSynonymAdvanceto(
  158962. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  158963. int bDesc, /* True if iterator is "rowid DESC" */
  158964. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  158965. int *pRc /* OUT: Error code */
  158966. ){
  158967. int rc = SQLITE_OK;
  158968. i64 iLast = *piLast;
  158969. Fts5ExprTerm *p;
  158970. int bEof = 0;
  158971. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  158972. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  158973. i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
  158974. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  158975. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  158976. }
  158977. }
  158978. }
  158979. if( rc!=SQLITE_OK ){
  158980. *pRc = rc;
  158981. bEof = 1;
  158982. }else{
  158983. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  158984. }
  158985. return bEof;
  158986. }
  158987. static int fts5ExprNearTest(
  158988. int *pRc,
  158989. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  158990. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  158991. ){
  158992. Fts5ExprNearset *pNear = pNode->pNear;
  158993. int rc = *pRc;
  158994. int i;
  158995. /* Check that each phrase in the nearset matches the current row.
  158996. ** Populate the pPhrase->poslist buffers at the same time. If any
  158997. ** phrase is not a match, break out of the loop early. */
  158998. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  158999. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  159000. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  159001. int bMatch = 0;
  159002. rc = fts5ExprPhraseIsMatch(pNode, pNear->pColset, pPhrase, &bMatch);
  159003. if( bMatch==0 ) break;
  159004. }else{
  159005. rc = sqlite3Fts5IterPoslistBuffer(
  159006. pPhrase->aTerm[0].pIter, &pPhrase->poslist
  159007. );
  159008. }
  159009. }
  159010. *pRc = rc;
  159011. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  159012. return 1;
  159013. }
  159014. return 0;
  159015. }
  159016. static int fts5ExprTokenTest(
  159017. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  159018. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  159019. ){
  159020. /* As this "NEAR" object is actually a single phrase that consists
  159021. ** of a single term only, grab pointers into the poslist managed by the
  159022. ** fts5_index.c iterator object. This is much faster than synthesizing
  159023. ** a new poslist the way we have to for more complicated phrase or NEAR
  159024. ** expressions. */
  159025. Fts5ExprNearset *pNear = pNode->pNear;
  159026. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  159027. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  159028. Fts5Colset *pColset = pNear->pColset;
  159029. int rc;
  159030. assert( pNode->eType==FTS5_TERM );
  159031. assert( pNear->nPhrase==1 && pPhrase->nTerm==1 );
  159032. assert( pPhrase->aTerm[0].pSynonym==0 );
  159033. rc = sqlite3Fts5IterPoslist(pIter, pColset,
  159034. (const u8**)&pPhrase->poslist.p, &pPhrase->poslist.n, &pNode->iRowid
  159035. );
  159036. pNode->bNomatch = (pPhrase->poslist.n==0);
  159037. return rc;
  159038. }
  159039. /*
  159040. ** All individual term iterators in pNear are guaranteed to be valid when
  159041. ** this function is called. This function checks if all term iterators
  159042. ** point to the same rowid, and if not, advances them until they do.
  159043. ** If an EOF is reached before this happens, *pbEof is set to true before
  159044. ** returning.
  159045. **
  159046. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  159047. ** otherwise. It is not considered an error code if an iterator reaches
  159048. ** EOF.
  159049. */
  159050. static int fts5ExprNearNextMatch(
  159051. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  159052. Fts5ExprNode *pNode
  159053. ){
  159054. Fts5ExprNearset *pNear = pNode->pNear;
  159055. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  159056. int rc = SQLITE_OK;
  159057. i64 iLast; /* Lastest rowid any iterator points to */
  159058. int i, j; /* Phrase and token index, respectively */
  159059. int bMatch; /* True if all terms are at the same rowid */
  159060. const int bDesc = pExpr->bDesc;
  159061. /* Check that this node should not be FTS5_TERM */
  159062. assert( pNear->nPhrase>1
  159063. || pNear->apPhrase[0]->nTerm>1
  159064. || pNear->apPhrase[0]->aTerm[0].pSynonym
  159065. );
  159066. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  159067. ** iterator skips through rowids in the default ascending order, this means
  159068. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  159069. ** means the minimum rowid. */
  159070. if( pLeft->aTerm[0].pSynonym ){
  159071. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  159072. }else{
  159073. iLast = sqlite3Fts5IterRowid(pLeft->aTerm[0].pIter);
  159074. }
  159075. do {
  159076. bMatch = 1;
  159077. for(i=0; i<pNear->nPhrase; i++){
  159078. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  159079. for(j=0; j<pPhrase->nTerm; j++){
  159080. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  159081. if( pTerm->pSynonym ){
  159082. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  159083. if( iRowid==iLast ) continue;
  159084. bMatch = 0;
  159085. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  159086. pNode->bEof = 1;
  159087. return rc;
  159088. }
  159089. }else{
  159090. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  159091. i64 iRowid = sqlite3Fts5IterRowid(pIter);
  159092. if( iRowid==iLast ) continue;
  159093. bMatch = 0;
  159094. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  159095. return rc;
  159096. }
  159097. }
  159098. }
  159099. }
  159100. }while( bMatch==0 );
  159101. pNode->iRowid = iLast;
  159102. pNode->bNomatch = (0==fts5ExprNearTest(&rc, pExpr, pNode));
  159103. return rc;
  159104. }
  159105. /*
  159106. ** Initialize all term iterators in the pNear object. If any term is found
  159107. ** to match no documents at all, return immediately without initializing any
  159108. ** further iterators.
  159109. */
  159110. static int fts5ExprNearInitAll(
  159111. Fts5Expr *pExpr,
  159112. Fts5ExprNode *pNode
  159113. ){
  159114. Fts5ExprNearset *pNear = pNode->pNear;
  159115. int i, j;
  159116. int rc = SQLITE_OK;
  159117. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  159118. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  159119. for(j=0; j<pPhrase->nTerm; j++){
  159120. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  159121. Fts5ExprTerm *p;
  159122. int bEof = 1;
  159123. for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
  159124. if( p->pIter ){
  159125. sqlite3Fts5IterClose(p->pIter);
  159126. p->pIter = 0;
  159127. }
  159128. rc = sqlite3Fts5IndexQuery(
  159129. pExpr->pIndex, p->zTerm, strlen(p->zTerm),
  159130. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  159131. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  159132. pNear->pColset,
  159133. &p->pIter
  159134. );
  159135. assert( rc==SQLITE_OK || p->pIter==0 );
  159136. if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
  159137. bEof = 0;
  159138. }
  159139. }
  159140. if( bEof ){
  159141. pNode->bEof = 1;
  159142. return rc;
  159143. }
  159144. }
  159145. }
  159146. return rc;
  159147. }
  159148. /* fts5ExprNodeNext() calls fts5ExprNodeNextMatch(). And vice-versa. */
  159149. static int fts5ExprNodeNextMatch(Fts5Expr*, Fts5ExprNode*);
  159150. /*
  159151. ** If pExpr is an ASC iterator, this function returns a value with the
  159152. ** same sign as:
  159153. **
  159154. ** (iLhs - iRhs)
  159155. **
  159156. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  159157. **
  159158. ** (iRhs - iLhs)
  159159. */
  159160. static int fts5RowidCmp(
  159161. Fts5Expr *pExpr,
  159162. i64 iLhs,
  159163. i64 iRhs
  159164. ){
  159165. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  159166. if( pExpr->bDesc==0 ){
  159167. if( iLhs<iRhs ) return -1;
  159168. return (iLhs > iRhs);
  159169. }else{
  159170. if( iLhs>iRhs ) return -1;
  159171. return (iLhs < iRhs);
  159172. }
  159173. }
  159174. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  159175. int i;
  159176. pNode->bEof = 1;
  159177. for(i=0; i<pNode->nChild; i++){
  159178. fts5ExprSetEof(pNode->apChild[i]);
  159179. }
  159180. }
  159181. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  159182. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  159183. Fts5ExprNearset *pNear = pNode->pNear;
  159184. int i;
  159185. for(i=0; i<pNear->nPhrase; i++){
  159186. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  159187. pPhrase->poslist.n = 0;
  159188. }
  159189. }else{
  159190. int i;
  159191. for(i=0; i<pNode->nChild; i++){
  159192. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  159193. }
  159194. }
  159195. }
  159196. static int fts5ExprNodeNext(Fts5Expr*, Fts5ExprNode*, int, i64);
  159197. /*
  159198. ** Argument pNode is an FTS5_AND node.
  159199. */
  159200. static int fts5ExprAndNextRowid(
  159201. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  159202. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  159203. ){
  159204. int iChild;
  159205. i64 iLast = pAnd->iRowid;
  159206. int rc = SQLITE_OK;
  159207. int bMatch;
  159208. assert( pAnd->bEof==0 );
  159209. do {
  159210. pAnd->bNomatch = 0;
  159211. bMatch = 1;
  159212. for(iChild=0; iChild<pAnd->nChild; iChild++){
  159213. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  159214. if( 0 && pChild->eType==FTS5_STRING ){
  159215. /* TODO */
  159216. }else{
  159217. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  159218. if( cmp>0 ){
  159219. /* Advance pChild until it points to iLast or laster */
  159220. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  159221. if( rc!=SQLITE_OK ) return rc;
  159222. }
  159223. }
  159224. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  159225. ** the child node is guaranteed to have advanced at least as far as
  159226. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  159227. ** new lastest rowid seen so far. */
  159228. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  159229. if( pChild->bEof ){
  159230. fts5ExprSetEof(pAnd);
  159231. bMatch = 1;
  159232. break;
  159233. }else if( iLast!=pChild->iRowid ){
  159234. bMatch = 0;
  159235. iLast = pChild->iRowid;
  159236. }
  159237. if( pChild->bNomatch ){
  159238. pAnd->bNomatch = 1;
  159239. }
  159240. }
  159241. }while( bMatch==0 );
  159242. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  159243. fts5ExprNodeZeroPoslist(pAnd);
  159244. }
  159245. pAnd->iRowid = iLast;
  159246. return SQLITE_OK;
  159247. }
  159248. /*
  159249. ** Compare the values currently indicated by the two nodes as follows:
  159250. **
  159251. ** res = (*p1) - (*p2)
  159252. **
  159253. ** Nodes that point to values that come later in the iteration order are
  159254. ** considered to be larger. Nodes at EOF are the largest of all.
  159255. **
  159256. ** This means that if the iteration order is ASC, then numerically larger
  159257. ** rowids are considered larger. Or if it is the default DESC, numerically
  159258. ** smaller rowids are larger.
  159259. */
  159260. static int fts5NodeCompare(
  159261. Fts5Expr *pExpr,
  159262. Fts5ExprNode *p1,
  159263. Fts5ExprNode *p2
  159264. ){
  159265. if( p2->bEof ) return -1;
  159266. if( p1->bEof ) return +1;
  159267. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  159268. }
  159269. /*
  159270. ** Advance node iterator pNode, part of expression pExpr. If argument
  159271. ** bFromValid is zero, then pNode is advanced exactly once. Or, if argument
  159272. ** bFromValid is non-zero, then pNode is advanced until it is at or past
  159273. ** rowid value iFrom. Whether "past" means "less than" or "greater than"
  159274. ** depends on whether this is an ASC or DESC iterator.
  159275. */
  159276. static int fts5ExprNodeNext(
  159277. Fts5Expr *pExpr,
  159278. Fts5ExprNode *pNode,
  159279. int bFromValid,
  159280. i64 iFrom
  159281. ){
  159282. int rc = SQLITE_OK;
  159283. if( pNode->bEof==0 ){
  159284. switch( pNode->eType ){
  159285. case FTS5_STRING: {
  159286. rc = fts5ExprNearAdvanceFirst(pExpr, pNode, bFromValid, iFrom);
  159287. break;
  159288. };
  159289. case FTS5_TERM: {
  159290. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  159291. if( bFromValid ){
  159292. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  159293. }else{
  159294. rc = sqlite3Fts5IterNext(pIter);
  159295. }
  159296. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  159297. assert( rc==SQLITE_OK );
  159298. rc = fts5ExprTokenTest(pExpr, pNode);
  159299. }else{
  159300. pNode->bEof = 1;
  159301. }
  159302. return rc;
  159303. };
  159304. case FTS5_AND: {
  159305. Fts5ExprNode *pLeft = pNode->apChild[0];
  159306. rc = fts5ExprNodeNext(pExpr, pLeft, bFromValid, iFrom);
  159307. break;
  159308. }
  159309. case FTS5_OR: {
  159310. int i;
  159311. i64 iLast = pNode->iRowid;
  159312. for(i=0; rc==SQLITE_OK && i<pNode->nChild; i++){
  159313. Fts5ExprNode *p1 = pNode->apChild[i];
  159314. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  159315. if( p1->bEof==0 ){
  159316. if( (p1->iRowid==iLast)
  159317. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  159318. ){
  159319. rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  159320. }
  159321. }
  159322. }
  159323. break;
  159324. }
  159325. default: assert( pNode->eType==FTS5_NOT ); {
  159326. assert( pNode->nChild==2 );
  159327. rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  159328. break;
  159329. }
  159330. }
  159331. if( rc==SQLITE_OK ){
  159332. rc = fts5ExprNodeNextMatch(pExpr, pNode);
  159333. }
  159334. }
  159335. /* Assert that if bFromValid was true, either:
  159336. **
  159337. ** a) an error occurred, or
  159338. ** b) the node is now at EOF, or
  159339. ** c) the node is now at or past rowid iFrom.
  159340. */
  159341. assert( bFromValid==0
  159342. || rc!=SQLITE_OK /* a */
  159343. || pNode->bEof /* b */
  159344. || pNode->iRowid==iFrom || pExpr->bDesc==(pNode->iRowid<iFrom) /* c */
  159345. );
  159346. return rc;
  159347. }
  159348. /*
  159349. ** If pNode currently points to a match, this function returns SQLITE_OK
  159350. ** without modifying it. Otherwise, pNode is advanced until it does point
  159351. ** to a match or EOF is reached.
  159352. */
  159353. static int fts5ExprNodeNextMatch(
  159354. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  159355. Fts5ExprNode *pNode /* Expression node to test */
  159356. ){
  159357. int rc = SQLITE_OK;
  159358. if( pNode->bEof==0 ){
  159359. switch( pNode->eType ){
  159360. case FTS5_STRING: {
  159361. /* Advance the iterators until they all point to the same rowid */
  159362. rc = fts5ExprNearNextMatch(pExpr, pNode);
  159363. break;
  159364. }
  159365. case FTS5_TERM: {
  159366. rc = fts5ExprTokenTest(pExpr, pNode);
  159367. break;
  159368. }
  159369. case FTS5_AND: {
  159370. rc = fts5ExprAndNextRowid(pExpr, pNode);
  159371. break;
  159372. }
  159373. case FTS5_OR: {
  159374. Fts5ExprNode *pNext = pNode->apChild[0];
  159375. int i;
  159376. for(i=1; i<pNode->nChild; i++){
  159377. Fts5ExprNode *pChild = pNode->apChild[i];
  159378. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  159379. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  159380. pNext = pChild;
  159381. }
  159382. }
  159383. pNode->iRowid = pNext->iRowid;
  159384. pNode->bEof = pNext->bEof;
  159385. pNode->bNomatch = pNext->bNomatch;
  159386. break;
  159387. }
  159388. default: assert( pNode->eType==FTS5_NOT ); {
  159389. Fts5ExprNode *p1 = pNode->apChild[0];
  159390. Fts5ExprNode *p2 = pNode->apChild[1];
  159391. assert( pNode->nChild==2 );
  159392. while( rc==SQLITE_OK && p1->bEof==0 ){
  159393. int cmp = fts5NodeCompare(pExpr, p1, p2);
  159394. if( cmp>0 ){
  159395. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  159396. cmp = fts5NodeCompare(pExpr, p1, p2);
  159397. }
  159398. assert( rc!=SQLITE_OK || cmp<=0 );
  159399. if( cmp || p2->bNomatch ) break;
  159400. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  159401. }
  159402. pNode->bEof = p1->bEof;
  159403. pNode->iRowid = p1->iRowid;
  159404. break;
  159405. }
  159406. }
  159407. }
  159408. return rc;
  159409. }
  159410. /*
  159411. ** Set node pNode, which is part of expression pExpr, to point to the first
  159412. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  159413. **
  159414. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  159415. ** It is not an error if there are no matches.
  159416. */
  159417. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  159418. int rc = SQLITE_OK;
  159419. pNode->bEof = 0;
  159420. if( Fts5NodeIsString(pNode) ){
  159421. /* Initialize all term iterators in the NEAR object. */
  159422. rc = fts5ExprNearInitAll(pExpr, pNode);
  159423. }else{
  159424. int i;
  159425. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  159426. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  159427. }
  159428. pNode->iRowid = pNode->apChild[0]->iRowid;
  159429. }
  159430. if( rc==SQLITE_OK ){
  159431. rc = fts5ExprNodeNextMatch(pExpr, pNode);
  159432. }
  159433. return rc;
  159434. }
  159435. /*
  159436. ** Begin iterating through the set of documents in index pIdx matched by
  159437. ** the MATCH expression passed as the first argument. If the "bDesc"
  159438. ** parameter is passed a non-zero value, iteration is in descending rowid
  159439. ** order. Or, if it is zero, in ascending order.
  159440. **
  159441. ** If iterating in ascending rowid order (bDesc==0), the first document
  159442. ** visited is that with the smallest rowid that is larger than or equal
  159443. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  159444. ** then the first document visited must have a rowid smaller than or
  159445. ** equal to iFirst.
  159446. **
  159447. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  159448. ** is not considered an error if the query does not match any documents.
  159449. */
  159450. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  159451. Fts5ExprNode *pRoot = p->pRoot;
  159452. int rc = SQLITE_OK;
  159453. if( pRoot ){
  159454. p->pIndex = pIdx;
  159455. p->bDesc = bDesc;
  159456. rc = fts5ExprNodeFirst(p, pRoot);
  159457. /* If not at EOF but the current rowid occurs earlier than iFirst in
  159458. ** the iteration order, move to document iFirst or later. */
  159459. if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
  159460. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  159461. }
  159462. /* If the iterator is not at a real match, skip forward until it is. */
  159463. while( pRoot->bNomatch && rc==SQLITE_OK && pRoot->bEof==0 ){
  159464. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  159465. }
  159466. }
  159467. return rc;
  159468. }
  159469. /*
  159470. ** Move to the next document
  159471. **
  159472. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  159473. ** is not considered an error if the query does not match any documents.
  159474. */
  159475. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  159476. int rc;
  159477. Fts5ExprNode *pRoot = p->pRoot;
  159478. do {
  159479. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  159480. }while( pRoot->bNomatch && pRoot->bEof==0 && rc==SQLITE_OK );
  159481. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  159482. pRoot->bEof = 1;
  159483. }
  159484. return rc;
  159485. }
  159486. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  159487. return (p->pRoot==0 || p->pRoot->bEof);
  159488. }
  159489. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  159490. return p->pRoot->iRowid;
  159491. }
  159492. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  159493. int rc = SQLITE_OK;
  159494. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  159495. return rc;
  159496. }
  159497. /*
  159498. ** Free the phrase object passed as the only argument.
  159499. */
  159500. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  159501. if( pPhrase ){
  159502. int i;
  159503. for(i=0; i<pPhrase->nTerm; i++){
  159504. Fts5ExprTerm *pSyn;
  159505. Fts5ExprTerm *pNext;
  159506. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  159507. sqlite3_free(pTerm->zTerm);
  159508. sqlite3Fts5IterClose(pTerm->pIter);
  159509. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  159510. pNext = pSyn->pSynonym;
  159511. sqlite3Fts5IterClose(pSyn->pIter);
  159512. sqlite3_free(pSyn);
  159513. }
  159514. }
  159515. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  159516. sqlite3_free(pPhrase);
  159517. }
  159518. }
  159519. /*
  159520. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  159521. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  159522. ** appended to it and the results returned.
  159523. **
  159524. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  159525. ** NULL returned.
  159526. */
  159527. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  159528. Fts5Parse *pParse, /* Parse context */
  159529. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  159530. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  159531. ){
  159532. const int SZALLOC = 8;
  159533. Fts5ExprNearset *pRet = 0;
  159534. if( pParse->rc==SQLITE_OK ){
  159535. if( pPhrase==0 ){
  159536. return pNear;
  159537. }
  159538. if( pNear==0 ){
  159539. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  159540. pRet = sqlite3_malloc(nByte);
  159541. if( pRet==0 ){
  159542. pParse->rc = SQLITE_NOMEM;
  159543. }else{
  159544. memset(pRet, 0, nByte);
  159545. }
  159546. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  159547. int nNew = pNear->nPhrase + SZALLOC;
  159548. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  159549. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  159550. if( pRet==0 ){
  159551. pParse->rc = SQLITE_NOMEM;
  159552. }
  159553. }else{
  159554. pRet = pNear;
  159555. }
  159556. }
  159557. if( pRet==0 ){
  159558. assert( pParse->rc!=SQLITE_OK );
  159559. sqlite3Fts5ParseNearsetFree(pNear);
  159560. sqlite3Fts5ParsePhraseFree(pPhrase);
  159561. }else{
  159562. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  159563. }
  159564. return pRet;
  159565. }
  159566. typedef struct TokenCtx TokenCtx;
  159567. struct TokenCtx {
  159568. Fts5ExprPhrase *pPhrase;
  159569. int rc;
  159570. };
  159571. /*
  159572. ** Callback for tokenizing terms used by ParseTerm().
  159573. */
  159574. static int fts5ParseTokenize(
  159575. void *pContext, /* Pointer to Fts5InsertCtx object */
  159576. int tflags, /* Mask of FTS5_TOKEN_* flags */
  159577. const char *pToken, /* Buffer containing token */
  159578. int nToken, /* Size of token in bytes */
  159579. int iUnused1, /* Start offset of token */
  159580. int iUnused2 /* End offset of token */
  159581. ){
  159582. int rc = SQLITE_OK;
  159583. const int SZALLOC = 8;
  159584. TokenCtx *pCtx = (TokenCtx*)pContext;
  159585. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  159586. /* If an error has already occurred, this is a no-op */
  159587. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  159588. assert( pPhrase==0 || pPhrase->nTerm>0 );
  159589. if( pPhrase && (tflags & FTS5_TOKEN_COLOCATED) ){
  159590. Fts5ExprTerm *pSyn;
  159591. int nByte = sizeof(Fts5ExprTerm) + nToken+1;
  159592. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  159593. if( pSyn==0 ){
  159594. rc = SQLITE_NOMEM;
  159595. }else{
  159596. memset(pSyn, 0, nByte);
  159597. pSyn->zTerm = (char*)&pSyn[1];
  159598. memcpy(pSyn->zTerm, pToken, nToken);
  159599. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  159600. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  159601. }
  159602. }else{
  159603. Fts5ExprTerm *pTerm;
  159604. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  159605. Fts5ExprPhrase *pNew;
  159606. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  159607. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  159608. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  159609. );
  159610. if( pNew==0 ){
  159611. rc = SQLITE_NOMEM;
  159612. }else{
  159613. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  159614. pCtx->pPhrase = pPhrase = pNew;
  159615. pNew->nTerm = nNew - SZALLOC;
  159616. }
  159617. }
  159618. if( rc==SQLITE_OK ){
  159619. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  159620. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  159621. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  159622. }
  159623. }
  159624. pCtx->rc = rc;
  159625. return rc;
  159626. }
  159627. /*
  159628. ** Free the phrase object passed as the only argument.
  159629. */
  159630. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  159631. fts5ExprPhraseFree(pPhrase);
  159632. }
  159633. /*
  159634. ** Free the phrase object passed as the second argument.
  159635. */
  159636. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  159637. if( pNear ){
  159638. int i;
  159639. for(i=0; i<pNear->nPhrase; i++){
  159640. fts5ExprPhraseFree(pNear->apPhrase[i]);
  159641. }
  159642. sqlite3_free(pNear->pColset);
  159643. sqlite3_free(pNear);
  159644. }
  159645. }
  159646. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  159647. assert( pParse->pExpr==0 );
  159648. pParse->pExpr = p;
  159649. }
  159650. /*
  159651. ** This function is called by the parser to process a string token. The
  159652. ** string may or may not be quoted. In any case it is tokenized and a
  159653. ** phrase object consisting of all tokens returned.
  159654. */
  159655. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  159656. Fts5Parse *pParse, /* Parse context */
  159657. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  159658. Fts5Token *pToken, /* String to tokenize */
  159659. int bPrefix /* True if there is a trailing "*" */
  159660. ){
  159661. Fts5Config *pConfig = pParse->pConfig;
  159662. TokenCtx sCtx; /* Context object passed to callback */
  159663. int rc; /* Tokenize return code */
  159664. char *z = 0;
  159665. memset(&sCtx, 0, sizeof(TokenCtx));
  159666. sCtx.pPhrase = pAppend;
  159667. rc = fts5ParseStringFromToken(pToken, &z);
  159668. if( rc==SQLITE_OK ){
  159669. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
  159670. int n;
  159671. sqlite3Fts5Dequote(z);
  159672. n = strlen(z);
  159673. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  159674. }
  159675. sqlite3_free(z);
  159676. if( rc || (rc = sCtx.rc) ){
  159677. pParse->rc = rc;
  159678. fts5ExprPhraseFree(sCtx.pPhrase);
  159679. sCtx.pPhrase = 0;
  159680. }else if( sCtx.pPhrase ){
  159681. if( pAppend==0 ){
  159682. if( (pParse->nPhrase % 8)==0 ){
  159683. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  159684. Fts5ExprPhrase **apNew;
  159685. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  159686. if( apNew==0 ){
  159687. pParse->rc = SQLITE_NOMEM;
  159688. fts5ExprPhraseFree(sCtx.pPhrase);
  159689. return 0;
  159690. }
  159691. pParse->apPhrase = apNew;
  159692. }
  159693. pParse->nPhrase++;
  159694. }
  159695. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  159696. assert( sCtx.pPhrase->nTerm>0 );
  159697. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  159698. }
  159699. return sCtx.pPhrase;
  159700. }
  159701. /*
  159702. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  159703. ** expression passed as the second argument.
  159704. */
  159705. static int sqlite3Fts5ExprClonePhrase(
  159706. Fts5Config *pConfig,
  159707. Fts5Expr *pExpr,
  159708. int iPhrase,
  159709. Fts5Expr **ppNew
  159710. ){
  159711. int rc = SQLITE_OK; /* Return code */
  159712. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  159713. int i; /* Used to iterate through phrase terms */
  159714. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  159715. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  159716. pOrig = pExpr->apExprPhrase[iPhrase];
  159717. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  159718. if( rc==SQLITE_OK ){
  159719. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  159720. sizeof(Fts5ExprPhrase*));
  159721. }
  159722. if( rc==SQLITE_OK ){
  159723. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  159724. sizeof(Fts5ExprNode));
  159725. }
  159726. if( rc==SQLITE_OK ){
  159727. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  159728. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  159729. }
  159730. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  159731. int tflags = 0;
  159732. Fts5ExprTerm *p;
  159733. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  159734. const char *zTerm = p->zTerm;
  159735. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, strlen(zTerm), 0, 0);
  159736. tflags = FTS5_TOKEN_COLOCATED;
  159737. }
  159738. if( rc==SQLITE_OK ){
  159739. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  159740. }
  159741. }
  159742. if( rc==SQLITE_OK ){
  159743. /* All the allocations succeeded. Put the expression object together. */
  159744. pNew->pIndex = pExpr->pIndex;
  159745. pNew->nPhrase = 1;
  159746. pNew->apExprPhrase[0] = sCtx.pPhrase;
  159747. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  159748. pNew->pRoot->pNear->nPhrase = 1;
  159749. sCtx.pPhrase->pNode = pNew->pRoot;
  159750. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  159751. pNew->pRoot->eType = FTS5_TERM;
  159752. }else{
  159753. pNew->pRoot->eType = FTS5_STRING;
  159754. }
  159755. }else{
  159756. sqlite3Fts5ExprFree(pNew);
  159757. fts5ExprPhraseFree(sCtx.pPhrase);
  159758. pNew = 0;
  159759. }
  159760. *ppNew = pNew;
  159761. return rc;
  159762. }
  159763. /*
  159764. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  159765. ** is expected. If token pTok does not contain "NEAR", store an error
  159766. ** in the pParse object.
  159767. */
  159768. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  159769. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  159770. sqlite3Fts5ParseError(
  159771. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  159772. );
  159773. }
  159774. }
  159775. static void sqlite3Fts5ParseSetDistance(
  159776. Fts5Parse *pParse,
  159777. Fts5ExprNearset *pNear,
  159778. Fts5Token *p
  159779. ){
  159780. int nNear = 0;
  159781. int i;
  159782. if( p->n ){
  159783. for(i=0; i<p->n; i++){
  159784. char c = (char)p->p[i];
  159785. if( c<'0' || c>'9' ){
  159786. sqlite3Fts5ParseError(
  159787. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  159788. );
  159789. return;
  159790. }
  159791. nNear = nNear * 10 + (p->p[i] - '0');
  159792. }
  159793. }else{
  159794. nNear = FTS5_DEFAULT_NEARDIST;
  159795. }
  159796. pNear->nNear = nNear;
  159797. }
  159798. /*
  159799. ** The second argument passed to this function may be NULL, or it may be
  159800. ** an existing Fts5Colset object. This function returns a pointer to
  159801. ** a new colset object containing the contents of (p) with new value column
  159802. ** number iCol appended.
  159803. **
  159804. ** If an OOM error occurs, store an error code in pParse and return NULL.
  159805. ** The old colset object (if any) is not freed in this case.
  159806. */
  159807. static Fts5Colset *fts5ParseColset(
  159808. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  159809. Fts5Colset *p, /* Existing colset object */
  159810. int iCol /* New column to add to colset object */
  159811. ){
  159812. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  159813. Fts5Colset *pNew; /* New colset object to return */
  159814. assert( pParse->rc==SQLITE_OK );
  159815. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  159816. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  159817. if( pNew==0 ){
  159818. pParse->rc = SQLITE_NOMEM;
  159819. }else{
  159820. int *aiCol = pNew->aiCol;
  159821. int i, j;
  159822. for(i=0; i<nCol; i++){
  159823. if( aiCol[i]==iCol ) return pNew;
  159824. if( aiCol[i]>iCol ) break;
  159825. }
  159826. for(j=nCol; j>i; j--){
  159827. aiCol[j] = aiCol[j-1];
  159828. }
  159829. aiCol[i] = iCol;
  159830. pNew->nCol = nCol+1;
  159831. #ifndef NDEBUG
  159832. /* Check that the array is in order and contains no duplicate entries. */
  159833. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  159834. #endif
  159835. }
  159836. return pNew;
  159837. }
  159838. static Fts5Colset *sqlite3Fts5ParseColset(
  159839. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  159840. Fts5Colset *pColset, /* Existing colset object */
  159841. Fts5Token *p
  159842. ){
  159843. Fts5Colset *pRet = 0;
  159844. int iCol;
  159845. char *z; /* Dequoted copy of token p */
  159846. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  159847. if( pParse->rc==SQLITE_OK ){
  159848. Fts5Config *pConfig = pParse->pConfig;
  159849. sqlite3Fts5Dequote(z);
  159850. for(iCol=0; iCol<pConfig->nCol; iCol++){
  159851. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  159852. }
  159853. if( iCol==pConfig->nCol ){
  159854. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  159855. }else{
  159856. pRet = fts5ParseColset(pParse, pColset, iCol);
  159857. }
  159858. sqlite3_free(z);
  159859. }
  159860. if( pRet==0 ){
  159861. assert( pParse->rc!=SQLITE_OK );
  159862. sqlite3_free(pColset);
  159863. }
  159864. return pRet;
  159865. }
  159866. static void sqlite3Fts5ParseSetColset(
  159867. Fts5Parse *pParse,
  159868. Fts5ExprNearset *pNear,
  159869. Fts5Colset *pColset
  159870. ){
  159871. if( pNear ){
  159872. pNear->pColset = pColset;
  159873. }else{
  159874. sqlite3_free(pColset);
  159875. }
  159876. }
  159877. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  159878. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  159879. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  159880. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  159881. p->nChild += pSub->nChild;
  159882. sqlite3_free(pSub);
  159883. }else{
  159884. p->apChild[p->nChild++] = pSub;
  159885. }
  159886. }
  159887. /*
  159888. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  159889. ** OOM error), leave an error code in pParse and return NULL.
  159890. */
  159891. static Fts5ExprNode *sqlite3Fts5ParseNode(
  159892. Fts5Parse *pParse, /* Parse context */
  159893. int eType, /* FTS5_STRING, AND, OR or NOT */
  159894. Fts5ExprNode *pLeft, /* Left hand child expression */
  159895. Fts5ExprNode *pRight, /* Right hand child expression */
  159896. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  159897. ){
  159898. Fts5ExprNode *pRet = 0;
  159899. if( pParse->rc==SQLITE_OK ){
  159900. int nChild = 0; /* Number of children of returned node */
  159901. int nByte; /* Bytes of space to allocate for this node */
  159902. assert( (eType!=FTS5_STRING && !pNear)
  159903. || (eType==FTS5_STRING && !pLeft && !pRight)
  159904. );
  159905. if( eType==FTS5_STRING && pNear==0 ) return 0;
  159906. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  159907. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  159908. if( eType==FTS5_NOT ){
  159909. nChild = 2;
  159910. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  159911. nChild = 2;
  159912. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  159913. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  159914. }
  159915. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  159916. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  159917. if( pRet ){
  159918. pRet->eType = eType;
  159919. pRet->pNear = pNear;
  159920. if( eType==FTS5_STRING ){
  159921. int iPhrase;
  159922. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  159923. pNear->apPhrase[iPhrase]->pNode = pRet;
  159924. }
  159925. if( pNear->nPhrase==1
  159926. && pNear->apPhrase[0]->nTerm==1
  159927. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  159928. ){
  159929. pRet->eType = FTS5_TERM;
  159930. }
  159931. }else{
  159932. fts5ExprAddChildren(pRet, pLeft);
  159933. fts5ExprAddChildren(pRet, pRight);
  159934. }
  159935. }
  159936. }
  159937. if( pRet==0 ){
  159938. assert( pParse->rc!=SQLITE_OK );
  159939. sqlite3Fts5ParseNodeFree(pLeft);
  159940. sqlite3Fts5ParseNodeFree(pRight);
  159941. sqlite3Fts5ParseNearsetFree(pNear);
  159942. }
  159943. return pRet;
  159944. }
  159945. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  159946. int nByte = 0;
  159947. Fts5ExprTerm *p;
  159948. char *zQuoted;
  159949. /* Determine the maximum amount of space required. */
  159950. for(p=pTerm; p; p=p->pSynonym){
  159951. nByte += strlen(pTerm->zTerm) * 2 + 3 + 2;
  159952. }
  159953. zQuoted = sqlite3_malloc(nByte);
  159954. if( zQuoted ){
  159955. int i = 0;
  159956. for(p=pTerm; p; p=p->pSynonym){
  159957. char *zIn = p->zTerm;
  159958. zQuoted[i++] = '"';
  159959. while( *zIn ){
  159960. if( *zIn=='"' ) zQuoted[i++] = '"';
  159961. zQuoted[i++] = *zIn++;
  159962. }
  159963. zQuoted[i++] = '"';
  159964. if( p->pSynonym ) zQuoted[i++] = '|';
  159965. }
  159966. if( pTerm->bPrefix ){
  159967. zQuoted[i++] = ' ';
  159968. zQuoted[i++] = '*';
  159969. }
  159970. zQuoted[i++] = '\0';
  159971. }
  159972. return zQuoted;
  159973. }
  159974. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  159975. char *zNew;
  159976. va_list ap;
  159977. va_start(ap, zFmt);
  159978. zNew = sqlite3_vmprintf(zFmt, ap);
  159979. va_end(ap);
  159980. if( zApp && zNew ){
  159981. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  159982. sqlite3_free(zNew);
  159983. zNew = zNew2;
  159984. }
  159985. sqlite3_free(zApp);
  159986. return zNew;
  159987. }
  159988. /*
  159989. ** Compose a tcl-readable representation of expression pExpr. Return a
  159990. ** pointer to a buffer containing that representation. It is the
  159991. ** responsibility of the caller to at some point free the buffer using
  159992. ** sqlite3_free().
  159993. */
  159994. static char *fts5ExprPrintTcl(
  159995. Fts5Config *pConfig,
  159996. const char *zNearsetCmd,
  159997. Fts5ExprNode *pExpr
  159998. ){
  159999. char *zRet = 0;
  160000. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  160001. Fts5ExprNearset *pNear = pExpr->pNear;
  160002. int i;
  160003. int iTerm;
  160004. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  160005. if( zRet==0 ) return 0;
  160006. if( pNear->pColset ){
  160007. int *aiCol = pNear->pColset->aiCol;
  160008. int nCol = pNear->pColset->nCol;
  160009. if( nCol==1 ){
  160010. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  160011. }else{
  160012. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  160013. for(i=1; i<pNear->pColset->nCol; i++){
  160014. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  160015. }
  160016. zRet = fts5PrintfAppend(zRet, "} ");
  160017. }
  160018. if( zRet==0 ) return 0;
  160019. }
  160020. if( pNear->nPhrase>1 ){
  160021. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  160022. if( zRet==0 ) return 0;
  160023. }
  160024. zRet = fts5PrintfAppend(zRet, "--");
  160025. if( zRet==0 ) return 0;
  160026. for(i=0; i<pNear->nPhrase; i++){
  160027. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160028. zRet = fts5PrintfAppend(zRet, " {");
  160029. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  160030. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  160031. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  160032. }
  160033. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  160034. if( zRet==0 ) return 0;
  160035. }
  160036. }else{
  160037. char const *zOp = 0;
  160038. int i;
  160039. switch( pExpr->eType ){
  160040. case FTS5_AND: zOp = "AND"; break;
  160041. case FTS5_NOT: zOp = "NOT"; break;
  160042. default:
  160043. assert( pExpr->eType==FTS5_OR );
  160044. zOp = "OR";
  160045. break;
  160046. }
  160047. zRet = sqlite3_mprintf("%s", zOp);
  160048. for(i=0; zRet && i<pExpr->nChild; i++){
  160049. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  160050. if( !z ){
  160051. sqlite3_free(zRet);
  160052. zRet = 0;
  160053. }else{
  160054. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  160055. }
  160056. }
  160057. }
  160058. return zRet;
  160059. }
  160060. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  160061. char *zRet = 0;
  160062. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  160063. Fts5ExprNearset *pNear = pExpr->pNear;
  160064. int i;
  160065. int iTerm;
  160066. if( pNear->pColset ){
  160067. int iCol = pNear->pColset->aiCol[0];
  160068. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  160069. if( zRet==0 ) return 0;
  160070. }
  160071. if( pNear->nPhrase>1 ){
  160072. zRet = fts5PrintfAppend(zRet, "NEAR(");
  160073. if( zRet==0 ) return 0;
  160074. }
  160075. for(i=0; i<pNear->nPhrase; i++){
  160076. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160077. if( i!=0 ){
  160078. zRet = fts5PrintfAppend(zRet, " ");
  160079. if( zRet==0 ) return 0;
  160080. }
  160081. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  160082. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  160083. if( zTerm ){
  160084. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  160085. sqlite3_free(zTerm);
  160086. }
  160087. if( zTerm==0 || zRet==0 ){
  160088. sqlite3_free(zRet);
  160089. return 0;
  160090. }
  160091. }
  160092. }
  160093. if( pNear->nPhrase>1 ){
  160094. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  160095. if( zRet==0 ) return 0;
  160096. }
  160097. }else{
  160098. char const *zOp = 0;
  160099. int i;
  160100. switch( pExpr->eType ){
  160101. case FTS5_AND: zOp = " AND "; break;
  160102. case FTS5_NOT: zOp = " NOT "; break;
  160103. default:
  160104. assert( pExpr->eType==FTS5_OR );
  160105. zOp = " OR ";
  160106. break;
  160107. }
  160108. for(i=0; i<pExpr->nChild; i++){
  160109. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  160110. if( z==0 ){
  160111. sqlite3_free(zRet);
  160112. zRet = 0;
  160113. }else{
  160114. int e = pExpr->apChild[i]->eType;
  160115. int b = (e!=FTS5_STRING && e!=FTS5_TERM);
  160116. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  160117. (i==0 ? "" : zOp),
  160118. (b?"(":""), z, (b?")":"")
  160119. );
  160120. }
  160121. if( zRet==0 ) break;
  160122. }
  160123. }
  160124. return zRet;
  160125. }
  160126. /*
  160127. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  160128. ** and fts5_expr_tcl() (bTcl!=0).
  160129. */
  160130. static void fts5ExprFunction(
  160131. sqlite3_context *pCtx, /* Function call context */
  160132. int nArg, /* Number of args */
  160133. sqlite3_value **apVal, /* Function arguments */
  160134. int bTcl
  160135. ){
  160136. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  160137. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  160138. const char *zExpr = 0;
  160139. char *zErr = 0;
  160140. Fts5Expr *pExpr = 0;
  160141. int rc;
  160142. int i;
  160143. const char **azConfig; /* Array of arguments for Fts5Config */
  160144. const char *zNearsetCmd = "nearset";
  160145. int nConfig; /* Size of azConfig[] */
  160146. Fts5Config *pConfig = 0;
  160147. int iArg = 1;
  160148. if( nArg<1 ){
  160149. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  160150. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  160151. );
  160152. sqlite3_result_error(pCtx, zErr, -1);
  160153. sqlite3_free(zErr);
  160154. return;
  160155. }
  160156. if( bTcl && nArg>1 ){
  160157. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  160158. iArg = 2;
  160159. }
  160160. nConfig = 3 + (nArg-iArg);
  160161. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  160162. if( azConfig==0 ){
  160163. sqlite3_result_error_nomem(pCtx);
  160164. return;
  160165. }
  160166. azConfig[0] = 0;
  160167. azConfig[1] = "main";
  160168. azConfig[2] = "tbl";
  160169. for(i=3; iArg<nArg; iArg++){
  160170. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  160171. }
  160172. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  160173. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  160174. if( rc==SQLITE_OK ){
  160175. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
  160176. }
  160177. if( rc==SQLITE_OK ){
  160178. char *zText;
  160179. if( pExpr->pRoot==0 ){
  160180. zText = sqlite3_mprintf("");
  160181. }else if( bTcl ){
  160182. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  160183. }else{
  160184. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  160185. }
  160186. if( zText==0 ){
  160187. rc = SQLITE_NOMEM;
  160188. }else{
  160189. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  160190. sqlite3_free(zText);
  160191. }
  160192. }
  160193. if( rc!=SQLITE_OK ){
  160194. if( zErr ){
  160195. sqlite3_result_error(pCtx, zErr, -1);
  160196. sqlite3_free(zErr);
  160197. }else{
  160198. sqlite3_result_error_code(pCtx, rc);
  160199. }
  160200. }
  160201. sqlite3_free((void *)azConfig);
  160202. sqlite3Fts5ConfigFree(pConfig);
  160203. sqlite3Fts5ExprFree(pExpr);
  160204. }
  160205. static void fts5ExprFunctionHr(
  160206. sqlite3_context *pCtx, /* Function call context */
  160207. int nArg, /* Number of args */
  160208. sqlite3_value **apVal /* Function arguments */
  160209. ){
  160210. fts5ExprFunction(pCtx, nArg, apVal, 0);
  160211. }
  160212. static void fts5ExprFunctionTcl(
  160213. sqlite3_context *pCtx, /* Function call context */
  160214. int nArg, /* Number of args */
  160215. sqlite3_value **apVal /* Function arguments */
  160216. ){
  160217. fts5ExprFunction(pCtx, nArg, apVal, 1);
  160218. }
  160219. /*
  160220. ** The implementation of an SQLite user-defined-function that accepts a
  160221. ** single integer as an argument. If the integer is an alpha-numeric
  160222. ** unicode code point, 1 is returned. Otherwise 0.
  160223. */
  160224. static void fts5ExprIsAlnum(
  160225. sqlite3_context *pCtx, /* Function call context */
  160226. int nArg, /* Number of args */
  160227. sqlite3_value **apVal /* Function arguments */
  160228. ){
  160229. int iCode;
  160230. if( nArg!=1 ){
  160231. sqlite3_result_error(pCtx,
  160232. "wrong number of arguments to function fts5_isalnum", -1
  160233. );
  160234. return;
  160235. }
  160236. iCode = sqlite3_value_int(apVal[0]);
  160237. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  160238. }
  160239. static void fts5ExprFold(
  160240. sqlite3_context *pCtx, /* Function call context */
  160241. int nArg, /* Number of args */
  160242. sqlite3_value **apVal /* Function arguments */
  160243. ){
  160244. if( nArg!=1 && nArg!=2 ){
  160245. sqlite3_result_error(pCtx,
  160246. "wrong number of arguments to function fts5_fold", -1
  160247. );
  160248. }else{
  160249. int iCode;
  160250. int bRemoveDiacritics = 0;
  160251. iCode = sqlite3_value_int(apVal[0]);
  160252. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  160253. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  160254. }
  160255. }
  160256. /*
  160257. ** This is called during initialization to register the fts5_expr() scalar
  160258. ** UDF with the SQLite handle passed as the only argument.
  160259. */
  160260. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  160261. struct Fts5ExprFunc {
  160262. const char *z;
  160263. void (*x)(sqlite3_context*,int,sqlite3_value**);
  160264. } aFunc[] = {
  160265. { "fts5_expr", fts5ExprFunctionHr },
  160266. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  160267. { "fts5_isalnum", fts5ExprIsAlnum },
  160268. { "fts5_fold", fts5ExprFold },
  160269. };
  160270. int i;
  160271. int rc = SQLITE_OK;
  160272. void *pCtx = (void*)pGlobal;
  160273. for(i=0; rc==SQLITE_OK && i<(sizeof(aFunc) / sizeof(aFunc[0])); i++){
  160274. struct Fts5ExprFunc *p = &aFunc[i];
  160275. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  160276. }
  160277. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  160278. #ifndef NDEBUG
  160279. (void)sqlite3Fts5ParserTrace;
  160280. #endif
  160281. return rc;
  160282. }
  160283. /*
  160284. ** Return the number of phrases in expression pExpr.
  160285. */
  160286. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  160287. return (pExpr ? pExpr->nPhrase : 0);
  160288. }
  160289. /*
  160290. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  160291. */
  160292. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  160293. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  160294. return pExpr->apExprPhrase[iPhrase]->nTerm;
  160295. }
  160296. /*
  160297. ** This function is used to access the current position list for phrase
  160298. ** iPhrase.
  160299. */
  160300. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  160301. int nRet;
  160302. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  160303. Fts5ExprNode *pNode = pPhrase->pNode;
  160304. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  160305. *pa = pPhrase->poslist.p;
  160306. nRet = pPhrase->poslist.n;
  160307. }else{
  160308. *pa = 0;
  160309. nRet = 0;
  160310. }
  160311. return nRet;
  160312. }
  160313. /*
  160314. ** 2014 August 11
  160315. **
  160316. ** The author disclaims copyright to this source code. In place of
  160317. ** a legal notice, here is a blessing:
  160318. **
  160319. ** May you do good and not evil.
  160320. ** May you find forgiveness for yourself and forgive others.
  160321. ** May you share freely, never taking more than you give.
  160322. **
  160323. ******************************************************************************
  160324. **
  160325. */
  160326. typedef struct Fts5HashEntry Fts5HashEntry;
  160327. /*
  160328. ** This file contains the implementation of an in-memory hash table used
  160329. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  160330. ** segment.
  160331. */
  160332. struct Fts5Hash {
  160333. int *pnByte; /* Pointer to bytes counter */
  160334. int nEntry; /* Number of entries currently in hash */
  160335. int nSlot; /* Size of aSlot[] array */
  160336. Fts5HashEntry *pScan; /* Current ordered scan item */
  160337. Fts5HashEntry **aSlot; /* Array of hash slots */
  160338. };
  160339. /*
  160340. ** Each entry in the hash table is represented by an object of the
  160341. ** following type. Each object, its key (zKey[]) and its current data
  160342. ** are stored in a single memory allocation. The position list data
  160343. ** immediately follows the key data in memory.
  160344. **
  160345. ** The data that follows the key is in a similar, but not identical format
  160346. ** to the doclist data stored in the database. It is:
  160347. **
  160348. ** * Rowid, as a varint
  160349. ** * Position list, without 0x00 terminator.
  160350. ** * Size of previous position list and rowid, as a 4 byte
  160351. ** big-endian integer.
  160352. **
  160353. ** iRowidOff:
  160354. ** Offset of last rowid written to data area. Relative to first byte of
  160355. ** structure.
  160356. **
  160357. ** nData:
  160358. ** Bytes of data written since iRowidOff.
  160359. */
  160360. struct Fts5HashEntry {
  160361. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  160362. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  160363. int nAlloc; /* Total size of allocation */
  160364. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  160365. int nData; /* Total bytes of data (incl. structure) */
  160366. u8 bDel; /* Set delete-flag @ iSzPoslist */
  160367. int iCol; /* Column of last value written */
  160368. int iPos; /* Position of last value written */
  160369. i64 iRowid; /* Rowid of last value written */
  160370. char zKey[8]; /* Nul-terminated entry key */
  160371. };
  160372. /*
  160373. ** Size of Fts5HashEntry without the zKey[] array.
  160374. */
  160375. #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
  160376. /*
  160377. ** Allocate a new hash table.
  160378. */
  160379. static int sqlite3Fts5HashNew(Fts5Hash **ppNew, int *pnByte){
  160380. int rc = SQLITE_OK;
  160381. Fts5Hash *pNew;
  160382. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  160383. if( pNew==0 ){
  160384. rc = SQLITE_NOMEM;
  160385. }else{
  160386. int nByte;
  160387. memset(pNew, 0, sizeof(Fts5Hash));
  160388. pNew->pnByte = pnByte;
  160389. pNew->nSlot = 1024;
  160390. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  160391. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  160392. if( pNew->aSlot==0 ){
  160393. sqlite3_free(pNew);
  160394. *ppNew = 0;
  160395. rc = SQLITE_NOMEM;
  160396. }else{
  160397. memset(pNew->aSlot, 0, nByte);
  160398. }
  160399. }
  160400. return rc;
  160401. }
  160402. /*
  160403. ** Free a hash table object.
  160404. */
  160405. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  160406. if( pHash ){
  160407. sqlite3Fts5HashClear(pHash);
  160408. sqlite3_free(pHash->aSlot);
  160409. sqlite3_free(pHash);
  160410. }
  160411. }
  160412. /*
  160413. ** Empty (but do not delete) a hash table.
  160414. */
  160415. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  160416. int i;
  160417. for(i=0; i<pHash->nSlot; i++){
  160418. Fts5HashEntry *pNext;
  160419. Fts5HashEntry *pSlot;
  160420. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  160421. pNext = pSlot->pHashNext;
  160422. sqlite3_free(pSlot);
  160423. }
  160424. }
  160425. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  160426. pHash->nEntry = 0;
  160427. }
  160428. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  160429. int i;
  160430. unsigned int h = 13;
  160431. for(i=n-1; i>=0; i--){
  160432. h = (h << 3) ^ h ^ p[i];
  160433. }
  160434. return (h % nSlot);
  160435. }
  160436. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  160437. int i;
  160438. unsigned int h = 13;
  160439. for(i=n-1; i>=0; i--){
  160440. h = (h << 3) ^ h ^ p[i];
  160441. }
  160442. h = (h << 3) ^ h ^ b;
  160443. return (h % nSlot);
  160444. }
  160445. /*
  160446. ** Resize the hash table by doubling the number of slots.
  160447. */
  160448. static int fts5HashResize(Fts5Hash *pHash){
  160449. int nNew = pHash->nSlot*2;
  160450. int i;
  160451. Fts5HashEntry **apNew;
  160452. Fts5HashEntry **apOld = pHash->aSlot;
  160453. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  160454. if( !apNew ) return SQLITE_NOMEM;
  160455. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  160456. for(i=0; i<pHash->nSlot; i++){
  160457. while( apOld[i] ){
  160458. int iHash;
  160459. Fts5HashEntry *p = apOld[i];
  160460. apOld[i] = p->pHashNext;
  160461. iHash = fts5HashKey(nNew, (u8*)p->zKey, strlen(p->zKey));
  160462. p->pHashNext = apNew[iHash];
  160463. apNew[iHash] = p;
  160464. }
  160465. }
  160466. sqlite3_free(apOld);
  160467. pHash->nSlot = nNew;
  160468. pHash->aSlot = apNew;
  160469. return SQLITE_OK;
  160470. }
  160471. static void fts5HashAddPoslistSize(Fts5HashEntry *p){
  160472. if( p->iSzPoslist ){
  160473. u8 *pPtr = (u8*)p;
  160474. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  160475. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  160476. assert( p->bDel==0 || p->bDel==1 );
  160477. if( nPos<=127 ){
  160478. pPtr[p->iSzPoslist] = nPos;
  160479. }else{
  160480. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  160481. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  160482. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  160483. p->nData += (nByte-1);
  160484. }
  160485. p->bDel = 0;
  160486. p->iSzPoslist = 0;
  160487. }
  160488. }
  160489. static int sqlite3Fts5HashWrite(
  160490. Fts5Hash *pHash,
  160491. i64 iRowid, /* Rowid for this entry */
  160492. int iCol, /* Column token appears in (-ve -> delete) */
  160493. int iPos, /* Position of token within column */
  160494. char bByte, /* First byte of token */
  160495. const char *pToken, int nToken /* Token to add or remove to or from index */
  160496. ){
  160497. unsigned int iHash;
  160498. Fts5HashEntry *p;
  160499. u8 *pPtr;
  160500. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  160501. /* Attempt to locate an existing hash entry */
  160502. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  160503. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  160504. if( p->zKey[0]==bByte
  160505. && memcmp(&p->zKey[1], pToken, nToken)==0
  160506. && p->zKey[nToken+1]==0
  160507. ){
  160508. break;
  160509. }
  160510. }
  160511. /* If an existing hash entry cannot be found, create a new one. */
  160512. if( p==0 ){
  160513. int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
  160514. if( nByte<128 ) nByte = 128;
  160515. if( (pHash->nEntry*2)>=pHash->nSlot ){
  160516. int rc = fts5HashResize(pHash);
  160517. if( rc!=SQLITE_OK ) return rc;
  160518. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  160519. }
  160520. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  160521. if( !p ) return SQLITE_NOMEM;
  160522. memset(p, 0, FTS5_HASHENTRYSIZE);
  160523. p->nAlloc = nByte;
  160524. p->zKey[0] = bByte;
  160525. memcpy(&p->zKey[1], pToken, nToken);
  160526. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
  160527. p->zKey[nToken+1] = '\0';
  160528. p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
  160529. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  160530. p->iSzPoslist = p->nData;
  160531. p->nData += 1;
  160532. p->iRowid = iRowid;
  160533. p->pHashNext = pHash->aSlot[iHash];
  160534. pHash->aSlot[iHash] = p;
  160535. pHash->nEntry++;
  160536. nIncr += p->nData;
  160537. }
  160538. /* Check there is enough space to append a new entry. Worst case scenario
  160539. ** is:
  160540. **
  160541. ** + 9 bytes for a new rowid,
  160542. ** + 4 byte reserved for the "poslist size" varint.
  160543. ** + 1 byte for a "new column" byte,
  160544. ** + 3 bytes for a new column number (16-bit max) as a varint,
  160545. ** + 5 bytes for the new position offset (32-bit max).
  160546. */
  160547. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  160548. int nNew = p->nAlloc * 2;
  160549. Fts5HashEntry *pNew;
  160550. Fts5HashEntry **pp;
  160551. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  160552. if( pNew==0 ) return SQLITE_NOMEM;
  160553. pNew->nAlloc = nNew;
  160554. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  160555. *pp = pNew;
  160556. p = pNew;
  160557. }
  160558. pPtr = (u8*)p;
  160559. nIncr -= p->nData;
  160560. /* If this is a new rowid, append the 4-byte size field for the previous
  160561. ** entry, and the new rowid for this entry. */
  160562. if( iRowid!=p->iRowid ){
  160563. fts5HashAddPoslistSize(p);
  160564. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  160565. p->iSzPoslist = p->nData;
  160566. p->nData += 1;
  160567. p->iCol = 0;
  160568. p->iPos = 0;
  160569. p->iRowid = iRowid;
  160570. }
  160571. if( iCol>=0 ){
  160572. /* Append a new column value, if necessary */
  160573. assert( iCol>=p->iCol );
  160574. if( iCol!=p->iCol ){
  160575. pPtr[p->nData++] = 0x01;
  160576. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  160577. p->iCol = iCol;
  160578. p->iPos = 0;
  160579. }
  160580. /* Append the new position offset */
  160581. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  160582. p->iPos = iPos;
  160583. }else{
  160584. /* This is a delete. Set the delete flag. */
  160585. p->bDel = 1;
  160586. }
  160587. nIncr += p->nData;
  160588. *pHash->pnByte += nIncr;
  160589. return SQLITE_OK;
  160590. }
  160591. /*
  160592. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  160593. ** each sorted in key order. This function merges the two lists into a
  160594. ** single list and returns a pointer to its first element.
  160595. */
  160596. static Fts5HashEntry *fts5HashEntryMerge(
  160597. Fts5HashEntry *pLeft,
  160598. Fts5HashEntry *pRight
  160599. ){
  160600. Fts5HashEntry *p1 = pLeft;
  160601. Fts5HashEntry *p2 = pRight;
  160602. Fts5HashEntry *pRet = 0;
  160603. Fts5HashEntry **ppOut = &pRet;
  160604. while( p1 || p2 ){
  160605. if( p1==0 ){
  160606. *ppOut = p2;
  160607. p2 = 0;
  160608. }else if( p2==0 ){
  160609. *ppOut = p1;
  160610. p1 = 0;
  160611. }else{
  160612. int i = 0;
  160613. while( p1->zKey[i]==p2->zKey[i] ) i++;
  160614. if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
  160615. /* p2 is smaller */
  160616. *ppOut = p2;
  160617. ppOut = &p2->pScanNext;
  160618. p2 = p2->pScanNext;
  160619. }else{
  160620. /* p1 is smaller */
  160621. *ppOut = p1;
  160622. ppOut = &p1->pScanNext;
  160623. p1 = p1->pScanNext;
  160624. }
  160625. *ppOut = 0;
  160626. }
  160627. }
  160628. return pRet;
  160629. }
  160630. /*
  160631. ** Extract all tokens from hash table iHash and link them into a list
  160632. ** in sorted order. The hash table is cleared before returning. It is
  160633. ** the responsibility of the caller to free the elements of the returned
  160634. ** list.
  160635. */
  160636. static int fts5HashEntrySort(
  160637. Fts5Hash *pHash,
  160638. const char *pTerm, int nTerm, /* Query prefix, if any */
  160639. Fts5HashEntry **ppSorted
  160640. ){
  160641. const int nMergeSlot = 32;
  160642. Fts5HashEntry **ap;
  160643. Fts5HashEntry *pList;
  160644. int iSlot;
  160645. int i;
  160646. *ppSorted = 0;
  160647. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  160648. if( !ap ) return SQLITE_NOMEM;
  160649. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  160650. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  160651. Fts5HashEntry *pIter;
  160652. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  160653. if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
  160654. Fts5HashEntry *pEntry = pIter;
  160655. pEntry->pScanNext = 0;
  160656. for(i=0; ap[i]; i++){
  160657. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  160658. ap[i] = 0;
  160659. }
  160660. ap[i] = pEntry;
  160661. }
  160662. }
  160663. }
  160664. pList = 0;
  160665. for(i=0; i<nMergeSlot; i++){
  160666. pList = fts5HashEntryMerge(pList, ap[i]);
  160667. }
  160668. pHash->nEntry = 0;
  160669. sqlite3_free(ap);
  160670. *ppSorted = pList;
  160671. return SQLITE_OK;
  160672. }
  160673. /*
  160674. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  160675. */
  160676. static int sqlite3Fts5HashQuery(
  160677. Fts5Hash *pHash, /* Hash table to query */
  160678. const char *pTerm, int nTerm, /* Query term */
  160679. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  160680. int *pnDoclist /* OUT: Size of doclist in bytes */
  160681. ){
  160682. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  160683. Fts5HashEntry *p;
  160684. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  160685. if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
  160686. }
  160687. if( p ){
  160688. fts5HashAddPoslistSize(p);
  160689. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  160690. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  160691. }else{
  160692. *ppDoclist = 0;
  160693. *pnDoclist = 0;
  160694. }
  160695. return SQLITE_OK;
  160696. }
  160697. static int sqlite3Fts5HashScanInit(
  160698. Fts5Hash *p, /* Hash table to query */
  160699. const char *pTerm, int nTerm /* Query prefix */
  160700. ){
  160701. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  160702. }
  160703. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  160704. assert( !sqlite3Fts5HashScanEof(p) );
  160705. p->pScan = p->pScan->pScanNext;
  160706. }
  160707. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  160708. return (p->pScan==0);
  160709. }
  160710. static void sqlite3Fts5HashScanEntry(
  160711. Fts5Hash *pHash,
  160712. const char **pzTerm, /* OUT: term (nul-terminated) */
  160713. const u8 **ppDoclist, /* OUT: pointer to doclist */
  160714. int *pnDoclist /* OUT: size of doclist in bytes */
  160715. ){
  160716. Fts5HashEntry *p;
  160717. if( (p = pHash->pScan) ){
  160718. int nTerm = strlen(p->zKey);
  160719. fts5HashAddPoslistSize(p);
  160720. *pzTerm = p->zKey;
  160721. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  160722. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  160723. }else{
  160724. *pzTerm = 0;
  160725. *ppDoclist = 0;
  160726. *pnDoclist = 0;
  160727. }
  160728. }
  160729. /*
  160730. ** 2014 May 31
  160731. **
  160732. ** The author disclaims copyright to this source code. In place of
  160733. ** a legal notice, here is a blessing:
  160734. **
  160735. ** May you do good and not evil.
  160736. ** May you find forgiveness for yourself and forgive others.
  160737. ** May you share freely, never taking more than you give.
  160738. **
  160739. ******************************************************************************
  160740. **
  160741. ** Low level access to the FTS index stored in the database file. The
  160742. ** routines in this file file implement all read and write access to the
  160743. ** %_data table. Other parts of the system access this functionality via
  160744. ** the interface defined in fts5Int.h.
  160745. */
  160746. /*
  160747. ** Overview:
  160748. **
  160749. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  160750. ** As well as the main term index, there may be up to 31 prefix indexes.
  160751. ** The format is similar to FTS3/4, except that:
  160752. **
  160753. ** * all segment b-tree leaf data is stored in fixed size page records
  160754. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  160755. ** taken to ensure it is possible to iterate in either direction through
  160756. ** the entries in a doclist, or to seek to a specific entry within a
  160757. ** doclist, without loading it into memory.
  160758. **
  160759. ** * large doclists that span many pages have associated "doclist index"
  160760. ** records that contain a copy of the first rowid on each page spanned by
  160761. ** the doclist. This is used to speed up seek operations, and merges of
  160762. ** large doclists with very small doclists.
  160763. **
  160764. ** * extra fields in the "structure record" record the state of ongoing
  160765. ** incremental merge operations.
  160766. **
  160767. */
  160768. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  160769. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  160770. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  160771. #define FTS5_MAIN_PREFIX '0'
  160772. #if FTS5_MAX_PREFIX_INDEXES > 31
  160773. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  160774. #endif
  160775. /*
  160776. ** Details:
  160777. **
  160778. ** The %_data table managed by this module,
  160779. **
  160780. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  160781. **
  160782. ** , contains the following 5 types of records. See the comments surrounding
  160783. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  160784. ** assigned to each fo them.
  160785. **
  160786. ** 1. Structure Records:
  160787. **
  160788. ** The set of segments that make up an index - the index structure - are
  160789. ** recorded in a single record within the %_data table. The record consists
  160790. ** of a single 32-bit configuration cookie value followed by a list of
  160791. ** SQLite varints. If the FTS table features more than one index (because
  160792. ** there are one or more prefix indexes), it is guaranteed that all share
  160793. ** the same cookie value.
  160794. **
  160795. ** Immediately following the configuration cookie, the record begins with
  160796. ** three varints:
  160797. **
  160798. ** + number of levels,
  160799. ** + total number of segments on all levels,
  160800. ** + value of write counter.
  160801. **
  160802. ** Then, for each level from 0 to nMax:
  160803. **
  160804. ** + number of input segments in ongoing merge.
  160805. ** + total number of segments in level.
  160806. ** + for each segment from oldest to newest:
  160807. ** + segment id (always > 0)
  160808. ** + first leaf page number (often 1, always greater than 0)
  160809. ** + final leaf page number
  160810. **
  160811. ** 2. The Averages Record:
  160812. **
  160813. ** A single record within the %_data table. The data is a list of varints.
  160814. ** The first value is the number of rows in the index. Then, for each column
  160815. ** from left to right, the total number of tokens in the column for all
  160816. ** rows of the table.
  160817. **
  160818. ** 3. Segment leaves:
  160819. **
  160820. ** TERM/DOCLIST FORMAT:
  160821. **
  160822. ** Most of each segment leaf is taken up by term/doclist data. The
  160823. ** general format of term/doclist, starting with the first term
  160824. ** on the leaf page, is:
  160825. **
  160826. ** varint : size of first term
  160827. ** blob: first term data
  160828. ** doclist: first doclist
  160829. ** zero-or-more {
  160830. ** varint: number of bytes in common with previous term
  160831. ** varint: number of bytes of new term data (nNew)
  160832. ** blob: nNew bytes of new term data
  160833. ** doclist: next doclist
  160834. ** }
  160835. **
  160836. ** doclist format:
  160837. **
  160838. ** varint: first rowid
  160839. ** poslist: first poslist
  160840. ** zero-or-more {
  160841. ** varint: rowid delta (always > 0)
  160842. ** poslist: next poslist
  160843. ** }
  160844. **
  160845. ** poslist format:
  160846. **
  160847. ** varint: size of poslist in bytes multiplied by 2, not including
  160848. ** this field. Plus 1 if this entry carries the "delete" flag.
  160849. ** collist: collist for column 0
  160850. ** zero-or-more {
  160851. ** 0x01 byte
  160852. ** varint: column number (I)
  160853. ** collist: collist for column I
  160854. ** }
  160855. **
  160856. ** collist format:
  160857. **
  160858. ** varint: first offset + 2
  160859. ** zero-or-more {
  160860. ** varint: offset delta + 2
  160861. ** }
  160862. **
  160863. ** PAGE FORMAT
  160864. **
  160865. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  160866. ** unsigned integer fields in big-endian format. They are:
  160867. **
  160868. ** * The byte offset of the first rowid on the page, if it exists
  160869. ** and occurs before the first term (otherwise 0).
  160870. **
  160871. ** * The byte offset of the start of the page footer. If the page
  160872. ** footer is 0 bytes in size, then this field is the same as the
  160873. ** size of the leaf page in bytes.
  160874. **
  160875. ** The page footer consists of a single varint for each term located
  160876. ** on the page. Each varint is the byte offset of the current term
  160877. ** within the page, delta-compressed against the previous value. In
  160878. ** other words, the first varint in the footer is the byte offset of
  160879. ** the first term, the second is the byte offset of the second less that
  160880. ** of the first, and so on.
  160881. **
  160882. ** The term/doclist format described above is accurate if the entire
  160883. ** term/doclist data fits on a single leaf page. If this is not the case,
  160884. ** the format is changed in two ways:
  160885. **
  160886. ** + if the first rowid on a page occurs before the first term, it
  160887. ** is stored as a literal value:
  160888. **
  160889. ** varint: first rowid
  160890. **
  160891. ** + the first term on each page is stored in the same way as the
  160892. ** very first term of the segment:
  160893. **
  160894. ** varint : size of first term
  160895. ** blob: first term data
  160896. **
  160897. ** 5. Segment doclist indexes:
  160898. **
  160899. ** Doclist indexes are themselves b-trees, however they usually consist of
  160900. ** a single leaf record only. The format of each doclist index leaf page
  160901. ** is:
  160902. **
  160903. ** * Flags byte. Bits are:
  160904. ** 0x01: Clear if leaf is also the root page, otherwise set.
  160905. **
  160906. ** * Page number of fts index leaf page. As a varint.
  160907. **
  160908. ** * First rowid on page indicated by previous field. As a varint.
  160909. **
  160910. ** * A list of varints, one for each subsequent termless page. A
  160911. ** positive delta if the termless page contains at least one rowid,
  160912. ** or an 0x00 byte otherwise.
  160913. **
  160914. ** Internal doclist index nodes are:
  160915. **
  160916. ** * Flags byte. Bits are:
  160917. ** 0x01: Clear for root page, otherwise set.
  160918. **
  160919. ** * Page number of first child page. As a varint.
  160920. **
  160921. ** * Copy of first rowid on page indicated by previous field. As a varint.
  160922. **
  160923. ** * A list of delta-encoded varints - the first rowid on each subsequent
  160924. ** child page.
  160925. **
  160926. */
  160927. /*
  160928. ** Rowids for the averages and structure records in the %_data table.
  160929. */
  160930. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  160931. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  160932. /*
  160933. ** Macros determining the rowids used by segment leaves and dlidx leaves
  160934. ** and nodes. All nodes and leaves are stored in the %_data table with large
  160935. ** positive rowids.
  160936. **
  160937. ** Each segment has a unique non-zero 16-bit id.
  160938. **
  160939. ** The rowid for each segment leaf is found by passing the segment id and
  160940. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  160941. ** sequentially starting from 1.
  160942. */
  160943. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  160944. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  160945. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  160946. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  160947. #define fts5_dri(segid, dlidx, height, pgno) ( \
  160948. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  160949. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  160950. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  160951. ((i64)(pgno)) \
  160952. )
  160953. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  160954. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  160955. /*
  160956. ** Maximum segments permitted in a single index
  160957. */
  160958. #define FTS5_MAX_SEGMENT 2000
  160959. #ifdef SQLITE_DEBUG
  160960. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  160961. #endif
  160962. /*
  160963. ** Each time a blob is read from the %_data table, it is padded with this
  160964. ** many zero bytes. This makes it easier to decode the various record formats
  160965. ** without overreading if the records are corrupt.
  160966. */
  160967. #define FTS5_DATA_ZERO_PADDING 8
  160968. #define FTS5_DATA_PADDING 20
  160969. typedef struct Fts5Data Fts5Data;
  160970. typedef struct Fts5DlidxIter Fts5DlidxIter;
  160971. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  160972. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  160973. typedef struct Fts5PageWriter Fts5PageWriter;
  160974. typedef struct Fts5SegIter Fts5SegIter;
  160975. typedef struct Fts5DoclistIter Fts5DoclistIter;
  160976. typedef struct Fts5SegWriter Fts5SegWriter;
  160977. typedef struct Fts5Structure Fts5Structure;
  160978. typedef struct Fts5StructureLevel Fts5StructureLevel;
  160979. typedef struct Fts5StructureSegment Fts5StructureSegment;
  160980. struct Fts5Data {
  160981. u8 *p; /* Pointer to buffer containing record */
  160982. int nn; /* Size of record in bytes */
  160983. int szLeaf; /* Size of leaf without page-index */
  160984. };
  160985. /*
  160986. ** One object per %_data table.
  160987. */
  160988. struct Fts5Index {
  160989. Fts5Config *pConfig; /* Virtual table configuration */
  160990. char *zDataTbl; /* Name of %_data table */
  160991. int nWorkUnit; /* Leaf pages in a "unit" of work */
  160992. /*
  160993. ** Variables related to the accumulation of tokens and doclists within the
  160994. ** in-memory hash tables before they are flushed to disk.
  160995. */
  160996. Fts5Hash *pHash; /* Hash table for in-memory data */
  160997. int nMaxPendingData; /* Max pending data before flush to disk */
  160998. int nPendingData; /* Current bytes of pending data */
  160999. i64 iWriteRowid; /* Rowid for current doc being written */
  161000. int bDelete; /* Current write is a delete */
  161001. /* Error state. */
  161002. int rc; /* Current error code */
  161003. /* State used by the fts5DataXXX() functions. */
  161004. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  161005. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  161006. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  161007. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  161008. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  161009. sqlite3_stmt *pIdxSelect;
  161010. int nRead; /* Total number of blocks read */
  161011. };
  161012. struct Fts5DoclistIter {
  161013. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  161014. /* Output variables. aPoslist==0 at EOF */
  161015. i64 iRowid;
  161016. u8 *aPoslist;
  161017. int nPoslist;
  161018. int nSize;
  161019. };
  161020. /*
  161021. ** The contents of the "structure" record for each index are represented
  161022. ** using an Fts5Structure record in memory. Which uses instances of the
  161023. ** other Fts5StructureXXX types as components.
  161024. */
  161025. struct Fts5StructureSegment {
  161026. int iSegid; /* Segment id */
  161027. int pgnoFirst; /* First leaf page number in segment */
  161028. int pgnoLast; /* Last leaf page number in segment */
  161029. };
  161030. struct Fts5StructureLevel {
  161031. int nMerge; /* Number of segments in incr-merge */
  161032. int nSeg; /* Total number of segments on level */
  161033. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  161034. };
  161035. struct Fts5Structure {
  161036. int nRef; /* Object reference count */
  161037. u64 nWriteCounter; /* Total leaves written to level 0 */
  161038. int nSegment; /* Total segments in this structure */
  161039. int nLevel; /* Number of levels in this index */
  161040. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  161041. };
  161042. /*
  161043. ** An object of type Fts5SegWriter is used to write to segments.
  161044. */
  161045. struct Fts5PageWriter {
  161046. int pgno; /* Page number for this page */
  161047. int iPrevPgidx; /* Previous value written into pgidx */
  161048. Fts5Buffer buf; /* Buffer containing leaf data */
  161049. Fts5Buffer pgidx; /* Buffer containing page-index */
  161050. Fts5Buffer term; /* Buffer containing previous term on page */
  161051. };
  161052. struct Fts5DlidxWriter {
  161053. int pgno; /* Page number for this page */
  161054. int bPrevValid; /* True if iPrev is valid */
  161055. i64 iPrev; /* Previous rowid value written to page */
  161056. Fts5Buffer buf; /* Buffer containing page data */
  161057. };
  161058. struct Fts5SegWriter {
  161059. int iSegid; /* Segid to write to */
  161060. Fts5PageWriter writer; /* PageWriter object */
  161061. i64 iPrevRowid; /* Previous rowid written to current leaf */
  161062. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  161063. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  161064. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  161065. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  161066. int nLeafWritten; /* Number of leaf pages written */
  161067. int nEmpty; /* Number of contiguous term-less nodes */
  161068. int nDlidx; /* Allocated size of aDlidx[] array */
  161069. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  161070. /* Values to insert into the %_idx table */
  161071. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  161072. int iBtPage; /* Page number corresponding to btterm */
  161073. };
  161074. /*
  161075. ** Object for iterating through the merged results of one or more segments,
  161076. ** visiting each term/rowid pair in the merged data.
  161077. **
  161078. ** nSeg is always a power of two greater than or equal to the number of
  161079. ** segments that this object is merging data from. Both the aSeg[] and
  161080. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  161081. ** with zeroed objects - these are handled as if they were iterators opened
  161082. ** on empty segments.
  161083. **
  161084. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  161085. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  161086. ** comparison in this context is the index of the iterator that currently
  161087. ** points to the smaller term/rowid combination. Iterators at EOF are
  161088. ** considered to be greater than all other iterators.
  161089. **
  161090. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  161091. ** the smallest key overall. aFirst[0] is unused.
  161092. */
  161093. typedef struct Fts5CResult Fts5CResult;
  161094. struct Fts5CResult {
  161095. u16 iFirst; /* aSeg[] index of firstest iterator */
  161096. u8 bTermEq; /* True if the terms are equal */
  161097. };
  161098. /*
  161099. ** Object for iterating through a single segment, visiting each term/rowid
  161100. ** pair in the segment.
  161101. **
  161102. ** pSeg:
  161103. ** The segment to iterate through.
  161104. **
  161105. ** iLeafPgno:
  161106. ** Current leaf page number within segment.
  161107. **
  161108. ** iLeafOffset:
  161109. ** Byte offset within the current leaf that is the first byte of the
  161110. ** position list data (one byte passed the position-list size field).
  161111. ** rowid field of the current entry. Usually this is the size field of the
  161112. ** position list data. The exception is if the rowid for the current entry
  161113. ** is the last thing on the leaf page.
  161114. **
  161115. ** pLeaf:
  161116. ** Buffer containing current leaf page data. Set to NULL at EOF.
  161117. **
  161118. ** iTermLeafPgno, iTermLeafOffset:
  161119. ** Leaf page number containing the last term read from the segment. And
  161120. ** the offset immediately following the term data.
  161121. **
  161122. ** flags:
  161123. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  161124. **
  161125. ** FTS5_SEGITER_ONETERM:
  161126. ** If set, set the iterator to point to EOF after the current doclist
  161127. ** has been exhausted. Do not proceed to the next term in the segment.
  161128. **
  161129. ** FTS5_SEGITER_REVERSE:
  161130. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  161131. ** it is set, iterate through rowid in descending order instead of the
  161132. ** default ascending order.
  161133. **
  161134. ** iRowidOffset/nRowidOffset/aRowidOffset:
  161135. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  161136. **
  161137. ** For each rowid on the page corresponding to the current term, the
  161138. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  161139. ** start of the "position-list-size" field within the page.
  161140. **
  161141. ** iTermIdx:
  161142. ** Index of current term on iTermLeafPgno.
  161143. */
  161144. struct Fts5SegIter {
  161145. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  161146. int flags; /* Mask of configuration flags */
  161147. int iLeafPgno; /* Current leaf page number */
  161148. Fts5Data *pLeaf; /* Current leaf data */
  161149. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  161150. int iLeafOffset; /* Byte offset within current leaf */
  161151. /* The page and offset from which the current term was read. The offset
  161152. ** is the offset of the first rowid in the current doclist. */
  161153. int iTermLeafPgno;
  161154. int iTermLeafOffset;
  161155. int iPgidxOff; /* Next offset in pgidx */
  161156. int iEndofDoclist;
  161157. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  161158. int iRowidOffset; /* Current entry in aRowidOffset[] */
  161159. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  161160. int *aRowidOffset; /* Array of offset to rowid fields */
  161161. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  161162. /* Variables populated based on current entry. */
  161163. Fts5Buffer term; /* Current term */
  161164. i64 iRowid; /* Current rowid */
  161165. int nPos; /* Number of bytes in current position list */
  161166. int bDel; /* True if the delete flag is set */
  161167. };
  161168. /*
  161169. ** Argument is a pointer to an Fts5Data structure that contains a
  161170. ** leaf page.
  161171. */
  161172. #define ASSERT_SZLEAF_OK(x) assert( \
  161173. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  161174. )
  161175. #define FTS5_SEGITER_ONETERM 0x01
  161176. #define FTS5_SEGITER_REVERSE 0x02
  161177. /*
  161178. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  161179. ** page. This macro evaluates to true if the leaf contains no terms, or
  161180. ** false if it contains at least one term.
  161181. */
  161182. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  161183. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  161184. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  161185. /*
  161186. ** poslist:
  161187. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  161188. ** There is no way to tell if this is populated or not.
  161189. */
  161190. struct Fts5IndexIter {
  161191. Fts5Index *pIndex; /* Index that owns this iterator */
  161192. Fts5Structure *pStruct; /* Database structure for this iterator */
  161193. Fts5Buffer poslist; /* Buffer containing current poslist */
  161194. int nSeg; /* Size of aSeg[] array */
  161195. int bRev; /* True to iterate in reverse order */
  161196. u8 bSkipEmpty; /* True to skip deleted entries */
  161197. u8 bEof; /* True at EOF */
  161198. u8 bFiltered; /* True if column-filter already applied */
  161199. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  161200. Fts5CResult *aFirst; /* Current merge state (see above) */
  161201. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  161202. };
  161203. /*
  161204. ** An instance of the following type is used to iterate through the contents
  161205. ** of a doclist-index record.
  161206. **
  161207. ** pData:
  161208. ** Record containing the doclist-index data.
  161209. **
  161210. ** bEof:
  161211. ** Set to true once iterator has reached EOF.
  161212. **
  161213. ** iOff:
  161214. ** Set to the current offset within record pData.
  161215. */
  161216. struct Fts5DlidxLvl {
  161217. Fts5Data *pData; /* Data for current page of this level */
  161218. int iOff; /* Current offset into pData */
  161219. int bEof; /* At EOF already */
  161220. int iFirstOff; /* Used by reverse iterators */
  161221. /* Output variables */
  161222. int iLeafPgno; /* Page number of current leaf page */
  161223. i64 iRowid; /* First rowid on leaf iLeafPgno */
  161224. };
  161225. struct Fts5DlidxIter {
  161226. int nLvl;
  161227. int iSegid;
  161228. Fts5DlidxLvl aLvl[1];
  161229. };
  161230. static void fts5PutU16(u8 *aOut, u16 iVal){
  161231. aOut[0] = (iVal>>8);
  161232. aOut[1] = (iVal&0xFF);
  161233. }
  161234. static u16 fts5GetU16(const u8 *aIn){
  161235. return ((u16)aIn[0] << 8) + aIn[1];
  161236. }
  161237. /*
  161238. ** Allocate and return a buffer at least nByte bytes in size.
  161239. **
  161240. ** If an OOM error is encountered, return NULL and set the error code in
  161241. ** the Fts5Index handle passed as the first argument.
  161242. */
  161243. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  161244. return sqlite3Fts5MallocZero(&p->rc, nByte);
  161245. }
  161246. /*
  161247. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  161248. **
  161249. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  161250. ** +ve if pRight is smaller than pLeft. In other words:
  161251. **
  161252. ** res = *pLeft - *pRight
  161253. */
  161254. #ifdef SQLITE_DEBUG
  161255. static int fts5BufferCompareBlob(
  161256. Fts5Buffer *pLeft, /* Left hand side of comparison */
  161257. const u8 *pRight, int nRight /* Right hand side of comparison */
  161258. ){
  161259. int nCmp = MIN(pLeft->n, nRight);
  161260. int res = memcmp(pLeft->p, pRight, nCmp);
  161261. return (res==0 ? (pLeft->n - nRight) : res);
  161262. }
  161263. #endif
  161264. /*
  161265. ** Compare the contents of the two buffers using memcmp(). If one buffer
  161266. ** is a prefix of the other, it is considered the lesser.
  161267. **
  161268. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  161269. ** +ve if pRight is smaller than pLeft. In other words:
  161270. **
  161271. ** res = *pLeft - *pRight
  161272. */
  161273. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  161274. int nCmp = MIN(pLeft->n, pRight->n);
  161275. int res = memcmp(pLeft->p, pRight->p, nCmp);
  161276. return (res==0 ? (pLeft->n - pRight->n) : res);
  161277. }
  161278. #ifdef SQLITE_DEBUG
  161279. static int fts5BlobCompare(
  161280. const u8 *pLeft, int nLeft,
  161281. const u8 *pRight, int nRight
  161282. ){
  161283. int nCmp = MIN(nLeft, nRight);
  161284. int res = memcmp(pLeft, pRight, nCmp);
  161285. return (res==0 ? (nLeft - nRight) : res);
  161286. }
  161287. #endif
  161288. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  161289. int ret;
  161290. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  161291. return ret;
  161292. }
  161293. /*
  161294. ** Close the read-only blob handle, if it is open.
  161295. */
  161296. static void fts5CloseReader(Fts5Index *p){
  161297. if( p->pReader ){
  161298. sqlite3_blob *pReader = p->pReader;
  161299. p->pReader = 0;
  161300. sqlite3_blob_close(pReader);
  161301. }
  161302. }
  161303. /*
  161304. ** Retrieve a record from the %_data table.
  161305. **
  161306. ** If an error occurs, NULL is returned and an error left in the
  161307. ** Fts5Index object.
  161308. */
  161309. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  161310. Fts5Data *pRet = 0;
  161311. if( p->rc==SQLITE_OK ){
  161312. int rc = SQLITE_OK;
  161313. if( p->pReader ){
  161314. /* This call may return SQLITE_ABORT if there has been a savepoint
  161315. ** rollback since it was last used. In this case a new blob handle
  161316. ** is required. */
  161317. sqlite3_blob *pBlob = p->pReader;
  161318. p->pReader = 0;
  161319. rc = sqlite3_blob_reopen(pBlob, iRowid);
  161320. assert( p->pReader==0 );
  161321. p->pReader = pBlob;
  161322. if( rc!=SQLITE_OK ){
  161323. fts5CloseReader(p);
  161324. }
  161325. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  161326. }
  161327. /* If the blob handle is not open at this point, open it and seek
  161328. ** to the requested entry. */
  161329. if( p->pReader==0 && rc==SQLITE_OK ){
  161330. Fts5Config *pConfig = p->pConfig;
  161331. rc = sqlite3_blob_open(pConfig->db,
  161332. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  161333. );
  161334. }
  161335. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  161336. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  161337. ** All the reasons those functions might return SQLITE_ERROR - missing
  161338. ** table, missing row, non-blob/text in block column - indicate
  161339. ** backing store corruption. */
  161340. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  161341. if( rc==SQLITE_OK ){
  161342. u8 *aOut = 0; /* Read blob data into this buffer */
  161343. int nByte = sqlite3_blob_bytes(p->pReader);
  161344. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  161345. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  161346. if( pRet ){
  161347. pRet->nn = nByte;
  161348. aOut = pRet->p = (u8*)&pRet[1];
  161349. }else{
  161350. rc = SQLITE_NOMEM;
  161351. }
  161352. if( rc==SQLITE_OK ){
  161353. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  161354. }
  161355. if( rc!=SQLITE_OK ){
  161356. sqlite3_free(pRet);
  161357. pRet = 0;
  161358. }else{
  161359. /* TODO1: Fix this */
  161360. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  161361. }
  161362. }
  161363. p->rc = rc;
  161364. p->nRead++;
  161365. }
  161366. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  161367. return pRet;
  161368. }
  161369. /*
  161370. ** Release a reference to data record returned by an earlier call to
  161371. ** fts5DataRead().
  161372. */
  161373. static void fts5DataRelease(Fts5Data *pData){
  161374. sqlite3_free(pData);
  161375. }
  161376. static int fts5IndexPrepareStmt(
  161377. Fts5Index *p,
  161378. sqlite3_stmt **ppStmt,
  161379. char *zSql
  161380. ){
  161381. if( p->rc==SQLITE_OK ){
  161382. if( zSql ){
  161383. p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
  161384. }else{
  161385. p->rc = SQLITE_NOMEM;
  161386. }
  161387. }
  161388. sqlite3_free(zSql);
  161389. return p->rc;
  161390. }
  161391. /*
  161392. ** INSERT OR REPLACE a record into the %_data table.
  161393. */
  161394. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  161395. if( p->rc!=SQLITE_OK ) return;
  161396. if( p->pWriter==0 ){
  161397. Fts5Config *pConfig = p->pConfig;
  161398. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  161399. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  161400. pConfig->zDb, pConfig->zName
  161401. ));
  161402. if( p->rc ) return;
  161403. }
  161404. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  161405. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  161406. sqlite3_step(p->pWriter);
  161407. p->rc = sqlite3_reset(p->pWriter);
  161408. }
  161409. /*
  161410. ** Execute the following SQL:
  161411. **
  161412. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  161413. */
  161414. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  161415. if( p->rc!=SQLITE_OK ) return;
  161416. if( p->pDeleter==0 ){
  161417. int rc;
  161418. Fts5Config *pConfig = p->pConfig;
  161419. char *zSql = sqlite3_mprintf(
  161420. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  161421. pConfig->zDb, pConfig->zName
  161422. );
  161423. if( zSql==0 ){
  161424. rc = SQLITE_NOMEM;
  161425. }else{
  161426. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
  161427. sqlite3_free(zSql);
  161428. }
  161429. if( rc!=SQLITE_OK ){
  161430. p->rc = rc;
  161431. return;
  161432. }
  161433. }
  161434. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  161435. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  161436. sqlite3_step(p->pDeleter);
  161437. p->rc = sqlite3_reset(p->pDeleter);
  161438. }
  161439. /*
  161440. ** Remove all records associated with segment iSegid.
  161441. */
  161442. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  161443. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  161444. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  161445. fts5DataDelete(p, iFirst, iLast);
  161446. if( p->pIdxDeleter==0 ){
  161447. Fts5Config *pConfig = p->pConfig;
  161448. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  161449. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  161450. pConfig->zDb, pConfig->zName
  161451. ));
  161452. }
  161453. if( p->rc==SQLITE_OK ){
  161454. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  161455. sqlite3_step(p->pIdxDeleter);
  161456. p->rc = sqlite3_reset(p->pIdxDeleter);
  161457. }
  161458. }
  161459. /*
  161460. ** Release a reference to an Fts5Structure object returned by an earlier
  161461. ** call to fts5StructureRead() or fts5StructureDecode().
  161462. */
  161463. static void fts5StructureRelease(Fts5Structure *pStruct){
  161464. if( pStruct && 0>=(--pStruct->nRef) ){
  161465. int i;
  161466. assert( pStruct->nRef==0 );
  161467. for(i=0; i<pStruct->nLevel; i++){
  161468. sqlite3_free(pStruct->aLevel[i].aSeg);
  161469. }
  161470. sqlite3_free(pStruct);
  161471. }
  161472. }
  161473. static void fts5StructureRef(Fts5Structure *pStruct){
  161474. pStruct->nRef++;
  161475. }
  161476. /*
  161477. ** Deserialize and return the structure record currently stored in serialized
  161478. ** form within buffer pData/nData.
  161479. **
  161480. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  161481. ** are over-allocated by one slot. This allows the structure contents
  161482. ** to be more easily edited.
  161483. **
  161484. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  161485. ** returned. Otherwise, *ppOut is set to point to the new object and
  161486. ** SQLITE_OK returned.
  161487. */
  161488. static int fts5StructureDecode(
  161489. const u8 *pData, /* Buffer containing serialized structure */
  161490. int nData, /* Size of buffer pData in bytes */
  161491. int *piCookie, /* Configuration cookie value */
  161492. Fts5Structure **ppOut /* OUT: Deserialized object */
  161493. ){
  161494. int rc = SQLITE_OK;
  161495. int i = 0;
  161496. int iLvl;
  161497. int nLevel = 0;
  161498. int nSegment = 0;
  161499. int nByte; /* Bytes of space to allocate at pRet */
  161500. Fts5Structure *pRet = 0; /* Structure object to return */
  161501. /* Grab the cookie value */
  161502. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  161503. i = 4;
  161504. /* Read the total number of levels and segments from the start of the
  161505. ** structure record. */
  161506. i += fts5GetVarint32(&pData[i], nLevel);
  161507. i += fts5GetVarint32(&pData[i], nSegment);
  161508. nByte = (
  161509. sizeof(Fts5Structure) + /* Main structure */
  161510. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  161511. );
  161512. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  161513. if( pRet ){
  161514. pRet->nRef = 1;
  161515. pRet->nLevel = nLevel;
  161516. pRet->nSegment = nSegment;
  161517. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  161518. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  161519. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  161520. int nTotal;
  161521. int iSeg;
  161522. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  161523. i += fts5GetVarint32(&pData[i], nTotal);
  161524. assert( nTotal>=pLvl->nMerge );
  161525. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  161526. nTotal * sizeof(Fts5StructureSegment)
  161527. );
  161528. if( rc==SQLITE_OK ){
  161529. pLvl->nSeg = nTotal;
  161530. for(iSeg=0; iSeg<nTotal; iSeg++){
  161531. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  161532. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  161533. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  161534. }
  161535. }else{
  161536. fts5StructureRelease(pRet);
  161537. pRet = 0;
  161538. }
  161539. }
  161540. }
  161541. *ppOut = pRet;
  161542. return rc;
  161543. }
  161544. /*
  161545. **
  161546. */
  161547. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  161548. if( *pRc==SQLITE_OK ){
  161549. Fts5Structure *pStruct = *ppStruct;
  161550. int nLevel = pStruct->nLevel;
  161551. int nByte = (
  161552. sizeof(Fts5Structure) + /* Main structure */
  161553. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  161554. );
  161555. pStruct = sqlite3_realloc(pStruct, nByte);
  161556. if( pStruct ){
  161557. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  161558. pStruct->nLevel++;
  161559. *ppStruct = pStruct;
  161560. }else{
  161561. *pRc = SQLITE_NOMEM;
  161562. }
  161563. }
  161564. }
  161565. /*
  161566. ** Extend level iLvl so that there is room for at least nExtra more
  161567. ** segments.
  161568. */
  161569. static void fts5StructureExtendLevel(
  161570. int *pRc,
  161571. Fts5Structure *pStruct,
  161572. int iLvl,
  161573. int nExtra,
  161574. int bInsert
  161575. ){
  161576. if( *pRc==SQLITE_OK ){
  161577. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  161578. Fts5StructureSegment *aNew;
  161579. int nByte;
  161580. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  161581. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  161582. if( aNew ){
  161583. if( bInsert==0 ){
  161584. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  161585. }else{
  161586. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  161587. memmove(&aNew[nExtra], aNew, nMove);
  161588. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  161589. }
  161590. pLvl->aSeg = aNew;
  161591. }else{
  161592. *pRc = SQLITE_NOMEM;
  161593. }
  161594. }
  161595. }
  161596. /*
  161597. ** Read, deserialize and return the structure record.
  161598. **
  161599. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  161600. ** are over-allocated as described for function fts5StructureDecode()
  161601. ** above.
  161602. **
  161603. ** If an error occurs, NULL is returned and an error code left in the
  161604. ** Fts5Index handle. If an error has already occurred when this function
  161605. ** is called, it is a no-op.
  161606. */
  161607. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  161608. Fts5Config *pConfig = p->pConfig;
  161609. Fts5Structure *pRet = 0; /* Object to return */
  161610. int iCookie; /* Configuration cookie */
  161611. Fts5Data *pData;
  161612. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  161613. if( p->rc ) return 0;
  161614. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  161615. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  161616. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  161617. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  161618. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  161619. }
  161620. fts5DataRelease(pData);
  161621. if( p->rc!=SQLITE_OK ){
  161622. fts5StructureRelease(pRet);
  161623. pRet = 0;
  161624. }
  161625. return pRet;
  161626. }
  161627. /*
  161628. ** Return the total number of segments in index structure pStruct. This
  161629. ** function is only ever used as part of assert() conditions.
  161630. */
  161631. #ifdef SQLITE_DEBUG
  161632. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  161633. int nSegment = 0; /* Total number of segments */
  161634. if( pStruct ){
  161635. int iLvl; /* Used to iterate through levels */
  161636. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  161637. nSegment += pStruct->aLevel[iLvl].nSeg;
  161638. }
  161639. }
  161640. return nSegment;
  161641. }
  161642. #endif
  161643. /*
  161644. ** Serialize and store the "structure" record.
  161645. **
  161646. ** If an error occurs, leave an error code in the Fts5Index object. If an
  161647. ** error has already occurred, this function is a no-op.
  161648. */
  161649. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  161650. if( p->rc==SQLITE_OK ){
  161651. Fts5Buffer buf; /* Buffer to serialize record into */
  161652. int iLvl; /* Used to iterate through levels */
  161653. int iCookie; /* Cookie value to store */
  161654. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  161655. memset(&buf, 0, sizeof(Fts5Buffer));
  161656. /* Append the current configuration cookie */
  161657. iCookie = p->pConfig->iCookie;
  161658. if( iCookie<0 ) iCookie = 0;
  161659. fts5BufferAppend32(&p->rc, &buf, iCookie);
  161660. fts5BufferAppendVarint(&p->rc, &buf, pStruct->nLevel);
  161661. fts5BufferAppendVarint(&p->rc, &buf, pStruct->nSegment);
  161662. fts5BufferAppendVarint(&p->rc, &buf, (i64)pStruct->nWriteCounter);
  161663. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  161664. int iSeg; /* Used to iterate through segments */
  161665. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  161666. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  161667. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  161668. assert( pLvl->nMerge<=pLvl->nSeg );
  161669. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  161670. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  161671. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  161672. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  161673. }
  161674. }
  161675. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  161676. fts5BufferFree(&buf);
  161677. }
  161678. }
  161679. #if 0
  161680. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  161681. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  161682. int rc = SQLITE_OK;
  161683. Fts5Buffer buf;
  161684. memset(&buf, 0, sizeof(buf));
  161685. fts5DebugStructure(&rc, &buf, pStruct);
  161686. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  161687. fflush(stdout);
  161688. fts5BufferFree(&buf);
  161689. }
  161690. #else
  161691. # define fts5PrintStructure(x,y)
  161692. #endif
  161693. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  161694. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  161695. }
  161696. /*
  161697. ** Return a copy of index structure pStruct. Except, promote as many
  161698. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  161699. ** returned.
  161700. */
  161701. static void fts5StructurePromoteTo(
  161702. Fts5Index *p,
  161703. int iPromote,
  161704. int szPromote,
  161705. Fts5Structure *pStruct
  161706. ){
  161707. int il, is;
  161708. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  161709. if( pOut->nMerge==0 ){
  161710. for(il=iPromote+1; il<pStruct->nLevel; il++){
  161711. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  161712. if( pLvl->nMerge ) return;
  161713. for(is=pLvl->nSeg-1; is>=0; is--){
  161714. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  161715. if( sz>szPromote ) return;
  161716. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  161717. if( p->rc ) return;
  161718. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  161719. pOut->nSeg++;
  161720. pLvl->nSeg--;
  161721. }
  161722. }
  161723. }
  161724. }
  161725. /*
  161726. ** A new segment has just been written to level iLvl of index structure
  161727. ** pStruct. This function determines if any segments should be promoted
  161728. ** as a result. Segments are promoted in two scenarios:
  161729. **
  161730. ** a) If the segment just written is smaller than one or more segments
  161731. ** within the previous populated level, it is promoted to the previous
  161732. ** populated level.
  161733. **
  161734. ** b) If the segment just written is larger than the newest segment on
  161735. ** the next populated level, then that segment, and any other adjacent
  161736. ** segments that are also smaller than the one just written, are
  161737. ** promoted.
  161738. **
  161739. ** If one or more segments are promoted, the structure object is updated
  161740. ** to reflect this.
  161741. */
  161742. static void fts5StructurePromote(
  161743. Fts5Index *p, /* FTS5 backend object */
  161744. int iLvl, /* Index level just updated */
  161745. Fts5Structure *pStruct /* Index structure */
  161746. ){
  161747. if( p->rc==SQLITE_OK ){
  161748. int iTst;
  161749. int iPromote = -1;
  161750. int szPromote = 0; /* Promote anything this size or smaller */
  161751. Fts5StructureSegment *pSeg; /* Segment just written */
  161752. int szSeg; /* Size of segment just written */
  161753. int nSeg = pStruct->aLevel[iLvl].nSeg;
  161754. if( nSeg==0 ) return;
  161755. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  161756. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  161757. /* Check for condition (a) */
  161758. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  161759. if( iTst>=0 ){
  161760. int i;
  161761. int szMax = 0;
  161762. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  161763. assert( pTst->nMerge==0 );
  161764. for(i=0; i<pTst->nSeg; i++){
  161765. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  161766. if( sz>szMax ) szMax = sz;
  161767. }
  161768. if( szMax>=szSeg ){
  161769. /* Condition (a) is true. Promote the newest segment on level
  161770. ** iLvl to level iTst. */
  161771. iPromote = iTst;
  161772. szPromote = szMax;
  161773. }
  161774. }
  161775. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  161776. ** is a no-op if it is not. */
  161777. if( iPromote<0 ){
  161778. iPromote = iLvl;
  161779. szPromote = szSeg;
  161780. }
  161781. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  161782. }
  161783. }
  161784. /*
  161785. ** Advance the iterator passed as the only argument. If the end of the
  161786. ** doclist-index page is reached, return non-zero.
  161787. */
  161788. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  161789. Fts5Data *pData = pLvl->pData;
  161790. if( pLvl->iOff==0 ){
  161791. assert( pLvl->bEof==0 );
  161792. pLvl->iOff = 1;
  161793. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  161794. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  161795. pLvl->iFirstOff = pLvl->iOff;
  161796. }else{
  161797. int iOff;
  161798. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  161799. if( pData->p[iOff] ) break;
  161800. }
  161801. if( iOff<pData->nn ){
  161802. i64 iVal;
  161803. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  161804. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  161805. pLvl->iRowid += iVal;
  161806. pLvl->iOff = iOff;
  161807. }else{
  161808. pLvl->bEof = 1;
  161809. }
  161810. }
  161811. return pLvl->bEof;
  161812. }
  161813. /*
  161814. ** Advance the iterator passed as the only argument.
  161815. */
  161816. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  161817. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  161818. assert( iLvl<pIter->nLvl );
  161819. if( fts5DlidxLvlNext(pLvl) ){
  161820. if( (iLvl+1) < pIter->nLvl ){
  161821. fts5DlidxIterNextR(p, pIter, iLvl+1);
  161822. if( pLvl[1].bEof==0 ){
  161823. fts5DataRelease(pLvl->pData);
  161824. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  161825. pLvl->pData = fts5DataRead(p,
  161826. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  161827. );
  161828. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  161829. }
  161830. }
  161831. }
  161832. return pIter->aLvl[0].bEof;
  161833. }
  161834. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  161835. return fts5DlidxIterNextR(p, pIter, 0);
  161836. }
  161837. /*
  161838. ** The iterator passed as the first argument has the following fields set
  161839. ** as follows. This function sets up the rest of the iterator so that it
  161840. ** points to the first rowid in the doclist-index.
  161841. **
  161842. ** pData:
  161843. ** pointer to doclist-index record,
  161844. **
  161845. ** When this function is called pIter->iLeafPgno is the page number the
  161846. ** doclist is associated with (the one featuring the term).
  161847. */
  161848. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  161849. int i;
  161850. for(i=0; i<pIter->nLvl; i++){
  161851. fts5DlidxLvlNext(&pIter->aLvl[i]);
  161852. }
  161853. return pIter->aLvl[0].bEof;
  161854. }
  161855. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  161856. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  161857. }
  161858. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  161859. int i;
  161860. /* Advance each level to the last entry on the last page */
  161861. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  161862. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  161863. while( fts5DlidxLvlNext(pLvl)==0 );
  161864. pLvl->bEof = 0;
  161865. if( i>0 ){
  161866. Fts5DlidxLvl *pChild = &pLvl[-1];
  161867. fts5DataRelease(pChild->pData);
  161868. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  161869. pChild->pData = fts5DataRead(p,
  161870. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  161871. );
  161872. }
  161873. }
  161874. }
  161875. /*
  161876. ** Move the iterator passed as the only argument to the previous entry.
  161877. */
  161878. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  161879. int iOff = pLvl->iOff;
  161880. assert( pLvl->bEof==0 );
  161881. if( iOff<=pLvl->iFirstOff ){
  161882. pLvl->bEof = 1;
  161883. }else{
  161884. u8 *a = pLvl->pData->p;
  161885. i64 iVal;
  161886. int iLimit;
  161887. int ii;
  161888. int nZero = 0;
  161889. /* Currently iOff points to the first byte of a varint. This block
  161890. ** decrements iOff until it points to the first byte of the previous
  161891. ** varint. Taking care not to read any memory locations that occur
  161892. ** before the buffer in memory. */
  161893. iLimit = (iOff>9 ? iOff-9 : 0);
  161894. for(iOff--; iOff>iLimit; iOff--){
  161895. if( (a[iOff-1] & 0x80)==0 ) break;
  161896. }
  161897. fts5GetVarint(&a[iOff], (u64*)&iVal);
  161898. pLvl->iRowid -= iVal;
  161899. pLvl->iLeafPgno--;
  161900. /* Skip backwards past any 0x00 varints. */
  161901. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  161902. nZero++;
  161903. }
  161904. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  161905. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  161906. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  161907. ** bytes before a[ii]. */
  161908. int bZero = 0; /* True if last 0x00 counts */
  161909. if( (ii-8)>=pLvl->iFirstOff ){
  161910. int j;
  161911. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  161912. bZero = (j>8);
  161913. }
  161914. if( bZero==0 ) nZero--;
  161915. }
  161916. pLvl->iLeafPgno -= nZero;
  161917. pLvl->iOff = iOff - nZero;
  161918. }
  161919. return pLvl->bEof;
  161920. }
  161921. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  161922. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  161923. assert( iLvl<pIter->nLvl );
  161924. if( fts5DlidxLvlPrev(pLvl) ){
  161925. if( (iLvl+1) < pIter->nLvl ){
  161926. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  161927. if( pLvl[1].bEof==0 ){
  161928. fts5DataRelease(pLvl->pData);
  161929. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  161930. pLvl->pData = fts5DataRead(p,
  161931. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  161932. );
  161933. if( pLvl->pData ){
  161934. while( fts5DlidxLvlNext(pLvl)==0 );
  161935. pLvl->bEof = 0;
  161936. }
  161937. }
  161938. }
  161939. }
  161940. return pIter->aLvl[0].bEof;
  161941. }
  161942. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  161943. return fts5DlidxIterPrevR(p, pIter, 0);
  161944. }
  161945. /*
  161946. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  161947. */
  161948. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  161949. if( pIter ){
  161950. int i;
  161951. for(i=0; i<pIter->nLvl; i++){
  161952. fts5DataRelease(pIter->aLvl[i].pData);
  161953. }
  161954. sqlite3_free(pIter);
  161955. }
  161956. }
  161957. static Fts5DlidxIter *fts5DlidxIterInit(
  161958. Fts5Index *p, /* Fts5 Backend to iterate within */
  161959. int bRev, /* True for ORDER BY ASC */
  161960. int iSegid, /* Segment id */
  161961. int iLeafPg /* Leaf page number to load dlidx for */
  161962. ){
  161963. Fts5DlidxIter *pIter = 0;
  161964. int i;
  161965. int bDone = 0;
  161966. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  161967. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  161968. Fts5DlidxIter *pNew;
  161969. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  161970. if( pNew==0 ){
  161971. p->rc = SQLITE_NOMEM;
  161972. }else{
  161973. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  161974. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  161975. pIter = pNew;
  161976. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  161977. pLvl->pData = fts5DataRead(p, iRowid);
  161978. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  161979. bDone = 1;
  161980. }
  161981. pIter->nLvl = i+1;
  161982. }
  161983. }
  161984. if( p->rc==SQLITE_OK ){
  161985. pIter->iSegid = iSegid;
  161986. if( bRev==0 ){
  161987. fts5DlidxIterFirst(pIter);
  161988. }else{
  161989. fts5DlidxIterLast(p, pIter);
  161990. }
  161991. }
  161992. if( p->rc!=SQLITE_OK ){
  161993. fts5DlidxIterFree(pIter);
  161994. pIter = 0;
  161995. }
  161996. return pIter;
  161997. }
  161998. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  161999. return pIter->aLvl[0].iRowid;
  162000. }
  162001. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  162002. return pIter->aLvl[0].iLeafPgno;
  162003. }
  162004. /*
  162005. ** Load the next leaf page into the segment iterator.
  162006. */
  162007. static void fts5SegIterNextPage(
  162008. Fts5Index *p, /* FTS5 backend object */
  162009. Fts5SegIter *pIter /* Iterator to advance to next page */
  162010. ){
  162011. Fts5Data *pLeaf;
  162012. Fts5StructureSegment *pSeg = pIter->pSeg;
  162013. fts5DataRelease(pIter->pLeaf);
  162014. pIter->iLeafPgno++;
  162015. if( pIter->pNextLeaf ){
  162016. pIter->pLeaf = pIter->pNextLeaf;
  162017. pIter->pNextLeaf = 0;
  162018. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  162019. pIter->pLeaf = fts5DataRead(p,
  162020. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  162021. );
  162022. }else{
  162023. pIter->pLeaf = 0;
  162024. }
  162025. pLeaf = pIter->pLeaf;
  162026. if( pLeaf ){
  162027. pIter->iPgidxOff = pLeaf->szLeaf;
  162028. if( fts5LeafIsTermless(pLeaf) ){
  162029. pIter->iEndofDoclist = pLeaf->nn+1;
  162030. }else{
  162031. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  162032. pIter->iEndofDoclist
  162033. );
  162034. }
  162035. }
  162036. }
  162037. /*
  162038. ** Argument p points to a buffer containing a varint to be interpreted as a
  162039. ** position list size field. Read the varint and return the number of bytes
  162040. ** read. Before returning, set *pnSz to the number of bytes in the position
  162041. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  162042. */
  162043. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  162044. int nSz;
  162045. int n = 0;
  162046. fts5FastGetVarint32(p, n, nSz);
  162047. assert_nc( nSz>=0 );
  162048. *pnSz = nSz/2;
  162049. *pbDel = nSz & 0x0001;
  162050. return n;
  162051. }
  162052. /*
  162053. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  162054. ** position-list size field. Read the value of the field and store it
  162055. ** in the following variables:
  162056. **
  162057. ** Fts5SegIter.nPos
  162058. ** Fts5SegIter.bDel
  162059. **
  162060. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  162061. ** position list content (if any).
  162062. */
  162063. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  162064. if( p->rc==SQLITE_OK ){
  162065. int iOff = pIter->iLeafOffset; /* Offset to read at */
  162066. int nSz;
  162067. ASSERT_SZLEAF_OK(pIter->pLeaf);
  162068. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  162069. pIter->bDel = (nSz & 0x0001);
  162070. pIter->nPos = nSz>>1;
  162071. pIter->iLeafOffset = iOff;
  162072. }
  162073. }
  162074. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  162075. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  162076. int iOff = pIter->iLeafOffset;
  162077. ASSERT_SZLEAF_OK(pIter->pLeaf);
  162078. if( iOff>=pIter->pLeaf->szLeaf ){
  162079. fts5SegIterNextPage(p, pIter);
  162080. if( pIter->pLeaf==0 ){
  162081. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  162082. return;
  162083. }
  162084. iOff = 4;
  162085. a = pIter->pLeaf->p;
  162086. }
  162087. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  162088. pIter->iLeafOffset = iOff;
  162089. }
  162090. /*
  162091. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  162092. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  162093. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  162094. ** the first term in the segment).
  162095. **
  162096. ** This function populates:
  162097. **
  162098. ** Fts5SegIter.term
  162099. ** Fts5SegIter.rowid
  162100. **
  162101. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  162102. ** the first position list. The position list belonging to document
  162103. ** (Fts5SegIter.iRowid).
  162104. */
  162105. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  162106. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  162107. int iOff = pIter->iLeafOffset; /* Offset to read at */
  162108. int nNew; /* Bytes of new data */
  162109. iOff += fts5GetVarint32(&a[iOff], nNew);
  162110. pIter->term.n = nKeep;
  162111. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  162112. iOff += nNew;
  162113. pIter->iTermLeafOffset = iOff;
  162114. pIter->iTermLeafPgno = pIter->iLeafPgno;
  162115. pIter->iLeafOffset = iOff;
  162116. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  162117. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  162118. }else{
  162119. int nExtra;
  162120. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  162121. pIter->iEndofDoclist += nExtra;
  162122. }
  162123. fts5SegIterLoadRowid(p, pIter);
  162124. }
  162125. /*
  162126. ** Initialize the iterator object pIter to iterate through the entries in
  162127. ** segment pSeg. The iterator is left pointing to the first entry when
  162128. ** this function returns.
  162129. **
  162130. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  162131. ** an error has already occurred when this function is called, it is a no-op.
  162132. */
  162133. static void fts5SegIterInit(
  162134. Fts5Index *p, /* FTS index object */
  162135. Fts5StructureSegment *pSeg, /* Description of segment */
  162136. Fts5SegIter *pIter /* Object to populate */
  162137. ){
  162138. if( pSeg->pgnoFirst==0 ){
  162139. /* This happens if the segment is being used as an input to an incremental
  162140. ** merge and all data has already been "trimmed". See function
  162141. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  162142. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  162143. ** at EOF already. */
  162144. assert( pIter->pLeaf==0 );
  162145. return;
  162146. }
  162147. if( p->rc==SQLITE_OK ){
  162148. memset(pIter, 0, sizeof(*pIter));
  162149. pIter->pSeg = pSeg;
  162150. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  162151. fts5SegIterNextPage(p, pIter);
  162152. }
  162153. if( p->rc==SQLITE_OK ){
  162154. pIter->iLeafOffset = 4;
  162155. assert_nc( pIter->pLeaf->nn>4 );
  162156. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  162157. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  162158. fts5SegIterLoadTerm(p, pIter, 0);
  162159. fts5SegIterLoadNPos(p, pIter);
  162160. }
  162161. }
  162162. /*
  162163. ** This function is only ever called on iterators created by calls to
  162164. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  162165. **
  162166. ** The iterator is in an unusual state when this function is called: the
  162167. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  162168. ** the position-list size field for the first relevant rowid on the page.
  162169. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  162170. **
  162171. ** This function advances the iterator so that it points to the last
  162172. ** relevant rowid on the page and, if necessary, initializes the
  162173. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  162174. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  162175. ** byte of the position list content associated with said rowid.
  162176. */
  162177. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  162178. int n = pIter->pLeaf->szLeaf;
  162179. int i = pIter->iLeafOffset;
  162180. u8 *a = pIter->pLeaf->p;
  162181. int iRowidOffset = 0;
  162182. if( n>pIter->iEndofDoclist ){
  162183. n = pIter->iEndofDoclist;
  162184. }
  162185. ASSERT_SZLEAF_OK(pIter->pLeaf);
  162186. while( 1 ){
  162187. i64 iDelta = 0;
  162188. int nPos;
  162189. int bDummy;
  162190. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  162191. i += nPos;
  162192. if( i>=n ) break;
  162193. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  162194. pIter->iRowid += iDelta;
  162195. if( iRowidOffset>=pIter->nRowidOffset ){
  162196. int nNew = pIter->nRowidOffset + 8;
  162197. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  162198. if( aNew==0 ){
  162199. p->rc = SQLITE_NOMEM;
  162200. break;
  162201. }
  162202. pIter->aRowidOffset = aNew;
  162203. pIter->nRowidOffset = nNew;
  162204. }
  162205. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  162206. pIter->iLeafOffset = i;
  162207. }
  162208. pIter->iRowidOffset = iRowidOffset;
  162209. fts5SegIterLoadNPos(p, pIter);
  162210. }
  162211. /*
  162212. **
  162213. */
  162214. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  162215. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  162216. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  162217. fts5DataRelease(pIter->pLeaf);
  162218. pIter->pLeaf = 0;
  162219. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  162220. Fts5Data *pNew;
  162221. pIter->iLeafPgno--;
  162222. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  162223. pIter->pSeg->iSegid, pIter->iLeafPgno
  162224. ));
  162225. if( pNew ){
  162226. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  162227. ** thing on the page - i.e. the first rowid is on the following page.
  162228. ** In this case leaf pIter->pLeaf==0, this iterator is at EOF. */
  162229. if( pIter->iLeafPgno==pIter->iTermLeafPgno
  162230. && pIter->iTermLeafOffset<pNew->szLeaf
  162231. ){
  162232. pIter->pLeaf = pNew;
  162233. pIter->iLeafOffset = pIter->iTermLeafOffset;
  162234. }else{
  162235. int iRowidOff;
  162236. iRowidOff = fts5LeafFirstRowidOff(pNew);
  162237. if( iRowidOff ){
  162238. pIter->pLeaf = pNew;
  162239. pIter->iLeafOffset = iRowidOff;
  162240. }
  162241. }
  162242. if( pIter->pLeaf ){
  162243. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  162244. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  162245. break;
  162246. }else{
  162247. fts5DataRelease(pNew);
  162248. }
  162249. }
  162250. }
  162251. if( pIter->pLeaf ){
  162252. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  162253. fts5SegIterReverseInitPage(p, pIter);
  162254. }
  162255. }
  162256. /*
  162257. ** Return true if the iterator passed as the second argument currently
  162258. ** points to a delete marker. A delete marker is an entry with a 0 byte
  162259. ** position-list.
  162260. */
  162261. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5IndexIter *pIter){
  162262. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  162263. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  162264. }
  162265. /*
  162266. ** Advance iterator pIter to the next entry.
  162267. **
  162268. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  162269. ** is not considered an error if the iterator reaches EOF. If an error has
  162270. ** already occurred when this function is called, it is a no-op.
  162271. */
  162272. static void fts5SegIterNext(
  162273. Fts5Index *p, /* FTS5 backend object */
  162274. Fts5SegIter *pIter, /* Iterator to advance */
  162275. int *pbNewTerm /* OUT: Set for new term */
  162276. ){
  162277. assert( pbNewTerm==0 || *pbNewTerm==0 );
  162278. if( p->rc==SQLITE_OK ){
  162279. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  162280. assert( pIter->pNextLeaf==0 );
  162281. if( pIter->iRowidOffset>0 ){
  162282. u8 *a = pIter->pLeaf->p;
  162283. int iOff;
  162284. int nPos;
  162285. int bDummy;
  162286. i64 iDelta;
  162287. pIter->iRowidOffset--;
  162288. pIter->iLeafOffset = iOff = pIter->aRowidOffset[pIter->iRowidOffset];
  162289. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
  162290. iOff += nPos;
  162291. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  162292. pIter->iRowid -= iDelta;
  162293. fts5SegIterLoadNPos(p, pIter);
  162294. }else{
  162295. fts5SegIterReverseNewPage(p, pIter);
  162296. }
  162297. }else{
  162298. Fts5Data *pLeaf = pIter->pLeaf;
  162299. int iOff;
  162300. int bNewTerm = 0;
  162301. int nKeep = 0;
  162302. /* Search for the end of the position list within the current page. */
  162303. u8 *a = pLeaf->p;
  162304. int n = pLeaf->szLeaf;
  162305. ASSERT_SZLEAF_OK(pLeaf);
  162306. iOff = pIter->iLeafOffset + pIter->nPos;
  162307. if( iOff<n ){
  162308. /* The next entry is on the current page. */
  162309. assert_nc( iOff<=pIter->iEndofDoclist );
  162310. if( iOff>=pIter->iEndofDoclist ){
  162311. bNewTerm = 1;
  162312. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  162313. iOff += fts5GetVarint32(&a[iOff], nKeep);
  162314. }
  162315. }else{
  162316. u64 iDelta;
  162317. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  162318. pIter->iRowid += iDelta;
  162319. assert_nc( iDelta>0 );
  162320. }
  162321. pIter->iLeafOffset = iOff;
  162322. }else if( pIter->pSeg==0 ){
  162323. const u8 *pList = 0;
  162324. const char *zTerm = 0;
  162325. int nList = 0;
  162326. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  162327. sqlite3Fts5HashScanNext(p->pHash);
  162328. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  162329. }
  162330. if( pList==0 ){
  162331. fts5DataRelease(pIter->pLeaf);
  162332. pIter->pLeaf = 0;
  162333. }else{
  162334. pIter->pLeaf->p = (u8*)pList;
  162335. pIter->pLeaf->nn = nList;
  162336. pIter->pLeaf->szLeaf = nList;
  162337. pIter->iEndofDoclist = nList+1;
  162338. sqlite3Fts5BufferSet(&p->rc, &pIter->term, strlen(zTerm), (u8*)zTerm);
  162339. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  162340. if( pbNewTerm ) *pbNewTerm = 1;
  162341. }
  162342. }else{
  162343. iOff = 0;
  162344. /* Next entry is not on the current page */
  162345. while( iOff==0 ){
  162346. fts5SegIterNextPage(p, pIter);
  162347. pLeaf = pIter->pLeaf;
  162348. if( pLeaf==0 ) break;
  162349. ASSERT_SZLEAF_OK(pLeaf);
  162350. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  162351. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  162352. pIter->iLeafOffset = iOff;
  162353. if( pLeaf->nn>pLeaf->szLeaf ){
  162354. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  162355. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  162356. );
  162357. }
  162358. }
  162359. else if( pLeaf->nn>pLeaf->szLeaf ){
  162360. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  162361. &pLeaf->p[pLeaf->szLeaf], iOff
  162362. );
  162363. pIter->iLeafOffset = iOff;
  162364. pIter->iEndofDoclist = iOff;
  162365. bNewTerm = 1;
  162366. }
  162367. if( iOff>=pLeaf->szLeaf ){
  162368. p->rc = FTS5_CORRUPT;
  162369. return;
  162370. }
  162371. }
  162372. }
  162373. /* Check if the iterator is now at EOF. If so, return early. */
  162374. if( pIter->pLeaf ){
  162375. if( bNewTerm ){
  162376. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  162377. fts5DataRelease(pIter->pLeaf);
  162378. pIter->pLeaf = 0;
  162379. }else{
  162380. fts5SegIterLoadTerm(p, pIter, nKeep);
  162381. fts5SegIterLoadNPos(p, pIter);
  162382. if( pbNewTerm ) *pbNewTerm = 1;
  162383. }
  162384. }else{
  162385. fts5SegIterLoadNPos(p, pIter);
  162386. }
  162387. }
  162388. }
  162389. }
  162390. }
  162391. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  162392. /*
  162393. ** Iterator pIter currently points to the first rowid in a doclist. This
  162394. ** function sets the iterator up so that iterates in reverse order through
  162395. ** the doclist.
  162396. */
  162397. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  162398. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  162399. Fts5Data *pLast = 0;
  162400. int pgnoLast = 0;
  162401. if( pDlidx ){
  162402. int iSegid = pIter->pSeg->iSegid;
  162403. pgnoLast = fts5DlidxIterPgno(pDlidx);
  162404. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  162405. }else{
  162406. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  162407. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  162408. ** position-list content for the current rowid. Back it up so that it
  162409. ** points to the start of the position-list size field. */
  162410. pIter->iLeafOffset -= sqlite3Fts5GetVarintLen(pIter->nPos*2+pIter->bDel);
  162411. /* If this condition is true then the largest rowid for the current
  162412. ** term may not be stored on the current page. So search forward to
  162413. ** see where said rowid really is. */
  162414. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  162415. int pgno;
  162416. Fts5StructureSegment *pSeg = pIter->pSeg;
  162417. /* The last rowid in the doclist may not be on the current page. Search
  162418. ** forward to find the page containing the last rowid. */
  162419. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  162420. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  162421. Fts5Data *pNew = fts5DataRead(p, iAbs);
  162422. if( pNew ){
  162423. int iRowid, bTermless;
  162424. iRowid = fts5LeafFirstRowidOff(pNew);
  162425. bTermless = fts5LeafIsTermless(pNew);
  162426. if( iRowid ){
  162427. SWAPVAL(Fts5Data*, pNew, pLast);
  162428. pgnoLast = pgno;
  162429. }
  162430. fts5DataRelease(pNew);
  162431. if( bTermless==0 ) break;
  162432. }
  162433. }
  162434. }
  162435. }
  162436. /* If pLast is NULL at this point, then the last rowid for this doclist
  162437. ** lies on the page currently indicated by the iterator. In this case
  162438. ** pIter->iLeafOffset is already set to point to the position-list size
  162439. ** field associated with the first relevant rowid on the page.
  162440. **
  162441. ** Or, if pLast is non-NULL, then it is the page that contains the last
  162442. ** rowid. In this case configure the iterator so that it points to the
  162443. ** first rowid on this page.
  162444. */
  162445. if( pLast ){
  162446. int iOff;
  162447. fts5DataRelease(pIter->pLeaf);
  162448. pIter->pLeaf = pLast;
  162449. pIter->iLeafPgno = pgnoLast;
  162450. iOff = fts5LeafFirstRowidOff(pLast);
  162451. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  162452. pIter->iLeafOffset = iOff;
  162453. if( fts5LeafIsTermless(pLast) ){
  162454. pIter->iEndofDoclist = pLast->nn+1;
  162455. }else{
  162456. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  162457. }
  162458. }
  162459. fts5SegIterReverseInitPage(p, pIter);
  162460. }
  162461. /*
  162462. ** Iterator pIter currently points to the first rowid of a doclist.
  162463. ** There is a doclist-index associated with the final term on the current
  162464. ** page. If the current term is the last term on the page, load the
  162465. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  162466. */
  162467. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  162468. int iSeg = pIter->pSeg->iSegid;
  162469. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  162470. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  162471. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  162472. assert( pIter->pDlidx==0 );
  162473. /* Check if the current doclist ends on this page. If it does, return
  162474. ** early without loading the doclist-index (as it belongs to a different
  162475. ** term. */
  162476. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  162477. && pIter->iEndofDoclist<pLeaf->szLeaf
  162478. ){
  162479. return;
  162480. }
  162481. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  162482. }
  162483. #define fts5IndexSkipVarint(a, iOff) { \
  162484. int iEnd = iOff+9; \
  162485. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  162486. }
  162487. /*
  162488. ** The iterator object passed as the second argument currently contains
  162489. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  162490. ** function searches the leaf page for a term matching (pTerm/nTerm).
  162491. **
  162492. ** If the specified term is found on the page, then the iterator is left
  162493. ** pointing to it. If argument bGe is zero and the term is not found,
  162494. ** the iterator is left pointing at EOF.
  162495. **
  162496. ** If bGe is non-zero and the specified term is not found, then the
  162497. ** iterator is left pointing to the smallest term in the segment that
  162498. ** is larger than the specified term, even if this term is not on the
  162499. ** current page.
  162500. */
  162501. static void fts5LeafSeek(
  162502. Fts5Index *p, /* Leave any error code here */
  162503. int bGe, /* True for a >= search */
  162504. Fts5SegIter *pIter, /* Iterator to seek */
  162505. const u8 *pTerm, int nTerm /* Term to search for */
  162506. ){
  162507. int iOff;
  162508. const u8 *a = pIter->pLeaf->p;
  162509. int szLeaf = pIter->pLeaf->szLeaf;
  162510. int n = pIter->pLeaf->nn;
  162511. int nMatch = 0;
  162512. int nKeep = 0;
  162513. int nNew = 0;
  162514. int iTermOff;
  162515. int iPgidx; /* Current offset in pgidx */
  162516. int bEndOfPage = 0;
  162517. assert( p->rc==SQLITE_OK );
  162518. iPgidx = szLeaf;
  162519. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  162520. iOff = iTermOff;
  162521. while( 1 ){
  162522. /* Figure out how many new bytes are in this term */
  162523. fts5FastGetVarint32(a, iOff, nNew);
  162524. if( nKeep<nMatch ){
  162525. goto search_failed;
  162526. }
  162527. assert( nKeep>=nMatch );
  162528. if( nKeep==nMatch ){
  162529. int nCmp;
  162530. int i;
  162531. nCmp = MIN(nNew, nTerm-nMatch);
  162532. for(i=0; i<nCmp; i++){
  162533. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  162534. }
  162535. nMatch += i;
  162536. if( nTerm==nMatch ){
  162537. if( i==nNew ){
  162538. goto search_success;
  162539. }else{
  162540. goto search_failed;
  162541. }
  162542. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  162543. goto search_failed;
  162544. }
  162545. }
  162546. if( iPgidx>=n ){
  162547. bEndOfPage = 1;
  162548. break;
  162549. }
  162550. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  162551. iTermOff += nKeep;
  162552. iOff = iTermOff;
  162553. /* Read the nKeep field of the next term. */
  162554. fts5FastGetVarint32(a, iOff, nKeep);
  162555. }
  162556. search_failed:
  162557. if( bGe==0 ){
  162558. fts5DataRelease(pIter->pLeaf);
  162559. pIter->pLeaf = 0;
  162560. return;
  162561. }else if( bEndOfPage ){
  162562. do {
  162563. fts5SegIterNextPage(p, pIter);
  162564. if( pIter->pLeaf==0 ) return;
  162565. a = pIter->pLeaf->p;
  162566. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  162567. fts5GetVarint32(&pIter->pLeaf->p[pIter->pLeaf->szLeaf], iOff);
  162568. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  162569. p->rc = FTS5_CORRUPT;
  162570. }else{
  162571. nKeep = 0;
  162572. iOff += fts5GetVarint32(&a[iOff], nNew);
  162573. break;
  162574. }
  162575. }
  162576. }while( 1 );
  162577. }
  162578. search_success:
  162579. pIter->iLeafOffset = iOff + nNew;
  162580. pIter->iTermLeafOffset = pIter->iLeafOffset;
  162581. pIter->iTermLeafPgno = pIter->iLeafPgno;
  162582. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  162583. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  162584. if( iPgidx>=n ){
  162585. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  162586. }else{
  162587. int nExtra;
  162588. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  162589. pIter->iEndofDoclist = iTermOff + nExtra;
  162590. }
  162591. pIter->iPgidxOff = iPgidx;
  162592. fts5SegIterLoadRowid(p, pIter);
  162593. fts5SegIterLoadNPos(p, pIter);
  162594. }
  162595. /*
  162596. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  162597. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  162598. **
  162599. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  162600. ** an error has already occurred when this function is called, it is a no-op.
  162601. */
  162602. static void fts5SegIterSeekInit(
  162603. Fts5Index *p, /* FTS5 backend */
  162604. Fts5Buffer *pBuf, /* Buffer to use for loading pages */
  162605. const u8 *pTerm, int nTerm, /* Term to seek to */
  162606. int flags, /* Mask of FTS5INDEX_XXX flags */
  162607. Fts5StructureSegment *pSeg, /* Description of segment */
  162608. Fts5SegIter *pIter /* Object to populate */
  162609. ){
  162610. int iPg = 1;
  162611. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  162612. int bDlidx = 0; /* True if there is a doclist-index */
  162613. static int nCall = 0;
  162614. nCall++;
  162615. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  162616. assert( pTerm && nTerm );
  162617. memset(pIter, 0, sizeof(*pIter));
  162618. pIter->pSeg = pSeg;
  162619. /* This block sets stack variable iPg to the leaf page number that may
  162620. ** contain term (pTerm/nTerm), if it is present in the segment. */
  162621. if( p->pIdxSelect==0 ){
  162622. Fts5Config *pConfig = p->pConfig;
  162623. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  162624. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  162625. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  162626. pConfig->zDb, pConfig->zName
  162627. ));
  162628. }
  162629. if( p->rc ) return;
  162630. sqlite3_bind_int(p->pIdxSelect, 1, pSeg->iSegid);
  162631. sqlite3_bind_blob(p->pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  162632. if( SQLITE_ROW==sqlite3_step(p->pIdxSelect) ){
  162633. i64 val = sqlite3_column_int(p->pIdxSelect, 0);
  162634. iPg = (int)(val>>1);
  162635. bDlidx = (val & 0x0001);
  162636. }
  162637. p->rc = sqlite3_reset(p->pIdxSelect);
  162638. if( iPg<pSeg->pgnoFirst ){
  162639. iPg = pSeg->pgnoFirst;
  162640. bDlidx = 0;
  162641. }
  162642. pIter->iLeafPgno = iPg - 1;
  162643. fts5SegIterNextPage(p, pIter);
  162644. if( pIter->pLeaf ){
  162645. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  162646. }
  162647. if( p->rc==SQLITE_OK && bGe==0 ){
  162648. pIter->flags |= FTS5_SEGITER_ONETERM;
  162649. if( pIter->pLeaf ){
  162650. if( flags & FTS5INDEX_QUERY_DESC ){
  162651. pIter->flags |= FTS5_SEGITER_REVERSE;
  162652. }
  162653. if( bDlidx ){
  162654. fts5SegIterLoadDlidx(p, pIter);
  162655. }
  162656. if( flags & FTS5INDEX_QUERY_DESC ){
  162657. fts5SegIterReverse(p, pIter);
  162658. }
  162659. }
  162660. }
  162661. /* Either:
  162662. **
  162663. ** 1) an error has occurred, or
  162664. ** 2) the iterator points to EOF, or
  162665. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  162666. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  162667. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  162668. */
  162669. assert( p->rc!=SQLITE_OK /* 1 */
  162670. || pIter->pLeaf==0 /* 2 */
  162671. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  162672. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  162673. );
  162674. }
  162675. /*
  162676. ** Initialize the object pIter to point to term pTerm/nTerm within the
  162677. ** in-memory hash table. If there is no such term in the hash-table, the
  162678. ** iterator is set to EOF.
  162679. **
  162680. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  162681. ** an error has already occurred when this function is called, it is a no-op.
  162682. */
  162683. static void fts5SegIterHashInit(
  162684. Fts5Index *p, /* FTS5 backend */
  162685. const u8 *pTerm, int nTerm, /* Term to seek to */
  162686. int flags, /* Mask of FTS5INDEX_XXX flags */
  162687. Fts5SegIter *pIter /* Object to populate */
  162688. ){
  162689. const u8 *pList = 0;
  162690. int nList = 0;
  162691. const u8 *z = 0;
  162692. int n = 0;
  162693. assert( p->pHash );
  162694. assert( p->rc==SQLITE_OK );
  162695. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  162696. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  162697. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  162698. n = (z ? strlen((const char*)z) : 0);
  162699. }else{
  162700. pIter->flags |= FTS5_SEGITER_ONETERM;
  162701. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  162702. z = pTerm;
  162703. n = nTerm;
  162704. }
  162705. if( pList ){
  162706. Fts5Data *pLeaf;
  162707. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  162708. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  162709. if( pLeaf==0 ) return;
  162710. pLeaf->p = (u8*)pList;
  162711. pLeaf->nn = pLeaf->szLeaf = nList;
  162712. pIter->pLeaf = pLeaf;
  162713. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  162714. pIter->iEndofDoclist = pLeaf->nn+1;
  162715. if( flags & FTS5INDEX_QUERY_DESC ){
  162716. pIter->flags |= FTS5_SEGITER_REVERSE;
  162717. fts5SegIterReverseInitPage(p, pIter);
  162718. }else{
  162719. fts5SegIterLoadNPos(p, pIter);
  162720. }
  162721. }
  162722. }
  162723. /*
  162724. ** Zero the iterator passed as the only argument.
  162725. */
  162726. static void fts5SegIterClear(Fts5SegIter *pIter){
  162727. fts5BufferFree(&pIter->term);
  162728. fts5DataRelease(pIter->pLeaf);
  162729. fts5DataRelease(pIter->pNextLeaf);
  162730. fts5DlidxIterFree(pIter->pDlidx);
  162731. sqlite3_free(pIter->aRowidOffset);
  162732. memset(pIter, 0, sizeof(Fts5SegIter));
  162733. }
  162734. #ifdef SQLITE_DEBUG
  162735. /*
  162736. ** This function is used as part of the big assert() procedure implemented by
  162737. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  162738. ** in *pRes is the correct result of comparing the current positions of the
  162739. ** two iterators.
  162740. */
  162741. static void fts5AssertComparisonResult(
  162742. Fts5IndexIter *pIter,
  162743. Fts5SegIter *p1,
  162744. Fts5SegIter *p2,
  162745. Fts5CResult *pRes
  162746. ){
  162747. int i1 = p1 - pIter->aSeg;
  162748. int i2 = p2 - pIter->aSeg;
  162749. if( p1->pLeaf || p2->pLeaf ){
  162750. if( p1->pLeaf==0 ){
  162751. assert( pRes->iFirst==i2 );
  162752. }else if( p2->pLeaf==0 ){
  162753. assert( pRes->iFirst==i1 );
  162754. }else{
  162755. int nMin = MIN(p1->term.n, p2->term.n);
  162756. int res = memcmp(p1->term.p, p2->term.p, nMin);
  162757. if( res==0 ) res = p1->term.n - p2->term.n;
  162758. if( res==0 ){
  162759. assert( pRes->bTermEq==1 );
  162760. assert( p1->iRowid!=p2->iRowid );
  162761. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  162762. }else{
  162763. assert( pRes->bTermEq==0 );
  162764. }
  162765. if( res<0 ){
  162766. assert( pRes->iFirst==i1 );
  162767. }else{
  162768. assert( pRes->iFirst==i2 );
  162769. }
  162770. }
  162771. }
  162772. }
  162773. /*
  162774. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  162775. ** is compiled. In that case, this function is essentially an assert()
  162776. ** statement used to verify that the contents of the pIter->aFirst[] array
  162777. ** are correct.
  162778. */
  162779. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5IndexIter *pIter){
  162780. if( p->rc==SQLITE_OK ){
  162781. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  162782. int i;
  162783. assert( (pFirst->pLeaf==0)==pIter->bEof );
  162784. /* Check that pIter->iSwitchRowid is set correctly. */
  162785. for(i=0; i<pIter->nSeg; i++){
  162786. Fts5SegIter *p1 = &pIter->aSeg[i];
  162787. assert( p1==pFirst
  162788. || p1->pLeaf==0
  162789. || fts5BufferCompare(&pFirst->term, &p1->term)
  162790. || p1->iRowid==pIter->iSwitchRowid
  162791. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  162792. );
  162793. }
  162794. for(i=0; i<pIter->nSeg; i+=2){
  162795. Fts5SegIter *p1 = &pIter->aSeg[i];
  162796. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  162797. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  162798. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  162799. }
  162800. for(i=1; i<(pIter->nSeg / 2); i+=2){
  162801. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  162802. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  162803. Fts5CResult *pRes = &pIter->aFirst[i];
  162804. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  162805. }
  162806. }
  162807. }
  162808. #else
  162809. # define fts5AssertMultiIterSetup(x,y)
  162810. #endif
  162811. /*
  162812. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  162813. **
  162814. ** If the returned value is non-zero, then it is the index of an entry
  162815. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  162816. ** to a key that is a duplicate of another, higher priority,
  162817. ** segment-iterator in the pSeg->aSeg[] array.
  162818. */
  162819. static int fts5MultiIterDoCompare(Fts5IndexIter *pIter, int iOut){
  162820. int i1; /* Index of left-hand Fts5SegIter */
  162821. int i2; /* Index of right-hand Fts5SegIter */
  162822. int iRes;
  162823. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  162824. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  162825. Fts5CResult *pRes = &pIter->aFirst[iOut];
  162826. assert( iOut<pIter->nSeg && iOut>0 );
  162827. assert( pIter->bRev==0 || pIter->bRev==1 );
  162828. if( iOut>=(pIter->nSeg/2) ){
  162829. i1 = (iOut - pIter->nSeg/2) * 2;
  162830. i2 = i1 + 1;
  162831. }else{
  162832. i1 = pIter->aFirst[iOut*2].iFirst;
  162833. i2 = pIter->aFirst[iOut*2+1].iFirst;
  162834. }
  162835. p1 = &pIter->aSeg[i1];
  162836. p2 = &pIter->aSeg[i2];
  162837. pRes->bTermEq = 0;
  162838. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  162839. iRes = i2;
  162840. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  162841. iRes = i1;
  162842. }else{
  162843. int res = fts5BufferCompare(&p1->term, &p2->term);
  162844. if( res==0 ){
  162845. assert( i2>i1 );
  162846. assert( i2!=0 );
  162847. pRes->bTermEq = 1;
  162848. if( p1->iRowid==p2->iRowid ){
  162849. p1->bDel = p2->bDel;
  162850. return i2;
  162851. }
  162852. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  162853. }
  162854. assert( res!=0 );
  162855. if( res<0 ){
  162856. iRes = i1;
  162857. }else{
  162858. iRes = i2;
  162859. }
  162860. }
  162861. pRes->iFirst = iRes;
  162862. return 0;
  162863. }
  162864. /*
  162865. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  162866. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  162867. */
  162868. static void fts5SegIterGotoPage(
  162869. Fts5Index *p, /* FTS5 backend object */
  162870. Fts5SegIter *pIter, /* Iterator to advance */
  162871. int iLeafPgno
  162872. ){
  162873. assert( iLeafPgno>pIter->iLeafPgno );
  162874. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  162875. p->rc = FTS5_CORRUPT;
  162876. }else{
  162877. fts5DataRelease(pIter->pNextLeaf);
  162878. pIter->pNextLeaf = 0;
  162879. pIter->iLeafPgno = iLeafPgno-1;
  162880. fts5SegIterNextPage(p, pIter);
  162881. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  162882. if( p->rc==SQLITE_OK ){
  162883. int iOff;
  162884. u8 *a = pIter->pLeaf->p;
  162885. int n = pIter->pLeaf->szLeaf;
  162886. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  162887. if( iOff<4 || iOff>=n ){
  162888. p->rc = FTS5_CORRUPT;
  162889. }else{
  162890. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  162891. pIter->iLeafOffset = iOff;
  162892. fts5SegIterLoadNPos(p, pIter);
  162893. }
  162894. }
  162895. }
  162896. }
  162897. /*
  162898. ** Advance the iterator passed as the second argument until it is at or
  162899. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  162900. ** always advanced at least once.
  162901. */
  162902. static void fts5SegIterNextFrom(
  162903. Fts5Index *p, /* FTS5 backend object */
  162904. Fts5SegIter *pIter, /* Iterator to advance */
  162905. i64 iMatch /* Advance iterator at least this far */
  162906. ){
  162907. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  162908. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  162909. int iLeafPgno = pIter->iLeafPgno;
  162910. int bMove = 1;
  162911. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  162912. assert( pIter->pDlidx );
  162913. assert( pIter->pLeaf );
  162914. if( bRev==0 ){
  162915. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  162916. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  162917. fts5DlidxIterNext(p, pDlidx);
  162918. }
  162919. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  162920. if( iLeafPgno>pIter->iLeafPgno ){
  162921. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  162922. bMove = 0;
  162923. }
  162924. }else{
  162925. assert( pIter->pNextLeaf==0 );
  162926. assert( iMatch<pIter->iRowid );
  162927. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  162928. fts5DlidxIterPrev(p, pDlidx);
  162929. }
  162930. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  162931. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  162932. if( iLeafPgno<pIter->iLeafPgno ){
  162933. pIter->iLeafPgno = iLeafPgno+1;
  162934. fts5SegIterReverseNewPage(p, pIter);
  162935. bMove = 0;
  162936. }
  162937. }
  162938. do{
  162939. if( bMove ) fts5SegIterNext(p, pIter, 0);
  162940. if( pIter->pLeaf==0 ) break;
  162941. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  162942. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  162943. bMove = 1;
  162944. }while( p->rc==SQLITE_OK );
  162945. }
  162946. /*
  162947. ** Free the iterator object passed as the second argument.
  162948. */
  162949. static void fts5MultiIterFree(Fts5Index *p, Fts5IndexIter *pIter){
  162950. if( pIter ){
  162951. int i;
  162952. for(i=0; i<pIter->nSeg; i++){
  162953. fts5SegIterClear(&pIter->aSeg[i]);
  162954. }
  162955. fts5StructureRelease(pIter->pStruct);
  162956. fts5BufferFree(&pIter->poslist);
  162957. sqlite3_free(pIter);
  162958. }
  162959. }
  162960. static void fts5MultiIterAdvanced(
  162961. Fts5Index *p, /* FTS5 backend to iterate within */
  162962. Fts5IndexIter *pIter, /* Iterator to update aFirst[] array for */
  162963. int iChanged, /* Index of sub-iterator just advanced */
  162964. int iMinset /* Minimum entry in aFirst[] to set */
  162965. ){
  162966. int i;
  162967. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  162968. int iEq;
  162969. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  162970. fts5SegIterNext(p, &pIter->aSeg[iEq], 0);
  162971. i = pIter->nSeg + iEq;
  162972. }
  162973. }
  162974. }
  162975. /*
  162976. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  162977. ** points to the same term though - just a different rowid. This function
  162978. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  162979. ** If it does so successfully, 0 is returned. Otherwise 1.
  162980. **
  162981. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  162982. ** on the iterator instead. That function does the same as this one, except
  162983. ** that it deals with more complicated cases as well.
  162984. */
  162985. static int fts5MultiIterAdvanceRowid(
  162986. Fts5Index *p, /* FTS5 backend to iterate within */
  162987. Fts5IndexIter *pIter, /* Iterator to update aFirst[] array for */
  162988. int iChanged /* Index of sub-iterator just advanced */
  162989. ){
  162990. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  162991. if( pNew->iRowid==pIter->iSwitchRowid
  162992. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  162993. ){
  162994. int i;
  162995. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  162996. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  162997. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  162998. Fts5CResult *pRes = &pIter->aFirst[i];
  162999. assert( pNew->pLeaf );
  163000. assert( pRes->bTermEq==0 || pOther->pLeaf );
  163001. if( pRes->bTermEq ){
  163002. if( pNew->iRowid==pOther->iRowid ){
  163003. return 1;
  163004. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  163005. pIter->iSwitchRowid = pOther->iRowid;
  163006. pNew = pOther;
  163007. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  163008. pIter->iSwitchRowid = pOther->iRowid;
  163009. }
  163010. }
  163011. pRes->iFirst = (pNew - pIter->aSeg);
  163012. if( i==1 ) break;
  163013. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  163014. }
  163015. }
  163016. return 0;
  163017. }
  163018. /*
  163019. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  163020. */
  163021. static void fts5MultiIterSetEof(Fts5IndexIter *pIter){
  163022. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  163023. pIter->bEof = pSeg->pLeaf==0;
  163024. pIter->iSwitchRowid = pSeg->iRowid;
  163025. }
  163026. /*
  163027. ** Move the iterator to the next entry.
  163028. **
  163029. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  163030. ** considered an error if the iterator reaches EOF, or if it is already at
  163031. ** EOF when this function is called.
  163032. */
  163033. static void fts5MultiIterNext(
  163034. Fts5Index *p,
  163035. Fts5IndexIter *pIter,
  163036. int bFrom, /* True if argument iFrom is valid */
  163037. i64 iFrom /* Advance at least as far as this */
  163038. ){
  163039. if( p->rc==SQLITE_OK ){
  163040. int bUseFrom = bFrom;
  163041. do {
  163042. int iFirst = pIter->aFirst[1].iFirst;
  163043. int bNewTerm = 0;
  163044. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  163045. assert( p->rc==SQLITE_OK );
  163046. if( bUseFrom && pSeg->pDlidx ){
  163047. fts5SegIterNextFrom(p, pSeg, iFrom);
  163048. }else{
  163049. fts5SegIterNext(p, pSeg, &bNewTerm);
  163050. }
  163051. if( pSeg->pLeaf==0 || bNewTerm
  163052. || fts5MultiIterAdvanceRowid(p, pIter, iFirst)
  163053. ){
  163054. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  163055. fts5MultiIterSetEof(pIter);
  163056. }
  163057. fts5AssertMultiIterSetup(p, pIter);
  163058. bUseFrom = 0;
  163059. }while( pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter) );
  163060. }
  163061. }
  163062. static Fts5IndexIter *fts5MultiIterAlloc(
  163063. Fts5Index *p, /* FTS5 backend to iterate within */
  163064. int nSeg
  163065. ){
  163066. Fts5IndexIter *pNew;
  163067. int nSlot; /* Power of two >= nSeg */
  163068. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  163069. pNew = fts5IdxMalloc(p,
  163070. sizeof(Fts5IndexIter) + /* pNew */
  163071. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  163072. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  163073. );
  163074. if( pNew ){
  163075. pNew->nSeg = nSlot;
  163076. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  163077. pNew->pIndex = p;
  163078. }
  163079. return pNew;
  163080. }
  163081. /*
  163082. ** Allocate a new Fts5IndexIter object.
  163083. **
  163084. ** The new object will be used to iterate through data in structure pStruct.
  163085. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  163086. ** is zero or greater, data from the first nSegment segments on level iLevel
  163087. ** is merged.
  163088. **
  163089. ** The iterator initially points to the first term/rowid entry in the
  163090. ** iterated data.
  163091. */
  163092. static void fts5MultiIterNew(
  163093. Fts5Index *p, /* FTS5 backend to iterate within */
  163094. Fts5Structure *pStruct, /* Structure of specific index */
  163095. int bSkipEmpty, /* True to ignore delete-keys */
  163096. int flags, /* FTS5INDEX_QUERY_XXX flags */
  163097. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  163098. int iLevel, /* Level to iterate (-1 for all) */
  163099. int nSegment, /* Number of segments to merge (iLevel>=0) */
  163100. Fts5IndexIter **ppOut /* New object */
  163101. ){
  163102. int nSeg = 0; /* Number of segment-iters in use */
  163103. int iIter = 0; /* */
  163104. int iSeg; /* Used to iterate through segments */
  163105. Fts5Buffer buf = {0,0,0}; /* Buffer used by fts5SegIterSeekInit() */
  163106. Fts5StructureLevel *pLvl;
  163107. Fts5IndexIter *pNew;
  163108. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  163109. /* Allocate space for the new multi-seg-iterator. */
  163110. if( p->rc==SQLITE_OK ){
  163111. if( iLevel<0 ){
  163112. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  163113. nSeg = pStruct->nSegment;
  163114. nSeg += (p->pHash ? 1 : 0);
  163115. }else{
  163116. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  163117. }
  163118. }
  163119. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  163120. if( pNew==0 ) return;
  163121. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  163122. pNew->bSkipEmpty = bSkipEmpty;
  163123. pNew->pStruct = pStruct;
  163124. fts5StructureRef(pStruct);
  163125. /* Initialize each of the component segment iterators. */
  163126. if( iLevel<0 ){
  163127. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  163128. if( p->pHash ){
  163129. /* Add a segment iterator for the current contents of the hash table. */
  163130. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  163131. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  163132. }
  163133. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  163134. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  163135. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  163136. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  163137. if( pTerm==0 ){
  163138. fts5SegIterInit(p, pSeg, pIter);
  163139. }else{
  163140. fts5SegIterSeekInit(p, &buf, pTerm, nTerm, flags, pSeg, pIter);
  163141. }
  163142. }
  163143. }
  163144. }else{
  163145. pLvl = &pStruct->aLevel[iLevel];
  163146. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  163147. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  163148. }
  163149. }
  163150. assert( iIter==nSeg );
  163151. /* If the above was successful, each component iterators now points
  163152. ** to the first entry in its segment. In this case initialize the
  163153. ** aFirst[] array. Or, if an error has occurred, free the iterator
  163154. ** object and set the output variable to NULL. */
  163155. if( p->rc==SQLITE_OK ){
  163156. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  163157. int iEq;
  163158. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  163159. fts5SegIterNext(p, &pNew->aSeg[iEq], 0);
  163160. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  163161. }
  163162. }
  163163. fts5MultiIterSetEof(pNew);
  163164. fts5AssertMultiIterSetup(p, pNew);
  163165. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  163166. fts5MultiIterNext(p, pNew, 0, 0);
  163167. }
  163168. }else{
  163169. fts5MultiIterFree(p, pNew);
  163170. *ppOut = 0;
  163171. }
  163172. fts5BufferFree(&buf);
  163173. }
  163174. /*
  163175. ** Create an Fts5IndexIter that iterates through the doclist provided
  163176. ** as the second argument.
  163177. */
  163178. static void fts5MultiIterNew2(
  163179. Fts5Index *p, /* FTS5 backend to iterate within */
  163180. Fts5Data *pData, /* Doclist to iterate through */
  163181. int bDesc, /* True for descending rowid order */
  163182. Fts5IndexIter **ppOut /* New object */
  163183. ){
  163184. Fts5IndexIter *pNew;
  163185. pNew = fts5MultiIterAlloc(p, 2);
  163186. if( pNew ){
  163187. Fts5SegIter *pIter = &pNew->aSeg[1];
  163188. pNew->bFiltered = 1;
  163189. pIter->flags = FTS5_SEGITER_ONETERM;
  163190. if( pData->szLeaf>0 ){
  163191. pIter->pLeaf = pData;
  163192. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  163193. pIter->iEndofDoclist = pData->nn;
  163194. pNew->aFirst[1].iFirst = 1;
  163195. if( bDesc ){
  163196. pNew->bRev = 1;
  163197. pIter->flags |= FTS5_SEGITER_REVERSE;
  163198. fts5SegIterReverseInitPage(p, pIter);
  163199. }else{
  163200. fts5SegIterLoadNPos(p, pIter);
  163201. }
  163202. pData = 0;
  163203. }else{
  163204. pNew->bEof = 1;
  163205. }
  163206. *ppOut = pNew;
  163207. }
  163208. fts5DataRelease(pData);
  163209. }
  163210. /*
  163211. ** Return true if the iterator is at EOF or if an error has occurred.
  163212. ** False otherwise.
  163213. */
  163214. static int fts5MultiIterEof(Fts5Index *p, Fts5IndexIter *pIter){
  163215. assert( p->rc
  163216. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->bEof
  163217. );
  163218. return (p->rc || pIter->bEof);
  163219. }
  163220. /*
  163221. ** Return the rowid of the entry that the iterator currently points
  163222. ** to. If the iterator points to EOF when this function is called the
  163223. ** results are undefined.
  163224. */
  163225. static i64 fts5MultiIterRowid(Fts5IndexIter *pIter){
  163226. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  163227. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  163228. }
  163229. /*
  163230. ** Move the iterator to the next entry at or following iMatch.
  163231. */
  163232. static void fts5MultiIterNextFrom(
  163233. Fts5Index *p,
  163234. Fts5IndexIter *pIter,
  163235. i64 iMatch
  163236. ){
  163237. while( 1 ){
  163238. i64 iRowid;
  163239. fts5MultiIterNext(p, pIter, 1, iMatch);
  163240. if( fts5MultiIterEof(p, pIter) ) break;
  163241. iRowid = fts5MultiIterRowid(pIter);
  163242. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  163243. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  163244. }
  163245. }
  163246. /*
  163247. ** Return a pointer to a buffer containing the term associated with the
  163248. ** entry that the iterator currently points to.
  163249. */
  163250. static const u8 *fts5MultiIterTerm(Fts5IndexIter *pIter, int *pn){
  163251. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  163252. *pn = p->term.n;
  163253. return p->term.p;
  163254. }
  163255. static void fts5ChunkIterate(
  163256. Fts5Index *p, /* Index object */
  163257. Fts5SegIter *pSeg, /* Poslist of this iterator */
  163258. void *pCtx, /* Context pointer for xChunk callback */
  163259. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  163260. ){
  163261. int nRem = pSeg->nPos; /* Number of bytes still to come */
  163262. Fts5Data *pData = 0;
  163263. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  163264. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  163265. int pgno = pSeg->iLeafPgno;
  163266. int pgnoSave = 0;
  163267. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  163268. pgnoSave = pgno+1;
  163269. }
  163270. while( 1 ){
  163271. xChunk(p, pCtx, pChunk, nChunk);
  163272. nRem -= nChunk;
  163273. fts5DataRelease(pData);
  163274. if( nRem<=0 ){
  163275. break;
  163276. }else{
  163277. pgno++;
  163278. pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  163279. if( pData==0 ) break;
  163280. pChunk = &pData->p[4];
  163281. nChunk = MIN(nRem, pData->szLeaf - 4);
  163282. if( pgno==pgnoSave ){
  163283. assert( pSeg->pNextLeaf==0 );
  163284. pSeg->pNextLeaf = pData;
  163285. pData = 0;
  163286. }
  163287. }
  163288. }
  163289. }
  163290. /*
  163291. ** Allocate a new segment-id for the structure pStruct. The new segment
  163292. ** id must be between 1 and 65335 inclusive, and must not be used by
  163293. ** any currently existing segment. If a free segment id cannot be found,
  163294. ** SQLITE_FULL is returned.
  163295. **
  163296. ** If an error has already occurred, this function is a no-op. 0 is
  163297. ** returned in this case.
  163298. */
  163299. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  163300. int iSegid = 0;
  163301. if( p->rc==SQLITE_OK ){
  163302. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  163303. p->rc = SQLITE_FULL;
  163304. }else{
  163305. while( iSegid==0 ){
  163306. int iLvl, iSeg;
  163307. sqlite3_randomness(sizeof(u32), (void*)&iSegid);
  163308. iSegid = iSegid & ((1 << FTS5_DATA_ID_B)-1);
  163309. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  163310. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  163311. if( iSegid==pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ){
  163312. iSegid = 0;
  163313. }
  163314. }
  163315. }
  163316. }
  163317. }
  163318. }
  163319. return iSegid;
  163320. }
  163321. /*
  163322. ** Discard all data currently cached in the hash-tables.
  163323. */
  163324. static void fts5IndexDiscardData(Fts5Index *p){
  163325. assert( p->pHash || p->nPendingData==0 );
  163326. if( p->pHash ){
  163327. sqlite3Fts5HashClear(p->pHash);
  163328. p->nPendingData = 0;
  163329. }
  163330. }
  163331. /*
  163332. ** Return the size of the prefix, in bytes, that buffer (nNew/pNew) shares
  163333. ** with buffer (nOld/pOld).
  163334. */
  163335. static int fts5PrefixCompress(
  163336. int nOld, const u8 *pOld,
  163337. int nNew, const u8 *pNew
  163338. ){
  163339. int i;
  163340. assert( fts5BlobCompare(pOld, nOld, pNew, nNew)<0 );
  163341. for(i=0; i<nOld; i++){
  163342. if( pOld[i]!=pNew[i] ) break;
  163343. }
  163344. return i;
  163345. }
  163346. static void fts5WriteDlidxClear(
  163347. Fts5Index *p,
  163348. Fts5SegWriter *pWriter,
  163349. int bFlush /* If true, write dlidx to disk */
  163350. ){
  163351. int i;
  163352. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  163353. for(i=0; i<pWriter->nDlidx; i++){
  163354. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  163355. if( pDlidx->buf.n==0 ) break;
  163356. if( bFlush ){
  163357. assert( pDlidx->pgno!=0 );
  163358. fts5DataWrite(p,
  163359. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  163360. pDlidx->buf.p, pDlidx->buf.n
  163361. );
  163362. }
  163363. sqlite3Fts5BufferZero(&pDlidx->buf);
  163364. pDlidx->bPrevValid = 0;
  163365. }
  163366. }
  163367. /*
  163368. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  163369. ** Any new array elements are zeroed before returning.
  163370. */
  163371. static int fts5WriteDlidxGrow(
  163372. Fts5Index *p,
  163373. Fts5SegWriter *pWriter,
  163374. int nLvl
  163375. ){
  163376. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  163377. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  163378. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  163379. );
  163380. if( aDlidx==0 ){
  163381. p->rc = SQLITE_NOMEM;
  163382. }else{
  163383. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  163384. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  163385. pWriter->aDlidx = aDlidx;
  163386. pWriter->nDlidx = nLvl;
  163387. }
  163388. }
  163389. return p->rc;
  163390. }
  163391. /*
  163392. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  163393. ** enough, flush it to disk and return 1. Otherwise discard it and return
  163394. ** zero.
  163395. */
  163396. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  163397. int bFlag = 0;
  163398. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  163399. ** to the database, also write the doclist-index to disk. */
  163400. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  163401. bFlag = 1;
  163402. }
  163403. fts5WriteDlidxClear(p, pWriter, bFlag);
  163404. pWriter->nEmpty = 0;
  163405. return bFlag;
  163406. }
  163407. /*
  163408. ** This function is called whenever processing of the doclist for the
  163409. ** last term on leaf page (pWriter->iBtPage) is completed.
  163410. **
  163411. ** The doclist-index for that term is currently stored in-memory within the
  163412. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  163413. ** writes it out to disk. Or, if it is too small to bother with, discards
  163414. ** it.
  163415. **
  163416. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  163417. */
  163418. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  163419. int bFlag;
  163420. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  163421. if( pWriter->iBtPage==0 ) return;
  163422. bFlag = fts5WriteFlushDlidx(p, pWriter);
  163423. if( p->rc==SQLITE_OK ){
  163424. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  163425. /* The following was already done in fts5WriteInit(): */
  163426. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  163427. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  163428. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  163429. sqlite3_step(p->pIdxWriter);
  163430. p->rc = sqlite3_reset(p->pIdxWriter);
  163431. }
  163432. pWriter->iBtPage = 0;
  163433. }
  163434. /*
  163435. ** This is called once for each leaf page except the first that contains
  163436. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  163437. ** is larger than all terms written to earlier leaves, and equal to or
  163438. ** smaller than the first term on the new leaf.
  163439. **
  163440. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  163441. ** has already occurred when this function is called, it is a no-op.
  163442. */
  163443. static void fts5WriteBtreeTerm(
  163444. Fts5Index *p, /* FTS5 backend object */
  163445. Fts5SegWriter *pWriter, /* Writer object */
  163446. int nTerm, const u8 *pTerm /* First term on new page */
  163447. ){
  163448. fts5WriteFlushBtree(p, pWriter);
  163449. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  163450. pWriter->iBtPage = pWriter->writer.pgno;
  163451. }
  163452. /*
  163453. ** This function is called when flushing a leaf page that contains no
  163454. ** terms at all to disk.
  163455. */
  163456. static void fts5WriteBtreeNoTerm(
  163457. Fts5Index *p, /* FTS5 backend object */
  163458. Fts5SegWriter *pWriter /* Writer object */
  163459. ){
  163460. /* If there were no rowids on the leaf page either and the doclist-index
  163461. ** has already been started, append an 0x00 byte to it. */
  163462. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  163463. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  163464. assert( pDlidx->bPrevValid );
  163465. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  163466. }
  163467. /* Increment the "number of sequential leaves without a term" counter. */
  163468. pWriter->nEmpty++;
  163469. }
  163470. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  163471. i64 iRowid;
  163472. int iOff;
  163473. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  163474. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  163475. return iRowid;
  163476. }
  163477. /*
  163478. ** Rowid iRowid has just been appended to the current leaf page. It is the
  163479. ** first on the page. This function appends an appropriate entry to the current
  163480. ** doclist-index.
  163481. */
  163482. static void fts5WriteDlidxAppend(
  163483. Fts5Index *p,
  163484. Fts5SegWriter *pWriter,
  163485. i64 iRowid
  163486. ){
  163487. int i;
  163488. int bDone = 0;
  163489. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  163490. i64 iVal;
  163491. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  163492. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  163493. /* The current doclist-index page is full. Write it to disk and push
  163494. ** a copy of iRowid (which will become the first rowid on the next
  163495. ** doclist-index leaf page) up into the next level of the b-tree
  163496. ** hierarchy. If the node being flushed is currently the root node,
  163497. ** also push its first rowid upwards. */
  163498. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  163499. fts5DataWrite(p,
  163500. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  163501. pDlidx->buf.p, pDlidx->buf.n
  163502. );
  163503. fts5WriteDlidxGrow(p, pWriter, i+2);
  163504. pDlidx = &pWriter->aDlidx[i];
  163505. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  163506. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  163507. /* This was the root node. Push its first rowid up to the new root. */
  163508. pDlidx[1].pgno = pDlidx->pgno;
  163509. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  163510. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  163511. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  163512. pDlidx[1].bPrevValid = 1;
  163513. pDlidx[1].iPrev = iFirst;
  163514. }
  163515. sqlite3Fts5BufferZero(&pDlidx->buf);
  163516. pDlidx->bPrevValid = 0;
  163517. pDlidx->pgno++;
  163518. }else{
  163519. bDone = 1;
  163520. }
  163521. if( pDlidx->bPrevValid ){
  163522. iVal = iRowid - pDlidx->iPrev;
  163523. }else{
  163524. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  163525. assert( pDlidx->buf.n==0 );
  163526. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  163527. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  163528. iVal = iRowid;
  163529. }
  163530. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  163531. pDlidx->bPrevValid = 1;
  163532. pDlidx->iPrev = iRowid;
  163533. }
  163534. }
  163535. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  163536. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  163537. Fts5PageWriter *pPage = &pWriter->writer;
  163538. i64 iRowid;
  163539. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  163540. /* Set the szLeaf header field. */
  163541. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  163542. fts5PutU16(&pPage->buf.p[2], pPage->buf.n);
  163543. if( pWriter->bFirstTermInPage ){
  163544. /* No term was written to this page. */
  163545. assert( pPage->pgidx.n==0 );
  163546. fts5WriteBtreeNoTerm(p, pWriter);
  163547. }else{
  163548. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  163549. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  163550. }
  163551. /* Write the page out to disk */
  163552. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  163553. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  163554. /* Initialize the next page. */
  163555. fts5BufferZero(&pPage->buf);
  163556. fts5BufferZero(&pPage->pgidx);
  163557. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  163558. pPage->iPrevPgidx = 0;
  163559. pPage->pgno++;
  163560. /* Increase the leaves written counter */
  163561. pWriter->nLeafWritten++;
  163562. /* The new leaf holds no terms or rowids */
  163563. pWriter->bFirstTermInPage = 1;
  163564. pWriter->bFirstRowidInPage = 1;
  163565. }
  163566. /*
  163567. ** Append term pTerm/nTerm to the segment being written by the writer passed
  163568. ** as the second argument.
  163569. **
  163570. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  163571. ** already occurred, this function is a no-op.
  163572. */
  163573. static void fts5WriteAppendTerm(
  163574. Fts5Index *p,
  163575. Fts5SegWriter *pWriter,
  163576. int nTerm, const u8 *pTerm
  163577. ){
  163578. int nPrefix; /* Bytes of prefix compression for term */
  163579. Fts5PageWriter *pPage = &pWriter->writer;
  163580. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  163581. assert( p->rc==SQLITE_OK );
  163582. assert( pPage->buf.n>=4 );
  163583. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  163584. /* If the current leaf page is full, flush it to disk. */
  163585. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  163586. if( pPage->buf.n>4 ){
  163587. fts5WriteFlushLeaf(p, pWriter);
  163588. }
  163589. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  163590. }
  163591. /* TODO1: Updating pgidx here. */
  163592. pPgidx->n += sqlite3Fts5PutVarint(
  163593. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  163594. );
  163595. pPage->iPrevPgidx = pPage->buf.n;
  163596. #if 0
  163597. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  163598. pPgidx->n += 2;
  163599. #endif
  163600. if( pWriter->bFirstTermInPage ){
  163601. nPrefix = 0;
  163602. if( pPage->pgno!=1 ){
  163603. /* This is the first term on a leaf that is not the leftmost leaf in
  163604. ** the segment b-tree. In this case it is necessary to add a term to
  163605. ** the b-tree hierarchy that is (a) larger than the largest term
  163606. ** already written to the segment and (b) smaller than or equal to
  163607. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  163608. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  163609. ** previous term.
  163610. **
  163611. ** Usually, the previous term is available in pPage->term. The exception
  163612. ** is if this is the first term written in an incremental-merge step.
  163613. ** In this case the previous term is not available, so just write a
  163614. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  163615. ** inefficient, but still correct. */
  163616. int n = nTerm;
  163617. if( pPage->term.n ){
  163618. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
  163619. }
  163620. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  163621. pPage = &pWriter->writer;
  163622. }
  163623. }else{
  163624. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
  163625. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  163626. }
  163627. /* Append the number of bytes of new data, then the term data itself
  163628. ** to the page. */
  163629. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  163630. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  163631. /* Update the Fts5PageWriter.term field. */
  163632. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  163633. pWriter->bFirstTermInPage = 0;
  163634. pWriter->bFirstRowidInPage = 0;
  163635. pWriter->bFirstRowidInDoclist = 1;
  163636. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  163637. pWriter->aDlidx[0].pgno = pPage->pgno;
  163638. }
  163639. /*
  163640. ** Append a rowid and position-list size field to the writers output.
  163641. */
  163642. static void fts5WriteAppendRowid(
  163643. Fts5Index *p,
  163644. Fts5SegWriter *pWriter,
  163645. i64 iRowid,
  163646. int nPos
  163647. ){
  163648. if( p->rc==SQLITE_OK ){
  163649. Fts5PageWriter *pPage = &pWriter->writer;
  163650. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  163651. fts5WriteFlushLeaf(p, pWriter);
  163652. }
  163653. /* If this is to be the first rowid written to the page, set the
  163654. ** rowid-pointer in the page-header. Also append a value to the dlidx
  163655. ** buffer, in case a doclist-index is required. */
  163656. if( pWriter->bFirstRowidInPage ){
  163657. fts5PutU16(pPage->buf.p, pPage->buf.n);
  163658. fts5WriteDlidxAppend(p, pWriter, iRowid);
  163659. }
  163660. /* Write the rowid. */
  163661. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  163662. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  163663. }else{
  163664. assert( p->rc || iRowid>pWriter->iPrevRowid );
  163665. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  163666. }
  163667. pWriter->iPrevRowid = iRowid;
  163668. pWriter->bFirstRowidInDoclist = 0;
  163669. pWriter->bFirstRowidInPage = 0;
  163670. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPos);
  163671. }
  163672. }
  163673. static void fts5WriteAppendPoslistData(
  163674. Fts5Index *p,
  163675. Fts5SegWriter *pWriter,
  163676. const u8 *aData,
  163677. int nData
  163678. ){
  163679. Fts5PageWriter *pPage = &pWriter->writer;
  163680. const u8 *a = aData;
  163681. int n = nData;
  163682. assert( p->pConfig->pgsz>0 );
  163683. while( p->rc==SQLITE_OK
  163684. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  163685. ){
  163686. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  163687. int nCopy = 0;
  163688. while( nCopy<nReq ){
  163689. i64 dummy;
  163690. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  163691. }
  163692. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  163693. a += nCopy;
  163694. n -= nCopy;
  163695. fts5WriteFlushLeaf(p, pWriter);
  163696. }
  163697. if( n>0 ){
  163698. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  163699. }
  163700. }
  163701. /*
  163702. ** Flush any data cached by the writer object to the database. Free any
  163703. ** allocations associated with the writer.
  163704. */
  163705. static void fts5WriteFinish(
  163706. Fts5Index *p,
  163707. Fts5SegWriter *pWriter, /* Writer object */
  163708. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  163709. ){
  163710. int i;
  163711. Fts5PageWriter *pLeaf = &pWriter->writer;
  163712. if( p->rc==SQLITE_OK ){
  163713. assert( pLeaf->pgno>=1 );
  163714. if( pLeaf->buf.n>4 ){
  163715. fts5WriteFlushLeaf(p, pWriter);
  163716. }
  163717. *pnLeaf = pLeaf->pgno-1;
  163718. fts5WriteFlushBtree(p, pWriter);
  163719. }
  163720. fts5BufferFree(&pLeaf->term);
  163721. fts5BufferFree(&pLeaf->buf);
  163722. fts5BufferFree(&pLeaf->pgidx);
  163723. fts5BufferFree(&pWriter->btterm);
  163724. for(i=0; i<pWriter->nDlidx; i++){
  163725. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  163726. }
  163727. sqlite3_free(pWriter->aDlidx);
  163728. }
  163729. static void fts5WriteInit(
  163730. Fts5Index *p,
  163731. Fts5SegWriter *pWriter,
  163732. int iSegid
  163733. ){
  163734. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  163735. memset(pWriter, 0, sizeof(Fts5SegWriter));
  163736. pWriter->iSegid = iSegid;
  163737. fts5WriteDlidxGrow(p, pWriter, 1);
  163738. pWriter->writer.pgno = 1;
  163739. pWriter->bFirstTermInPage = 1;
  163740. pWriter->iBtPage = 1;
  163741. /* Grow the two buffers to pgsz + padding bytes in size. */
  163742. fts5BufferGrow(&p->rc, &pWriter->writer.pgidx, nBuffer);
  163743. fts5BufferGrow(&p->rc, &pWriter->writer.buf, nBuffer);
  163744. if( p->pIdxWriter==0 ){
  163745. Fts5Config *pConfig = p->pConfig;
  163746. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  163747. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  163748. pConfig->zDb, pConfig->zName
  163749. ));
  163750. }
  163751. if( p->rc==SQLITE_OK ){
  163752. /* Initialize the 4-byte leaf-page header to 0x00. */
  163753. memset(pWriter->writer.buf.p, 0, 4);
  163754. pWriter->writer.buf.n = 4;
  163755. /* Bind the current output segment id to the index-writer. This is an
  163756. ** optimization over binding the same value over and over as rows are
  163757. ** inserted into %_idx by the current writer. */
  163758. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  163759. }
  163760. }
  163761. /*
  163762. ** Iterator pIter was used to iterate through the input segments of on an
  163763. ** incremental merge operation. This function is called if the incremental
  163764. ** merge step has finished but the input has not been completely exhausted.
  163765. */
  163766. static void fts5TrimSegments(Fts5Index *p, Fts5IndexIter *pIter){
  163767. int i;
  163768. Fts5Buffer buf;
  163769. memset(&buf, 0, sizeof(Fts5Buffer));
  163770. for(i=0; i<pIter->nSeg; i++){
  163771. Fts5SegIter *pSeg = &pIter->aSeg[i];
  163772. if( pSeg->pSeg==0 ){
  163773. /* no-op */
  163774. }else if( pSeg->pLeaf==0 ){
  163775. /* All keys from this input segment have been transfered to the output.
  163776. ** Set both the first and last page-numbers to 0 to indicate that the
  163777. ** segment is now empty. */
  163778. pSeg->pSeg->pgnoLast = 0;
  163779. pSeg->pSeg->pgnoFirst = 0;
  163780. }else{
  163781. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  163782. i64 iLeafRowid;
  163783. Fts5Data *pData;
  163784. int iId = pSeg->pSeg->iSegid;
  163785. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  163786. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  163787. pData = fts5DataRead(p, iLeafRowid);
  163788. if( pData ){
  163789. fts5BufferZero(&buf);
  163790. fts5BufferGrow(&p->rc, &buf, pData->nn);
  163791. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  163792. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  163793. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  163794. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  163795. if( p->rc==SQLITE_OK ){
  163796. /* Set the szLeaf field */
  163797. fts5PutU16(&buf.p[2], buf.n);
  163798. }
  163799. /* Set up the new page-index array */
  163800. fts5BufferAppendVarint(&p->rc, &buf, 4);
  163801. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  163802. && pSeg->iEndofDoclist<pData->szLeaf
  163803. ){
  163804. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  163805. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  163806. fts5BufferAppendBlob(&p->rc, &buf,
  163807. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  163808. );
  163809. }
  163810. fts5DataRelease(pData);
  163811. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  163812. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  163813. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  163814. }
  163815. }
  163816. }
  163817. fts5BufferFree(&buf);
  163818. }
  163819. static void fts5MergeChunkCallback(
  163820. Fts5Index *p,
  163821. void *pCtx,
  163822. const u8 *pChunk, int nChunk
  163823. ){
  163824. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  163825. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  163826. }
  163827. /*
  163828. **
  163829. */
  163830. static void fts5IndexMergeLevel(
  163831. Fts5Index *p, /* FTS5 backend object */
  163832. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  163833. int iLvl, /* Level to read input from */
  163834. int *pnRem /* Write up to this many output leaves */
  163835. ){
  163836. Fts5Structure *pStruct = *ppStruct;
  163837. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  163838. Fts5StructureLevel *pLvlOut;
  163839. Fts5IndexIter *pIter = 0; /* Iterator to read input data */
  163840. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  163841. int nInput; /* Number of input segments */
  163842. Fts5SegWriter writer; /* Writer object */
  163843. Fts5StructureSegment *pSeg; /* Output segment */
  163844. Fts5Buffer term;
  163845. int bOldest; /* True if the output segment is the oldest */
  163846. assert( iLvl<pStruct->nLevel );
  163847. assert( pLvl->nMerge<=pLvl->nSeg );
  163848. memset(&writer, 0, sizeof(Fts5SegWriter));
  163849. memset(&term, 0, sizeof(Fts5Buffer));
  163850. if( pLvl->nMerge ){
  163851. pLvlOut = &pStruct->aLevel[iLvl+1];
  163852. assert( pLvlOut->nSeg>0 );
  163853. nInput = pLvl->nMerge;
  163854. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  163855. fts5WriteInit(p, &writer, pSeg->iSegid);
  163856. writer.writer.pgno = pSeg->pgnoLast+1;
  163857. writer.iBtPage = 0;
  163858. }else{
  163859. int iSegid = fts5AllocateSegid(p, pStruct);
  163860. /* Extend the Fts5Structure object as required to ensure the output
  163861. ** segment exists. */
  163862. if( iLvl==pStruct->nLevel-1 ){
  163863. fts5StructureAddLevel(&p->rc, ppStruct);
  163864. pStruct = *ppStruct;
  163865. }
  163866. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  163867. if( p->rc ) return;
  163868. pLvl = &pStruct->aLevel[iLvl];
  163869. pLvlOut = &pStruct->aLevel[iLvl+1];
  163870. fts5WriteInit(p, &writer, iSegid);
  163871. /* Add the new segment to the output level */
  163872. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  163873. pLvlOut->nSeg++;
  163874. pSeg->pgnoFirst = 1;
  163875. pSeg->iSegid = iSegid;
  163876. pStruct->nSegment++;
  163877. /* Read input from all segments in the input level */
  163878. nInput = pLvl->nSeg;
  163879. }
  163880. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  163881. assert( iLvl>=0 );
  163882. for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, iLvl, nInput, &pIter);
  163883. fts5MultiIterEof(p, pIter)==0;
  163884. fts5MultiIterNext(p, pIter, 0, 0)
  163885. ){
  163886. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  163887. int nPos; /* position-list size field value */
  163888. int nTerm;
  163889. const u8 *pTerm;
  163890. /* Check for key annihilation. */
  163891. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  163892. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  163893. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  163894. if( pnRem && writer.nLeafWritten>nRem ){
  163895. break;
  163896. }
  163897. /* This is a new term. Append a term to the output segment. */
  163898. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  163899. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  163900. }
  163901. /* Append the rowid to the output */
  163902. /* WRITEPOSLISTSIZE */
  163903. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  163904. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter), nPos);
  163905. /* Append the position-list data to the output */
  163906. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  163907. }
  163908. /* Flush the last leaf page to disk. Set the output segment b-tree height
  163909. ** and last leaf page number at the same time. */
  163910. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  163911. if( fts5MultiIterEof(p, pIter) ){
  163912. int i;
  163913. /* Remove the redundant segments from the %_data table */
  163914. for(i=0; i<nInput; i++){
  163915. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  163916. }
  163917. /* Remove the redundant segments from the input level */
  163918. if( pLvl->nSeg!=nInput ){
  163919. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  163920. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  163921. }
  163922. pStruct->nSegment -= nInput;
  163923. pLvl->nSeg -= nInput;
  163924. pLvl->nMerge = 0;
  163925. if( pSeg->pgnoLast==0 ){
  163926. pLvlOut->nSeg--;
  163927. pStruct->nSegment--;
  163928. }
  163929. }else{
  163930. assert( pSeg->pgnoLast>0 );
  163931. fts5TrimSegments(p, pIter);
  163932. pLvl->nMerge = nInput;
  163933. }
  163934. fts5MultiIterFree(p, pIter);
  163935. fts5BufferFree(&term);
  163936. if( pnRem ) *pnRem -= writer.nLeafWritten;
  163937. }
  163938. /*
  163939. ** Do up to nPg pages of automerge work on the index.
  163940. */
  163941. static void fts5IndexMerge(
  163942. Fts5Index *p, /* FTS5 backend object */
  163943. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  163944. int nPg /* Pages of work to do */
  163945. ){
  163946. int nRem = nPg;
  163947. Fts5Structure *pStruct = *ppStruct;
  163948. while( nRem>0 && p->rc==SQLITE_OK ){
  163949. int iLvl; /* To iterate through levels */
  163950. int iBestLvl = 0; /* Level offering the most input segments */
  163951. int nBest = 0; /* Number of input segments on best level */
  163952. /* Set iBestLvl to the level to read input segments from. */
  163953. assert( pStruct->nLevel>0 );
  163954. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  163955. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  163956. if( pLvl->nMerge ){
  163957. if( pLvl->nMerge>nBest ){
  163958. iBestLvl = iLvl;
  163959. nBest = pLvl->nMerge;
  163960. }
  163961. break;
  163962. }
  163963. if( pLvl->nSeg>nBest ){
  163964. nBest = pLvl->nSeg;
  163965. iBestLvl = iLvl;
  163966. }
  163967. }
  163968. /* If nBest is still 0, then the index must be empty. */
  163969. #ifdef SQLITE_DEBUG
  163970. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  163971. assert( pStruct->aLevel[iLvl].nSeg==0 );
  163972. }
  163973. #endif
  163974. if( nBest<p->pConfig->nAutomerge
  163975. && pStruct->aLevel[iBestLvl].nMerge==0
  163976. ){
  163977. break;
  163978. }
  163979. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  163980. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  163981. fts5StructurePromote(p, iBestLvl+1, pStruct);
  163982. }
  163983. }
  163984. *ppStruct = pStruct;
  163985. }
  163986. /*
  163987. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  163988. ** segment. This function updates the write-counter accordingly and, if
  163989. ** necessary, performs incremental merge work.
  163990. **
  163991. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  163992. ** already occurred, this function is a no-op.
  163993. */
  163994. static void fts5IndexAutomerge(
  163995. Fts5Index *p, /* FTS5 backend object */
  163996. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  163997. int nLeaf /* Number of output leaves just written */
  163998. ){
  163999. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  164000. Fts5Structure *pStruct = *ppStruct;
  164001. u64 nWrite; /* Initial value of write-counter */
  164002. int nWork; /* Number of work-quanta to perform */
  164003. int nRem; /* Number of leaf pages left to write */
  164004. /* Update the write-counter. While doing so, set nWork. */
  164005. nWrite = pStruct->nWriteCounter;
  164006. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  164007. pStruct->nWriteCounter += nLeaf;
  164008. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  164009. fts5IndexMerge(p, ppStruct, nRem);
  164010. }
  164011. }
  164012. static void fts5IndexCrisismerge(
  164013. Fts5Index *p, /* FTS5 backend object */
  164014. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  164015. ){
  164016. const int nCrisis = p->pConfig->nCrisisMerge;
  164017. Fts5Structure *pStruct = *ppStruct;
  164018. int iLvl = 0;
  164019. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  164020. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  164021. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  164022. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  164023. fts5StructurePromote(p, iLvl+1, pStruct);
  164024. iLvl++;
  164025. }
  164026. *ppStruct = pStruct;
  164027. }
  164028. static int fts5IndexReturn(Fts5Index *p){
  164029. int rc = p->rc;
  164030. p->rc = SQLITE_OK;
  164031. return rc;
  164032. }
  164033. typedef struct Fts5FlushCtx Fts5FlushCtx;
  164034. struct Fts5FlushCtx {
  164035. Fts5Index *pIdx;
  164036. Fts5SegWriter writer;
  164037. };
  164038. /*
  164039. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  164040. ** in a 32-bit integer. Return the size of the largest prefix of this
  164041. ** list nMax bytes or less in size.
  164042. */
  164043. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  164044. int ret;
  164045. u32 dummy;
  164046. ret = fts5GetVarint32(aBuf, dummy);
  164047. if( ret<nMax ){
  164048. while( 1 ){
  164049. int i = fts5GetVarint32(&aBuf[ret], dummy);
  164050. if( (ret + i) > nMax ) break;
  164051. ret += i;
  164052. }
  164053. }
  164054. return ret;
  164055. }
  164056. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  164057. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  164058. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  164059. (pBuf)->n += nBlob; \
  164060. }
  164061. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  164062. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  164063. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  164064. }
  164065. /*
  164066. ** Flush the contents of in-memory hash table iHash to a new level-0
  164067. ** segment on disk. Also update the corresponding structure record.
  164068. **
  164069. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  164070. ** already occurred, this function is a no-op.
  164071. */
  164072. static void fts5FlushOneHash(Fts5Index *p){
  164073. Fts5Hash *pHash = p->pHash;
  164074. Fts5Structure *pStruct;
  164075. int iSegid;
  164076. int pgnoLast = 0; /* Last leaf page number in segment */
  164077. /* Obtain a reference to the index structure and allocate a new segment-id
  164078. ** for the new level-0 segment. */
  164079. pStruct = fts5StructureRead(p);
  164080. iSegid = fts5AllocateSegid(p, pStruct);
  164081. if( iSegid ){
  164082. const int pgsz = p->pConfig->pgsz;
  164083. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  164084. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  164085. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  164086. Fts5SegWriter writer;
  164087. fts5WriteInit(p, &writer, iSegid);
  164088. pBuf = &writer.writer.buf;
  164089. pPgidx = &writer.writer.pgidx;
  164090. /* fts5WriteInit() should have initialized the buffers to (most likely)
  164091. ** the maximum space required. */
  164092. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  164093. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  164094. /* Begin scanning through hash table entries. This loop runs once for each
  164095. ** term/doclist currently stored within the hash table. */
  164096. if( p->rc==SQLITE_OK ){
  164097. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  164098. }
  164099. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  164100. const char *zTerm; /* Buffer containing term */
  164101. const u8 *pDoclist; /* Pointer to doclist for this term */
  164102. int nDoclist; /* Size of doclist in bytes */
  164103. /* Write the term for this entry to disk. */
  164104. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  164105. fts5WriteAppendTerm(p, &writer, strlen(zTerm), (const u8*)zTerm);
  164106. assert( writer.bFirstRowidInPage==0 );
  164107. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  164108. /* The entire doclist will fit on the current leaf. */
  164109. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  164110. }else{
  164111. i64 iRowid = 0;
  164112. i64 iDelta = 0;
  164113. int iOff = 0;
  164114. /* The entire doclist will not fit on this leaf. The following
  164115. ** loop iterates through the poslists that make up the current
  164116. ** doclist. */
  164117. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  164118. int nPos;
  164119. int nCopy;
  164120. int bDummy;
  164121. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  164122. nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  164123. nCopy += nPos;
  164124. iRowid += iDelta;
  164125. if( writer.bFirstRowidInPage ){
  164126. fts5PutU16(&pBuf->p[0], pBuf->n); /* first rowid on page */
  164127. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  164128. writer.bFirstRowidInPage = 0;
  164129. fts5WriteDlidxAppend(p, &writer, iRowid);
  164130. }else{
  164131. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  164132. }
  164133. assert( pBuf->n<=pBuf->nSpace );
  164134. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  164135. /* The entire poslist will fit on the current leaf. So copy
  164136. ** it in one go. */
  164137. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  164138. }else{
  164139. /* The entire poslist will not fit on this leaf. So it needs
  164140. ** to be broken into sections. The only qualification being
  164141. ** that each varint must be stored contiguously. */
  164142. const u8 *pPoslist = &pDoclist[iOff];
  164143. int iPos = 0;
  164144. while( p->rc==SQLITE_OK ){
  164145. int nSpace = pgsz - pBuf->n - pPgidx->n;
  164146. int n = 0;
  164147. if( (nCopy - iPos)<=nSpace ){
  164148. n = nCopy - iPos;
  164149. }else{
  164150. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  164151. }
  164152. assert( n>0 );
  164153. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  164154. iPos += n;
  164155. if( (pBuf->n + pPgidx->n)>=pgsz ){
  164156. fts5WriteFlushLeaf(p, &writer);
  164157. }
  164158. if( iPos>=nCopy ) break;
  164159. }
  164160. }
  164161. iOff += nCopy;
  164162. }
  164163. }
  164164. /* TODO2: Doclist terminator written here. */
  164165. /* pBuf->p[pBuf->n++] = '\0'; */
  164166. assert( pBuf->n<=pBuf->nSpace );
  164167. sqlite3Fts5HashScanNext(pHash);
  164168. }
  164169. sqlite3Fts5HashClear(pHash);
  164170. fts5WriteFinish(p, &writer, &pgnoLast);
  164171. /* Update the Fts5Structure. It is written back to the database by the
  164172. ** fts5StructureRelease() call below. */
  164173. if( pStruct->nLevel==0 ){
  164174. fts5StructureAddLevel(&p->rc, &pStruct);
  164175. }
  164176. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  164177. if( p->rc==SQLITE_OK ){
  164178. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  164179. pSeg->iSegid = iSegid;
  164180. pSeg->pgnoFirst = 1;
  164181. pSeg->pgnoLast = pgnoLast;
  164182. pStruct->nSegment++;
  164183. }
  164184. fts5StructurePromote(p, 0, pStruct);
  164185. }
  164186. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  164187. fts5IndexCrisismerge(p, &pStruct);
  164188. fts5StructureWrite(p, pStruct);
  164189. fts5StructureRelease(pStruct);
  164190. }
  164191. /*
  164192. ** Flush any data stored in the in-memory hash tables to the database.
  164193. */
  164194. static void fts5IndexFlush(Fts5Index *p){
  164195. /* Unless it is empty, flush the hash table to disk */
  164196. if( p->nPendingData ){
  164197. assert( p->pHash );
  164198. p->nPendingData = 0;
  164199. fts5FlushOneHash(p);
  164200. }
  164201. }
  164202. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  164203. Fts5Structure *pStruct;
  164204. Fts5Structure *pNew = 0;
  164205. int nSeg = 0;
  164206. assert( p->rc==SQLITE_OK );
  164207. fts5IndexFlush(p);
  164208. pStruct = fts5StructureRead(p);
  164209. if( pStruct ){
  164210. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  164211. nSeg = pStruct->nSegment;
  164212. if( nSeg>1 ){
  164213. int nByte = sizeof(Fts5Structure);
  164214. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  164215. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  164216. }
  164217. }
  164218. if( pNew ){
  164219. Fts5StructureLevel *pLvl;
  164220. int nByte = nSeg * sizeof(Fts5StructureSegment);
  164221. pNew->nLevel = pStruct->nLevel+1;
  164222. pNew->nRef = 1;
  164223. pNew->nWriteCounter = pStruct->nWriteCounter;
  164224. pLvl = &pNew->aLevel[pStruct->nLevel];
  164225. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  164226. if( pLvl->aSeg ){
  164227. int iLvl, iSeg;
  164228. int iSegOut = 0;
  164229. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  164230. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  164231. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  164232. iSegOut++;
  164233. }
  164234. }
  164235. pNew->nSegment = pLvl->nSeg = nSeg;
  164236. }else{
  164237. sqlite3_free(pNew);
  164238. pNew = 0;
  164239. }
  164240. }
  164241. if( pNew ){
  164242. int iLvl = pNew->nLevel-1;
  164243. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  164244. int nRem = FTS5_OPT_WORK_UNIT;
  164245. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  164246. }
  164247. fts5StructureWrite(p, pNew);
  164248. fts5StructureRelease(pNew);
  164249. }
  164250. fts5StructureRelease(pStruct);
  164251. return fts5IndexReturn(p);
  164252. }
  164253. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  164254. Fts5Structure *pStruct;
  164255. pStruct = fts5StructureRead(p);
  164256. if( pStruct && pStruct->nLevel ){
  164257. fts5IndexMerge(p, &pStruct, nMerge);
  164258. fts5StructureWrite(p, pStruct);
  164259. }
  164260. fts5StructureRelease(pStruct);
  164261. return fts5IndexReturn(p);
  164262. }
  164263. static void fts5PoslistCallback(
  164264. Fts5Index *p,
  164265. void *pContext,
  164266. const u8 *pChunk, int nChunk
  164267. ){
  164268. assert_nc( nChunk>=0 );
  164269. if( nChunk>0 ){
  164270. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  164271. }
  164272. }
  164273. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  164274. struct PoslistCallbackCtx {
  164275. Fts5Buffer *pBuf; /* Append to this buffer */
  164276. Fts5Colset *pColset; /* Restrict matches to this column */
  164277. int eState; /* See above */
  164278. };
  164279. /*
  164280. ** TODO: Make this more efficient!
  164281. */
  164282. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  164283. int i;
  164284. for(i=0; i<pColset->nCol; i++){
  164285. if( pColset->aiCol[i]==iCol ) return 1;
  164286. }
  164287. return 0;
  164288. }
  164289. static void fts5PoslistFilterCallback(
  164290. Fts5Index *p,
  164291. void *pContext,
  164292. const u8 *pChunk, int nChunk
  164293. ){
  164294. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  164295. assert_nc( nChunk>=0 );
  164296. if( nChunk>0 ){
  164297. /* Search through to find the first varint with value 1. This is the
  164298. ** start of the next columns hits. */
  164299. int i = 0;
  164300. int iStart = 0;
  164301. if( pCtx->eState==2 ){
  164302. int iCol;
  164303. fts5FastGetVarint32(pChunk, i, iCol);
  164304. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  164305. pCtx->eState = 1;
  164306. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  164307. }else{
  164308. pCtx->eState = 0;
  164309. }
  164310. }
  164311. do {
  164312. while( i<nChunk && pChunk[i]!=0x01 ){
  164313. while( pChunk[i] & 0x80 ) i++;
  164314. i++;
  164315. }
  164316. if( pCtx->eState ){
  164317. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  164318. }
  164319. if( i<nChunk ){
  164320. int iCol;
  164321. iStart = i;
  164322. i++;
  164323. if( i>=nChunk ){
  164324. pCtx->eState = 2;
  164325. }else{
  164326. fts5FastGetVarint32(pChunk, i, iCol);
  164327. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  164328. if( pCtx->eState ){
  164329. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  164330. iStart = i;
  164331. }
  164332. }
  164333. }
  164334. }while( i<nChunk );
  164335. }
  164336. }
  164337. /*
  164338. ** Iterator pIter currently points to a valid entry (not EOF). This
  164339. ** function appends the position list data for the current entry to
  164340. ** buffer pBuf. It does not make a copy of the position-list size
  164341. ** field.
  164342. */
  164343. static void fts5SegiterPoslist(
  164344. Fts5Index *p,
  164345. Fts5SegIter *pSeg,
  164346. Fts5Colset *pColset,
  164347. Fts5Buffer *pBuf
  164348. ){
  164349. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  164350. if( pColset==0 ){
  164351. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  164352. }else{
  164353. PoslistCallbackCtx sCtx;
  164354. sCtx.pBuf = pBuf;
  164355. sCtx.pColset = pColset;
  164356. sCtx.eState = pColset ? fts5IndexColsetTest(pColset, 0) : 1;
  164357. assert( sCtx.eState==0 || sCtx.eState==1 );
  164358. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  164359. }
  164360. }
  164361. }
  164362. /*
  164363. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  164364. ** the position list contains entries for column iCol, then (*pa) is set
  164365. ** to point to the sub-position-list for that column and the number of
  164366. ** bytes in it returned. Or, if the argument position list does not
  164367. ** contain any entries for column iCol, return 0.
  164368. */
  164369. static int fts5IndexExtractCol(
  164370. const u8 **pa, /* IN/OUT: Pointer to poslist */
  164371. int n, /* IN: Size of poslist in bytes */
  164372. int iCol /* Column to extract from poslist */
  164373. ){
  164374. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  164375. const u8 *p = *pa;
  164376. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  164377. u8 prev = 0;
  164378. while( iCol!=iCurrent ){
  164379. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  164380. ** not part of a varint */
  164381. while( (prev & 0x80) || *p!=0x01 ){
  164382. prev = *p++;
  164383. if( p==pEnd ) return 0;
  164384. }
  164385. *pa = p++;
  164386. p += fts5GetVarint32(p, iCurrent);
  164387. }
  164388. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  164389. ** not part of a varint */
  164390. assert( (prev & 0x80)==0 );
  164391. while( p<pEnd && ((prev & 0x80) || *p!=0x01) ){
  164392. prev = *p++;
  164393. }
  164394. return p - (*pa);
  164395. }
  164396. /*
  164397. ** Iterator pMulti currently points to a valid entry (not EOF). This
  164398. ** function appends the following to buffer pBuf:
  164399. **
  164400. ** * The varint iDelta, and
  164401. ** * the position list that currently points to, including the size field.
  164402. **
  164403. ** If argument pColset is NULL, then the position list is filtered according
  164404. ** to pColset before being appended to the buffer. If this means there are
  164405. ** no entries in the position list, nothing is appended to the buffer (not
  164406. ** even iDelta).
  164407. **
  164408. ** If an error occurs, an error code is left in p->rc.
  164409. */
  164410. static int fts5AppendPoslist(
  164411. Fts5Index *p,
  164412. i64 iDelta,
  164413. Fts5IndexIter *pMulti,
  164414. Fts5Colset *pColset,
  164415. Fts5Buffer *pBuf
  164416. ){
  164417. if( p->rc==SQLITE_OK ){
  164418. Fts5SegIter *pSeg = &pMulti->aSeg[ pMulti->aFirst[1].iFirst ];
  164419. assert( fts5MultiIterEof(p, pMulti)==0 );
  164420. assert( pSeg->nPos>0 );
  164421. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+9+9) ){
  164422. int iSv1;
  164423. int iSv2;
  164424. int iData;
  164425. /* Append iDelta */
  164426. iSv1 = pBuf->n;
  164427. fts5BufferSafeAppendVarint(pBuf, iDelta);
  164428. /* WRITEPOSLISTSIZE */
  164429. iSv2 = pBuf->n;
  164430. fts5BufferSafeAppendVarint(pBuf, pSeg->nPos*2);
  164431. iData = pBuf->n;
  164432. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf
  164433. && (pColset==0 || pColset->nCol==1)
  164434. ){
  164435. const u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  164436. int nPos;
  164437. if( pColset ){
  164438. nPos = fts5IndexExtractCol(&pPos, pSeg->nPos, pColset->aiCol[0]);
  164439. }else{
  164440. nPos = pSeg->nPos;
  164441. }
  164442. fts5BufferSafeAppendBlob(pBuf, pPos, nPos);
  164443. }else{
  164444. fts5SegiterPoslist(p, pSeg, pColset, pBuf);
  164445. }
  164446. if( pColset ){
  164447. int nActual = pBuf->n - iData;
  164448. if( nActual!=pSeg->nPos ){
  164449. if( nActual==0 ){
  164450. pBuf->n = iSv1;
  164451. return 1;
  164452. }else{
  164453. int nReq = sqlite3Fts5GetVarintLen((u32)(nActual*2));
  164454. while( iSv2<(iData-nReq) ){ pBuf->p[iSv2++] = 0x80; }
  164455. sqlite3Fts5PutVarint(&pBuf->p[iSv2], nActual*2);
  164456. }
  164457. }
  164458. }
  164459. }
  164460. }
  164461. return 0;
  164462. }
  164463. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  164464. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  164465. assert( pIter->aPoslist );
  164466. if( p>=pIter->aEof ){
  164467. pIter->aPoslist = 0;
  164468. }else{
  164469. i64 iDelta;
  164470. p += fts5GetVarint(p, (u64*)&iDelta);
  164471. pIter->iRowid += iDelta;
  164472. /* Read position list size */
  164473. if( p[0] & 0x80 ){
  164474. int nPos;
  164475. pIter->nSize = fts5GetVarint32(p, nPos);
  164476. pIter->nPoslist = (nPos>>1);
  164477. }else{
  164478. pIter->nPoslist = ((int)(p[0])) >> 1;
  164479. pIter->nSize = 1;
  164480. }
  164481. pIter->aPoslist = p;
  164482. }
  164483. }
  164484. static void fts5DoclistIterInit(
  164485. Fts5Buffer *pBuf,
  164486. Fts5DoclistIter *pIter
  164487. ){
  164488. memset(pIter, 0, sizeof(*pIter));
  164489. pIter->aPoslist = pBuf->p;
  164490. pIter->aEof = &pBuf->p[pBuf->n];
  164491. fts5DoclistIterNext(pIter);
  164492. }
  164493. #if 0
  164494. /*
  164495. ** Append a doclist to buffer pBuf.
  164496. **
  164497. ** This function assumes that space within the buffer has already been
  164498. ** allocated.
  164499. */
  164500. static void fts5MergeAppendDocid(
  164501. Fts5Buffer *pBuf, /* Buffer to write to */
  164502. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  164503. i64 iRowid /* Rowid to append */
  164504. ){
  164505. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  164506. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  164507. *piLastRowid = iRowid;
  164508. }
  164509. #endif
  164510. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  164511. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  164512. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  164513. (iLastRowid) = (iRowid); \
  164514. }
  164515. /*
  164516. ** Buffers p1 and p2 contain doclists. This function merges the content
  164517. ** of the two doclists together and sets buffer p1 to the result before
  164518. ** returning.
  164519. **
  164520. ** If an error occurs, an error code is left in p->rc. If an error has
  164521. ** already occurred, this function is a no-op.
  164522. */
  164523. static void fts5MergePrefixLists(
  164524. Fts5Index *p, /* FTS5 backend object */
  164525. Fts5Buffer *p1, /* First list to merge */
  164526. Fts5Buffer *p2 /* Second list to merge */
  164527. ){
  164528. if( p2->n ){
  164529. i64 iLastRowid = 0;
  164530. Fts5DoclistIter i1;
  164531. Fts5DoclistIter i2;
  164532. Fts5Buffer out;
  164533. Fts5Buffer tmp;
  164534. memset(&out, 0, sizeof(out));
  164535. memset(&tmp, 0, sizeof(tmp));
  164536. sqlite3Fts5BufferGrow(&p->rc, &out, p1->n + p2->n);
  164537. fts5DoclistIterInit(p1, &i1);
  164538. fts5DoclistIterInit(p2, &i2);
  164539. while( p->rc==SQLITE_OK && (i1.aPoslist!=0 || i2.aPoslist!=0) ){
  164540. if( i2.aPoslist==0 || (i1.aPoslist && i1.iRowid<i2.iRowid) ){
  164541. /* Copy entry from i1 */
  164542. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  164543. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  164544. fts5DoclistIterNext(&i1);
  164545. }
  164546. else if( i1.aPoslist==0 || i2.iRowid!=i1.iRowid ){
  164547. /* Copy entry from i2 */
  164548. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  164549. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  164550. fts5DoclistIterNext(&i2);
  164551. }
  164552. else{
  164553. i64 iPos1 = 0;
  164554. i64 iPos2 = 0;
  164555. int iOff1 = 0;
  164556. int iOff2 = 0;
  164557. u8 *a1 = &i1.aPoslist[i1.nSize];
  164558. u8 *a2 = &i2.aPoslist[i2.nSize];
  164559. Fts5PoslistWriter writer;
  164560. memset(&writer, 0, sizeof(writer));
  164561. /* Merge the two position lists. */
  164562. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  164563. fts5BufferZero(&tmp);
  164564. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  164565. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  164566. while( p->rc==SQLITE_OK && (iPos1>=0 || iPos2>=0) ){
  164567. i64 iNew;
  164568. if( iPos2<0 || (iPos1>=0 && iPos1<iPos2) ){
  164569. iNew = iPos1;
  164570. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  164571. }else{
  164572. iNew = iPos2;
  164573. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  164574. if( iPos1==iPos2 ){
  164575. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1,&iPos1);
  164576. }
  164577. }
  164578. p->rc = sqlite3Fts5PoslistWriterAppend(&tmp, &writer, iNew);
  164579. }
  164580. /* WRITEPOSLISTSIZE */
  164581. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  164582. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  164583. fts5DoclistIterNext(&i1);
  164584. fts5DoclistIterNext(&i2);
  164585. }
  164586. }
  164587. fts5BufferSet(&p->rc, p1, out.n, out.p);
  164588. fts5BufferFree(&tmp);
  164589. fts5BufferFree(&out);
  164590. }
  164591. }
  164592. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  164593. Fts5Buffer tmp = *p1;
  164594. *p1 = *p2;
  164595. *p2 = tmp;
  164596. }
  164597. static void fts5SetupPrefixIter(
  164598. Fts5Index *p, /* Index to read from */
  164599. int bDesc, /* True for "ORDER BY rowid DESC" */
  164600. const u8 *pToken, /* Buffer containing prefix to match */
  164601. int nToken, /* Size of buffer pToken in bytes */
  164602. Fts5Colset *pColset, /* Restrict matches to these columns */
  164603. Fts5IndexIter **ppIter /* OUT: New iterator */
  164604. ){
  164605. Fts5Structure *pStruct;
  164606. Fts5Buffer *aBuf;
  164607. const int nBuf = 32;
  164608. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  164609. pStruct = fts5StructureRead(p);
  164610. if( aBuf && pStruct ){
  164611. const int flags = FTS5INDEX_QUERY_SCAN;
  164612. int i;
  164613. i64 iLastRowid = 0;
  164614. Fts5IndexIter *p1 = 0; /* Iterator used to gather data from index */
  164615. Fts5Data *pData;
  164616. Fts5Buffer doclist;
  164617. memset(&doclist, 0, sizeof(doclist));
  164618. for(fts5MultiIterNew(p, pStruct, 1, flags, pToken, nToken, -1, 0, &p1);
  164619. fts5MultiIterEof(p, p1)==0;
  164620. fts5MultiIterNext(p, p1, 0, 0)
  164621. ){
  164622. i64 iRowid = fts5MultiIterRowid(p1);
  164623. int nTerm;
  164624. const u8 *pTerm = fts5MultiIterTerm(p1, &nTerm);
  164625. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  164626. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  164627. if( doclist.n>0 && iRowid<=iLastRowid ){
  164628. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  164629. assert( i<nBuf );
  164630. if( aBuf[i].n==0 ){
  164631. fts5BufferSwap(&doclist, &aBuf[i]);
  164632. fts5BufferZero(&doclist);
  164633. }else{
  164634. fts5MergePrefixLists(p, &doclist, &aBuf[i]);
  164635. fts5BufferZero(&aBuf[i]);
  164636. }
  164637. }
  164638. iLastRowid = 0;
  164639. }
  164640. if( !fts5AppendPoslist(p, iRowid-iLastRowid, p1, pColset, &doclist) ){
  164641. iLastRowid = iRowid;
  164642. }
  164643. }
  164644. for(i=0; i<nBuf; i++){
  164645. if( p->rc==SQLITE_OK ){
  164646. fts5MergePrefixLists(p, &doclist, &aBuf[i]);
  164647. }
  164648. fts5BufferFree(&aBuf[i]);
  164649. }
  164650. fts5MultiIterFree(p, p1);
  164651. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  164652. if( pData ){
  164653. pData->p = (u8*)&pData[1];
  164654. pData->nn = pData->szLeaf = doclist.n;
  164655. memcpy(pData->p, doclist.p, doclist.n);
  164656. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  164657. }
  164658. fts5BufferFree(&doclist);
  164659. }
  164660. fts5StructureRelease(pStruct);
  164661. sqlite3_free(aBuf);
  164662. }
  164663. /*
  164664. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  164665. ** to the document with rowid iRowid.
  164666. */
  164667. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  164668. assert( p->rc==SQLITE_OK );
  164669. /* Allocate the hash table if it has not already been allocated */
  164670. if( p->pHash==0 ){
  164671. p->rc = sqlite3Fts5HashNew(&p->pHash, &p->nPendingData);
  164672. }
  164673. /* Flush the hash table to disk if required */
  164674. if( iRowid<p->iWriteRowid
  164675. || (iRowid==p->iWriteRowid && p->bDelete==0)
  164676. || (p->nPendingData > p->nMaxPendingData)
  164677. ){
  164678. fts5IndexFlush(p);
  164679. }
  164680. p->iWriteRowid = iRowid;
  164681. p->bDelete = bDelete;
  164682. return fts5IndexReturn(p);
  164683. }
  164684. /*
  164685. ** Commit data to disk.
  164686. */
  164687. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
  164688. assert( p->rc==SQLITE_OK );
  164689. fts5IndexFlush(p);
  164690. if( bCommit ) fts5CloseReader(p);
  164691. return fts5IndexReturn(p);
  164692. }
  164693. /*
  164694. ** Discard any data stored in the in-memory hash tables. Do not write it
  164695. ** to the database. Additionally, assume that the contents of the %_data
  164696. ** table may have changed on disk. So any in-memory caches of %_data
  164697. ** records must be invalidated.
  164698. */
  164699. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  164700. fts5CloseReader(p);
  164701. fts5IndexDiscardData(p);
  164702. assert( p->rc==SQLITE_OK );
  164703. return SQLITE_OK;
  164704. }
  164705. /*
  164706. ** The %_data table is completely empty when this function is called. This
  164707. ** function populates it with the initial structure objects for each index,
  164708. ** and the initial version of the "averages" record (a zero-byte blob).
  164709. */
  164710. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  164711. Fts5Structure s;
  164712. memset(&s, 0, sizeof(Fts5Structure));
  164713. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  164714. fts5StructureWrite(p, &s);
  164715. return fts5IndexReturn(p);
  164716. }
  164717. /*
  164718. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  164719. ** and initialize the underlying %_data table.
  164720. **
  164721. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  164722. ** Otherwise, set *pp to NULL and return an SQLite error code.
  164723. */
  164724. static int sqlite3Fts5IndexOpen(
  164725. Fts5Config *pConfig,
  164726. int bCreate,
  164727. Fts5Index **pp,
  164728. char **pzErr
  164729. ){
  164730. int rc = SQLITE_OK;
  164731. Fts5Index *p; /* New object */
  164732. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  164733. if( rc==SQLITE_OK ){
  164734. p->pConfig = pConfig;
  164735. p->nWorkUnit = FTS5_WORK_UNIT;
  164736. p->nMaxPendingData = 1024*1024;
  164737. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  164738. if( p->zDataTbl && bCreate ){
  164739. rc = sqlite3Fts5CreateTable(
  164740. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  164741. );
  164742. if( rc==SQLITE_OK ){
  164743. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  164744. "segid, term, pgno, PRIMARY KEY(segid, term)",
  164745. 1, pzErr
  164746. );
  164747. }
  164748. if( rc==SQLITE_OK ){
  164749. rc = sqlite3Fts5IndexReinit(p);
  164750. }
  164751. }
  164752. }
  164753. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  164754. if( rc ){
  164755. sqlite3Fts5IndexClose(p);
  164756. *pp = 0;
  164757. }
  164758. return rc;
  164759. }
  164760. /*
  164761. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  164762. */
  164763. static int sqlite3Fts5IndexClose(Fts5Index *p){
  164764. int rc = SQLITE_OK;
  164765. if( p ){
  164766. assert( p->pReader==0 );
  164767. sqlite3_finalize(p->pWriter);
  164768. sqlite3_finalize(p->pDeleter);
  164769. sqlite3_finalize(p->pIdxWriter);
  164770. sqlite3_finalize(p->pIdxDeleter);
  164771. sqlite3_finalize(p->pIdxSelect);
  164772. sqlite3Fts5HashFree(p->pHash);
  164773. sqlite3_free(p->zDataTbl);
  164774. sqlite3_free(p);
  164775. }
  164776. return rc;
  164777. }
  164778. /*
  164779. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  164780. ** size. Return the number of bytes in the nChar character prefix of the
  164781. ** buffer, or 0 if there are less than nChar characters in total.
  164782. */
  164783. static int fts5IndexCharlenToBytelen(const char *p, int nByte, int nChar){
  164784. int n = 0;
  164785. int i;
  164786. for(i=0; i<nChar; i++){
  164787. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  164788. if( (unsigned char)p[n++]>=0xc0 ){
  164789. while( (p[n] & 0xc0)==0x80 ) n++;
  164790. }
  164791. }
  164792. return n;
  164793. }
  164794. /*
  164795. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  164796. ** unicode characters in the string.
  164797. */
  164798. static int fts5IndexCharlen(const char *pIn, int nIn){
  164799. int nChar = 0;
  164800. int i = 0;
  164801. while( i<nIn ){
  164802. if( (unsigned char)pIn[i++]>=0xc0 ){
  164803. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  164804. }
  164805. nChar++;
  164806. }
  164807. return nChar;
  164808. }
  164809. /*
  164810. ** Insert or remove data to or from the index. Each time a document is
  164811. ** added to or removed from the index, this function is called one or more
  164812. ** times.
  164813. **
  164814. ** For an insert, it must be called once for each token in the new document.
  164815. ** If the operation is a delete, it must be called (at least) once for each
  164816. ** unique token in the document with an iCol value less than zero. The iPos
  164817. ** argument is ignored for a delete.
  164818. */
  164819. static int sqlite3Fts5IndexWrite(
  164820. Fts5Index *p, /* Index to write to */
  164821. int iCol, /* Column token appears in (-ve -> delete) */
  164822. int iPos, /* Position of token within column */
  164823. const char *pToken, int nToken /* Token to add or remove to or from index */
  164824. ){
  164825. int i; /* Used to iterate through indexes */
  164826. int rc = SQLITE_OK; /* Return code */
  164827. Fts5Config *pConfig = p->pConfig;
  164828. assert( p->rc==SQLITE_OK );
  164829. assert( (iCol<0)==p->bDelete );
  164830. /* Add the entry to the main terms index. */
  164831. rc = sqlite3Fts5HashWrite(
  164832. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  164833. );
  164834. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  164835. int nByte = fts5IndexCharlenToBytelen(pToken, nToken, pConfig->aPrefix[i]);
  164836. if( nByte ){
  164837. rc = sqlite3Fts5HashWrite(p->pHash,
  164838. p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX+i+1, pToken, nByte
  164839. );
  164840. }
  164841. }
  164842. return rc;
  164843. }
  164844. /*
  164845. ** Open a new iterator to iterate though all rowid that match the
  164846. ** specified token or token prefix.
  164847. */
  164848. static int sqlite3Fts5IndexQuery(
  164849. Fts5Index *p, /* FTS index to query */
  164850. const char *pToken, int nToken, /* Token (or prefix) to query for */
  164851. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  164852. Fts5Colset *pColset, /* Match these columns only */
  164853. Fts5IndexIter **ppIter /* OUT: New iterator object */
  164854. ){
  164855. Fts5Config *pConfig = p->pConfig;
  164856. Fts5IndexIter *pRet = 0;
  164857. int iIdx = 0;
  164858. Fts5Buffer buf = {0, 0, 0};
  164859. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  164860. assert( (flags & FTS5INDEX_QUERY_SCAN)==0
  164861. || (flags & FTS5INDEX_QUERY_SCAN)==FTS5INDEX_QUERY_SCAN
  164862. );
  164863. if( sqlite3Fts5BufferGrow(&p->rc, &buf, nToken+1)==0 ){
  164864. memcpy(&buf.p[1], pToken, nToken);
  164865. #ifdef SQLITE_DEBUG
  164866. /* If the QUERY_TEST_NOIDX flag was specified, then this must be a
  164867. ** prefix-query. Instead of using a prefix-index (if one exists),
  164868. ** evaluate the prefix query using the main FTS index. This is used
  164869. ** for internal sanity checking by the integrity-check in debug
  164870. ** mode only. */
  164871. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  164872. assert( flags & FTS5INDEX_QUERY_PREFIX );
  164873. iIdx = 1+pConfig->nPrefix;
  164874. }else
  164875. #endif
  164876. if( flags & FTS5INDEX_QUERY_PREFIX ){
  164877. int nChar = fts5IndexCharlen(pToken, nToken);
  164878. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  164879. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  164880. }
  164881. }
  164882. if( iIdx<=pConfig->nPrefix ){
  164883. Fts5Structure *pStruct = fts5StructureRead(p);
  164884. buf.p[0] = FTS5_MAIN_PREFIX + iIdx;
  164885. if( pStruct ){
  164886. fts5MultiIterNew(p, pStruct, 1, flags, buf.p, nToken+1, -1, 0, &pRet);
  164887. fts5StructureRelease(pStruct);
  164888. }
  164889. }else{
  164890. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  164891. buf.p[0] = FTS5_MAIN_PREFIX;
  164892. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  164893. }
  164894. if( p->rc ){
  164895. sqlite3Fts5IterClose(pRet);
  164896. pRet = 0;
  164897. fts5CloseReader(p);
  164898. }
  164899. *ppIter = pRet;
  164900. sqlite3Fts5BufferFree(&buf);
  164901. }
  164902. return fts5IndexReturn(p);
  164903. }
  164904. /*
  164905. ** Return true if the iterator passed as the only argument is at EOF.
  164906. */
  164907. static int sqlite3Fts5IterEof(Fts5IndexIter *pIter){
  164908. assert( pIter->pIndex->rc==SQLITE_OK );
  164909. return pIter->bEof;
  164910. }
  164911. /*
  164912. ** Move to the next matching rowid.
  164913. */
  164914. static int sqlite3Fts5IterNext(Fts5IndexIter *pIter){
  164915. assert( pIter->pIndex->rc==SQLITE_OK );
  164916. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  164917. return fts5IndexReturn(pIter->pIndex);
  164918. }
  164919. /*
  164920. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  164921. */
  164922. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIter){
  164923. Fts5Index *p = pIter->pIndex;
  164924. assert( pIter->pIndex->rc==SQLITE_OK );
  164925. fts5MultiIterNext(p, pIter, 0, 0);
  164926. if( p->rc==SQLITE_OK ){
  164927. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  164928. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  164929. fts5DataRelease(pSeg->pLeaf);
  164930. pSeg->pLeaf = 0;
  164931. pIter->bEof = 1;
  164932. }
  164933. }
  164934. return fts5IndexReturn(pIter->pIndex);
  164935. }
  164936. /*
  164937. ** Move to the next matching rowid that occurs at or after iMatch. The
  164938. ** definition of "at or after" depends on whether this iterator iterates
  164939. ** in ascending or descending rowid order.
  164940. */
  164941. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIter, i64 iMatch){
  164942. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  164943. return fts5IndexReturn(pIter->pIndex);
  164944. }
  164945. /*
  164946. ** Return the current rowid.
  164947. */
  164948. static i64 sqlite3Fts5IterRowid(Fts5IndexIter *pIter){
  164949. return fts5MultiIterRowid(pIter);
  164950. }
  164951. /*
  164952. ** Return the current term.
  164953. */
  164954. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIter, int *pn){
  164955. int n;
  164956. const char *z = (const char*)fts5MultiIterTerm(pIter, &n);
  164957. *pn = n-1;
  164958. return &z[1];
  164959. }
  164960. static int fts5IndexExtractColset (
  164961. Fts5Colset *pColset, /* Colset to filter on */
  164962. const u8 *pPos, int nPos, /* Position list */
  164963. Fts5Buffer *pBuf /* Output buffer */
  164964. ){
  164965. int rc = SQLITE_OK;
  164966. int i;
  164967. fts5BufferZero(pBuf);
  164968. for(i=0; i<pColset->nCol; i++){
  164969. const u8 *pSub = pPos;
  164970. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  164971. if( nSub ){
  164972. fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
  164973. }
  164974. }
  164975. return rc;
  164976. }
  164977. /*
  164978. ** Return a pointer to a buffer containing a copy of the position list for
  164979. ** the current entry. Output variable *pn is set to the size of the buffer
  164980. ** in bytes before returning.
  164981. **
  164982. ** The returned position list does not include the "number of bytes" varint
  164983. ** field that starts the position list on disk.
  164984. */
  164985. static int sqlite3Fts5IterPoslist(
  164986. Fts5IndexIter *pIter,
  164987. Fts5Colset *pColset, /* Column filter (or NULL) */
  164988. const u8 **pp, /* OUT: Pointer to position-list data */
  164989. int *pn, /* OUT: Size of position-list in bytes */
  164990. i64 *piRowid /* OUT: Current rowid */
  164991. ){
  164992. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  164993. assert( pIter->pIndex->rc==SQLITE_OK );
  164994. *piRowid = pSeg->iRowid;
  164995. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  164996. u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  164997. if( pColset==0 || pIter->bFiltered ){
  164998. *pn = pSeg->nPos;
  164999. *pp = pPos;
  165000. }else if( pColset->nCol==1 ){
  165001. *pp = pPos;
  165002. *pn = fts5IndexExtractCol(pp, pSeg->nPos, pColset->aiCol[0]);
  165003. }else{
  165004. fts5BufferZero(&pIter->poslist);
  165005. fts5IndexExtractColset(pColset, pPos, pSeg->nPos, &pIter->poslist);
  165006. *pp = pIter->poslist.p;
  165007. *pn = pIter->poslist.n;
  165008. }
  165009. }else{
  165010. fts5BufferZero(&pIter->poslist);
  165011. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  165012. *pp = pIter->poslist.p;
  165013. *pn = pIter->poslist.n;
  165014. }
  165015. return fts5IndexReturn(pIter->pIndex);
  165016. }
  165017. /*
  165018. ** This function is similar to sqlite3Fts5IterPoslist(), except that it
  165019. ** copies the position list into the buffer supplied as the second
  165020. ** argument.
  165021. */
  165022. static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf){
  165023. Fts5Index *p = pIter->pIndex;
  165024. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  165025. assert( p->rc==SQLITE_OK );
  165026. fts5BufferZero(pBuf);
  165027. fts5SegiterPoslist(p, pSeg, 0, pBuf);
  165028. return fts5IndexReturn(p);
  165029. }
  165030. /*
  165031. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  165032. */
  165033. static void sqlite3Fts5IterClose(Fts5IndexIter *pIter){
  165034. if( pIter ){
  165035. Fts5Index *pIndex = pIter->pIndex;
  165036. fts5MultiIterFree(pIter->pIndex, pIter);
  165037. fts5CloseReader(pIndex);
  165038. }
  165039. }
  165040. /*
  165041. ** Read and decode the "averages" record from the database.
  165042. **
  165043. ** Parameter anSize must point to an array of size nCol, where nCol is
  165044. ** the number of user defined columns in the FTS table.
  165045. */
  165046. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  165047. int nCol = p->pConfig->nCol;
  165048. Fts5Data *pData;
  165049. *pnRow = 0;
  165050. memset(anSize, 0, sizeof(i64) * nCol);
  165051. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  165052. if( p->rc==SQLITE_OK && pData->nn ){
  165053. int i = 0;
  165054. int iCol;
  165055. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  165056. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  165057. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  165058. }
  165059. }
  165060. fts5DataRelease(pData);
  165061. return fts5IndexReturn(p);
  165062. }
  165063. /*
  165064. ** Replace the current "averages" record with the contents of the buffer
  165065. ** supplied as the second argument.
  165066. */
  165067. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  165068. assert( p->rc==SQLITE_OK );
  165069. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  165070. return fts5IndexReturn(p);
  165071. }
  165072. /*
  165073. ** Return the total number of blocks this module has read from the %_data
  165074. ** table since it was created.
  165075. */
  165076. static int sqlite3Fts5IndexReads(Fts5Index *p){
  165077. return p->nRead;
  165078. }
  165079. /*
  165080. ** Set the 32-bit cookie value stored at the start of all structure
  165081. ** records to the value passed as the second argument.
  165082. **
  165083. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  165084. ** occurs.
  165085. */
  165086. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  165087. int rc; /* Return code */
  165088. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  165089. u8 aCookie[4]; /* Binary representation of iNew */
  165090. sqlite3_blob *pBlob = 0;
  165091. assert( p->rc==SQLITE_OK );
  165092. sqlite3Fts5Put32(aCookie, iNew);
  165093. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  165094. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  165095. );
  165096. if( rc==SQLITE_OK ){
  165097. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  165098. rc = sqlite3_blob_close(pBlob);
  165099. }
  165100. return rc;
  165101. }
  165102. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  165103. Fts5Structure *pStruct;
  165104. pStruct = fts5StructureRead(p);
  165105. fts5StructureRelease(pStruct);
  165106. return fts5IndexReturn(p);
  165107. }
  165108. /*************************************************************************
  165109. **************************************************************************
  165110. ** Below this point is the implementation of the integrity-check
  165111. ** functionality.
  165112. */
  165113. /*
  165114. ** Return a simple checksum value based on the arguments.
  165115. */
  165116. static u64 fts5IndexEntryCksum(
  165117. i64 iRowid,
  165118. int iCol,
  165119. int iPos,
  165120. int iIdx,
  165121. const char *pTerm,
  165122. int nTerm
  165123. ){
  165124. int i;
  165125. u64 ret = iRowid;
  165126. ret += (ret<<3) + iCol;
  165127. ret += (ret<<3) + iPos;
  165128. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  165129. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  165130. return ret;
  165131. }
  165132. #ifdef SQLITE_DEBUG
  165133. /*
  165134. ** This function is purely an internal test. It does not contribute to
  165135. ** FTS functionality, or even the integrity-check, in any way.
  165136. **
  165137. ** Instead, it tests that the same set of pgno/rowid combinations are
  165138. ** visited regardless of whether the doclist-index identified by parameters
  165139. ** iSegid/iLeaf is iterated in forwards or reverse order.
  165140. */
  165141. static void fts5TestDlidxReverse(
  165142. Fts5Index *p,
  165143. int iSegid, /* Segment id to load from */
  165144. int iLeaf /* Load doclist-index for this leaf */
  165145. ){
  165146. Fts5DlidxIter *pDlidx = 0;
  165147. u64 cksum1 = 13;
  165148. u64 cksum2 = 13;
  165149. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  165150. fts5DlidxIterEof(p, pDlidx)==0;
  165151. fts5DlidxIterNext(p, pDlidx)
  165152. ){
  165153. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  165154. int pgno = fts5DlidxIterPgno(pDlidx);
  165155. assert( pgno>iLeaf );
  165156. cksum1 += iRowid + ((i64)pgno<<32);
  165157. }
  165158. fts5DlidxIterFree(pDlidx);
  165159. pDlidx = 0;
  165160. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  165161. fts5DlidxIterEof(p, pDlidx)==0;
  165162. fts5DlidxIterPrev(p, pDlidx)
  165163. ){
  165164. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  165165. int pgno = fts5DlidxIterPgno(pDlidx);
  165166. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  165167. cksum2 += iRowid + ((i64)pgno<<32);
  165168. }
  165169. fts5DlidxIterFree(pDlidx);
  165170. pDlidx = 0;
  165171. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  165172. }
  165173. static int fts5QueryCksum(
  165174. Fts5Index *p, /* Fts5 index object */
  165175. int iIdx,
  165176. const char *z, /* Index key to query for */
  165177. int n, /* Size of index key in bytes */
  165178. int flags, /* Flags for Fts5IndexQuery */
  165179. u64 *pCksum /* IN/OUT: Checksum value */
  165180. ){
  165181. u64 cksum = *pCksum;
  165182. Fts5IndexIter *pIdxIter = 0;
  165183. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIdxIter);
  165184. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIdxIter) ){
  165185. i64 dummy;
  165186. const u8 *pPos;
  165187. int nPos;
  165188. i64 rowid = sqlite3Fts5IterRowid(pIdxIter);
  165189. rc = sqlite3Fts5IterPoslist(pIdxIter, 0, &pPos, &nPos, &dummy);
  165190. if( rc==SQLITE_OK ){
  165191. Fts5PoslistReader sReader;
  165192. for(sqlite3Fts5PoslistReaderInit(pPos, nPos, &sReader);
  165193. sReader.bEof==0;
  165194. sqlite3Fts5PoslistReaderNext(&sReader)
  165195. ){
  165196. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  165197. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  165198. cksum ^= fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  165199. }
  165200. rc = sqlite3Fts5IterNext(pIdxIter);
  165201. }
  165202. }
  165203. sqlite3Fts5IterClose(pIdxIter);
  165204. *pCksum = cksum;
  165205. return rc;
  165206. }
  165207. /*
  165208. ** This function is also purely an internal test. It does not contribute to
  165209. ** FTS functionality, or even the integrity-check, in any way.
  165210. */
  165211. static void fts5TestTerm(
  165212. Fts5Index *p,
  165213. Fts5Buffer *pPrev, /* Previous term */
  165214. const char *z, int n, /* Possibly new term to test */
  165215. u64 expected,
  165216. u64 *pCksum
  165217. ){
  165218. int rc = p->rc;
  165219. if( pPrev->n==0 ){
  165220. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  165221. }else
  165222. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  165223. u64 cksum3 = *pCksum;
  165224. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  165225. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  165226. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  165227. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  165228. u64 ck1 = 0;
  165229. u64 ck2 = 0;
  165230. /* Check that the results returned for ASC and DESC queries are
  165231. ** the same. If not, call this corruption. */
  165232. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  165233. if( rc==SQLITE_OK ){
  165234. int f = flags|FTS5INDEX_QUERY_DESC;
  165235. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  165236. }
  165237. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  165238. /* If this is a prefix query, check that the results returned if the
  165239. ** the index is disabled are the same. In both ASC and DESC order.
  165240. **
  165241. ** This check may only be performed if the hash table is empty. This
  165242. ** is because the hash table only supports a single scan query at
  165243. ** a time, and the multi-iter loop from which this function is called
  165244. ** is already performing such a scan. */
  165245. if( p->nPendingData==0 ){
  165246. if( iIdx>0 && rc==SQLITE_OK ){
  165247. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  165248. ck2 = 0;
  165249. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  165250. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  165251. }
  165252. if( iIdx>0 && rc==SQLITE_OK ){
  165253. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  165254. ck2 = 0;
  165255. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  165256. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  165257. }
  165258. }
  165259. cksum3 ^= ck1;
  165260. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  165261. if( rc==SQLITE_OK && cksum3!=expected ){
  165262. rc = FTS5_CORRUPT;
  165263. }
  165264. *pCksum = cksum3;
  165265. }
  165266. p->rc = rc;
  165267. }
  165268. #else
  165269. # define fts5TestDlidxReverse(x,y,z)
  165270. # define fts5TestTerm(u,v,w,x,y,z)
  165271. #endif
  165272. /*
  165273. ** Check that:
  165274. **
  165275. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  165276. ** contain zero terms.
  165277. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  165278. ** contain zero rowids.
  165279. */
  165280. static void fts5IndexIntegrityCheckEmpty(
  165281. Fts5Index *p,
  165282. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  165283. int iFirst,
  165284. int iNoRowid,
  165285. int iLast
  165286. ){
  165287. int i;
  165288. /* Now check that the iter.nEmpty leaves following the current leaf
  165289. ** (a) exist and (b) contain no terms. */
  165290. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  165291. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  165292. if( pLeaf ){
  165293. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  165294. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  165295. }
  165296. fts5DataRelease(pLeaf);
  165297. }
  165298. }
  165299. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  165300. int iTermOff = 0;
  165301. int ii;
  165302. Fts5Buffer buf1 = {0,0,0};
  165303. Fts5Buffer buf2 = {0,0,0};
  165304. ii = pLeaf->szLeaf;
  165305. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  165306. int res;
  165307. int iOff;
  165308. int nIncr;
  165309. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  165310. iTermOff += nIncr;
  165311. iOff = iTermOff;
  165312. if( iOff>=pLeaf->szLeaf ){
  165313. p->rc = FTS5_CORRUPT;
  165314. }else if( iTermOff==nIncr ){
  165315. int nByte;
  165316. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  165317. if( (iOff+nByte)>pLeaf->szLeaf ){
  165318. p->rc = FTS5_CORRUPT;
  165319. }else{
  165320. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  165321. }
  165322. }else{
  165323. int nKeep, nByte;
  165324. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  165325. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  165326. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  165327. p->rc = FTS5_CORRUPT;
  165328. }else{
  165329. buf1.n = nKeep;
  165330. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  165331. }
  165332. if( p->rc==SQLITE_OK ){
  165333. res = fts5BufferCompare(&buf1, &buf2);
  165334. if( res<=0 ) p->rc = FTS5_CORRUPT;
  165335. }
  165336. }
  165337. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  165338. }
  165339. fts5BufferFree(&buf1);
  165340. fts5BufferFree(&buf2);
  165341. }
  165342. static void fts5IndexIntegrityCheckSegment(
  165343. Fts5Index *p, /* FTS5 backend object */
  165344. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  165345. ){
  165346. Fts5Config *pConfig = p->pConfig;
  165347. sqlite3_stmt *pStmt = 0;
  165348. int rc2;
  165349. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  165350. int iDlidxPrevLeaf = pSeg->pgnoLast;
  165351. if( pSeg->pgnoFirst==0 ) return;
  165352. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  165353. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  165354. pConfig->zDb, pConfig->zName, pSeg->iSegid
  165355. ));
  165356. /* Iterate through the b-tree hierarchy. */
  165357. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  165358. i64 iRow; /* Rowid for this leaf */
  165359. Fts5Data *pLeaf; /* Data for this leaf */
  165360. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  165361. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  165362. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  165363. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  165364. /* If the leaf in question has already been trimmed from the segment,
  165365. ** ignore this b-tree entry. Otherwise, load it into memory. */
  165366. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  165367. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  165368. pLeaf = fts5DataRead(p, iRow);
  165369. if( pLeaf==0 ) break;
  165370. /* Check that the leaf contains at least one term, and that it is equal
  165371. ** to or larger than the split-key in zIdxTerm. Also check that if there
  165372. ** is also a rowid pointer within the leaf page header, it points to a
  165373. ** location before the term. */
  165374. if( pLeaf->nn<=pLeaf->szLeaf ){
  165375. p->rc = FTS5_CORRUPT;
  165376. }else{
  165377. int iOff; /* Offset of first term on leaf */
  165378. int iRowidOff; /* Offset of first rowid on leaf */
  165379. int nTerm; /* Size of term on leaf in bytes */
  165380. int res; /* Comparison of term and split-key */
  165381. iOff = fts5LeafFirstTermOff(pLeaf);
  165382. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  165383. if( iRowidOff>=iOff ){
  165384. p->rc = FTS5_CORRUPT;
  165385. }else{
  165386. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  165387. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  165388. if( res==0 ) res = nTerm - nIdxTerm;
  165389. if( res<0 ) p->rc = FTS5_CORRUPT;
  165390. }
  165391. fts5IntegrityCheckPgidx(p, pLeaf);
  165392. }
  165393. fts5DataRelease(pLeaf);
  165394. if( p->rc ) break;
  165395. /* Now check that the iter.nEmpty leaves following the current leaf
  165396. ** (a) exist and (b) contain no terms. */
  165397. fts5IndexIntegrityCheckEmpty(
  165398. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  165399. );
  165400. if( p->rc ) break;
  165401. /* If there is a doclist-index, check that it looks right. */
  165402. if( bIdxDlidx ){
  165403. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  165404. int iPrevLeaf = iIdxLeaf;
  165405. int iSegid = pSeg->iSegid;
  165406. int iPg = 0;
  165407. i64 iKey;
  165408. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  165409. fts5DlidxIterEof(p, pDlidx)==0;
  165410. fts5DlidxIterNext(p, pDlidx)
  165411. ){
  165412. /* Check any rowid-less pages that occur before the current leaf. */
  165413. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  165414. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  165415. pLeaf = fts5DataRead(p, iKey);
  165416. if( pLeaf ){
  165417. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  165418. fts5DataRelease(pLeaf);
  165419. }
  165420. }
  165421. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  165422. /* Check that the leaf page indicated by the iterator really does
  165423. ** contain the rowid suggested by the same. */
  165424. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  165425. pLeaf = fts5DataRead(p, iKey);
  165426. if( pLeaf ){
  165427. i64 iRowid;
  165428. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  165429. ASSERT_SZLEAF_OK(pLeaf);
  165430. if( iRowidOff>=pLeaf->szLeaf ){
  165431. p->rc = FTS5_CORRUPT;
  165432. }else{
  165433. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  165434. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  165435. }
  165436. fts5DataRelease(pLeaf);
  165437. }
  165438. }
  165439. iDlidxPrevLeaf = iPg;
  165440. fts5DlidxIterFree(pDlidx);
  165441. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  165442. }else{
  165443. iDlidxPrevLeaf = pSeg->pgnoLast;
  165444. /* TODO: Check there is no doclist index */
  165445. }
  165446. iIdxPrevLeaf = iIdxLeaf;
  165447. }
  165448. rc2 = sqlite3_finalize(pStmt);
  165449. if( p->rc==SQLITE_OK ) p->rc = rc2;
  165450. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  165451. #if 0
  165452. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  165453. p->rc = FTS5_CORRUPT;
  165454. }
  165455. #endif
  165456. }
  165457. /*
  165458. ** Run internal checks to ensure that the FTS index (a) is internally
  165459. ** consistent and (b) contains entries for which the XOR of the checksums
  165460. ** as calculated by fts5IndexEntryCksum() is cksum.
  165461. **
  165462. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  165463. ** checksum does not match. Return SQLITE_OK if all checks pass without
  165464. ** error, or some other SQLite error code if another error (e.g. OOM)
  165465. ** occurs.
  165466. */
  165467. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  165468. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  165469. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  165470. Fts5IndexIter *pIter; /* Used to iterate through entire index */
  165471. Fts5Structure *pStruct; /* Index structure */
  165472. /* Used by extra internal tests only run if NDEBUG is not defined */
  165473. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  165474. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  165475. /* Load the FTS index structure */
  165476. pStruct = fts5StructureRead(p);
  165477. /* Check that the internal nodes of each segment match the leaves */
  165478. if( pStruct ){
  165479. int iLvl, iSeg;
  165480. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  165481. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  165482. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  165483. fts5IndexIntegrityCheckSegment(p, pSeg);
  165484. }
  165485. }
  165486. }
  165487. /* The cksum argument passed to this function is a checksum calculated
  165488. ** based on all expected entries in the FTS index (including prefix index
  165489. ** entries). This block checks that a checksum calculated based on the
  165490. ** actual contents of FTS index is identical.
  165491. **
  165492. ** Two versions of the same checksum are calculated. The first (stack
  165493. ** variable cksum2) based on entries extracted from the full-text index
  165494. ** while doing a linear scan of each individual index in turn.
  165495. **
  165496. ** As each term visited by the linear scans, a separate query for the
  165497. ** same term is performed. cksum3 is calculated based on the entries
  165498. ** extracted by these queries.
  165499. */
  165500. for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, -1, 0, &pIter);
  165501. fts5MultiIterEof(p, pIter)==0;
  165502. fts5MultiIterNext(p, pIter, 0, 0)
  165503. ){
  165504. int n; /* Size of term in bytes */
  165505. i64 iPos = 0; /* Position read from poslist */
  165506. int iOff = 0; /* Offset within poslist */
  165507. i64 iRowid = fts5MultiIterRowid(pIter);
  165508. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  165509. /* If this is a new term, query for it. Update cksum3 with the results. */
  165510. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  165511. poslist.n = 0;
  165512. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst] , 0, &poslist);
  165513. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  165514. int iCol = FTS5_POS2COLUMN(iPos);
  165515. int iTokOff = FTS5_POS2OFFSET(iPos);
  165516. cksum2 ^= fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  165517. }
  165518. }
  165519. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  165520. fts5MultiIterFree(p, pIter);
  165521. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  165522. fts5StructureRelease(pStruct);
  165523. fts5BufferFree(&term);
  165524. fts5BufferFree(&poslist);
  165525. return fts5IndexReturn(p);
  165526. }
  165527. /*
  165528. ** Calculate and return a checksum that is the XOR of the index entry
  165529. ** checksum of all entries that would be generated by the token specified
  165530. ** by the final 5 arguments.
  165531. */
  165532. static u64 sqlite3Fts5IndexCksum(
  165533. Fts5Config *pConfig, /* Configuration object */
  165534. i64 iRowid, /* Document term appears in */
  165535. int iCol, /* Column term appears in */
  165536. int iPos, /* Position term appears in */
  165537. const char *pTerm, int nTerm /* Term at iPos */
  165538. ){
  165539. u64 ret = 0; /* Return value */
  165540. int iIdx; /* For iterating through indexes */
  165541. ret = fts5IndexEntryCksum(iRowid, iCol, iPos, 0, pTerm, nTerm);
  165542. for(iIdx=0; iIdx<pConfig->nPrefix; iIdx++){
  165543. int nByte = fts5IndexCharlenToBytelen(pTerm, nTerm, pConfig->aPrefix[iIdx]);
  165544. if( nByte ){
  165545. ret ^= fts5IndexEntryCksum(iRowid, iCol, iPos, iIdx+1, pTerm, nByte);
  165546. }
  165547. }
  165548. return ret;
  165549. }
  165550. /*************************************************************************
  165551. **************************************************************************
  165552. ** Below this point is the implementation of the fts5_decode() scalar
  165553. ** function only.
  165554. */
  165555. /*
  165556. ** Decode a segment-data rowid from the %_data table. This function is
  165557. ** the opposite of macro FTS5_SEGMENT_ROWID().
  165558. */
  165559. static void fts5DecodeRowid(
  165560. i64 iRowid, /* Rowid from %_data table */
  165561. int *piSegid, /* OUT: Segment id */
  165562. int *pbDlidx, /* OUT: Dlidx flag */
  165563. int *piHeight, /* OUT: Height */
  165564. int *piPgno /* OUT: Page number */
  165565. ){
  165566. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  165567. iRowid >>= FTS5_DATA_PAGE_B;
  165568. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  165569. iRowid >>= FTS5_DATA_HEIGHT_B;
  165570. *pbDlidx = (int)(iRowid & 0x0001);
  165571. iRowid >>= FTS5_DATA_DLI_B;
  165572. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  165573. }
  165574. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  165575. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  165576. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  165577. if( iSegid==0 ){
  165578. if( iKey==FTS5_AVERAGES_ROWID ){
  165579. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  165580. }else{
  165581. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  165582. }
  165583. }
  165584. else{
  165585. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  165586. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  165587. );
  165588. }
  165589. }
  165590. static void fts5DebugStructure(
  165591. int *pRc, /* IN/OUT: error code */
  165592. Fts5Buffer *pBuf,
  165593. Fts5Structure *p
  165594. ){
  165595. int iLvl, iSeg; /* Iterate through levels, segments */
  165596. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  165597. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  165598. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  165599. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  165600. );
  165601. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  165602. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  165603. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  165604. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  165605. );
  165606. }
  165607. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  165608. }
  165609. }
  165610. /*
  165611. ** This is part of the fts5_decode() debugging aid.
  165612. **
  165613. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  165614. ** function appends a human-readable representation of the same object
  165615. ** to the buffer passed as the second argument.
  165616. */
  165617. static void fts5DecodeStructure(
  165618. int *pRc, /* IN/OUT: error code */
  165619. Fts5Buffer *pBuf,
  165620. const u8 *pBlob, int nBlob
  165621. ){
  165622. int rc; /* Return code */
  165623. Fts5Structure *p = 0; /* Decoded structure object */
  165624. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  165625. if( rc!=SQLITE_OK ){
  165626. *pRc = rc;
  165627. return;
  165628. }
  165629. fts5DebugStructure(pRc, pBuf, p);
  165630. fts5StructureRelease(p);
  165631. }
  165632. /*
  165633. ** This is part of the fts5_decode() debugging aid.
  165634. **
  165635. ** Arguments pBlob/nBlob contain an "averages" record. This function
  165636. ** appends a human-readable representation of record to the buffer passed
  165637. ** as the second argument.
  165638. */
  165639. static void fts5DecodeAverages(
  165640. int *pRc, /* IN/OUT: error code */
  165641. Fts5Buffer *pBuf,
  165642. const u8 *pBlob, int nBlob
  165643. ){
  165644. int i = 0;
  165645. const char *zSpace = "";
  165646. while( i<nBlob ){
  165647. u64 iVal;
  165648. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  165649. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  165650. zSpace = " ";
  165651. }
  165652. }
  165653. /*
  165654. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  165655. ** each varint and append its string representation to buffer pBuf. Return
  165656. ** after either the input buffer is exhausted or a 0 value is read.
  165657. **
  165658. ** The return value is the number of bytes read from the input buffer.
  165659. */
  165660. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  165661. int iOff = 0;
  165662. while( iOff<n ){
  165663. int iVal;
  165664. iOff += fts5GetVarint32(&a[iOff], iVal);
  165665. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  165666. }
  165667. return iOff;
  165668. }
  165669. /*
  165670. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  165671. ** may or may not finish within the buffer. This function appends a text
  165672. ** representation of the part of the doclist that is present to buffer
  165673. ** pBuf.
  165674. **
  165675. ** The return value is the number of bytes read from the input buffer.
  165676. */
  165677. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  165678. i64 iDocid = 0;
  165679. int iOff = 0;
  165680. if( n>0 ){
  165681. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  165682. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  165683. }
  165684. while( iOff<n ){
  165685. int nPos;
  165686. int bDummy;
  165687. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
  165688. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  165689. if( iOff<n ){
  165690. i64 iDelta;
  165691. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  165692. iDocid += iDelta;
  165693. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  165694. }
  165695. }
  165696. return iOff;
  165697. }
  165698. /*
  165699. ** The implementation of user-defined scalar function fts5_decode().
  165700. */
  165701. static void fts5DecodeFunction(
  165702. sqlite3_context *pCtx, /* Function call context */
  165703. int nArg, /* Number of args (always 2) */
  165704. sqlite3_value **apVal /* Function arguments */
  165705. ){
  165706. i64 iRowid; /* Rowid for record being decoded */
  165707. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  165708. const u8 *aBlob; int n; /* Record to decode */
  165709. u8 *a = 0;
  165710. Fts5Buffer s; /* Build up text to return here */
  165711. int rc = SQLITE_OK; /* Return code */
  165712. int nSpace = 0;
  165713. assert( nArg==2 );
  165714. memset(&s, 0, sizeof(Fts5Buffer));
  165715. iRowid = sqlite3_value_int64(apVal[0]);
  165716. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  165717. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  165718. ** buffer overreads even if the record is corrupt. */
  165719. n = sqlite3_value_bytes(apVal[1]);
  165720. aBlob = sqlite3_value_blob(apVal[1]);
  165721. nSpace = n + FTS5_DATA_ZERO_PADDING;
  165722. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  165723. if( a==0 ) goto decode_out;
  165724. memcpy(a, aBlob, n);
  165725. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  165726. fts5DebugRowid(&rc, &s, iRowid);
  165727. if( bDlidx ){
  165728. Fts5Data dlidx;
  165729. Fts5DlidxLvl lvl;
  165730. dlidx.p = a;
  165731. dlidx.nn = n;
  165732. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  165733. lvl.pData = &dlidx;
  165734. lvl.iLeafPgno = iPgno;
  165735. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  165736. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  165737. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  165738. );
  165739. }
  165740. }else if( iSegid==0 ){
  165741. if( iRowid==FTS5_AVERAGES_ROWID ){
  165742. fts5DecodeAverages(&rc, &s, a, n);
  165743. }else{
  165744. fts5DecodeStructure(&rc, &s, a, n);
  165745. }
  165746. }else{
  165747. Fts5Buffer term; /* Current term read from page */
  165748. int szLeaf; /* Offset of pgidx in a[] */
  165749. int iPgidxOff;
  165750. int iPgidxPrev = 0; /* Previous value read from pgidx */
  165751. int iTermOff = 0;
  165752. int iRowidOff = 0;
  165753. int iOff;
  165754. int nDoclist;
  165755. memset(&term, 0, sizeof(Fts5Buffer));
  165756. if( n<4 ){
  165757. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  165758. goto decode_out;
  165759. }else{
  165760. iRowidOff = fts5GetU16(&a[0]);
  165761. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  165762. if( iPgidxOff<n ){
  165763. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  165764. }
  165765. }
  165766. /* Decode the position list tail at the start of the page */
  165767. if( iRowidOff!=0 ){
  165768. iOff = iRowidOff;
  165769. }else if( iTermOff!=0 ){
  165770. iOff = iTermOff;
  165771. }else{
  165772. iOff = szLeaf;
  165773. }
  165774. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  165775. /* Decode any more doclist data that appears on the page before the
  165776. ** first term. */
  165777. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  165778. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  165779. while( iPgidxOff<n ){
  165780. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  165781. int nByte; /* Bytes of data */
  165782. int iEnd;
  165783. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  165784. iPgidxPrev += nByte;
  165785. iOff = iPgidxPrev;
  165786. if( iPgidxOff<n ){
  165787. fts5GetVarint32(&a[iPgidxOff], nByte);
  165788. iEnd = iPgidxPrev + nByte;
  165789. }else{
  165790. iEnd = szLeaf;
  165791. }
  165792. if( bFirst==0 ){
  165793. iOff += fts5GetVarint32(&a[iOff], nByte);
  165794. term.n = nByte;
  165795. }
  165796. iOff += fts5GetVarint32(&a[iOff], nByte);
  165797. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  165798. iOff += nByte;
  165799. sqlite3Fts5BufferAppendPrintf(
  165800. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  165801. );
  165802. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  165803. }
  165804. fts5BufferFree(&term);
  165805. }
  165806. decode_out:
  165807. sqlite3_free(a);
  165808. if( rc==SQLITE_OK ){
  165809. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  165810. }else{
  165811. sqlite3_result_error_code(pCtx, rc);
  165812. }
  165813. fts5BufferFree(&s);
  165814. }
  165815. /*
  165816. ** The implementation of user-defined scalar function fts5_rowid().
  165817. */
  165818. static void fts5RowidFunction(
  165819. sqlite3_context *pCtx, /* Function call context */
  165820. int nArg, /* Number of args (always 2) */
  165821. sqlite3_value **apVal /* Function arguments */
  165822. ){
  165823. const char *zArg;
  165824. if( nArg==0 ){
  165825. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  165826. }else{
  165827. zArg = (const char*)sqlite3_value_text(apVal[0]);
  165828. if( 0==sqlite3_stricmp(zArg, "segment") ){
  165829. i64 iRowid;
  165830. int segid, pgno;
  165831. if( nArg!=3 ){
  165832. sqlite3_result_error(pCtx,
  165833. "should be: fts5_rowid('segment', segid, pgno))", -1
  165834. );
  165835. }else{
  165836. segid = sqlite3_value_int(apVal[1]);
  165837. pgno = sqlite3_value_int(apVal[2]);
  165838. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  165839. sqlite3_result_int64(pCtx, iRowid);
  165840. }
  165841. }else{
  165842. sqlite3_result_error(pCtx,
  165843. "first arg to fts5_rowid() must be 'segment'" , -1
  165844. );
  165845. }
  165846. }
  165847. }
  165848. /*
  165849. ** This is called as part of registering the FTS5 module with database
  165850. ** connection db. It registers several user-defined scalar functions useful
  165851. ** with FTS5.
  165852. **
  165853. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  165854. ** SQLite error code is returned instead.
  165855. */
  165856. static int sqlite3Fts5IndexInit(sqlite3 *db){
  165857. int rc = sqlite3_create_function(
  165858. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  165859. );
  165860. if( rc==SQLITE_OK ){
  165861. rc = sqlite3_create_function(
  165862. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  165863. );
  165864. }
  165865. return rc;
  165866. }
  165867. /*
  165868. ** 2014 Jun 09
  165869. **
  165870. ** The author disclaims copyright to this source code. In place of
  165871. ** a legal notice, here is a blessing:
  165872. **
  165873. ** May you do good and not evil.
  165874. ** May you find forgiveness for yourself and forgive others.
  165875. ** May you share freely, never taking more than you give.
  165876. **
  165877. ******************************************************************************
  165878. **
  165879. ** This is an SQLite module implementing full-text search.
  165880. */
  165881. /*
  165882. ** This variable is set to false when running tests for which the on disk
  165883. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  165884. ** assert() conditions in the fts5 code are activated - conditions that are
  165885. ** only true if it is guaranteed that the fts5 database is not corrupt.
  165886. */
  165887. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  165888. typedef struct Fts5Auxdata Fts5Auxdata;
  165889. typedef struct Fts5Auxiliary Fts5Auxiliary;
  165890. typedef struct Fts5Cursor Fts5Cursor;
  165891. typedef struct Fts5Sorter Fts5Sorter;
  165892. typedef struct Fts5Table Fts5Table;
  165893. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  165894. /*
  165895. ** NOTES ON TRANSACTIONS:
  165896. **
  165897. ** SQLite invokes the following virtual table methods as transactions are
  165898. ** opened and closed by the user:
  165899. **
  165900. ** xBegin(): Start of a new transaction.
  165901. ** xSync(): Initial part of two-phase commit.
  165902. ** xCommit(): Final part of two-phase commit.
  165903. ** xRollback(): Rollback the transaction.
  165904. **
  165905. ** Anything that is required as part of a commit that may fail is performed
  165906. ** in the xSync() callback. Current versions of SQLite ignore any errors
  165907. ** returned by xCommit().
  165908. **
  165909. ** And as sub-transactions are opened/closed:
  165910. **
  165911. ** xSavepoint(int S): Open savepoint S.
  165912. ** xRelease(int S): Commit and close savepoint S.
  165913. ** xRollbackTo(int S): Rollback to start of savepoint S.
  165914. **
  165915. ** During a write-transaction the fts5_index.c module may cache some data
  165916. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  165917. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  165918. ** is called.
  165919. **
  165920. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  165921. ** structure is used to record the current transaction state. This information
  165922. ** is not required, but it is used in the assert() statements executed by
  165923. ** function fts5CheckTransactionState() (see below).
  165924. */
  165925. struct Fts5TransactionState {
  165926. int eState; /* 0==closed, 1==open, 2==synced */
  165927. int iSavepoint; /* Number of open savepoints (0 -> none) */
  165928. };
  165929. /*
  165930. ** A single object of this type is allocated when the FTS5 module is
  165931. ** registered with a database handle. It is used to store pointers to
  165932. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  165933. */
  165934. struct Fts5Global {
  165935. fts5_api api; /* User visible part of object (see fts5.h) */
  165936. sqlite3 *db; /* Associated database connection */
  165937. i64 iNextId; /* Used to allocate unique cursor ids */
  165938. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  165939. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  165940. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  165941. Fts5Cursor *pCsr; /* First in list of all open cursors */
  165942. };
  165943. /*
  165944. ** Each auxiliary function registered with the FTS5 module is represented
  165945. ** by an object of the following type. All such objects are stored as part
  165946. ** of the Fts5Global.pAux list.
  165947. */
  165948. struct Fts5Auxiliary {
  165949. Fts5Global *pGlobal; /* Global context for this function */
  165950. char *zFunc; /* Function name (nul-terminated) */
  165951. void *pUserData; /* User-data pointer */
  165952. fts5_extension_function xFunc; /* Callback function */
  165953. void (*xDestroy)(void*); /* Destructor function */
  165954. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  165955. };
  165956. /*
  165957. ** Each tokenizer module registered with the FTS5 module is represented
  165958. ** by an object of the following type. All such objects are stored as part
  165959. ** of the Fts5Global.pTok list.
  165960. */
  165961. struct Fts5TokenizerModule {
  165962. char *zName; /* Name of tokenizer */
  165963. void *pUserData; /* User pointer passed to xCreate() */
  165964. fts5_tokenizer x; /* Tokenizer functions */
  165965. void (*xDestroy)(void*); /* Destructor function */
  165966. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  165967. };
  165968. /*
  165969. ** Virtual-table object.
  165970. */
  165971. struct Fts5Table {
  165972. sqlite3_vtab base; /* Base class used by SQLite core */
  165973. Fts5Config *pConfig; /* Virtual table configuration */
  165974. Fts5Index *pIndex; /* Full-text index */
  165975. Fts5Storage *pStorage; /* Document store */
  165976. Fts5Global *pGlobal; /* Global (connection wide) data */
  165977. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  165978. #ifdef SQLITE_DEBUG
  165979. struct Fts5TransactionState ts;
  165980. #endif
  165981. };
  165982. struct Fts5MatchPhrase {
  165983. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  165984. int nTerm; /* Size of phrase in terms */
  165985. };
  165986. /*
  165987. ** pStmt:
  165988. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  165989. **
  165990. ** aIdx[]:
  165991. ** There is one entry in the aIdx[] array for each phrase in the query,
  165992. ** the value of which is the offset within aPoslist[] following the last
  165993. ** byte of the position list for the corresponding phrase.
  165994. */
  165995. struct Fts5Sorter {
  165996. sqlite3_stmt *pStmt;
  165997. i64 iRowid; /* Current rowid */
  165998. const u8 *aPoslist; /* Position lists for current row */
  165999. int nIdx; /* Number of entries in aIdx[] */
  166000. int aIdx[1]; /* Offsets into aPoslist for current row */
  166001. };
  166002. /*
  166003. ** Virtual-table cursor object.
  166004. **
  166005. ** iSpecial:
  166006. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  166007. ** then this variable contains the result of the query.
  166008. **
  166009. ** iFirstRowid, iLastRowid:
  166010. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  166011. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  166012. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  166013. ** WHERE clause in the user's query might have been:
  166014. **
  166015. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  166016. **
  166017. ** If the cursor iterates in descending order of rowid, iFirstRowid
  166018. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  166019. ** the lower.
  166020. */
  166021. struct Fts5Cursor {
  166022. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  166023. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  166024. int *aColumnSize; /* Values for xColumnSize() */
  166025. i64 iCsrId; /* Cursor id */
  166026. /* Zero from this point onwards on cursor reset */
  166027. int ePlan; /* FTS5_PLAN_XXX value */
  166028. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  166029. i64 iFirstRowid; /* Return no rowids earlier than this */
  166030. i64 iLastRowid; /* Return no rowids later than this */
  166031. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  166032. Fts5Expr *pExpr; /* Expression for MATCH queries */
  166033. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  166034. int csrflags; /* Mask of cursor flags (see below) */
  166035. i64 iSpecial; /* Result of special query */
  166036. /* "rank" function. Populated on demand from vtab.xColumn(). */
  166037. char *zRank; /* Custom rank function */
  166038. char *zRankArgs; /* Custom rank function args */
  166039. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  166040. int nRankArg; /* Number of trailing arguments for rank() */
  166041. sqlite3_value **apRankArg; /* Array of trailing arguments */
  166042. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  166043. /* Auxiliary data storage */
  166044. Fts5Auxiliary *pAux; /* Currently executing extension function */
  166045. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  166046. /* Cache used by auxiliary functions xInst() and xInstCount() */
  166047. Fts5PoslistReader *aInstIter; /* One for each phrase */
  166048. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  166049. int nInstCount; /* Number of phrase instances */
  166050. int *aInst; /* 3 integers per phrase instance */
  166051. };
  166052. /*
  166053. ** Bits that make up the "idxNum" parameter passed indirectly by
  166054. ** xBestIndex() to xFilter().
  166055. */
  166056. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  166057. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  166058. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  166059. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  166060. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  166061. #define FTS5_BI_ORDER_RANK 0x0020
  166062. #define FTS5_BI_ORDER_ROWID 0x0040
  166063. #define FTS5_BI_ORDER_DESC 0x0080
  166064. /*
  166065. ** Values for Fts5Cursor.csrflags
  166066. */
  166067. #define FTS5CSR_REQUIRE_CONTENT 0x01
  166068. #define FTS5CSR_REQUIRE_DOCSIZE 0x02
  166069. #define FTS5CSR_REQUIRE_INST 0x04
  166070. #define FTS5CSR_EOF 0x08
  166071. #define FTS5CSR_FREE_ZRANK 0x10
  166072. #define FTS5CSR_REQUIRE_RESEEK 0x20
  166073. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  166074. #define BitFlagTest(x,y) (((x) & (y))!=0)
  166075. /*
  166076. ** Macros to Set(), Clear() and Test() cursor flags.
  166077. */
  166078. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  166079. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  166080. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  166081. struct Fts5Auxdata {
  166082. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  166083. void *pPtr; /* Pointer value */
  166084. void(*xDelete)(void*); /* Destructor */
  166085. Fts5Auxdata *pNext; /* Next object in linked list */
  166086. };
  166087. #ifdef SQLITE_DEBUG
  166088. #define FTS5_BEGIN 1
  166089. #define FTS5_SYNC 2
  166090. #define FTS5_COMMIT 3
  166091. #define FTS5_ROLLBACK 4
  166092. #define FTS5_SAVEPOINT 5
  166093. #define FTS5_RELEASE 6
  166094. #define FTS5_ROLLBACKTO 7
  166095. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  166096. switch( op ){
  166097. case FTS5_BEGIN:
  166098. assert( p->ts.eState==0 );
  166099. p->ts.eState = 1;
  166100. p->ts.iSavepoint = -1;
  166101. break;
  166102. case FTS5_SYNC:
  166103. assert( p->ts.eState==1 );
  166104. p->ts.eState = 2;
  166105. break;
  166106. case FTS5_COMMIT:
  166107. assert( p->ts.eState==2 );
  166108. p->ts.eState = 0;
  166109. break;
  166110. case FTS5_ROLLBACK:
  166111. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  166112. p->ts.eState = 0;
  166113. break;
  166114. case FTS5_SAVEPOINT:
  166115. assert( p->ts.eState==1 );
  166116. assert( iSavepoint>=0 );
  166117. assert( iSavepoint>p->ts.iSavepoint );
  166118. p->ts.iSavepoint = iSavepoint;
  166119. break;
  166120. case FTS5_RELEASE:
  166121. assert( p->ts.eState==1 );
  166122. assert( iSavepoint>=0 );
  166123. assert( iSavepoint<=p->ts.iSavepoint );
  166124. p->ts.iSavepoint = iSavepoint-1;
  166125. break;
  166126. case FTS5_ROLLBACKTO:
  166127. assert( p->ts.eState==1 );
  166128. assert( iSavepoint>=0 );
  166129. assert( iSavepoint<=p->ts.iSavepoint );
  166130. p->ts.iSavepoint = iSavepoint;
  166131. break;
  166132. }
  166133. }
  166134. #else
  166135. # define fts5CheckTransactionState(x,y,z)
  166136. #endif
  166137. /*
  166138. ** Return true if pTab is a contentless table.
  166139. */
  166140. static int fts5IsContentless(Fts5Table *pTab){
  166141. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  166142. }
  166143. /*
  166144. ** Delete a virtual table handle allocated by fts5InitVtab().
  166145. */
  166146. static void fts5FreeVtab(Fts5Table *pTab){
  166147. if( pTab ){
  166148. sqlite3Fts5IndexClose(pTab->pIndex);
  166149. sqlite3Fts5StorageClose(pTab->pStorage);
  166150. sqlite3Fts5ConfigFree(pTab->pConfig);
  166151. sqlite3_free(pTab);
  166152. }
  166153. }
  166154. /*
  166155. ** The xDisconnect() virtual table method.
  166156. */
  166157. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  166158. fts5FreeVtab((Fts5Table*)pVtab);
  166159. return SQLITE_OK;
  166160. }
  166161. /*
  166162. ** The xDestroy() virtual table method.
  166163. */
  166164. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  166165. Fts5Table *pTab = (Fts5Table*)pVtab;
  166166. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  166167. if( rc==SQLITE_OK ){
  166168. fts5FreeVtab((Fts5Table*)pVtab);
  166169. }
  166170. return rc;
  166171. }
  166172. /*
  166173. ** This function is the implementation of both the xConnect and xCreate
  166174. ** methods of the FTS3 virtual table.
  166175. **
  166176. ** The argv[] array contains the following:
  166177. **
  166178. ** argv[0] -> module name ("fts5")
  166179. ** argv[1] -> database name
  166180. ** argv[2] -> table name
  166181. ** argv[...] -> "column name" and other module argument fields.
  166182. */
  166183. static int fts5InitVtab(
  166184. int bCreate, /* True for xCreate, false for xConnect */
  166185. sqlite3 *db, /* The SQLite database connection */
  166186. void *pAux, /* Hash table containing tokenizers */
  166187. int argc, /* Number of elements in argv array */
  166188. const char * const *argv, /* xCreate/xConnect argument array */
  166189. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  166190. char **pzErr /* Write any error message here */
  166191. ){
  166192. Fts5Global *pGlobal = (Fts5Global*)pAux;
  166193. const char **azConfig = (const char**)argv;
  166194. int rc = SQLITE_OK; /* Return code */
  166195. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  166196. Fts5Table *pTab = 0; /* New virtual table object */
  166197. /* Allocate the new vtab object and parse the configuration */
  166198. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  166199. if( rc==SQLITE_OK ){
  166200. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  166201. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  166202. }
  166203. if( rc==SQLITE_OK ){
  166204. pTab->pConfig = pConfig;
  166205. pTab->pGlobal = pGlobal;
  166206. }
  166207. /* Open the index sub-system */
  166208. if( rc==SQLITE_OK ){
  166209. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  166210. }
  166211. /* Open the storage sub-system */
  166212. if( rc==SQLITE_OK ){
  166213. rc = sqlite3Fts5StorageOpen(
  166214. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  166215. );
  166216. }
  166217. /* Call sqlite3_declare_vtab() */
  166218. if( rc==SQLITE_OK ){
  166219. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  166220. }
  166221. if( rc!=SQLITE_OK ){
  166222. fts5FreeVtab(pTab);
  166223. pTab = 0;
  166224. }else if( bCreate ){
  166225. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  166226. }
  166227. *ppVTab = (sqlite3_vtab*)pTab;
  166228. return rc;
  166229. }
  166230. /*
  166231. ** The xConnect() and xCreate() methods for the virtual table. All the
  166232. ** work is done in function fts5InitVtab().
  166233. */
  166234. static int fts5ConnectMethod(
  166235. sqlite3 *db, /* Database connection */
  166236. void *pAux, /* Pointer to tokenizer hash table */
  166237. int argc, /* Number of elements in argv array */
  166238. const char * const *argv, /* xCreate/xConnect argument array */
  166239. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  166240. char **pzErr /* OUT: sqlite3_malloc'd error message */
  166241. ){
  166242. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  166243. }
  166244. static int fts5CreateMethod(
  166245. sqlite3 *db, /* Database connection */
  166246. void *pAux, /* Pointer to tokenizer hash table */
  166247. int argc, /* Number of elements in argv array */
  166248. const char * const *argv, /* xCreate/xConnect argument array */
  166249. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  166250. char **pzErr /* OUT: sqlite3_malloc'd error message */
  166251. ){
  166252. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  166253. }
  166254. /*
  166255. ** The different query plans.
  166256. */
  166257. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  166258. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  166259. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  166260. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  166261. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  166262. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  166263. /*
  166264. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  166265. ** extension is currently being used by a version of SQLite too old to
  166266. ** support index-info flags. In that case this function is a no-op.
  166267. */
  166268. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  166269. #if SQLITE_VERSION_NUMBER>=3008012
  166270. if( sqlite3_libversion_number()>=3008012 ){
  166271. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  166272. }
  166273. #endif
  166274. }
  166275. /*
  166276. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  166277. ** WHERE constraint, it searches for the following:
  166278. **
  166279. ** 1. A MATCH constraint against the special column.
  166280. ** 2. A MATCH constraint against the "rank" column.
  166281. ** 3. An == constraint against the rowid column.
  166282. ** 4. A < or <= constraint against the rowid column.
  166283. ** 5. A > or >= constraint against the rowid column.
  166284. **
  166285. ** Within the ORDER BY, either:
  166286. **
  166287. ** 5. ORDER BY rank [ASC|DESC]
  166288. ** 6. ORDER BY rowid [ASC|DESC]
  166289. **
  166290. ** Costs are assigned as follows:
  166291. **
  166292. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  166293. ** cost is unconditionally set to 1e50 (a really big number).
  166294. **
  166295. ** a) If a MATCH operator is present, the cost depends on the other
  166296. ** constraints also present. As follows:
  166297. **
  166298. ** * No other constraints: cost=1000.0
  166299. ** * One rowid range constraint: cost=750.0
  166300. ** * Both rowid range constraints: cost=500.0
  166301. ** * An == rowid constraint: cost=100.0
  166302. **
  166303. ** b) Otherwise, if there is no MATCH:
  166304. **
  166305. ** * No other constraints: cost=1000000.0
  166306. ** * One rowid range constraint: cost=750000.0
  166307. ** * Both rowid range constraints: cost=250000.0
  166308. ** * An == rowid constraint: cost=10.0
  166309. **
  166310. ** Costs are not modified by the ORDER BY clause.
  166311. */
  166312. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  166313. Fts5Table *pTab = (Fts5Table*)pVTab;
  166314. Fts5Config *pConfig = pTab->pConfig;
  166315. int idxFlags = 0; /* Parameter passed through to xFilter() */
  166316. int bHasMatch;
  166317. int iNext;
  166318. int i;
  166319. struct Constraint {
  166320. int op; /* Mask against sqlite3_index_constraint.op */
  166321. int fts5op; /* FTS5 mask for idxFlags */
  166322. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  166323. int omit; /* True to omit this if found */
  166324. int iConsIndex; /* Index in pInfo->aConstraint[] */
  166325. } aConstraint[] = {
  166326. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  166327. FTS5_BI_MATCH, 1, 1, -1},
  166328. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  166329. FTS5_BI_RANK, 2, 1, -1},
  166330. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  166331. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  166332. FTS5_BI_ROWID_LE, 0, 0, -1},
  166333. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  166334. FTS5_BI_ROWID_GE, 0, 0, -1},
  166335. };
  166336. int aColMap[3];
  166337. aColMap[0] = -1;
  166338. aColMap[1] = pConfig->nCol;
  166339. aColMap[2] = pConfig->nCol+1;
  166340. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  166341. for(i=0; i<pInfo->nConstraint; i++){
  166342. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  166343. int j;
  166344. for(j=0; j<sizeof(aConstraint)/sizeof(aConstraint[0]); j++){
  166345. struct Constraint *pC = &aConstraint[j];
  166346. if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
  166347. if( p->usable ){
  166348. pC->iConsIndex = i;
  166349. idxFlags |= pC->fts5op;
  166350. }else if( j==0 ){
  166351. /* As there exists an unusable MATCH constraint this is an
  166352. ** unusable plan. Set a prohibitively high cost. */
  166353. pInfo->estimatedCost = 1e50;
  166354. return SQLITE_OK;
  166355. }
  166356. }
  166357. }
  166358. }
  166359. /* Set idxFlags flags for the ORDER BY clause */
  166360. if( pInfo->nOrderBy==1 ){
  166361. int iSort = pInfo->aOrderBy[0].iColumn;
  166362. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  166363. idxFlags |= FTS5_BI_ORDER_RANK;
  166364. }else if( iSort==-1 ){
  166365. idxFlags |= FTS5_BI_ORDER_ROWID;
  166366. }
  166367. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  166368. pInfo->orderByConsumed = 1;
  166369. if( pInfo->aOrderBy[0].desc ){
  166370. idxFlags |= FTS5_BI_ORDER_DESC;
  166371. }
  166372. }
  166373. }
  166374. /* Calculate the estimated cost based on the flags set in idxFlags. */
  166375. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  166376. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  166377. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  166378. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  166379. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  166380. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  166381. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  166382. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  166383. }else{
  166384. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  166385. }
  166386. /* Assign argvIndex values to each constraint in use. */
  166387. iNext = 1;
  166388. for(i=0; i<sizeof(aConstraint)/sizeof(aConstraint[0]); i++){
  166389. struct Constraint *pC = &aConstraint[i];
  166390. if( pC->iConsIndex>=0 ){
  166391. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  166392. pInfo->aConstraintUsage[pC->iConsIndex].omit = pC->omit;
  166393. }
  166394. }
  166395. pInfo->idxNum = idxFlags;
  166396. return SQLITE_OK;
  166397. }
  166398. /*
  166399. ** Implementation of xOpen method.
  166400. */
  166401. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  166402. Fts5Table *pTab = (Fts5Table*)pVTab;
  166403. Fts5Config *pConfig = pTab->pConfig;
  166404. Fts5Cursor *pCsr; /* New cursor object */
  166405. int nByte; /* Bytes of space to allocate */
  166406. int rc = SQLITE_OK; /* Return code */
  166407. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  166408. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  166409. if( pCsr ){
  166410. Fts5Global *pGlobal = pTab->pGlobal;
  166411. memset(pCsr, 0, nByte);
  166412. pCsr->aColumnSize = (int*)&pCsr[1];
  166413. pCsr->pNext = pGlobal->pCsr;
  166414. pGlobal->pCsr = pCsr;
  166415. pCsr->iCsrId = ++pGlobal->iNextId;
  166416. }else{
  166417. rc = SQLITE_NOMEM;
  166418. }
  166419. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  166420. return rc;
  166421. }
  166422. static int fts5StmtType(Fts5Cursor *pCsr){
  166423. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  166424. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  166425. }
  166426. return FTS5_STMT_LOOKUP;
  166427. }
  166428. /*
  166429. ** This function is called after the cursor passed as the only argument
  166430. ** is moved to point at a different row. It clears all cached data
  166431. ** specific to the previous row stored by the cursor object.
  166432. */
  166433. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  166434. CsrFlagSet(pCsr,
  166435. FTS5CSR_REQUIRE_CONTENT
  166436. | FTS5CSR_REQUIRE_DOCSIZE
  166437. | FTS5CSR_REQUIRE_INST
  166438. );
  166439. }
  166440. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  166441. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  166442. Fts5Auxdata *pData;
  166443. Fts5Auxdata *pNext;
  166444. sqlite3_free(pCsr->aInstIter);
  166445. sqlite3_free(pCsr->aInst);
  166446. if( pCsr->pStmt ){
  166447. int eStmt = fts5StmtType(pCsr);
  166448. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  166449. }
  166450. if( pCsr->pSorter ){
  166451. Fts5Sorter *pSorter = pCsr->pSorter;
  166452. sqlite3_finalize(pSorter->pStmt);
  166453. sqlite3_free(pSorter);
  166454. }
  166455. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  166456. sqlite3Fts5ExprFree(pCsr->pExpr);
  166457. }
  166458. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  166459. pNext = pData->pNext;
  166460. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  166461. sqlite3_free(pData);
  166462. }
  166463. sqlite3_finalize(pCsr->pRankArgStmt);
  166464. sqlite3_free(pCsr->apRankArg);
  166465. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  166466. sqlite3_free(pCsr->zRank);
  166467. sqlite3_free(pCsr->zRankArgs);
  166468. }
  166469. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  166470. }
  166471. /*
  166472. ** Close the cursor. For additional information see the documentation
  166473. ** on the xClose method of the virtual table interface.
  166474. */
  166475. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  166476. if( pCursor ){
  166477. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  166478. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  166479. Fts5Cursor **pp;
  166480. fts5FreeCursorComponents(pCsr);
  166481. /* Remove the cursor from the Fts5Global.pCsr list */
  166482. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  166483. *pp = pCsr->pNext;
  166484. sqlite3_free(pCsr);
  166485. }
  166486. return SQLITE_OK;
  166487. }
  166488. static int fts5SorterNext(Fts5Cursor *pCsr){
  166489. Fts5Sorter *pSorter = pCsr->pSorter;
  166490. int rc;
  166491. rc = sqlite3_step(pSorter->pStmt);
  166492. if( rc==SQLITE_DONE ){
  166493. rc = SQLITE_OK;
  166494. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166495. }else if( rc==SQLITE_ROW ){
  166496. const u8 *a;
  166497. const u8 *aBlob;
  166498. int nBlob;
  166499. int i;
  166500. int iOff = 0;
  166501. rc = SQLITE_OK;
  166502. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  166503. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  166504. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  166505. for(i=0; i<(pSorter->nIdx-1); i++){
  166506. int iVal;
  166507. a += fts5GetVarint32(a, iVal);
  166508. iOff += iVal;
  166509. pSorter->aIdx[i] = iOff;
  166510. }
  166511. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  166512. pSorter->aPoslist = a;
  166513. fts5CsrNewrow(pCsr);
  166514. }
  166515. return rc;
  166516. }
  166517. /*
  166518. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  166519. ** open on table pTab.
  166520. */
  166521. static void fts5TripCursors(Fts5Table *pTab){
  166522. Fts5Cursor *pCsr;
  166523. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  166524. if( pCsr->ePlan==FTS5_PLAN_MATCH
  166525. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  166526. ){
  166527. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  166528. }
  166529. }
  166530. }
  166531. /*
  166532. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  166533. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  166534. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  166535. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  166536. **
  166537. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  166538. ** to 1 before returning. Otherwise, leave it unchanged.
  166539. **
  166540. ** Return SQLITE_OK if successful or if no reseek was required, or an
  166541. ** error code if an error occurred.
  166542. */
  166543. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  166544. int rc = SQLITE_OK;
  166545. assert( *pbSkip==0 );
  166546. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  166547. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  166548. int bDesc = pCsr->bDesc;
  166549. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  166550. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  166551. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  166552. *pbSkip = 1;
  166553. }
  166554. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  166555. fts5CsrNewrow(pCsr);
  166556. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  166557. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166558. }
  166559. }
  166560. return rc;
  166561. }
  166562. /*
  166563. ** Advance the cursor to the next row in the table that matches the
  166564. ** search criteria.
  166565. **
  166566. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  166567. ** even if we reach end-of-file. The fts5EofMethod() will be called
  166568. ** subsequently to determine whether or not an EOF was hit.
  166569. */
  166570. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  166571. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  166572. int rc = SQLITE_OK;
  166573. assert( (pCsr->ePlan<3)==
  166574. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  166575. );
  166576. if( pCsr->ePlan<3 ){
  166577. int bSkip = 0;
  166578. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  166579. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  166580. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  166581. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166582. }
  166583. fts5CsrNewrow(pCsr);
  166584. }else{
  166585. switch( pCsr->ePlan ){
  166586. case FTS5_PLAN_SPECIAL: {
  166587. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166588. break;
  166589. }
  166590. case FTS5_PLAN_SORTED_MATCH: {
  166591. rc = fts5SorterNext(pCsr);
  166592. break;
  166593. }
  166594. default:
  166595. rc = sqlite3_step(pCsr->pStmt);
  166596. if( rc!=SQLITE_ROW ){
  166597. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166598. rc = sqlite3_reset(pCsr->pStmt);
  166599. }else{
  166600. rc = SQLITE_OK;
  166601. }
  166602. break;
  166603. }
  166604. }
  166605. return rc;
  166606. }
  166607. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  166608. Fts5Config *pConfig = pTab->pConfig;
  166609. Fts5Sorter *pSorter;
  166610. int nPhrase;
  166611. int nByte;
  166612. int rc = SQLITE_OK;
  166613. char *zSql;
  166614. const char *zRank = pCsr->zRank;
  166615. const char *zRankArgs = pCsr->zRankArgs;
  166616. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  166617. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  166618. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  166619. if( pSorter==0 ) return SQLITE_NOMEM;
  166620. memset(pSorter, 0, nByte);
  166621. pSorter->nIdx = nPhrase;
  166622. /* TODO: It would be better to have some system for reusing statement
  166623. ** handles here, rather than preparing a new one for each query. But that
  166624. ** is not possible as SQLite reference counts the virtual table objects.
  166625. ** And since the statement required here reads from this very virtual
  166626. ** table, saving it creates a circular reference.
  166627. **
  166628. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  166629. zSql = sqlite3Fts5Mprintf(&rc,
  166630. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  166631. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  166632. (zRankArgs ? ", " : ""),
  166633. (zRankArgs ? zRankArgs : ""),
  166634. bDesc ? "DESC" : "ASC"
  166635. );
  166636. if( zSql ){
  166637. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pSorter->pStmt, 0);
  166638. sqlite3_free(zSql);
  166639. }
  166640. pCsr->pSorter = pSorter;
  166641. if( rc==SQLITE_OK ){
  166642. assert( pTab->pSortCsr==0 );
  166643. pTab->pSortCsr = pCsr;
  166644. rc = fts5SorterNext(pCsr);
  166645. pTab->pSortCsr = 0;
  166646. }
  166647. if( rc!=SQLITE_OK ){
  166648. sqlite3_finalize(pSorter->pStmt);
  166649. sqlite3_free(pSorter);
  166650. pCsr->pSorter = 0;
  166651. }
  166652. return rc;
  166653. }
  166654. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  166655. int rc;
  166656. Fts5Expr *pExpr = pCsr->pExpr;
  166657. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  166658. if( sqlite3Fts5ExprEof(pExpr) ){
  166659. CsrFlagSet(pCsr, FTS5CSR_EOF);
  166660. }
  166661. fts5CsrNewrow(pCsr);
  166662. return rc;
  166663. }
  166664. /*
  166665. ** Process a "special" query. A special query is identified as one with a
  166666. ** MATCH expression that begins with a '*' character. The remainder of
  166667. ** the text passed to the MATCH operator are used as the special query
  166668. ** parameters.
  166669. */
  166670. static int fts5SpecialMatch(
  166671. Fts5Table *pTab,
  166672. Fts5Cursor *pCsr,
  166673. const char *zQuery
  166674. ){
  166675. int rc = SQLITE_OK; /* Return code */
  166676. const char *z = zQuery; /* Special query text */
  166677. int n; /* Number of bytes in text at z */
  166678. while( z[0]==' ' ) z++;
  166679. for(n=0; z[n] && z[n]!=' '; n++);
  166680. assert( pTab->base.zErrMsg==0 );
  166681. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  166682. if( 0==sqlite3_strnicmp("reads", z, n) ){
  166683. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  166684. }
  166685. else if( 0==sqlite3_strnicmp("id", z, n) ){
  166686. pCsr->iSpecial = pCsr->iCsrId;
  166687. }
  166688. else{
  166689. /* An unrecognized directive. Return an error message. */
  166690. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  166691. rc = SQLITE_ERROR;
  166692. }
  166693. return rc;
  166694. }
  166695. /*
  166696. ** Search for an auxiliary function named zName that can be used with table
  166697. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  166698. ** structure. Otherwise, if no such function exists, return NULL.
  166699. */
  166700. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  166701. Fts5Auxiliary *pAux;
  166702. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  166703. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  166704. }
  166705. /* No function of the specified name was found. Return 0. */
  166706. return 0;
  166707. }
  166708. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  166709. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  166710. Fts5Config *pConfig = pTab->pConfig;
  166711. int rc = SQLITE_OK;
  166712. Fts5Auxiliary *pAux = 0;
  166713. const char *zRank = pCsr->zRank;
  166714. const char *zRankArgs = pCsr->zRankArgs;
  166715. if( zRankArgs ){
  166716. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  166717. if( zSql ){
  166718. sqlite3_stmt *pStmt = 0;
  166719. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
  166720. sqlite3_free(zSql);
  166721. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  166722. if( rc==SQLITE_OK ){
  166723. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  166724. int nByte;
  166725. pCsr->nRankArg = sqlite3_column_count(pStmt);
  166726. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  166727. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  166728. if( rc==SQLITE_OK ){
  166729. int i;
  166730. for(i=0; i<pCsr->nRankArg; i++){
  166731. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  166732. }
  166733. }
  166734. pCsr->pRankArgStmt = pStmt;
  166735. }else{
  166736. rc = sqlite3_finalize(pStmt);
  166737. assert( rc!=SQLITE_OK );
  166738. }
  166739. }
  166740. }
  166741. }
  166742. if( rc==SQLITE_OK ){
  166743. pAux = fts5FindAuxiliary(pTab, zRank);
  166744. if( pAux==0 ){
  166745. assert( pTab->base.zErrMsg==0 );
  166746. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  166747. rc = SQLITE_ERROR;
  166748. }
  166749. }
  166750. pCsr->pRank = pAux;
  166751. return rc;
  166752. }
  166753. static int fts5CursorParseRank(
  166754. Fts5Config *pConfig,
  166755. Fts5Cursor *pCsr,
  166756. sqlite3_value *pRank
  166757. ){
  166758. int rc = SQLITE_OK;
  166759. if( pRank ){
  166760. const char *z = (const char*)sqlite3_value_text(pRank);
  166761. char *zRank = 0;
  166762. char *zRankArgs = 0;
  166763. if( z==0 ){
  166764. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  166765. }else{
  166766. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  166767. }
  166768. if( rc==SQLITE_OK ){
  166769. pCsr->zRank = zRank;
  166770. pCsr->zRankArgs = zRankArgs;
  166771. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  166772. }else if( rc==SQLITE_ERROR ){
  166773. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  166774. "parse error in rank function: %s", z
  166775. );
  166776. }
  166777. }else{
  166778. if( pConfig->zRank ){
  166779. pCsr->zRank = (char*)pConfig->zRank;
  166780. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  166781. }else{
  166782. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  166783. pCsr->zRankArgs = 0;
  166784. }
  166785. }
  166786. return rc;
  166787. }
  166788. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  166789. if( pVal ){
  166790. int eType = sqlite3_value_numeric_type(pVal);
  166791. if( eType==SQLITE_INTEGER ){
  166792. return sqlite3_value_int64(pVal);
  166793. }
  166794. }
  166795. return iDefault;
  166796. }
  166797. /*
  166798. ** This is the xFilter interface for the virtual table. See
  166799. ** the virtual table xFilter method documentation for additional
  166800. ** information.
  166801. **
  166802. ** There are three possible query strategies:
  166803. **
  166804. ** 1. Full-text search using a MATCH operator.
  166805. ** 2. A by-rowid lookup.
  166806. ** 3. A full-table scan.
  166807. */
  166808. static int fts5FilterMethod(
  166809. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  166810. int idxNum, /* Strategy index */
  166811. const char *idxStr, /* Unused */
  166812. int nVal, /* Number of elements in apVal */
  166813. sqlite3_value **apVal /* Arguments for the indexing scheme */
  166814. ){
  166815. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  166816. Fts5Config *pConfig = pTab->pConfig;
  166817. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  166818. int rc = SQLITE_OK; /* Error code */
  166819. int iVal = 0; /* Counter for apVal[] */
  166820. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  166821. int bOrderByRank; /* True if ORDER BY rank */
  166822. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  166823. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  166824. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  166825. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  166826. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  166827. char **pzErrmsg = pConfig->pzErrmsg;
  166828. if( pCsr->ePlan ){
  166829. fts5FreeCursorComponents(pCsr);
  166830. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  166831. }
  166832. assert( pCsr->pStmt==0 );
  166833. assert( pCsr->pExpr==0 );
  166834. assert( pCsr->csrflags==0 );
  166835. assert( pCsr->pRank==0 );
  166836. assert( pCsr->zRank==0 );
  166837. assert( pCsr->zRankArgs==0 );
  166838. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  166839. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  166840. /* Decode the arguments passed through to this function.
  166841. **
  166842. ** Note: The following set of if(...) statements must be in the same
  166843. ** order as the corresponding entries in the struct at the top of
  166844. ** fts5BestIndexMethod(). */
  166845. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  166846. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  166847. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  166848. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  166849. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  166850. assert( iVal==nVal );
  166851. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  166852. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  166853. /* Set the cursor upper and lower rowid limits. Only some strategies
  166854. ** actually use them. This is ok, as the xBestIndex() method leaves the
  166855. ** sqlite3_index_constraint.omit flag clear for range constraints
  166856. ** on the rowid field. */
  166857. if( pRowidEq ){
  166858. pRowidLe = pRowidGe = pRowidEq;
  166859. }
  166860. if( bDesc ){
  166861. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  166862. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  166863. }else{
  166864. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  166865. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  166866. }
  166867. if( pTab->pSortCsr ){
  166868. /* If pSortCsr is non-NULL, then this call is being made as part of
  166869. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  166870. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  166871. ** return results to the user for this query. The current cursor
  166872. ** (pCursor) is used to execute the query issued by function
  166873. ** fts5CursorFirstSorted() above. */
  166874. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  166875. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  166876. assert( pCsr->iLastRowid==LARGEST_INT64 );
  166877. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  166878. pCsr->ePlan = FTS5_PLAN_SOURCE;
  166879. pCsr->pExpr = pTab->pSortCsr->pExpr;
  166880. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  166881. }else if( pMatch ){
  166882. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  166883. if( zExpr==0 ) zExpr = "";
  166884. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  166885. if( rc==SQLITE_OK ){
  166886. if( zExpr[0]=='*' ){
  166887. /* The user has issued a query of the form "MATCH '*...'". This
  166888. ** indicates that the MATCH expression is not a full text query,
  166889. ** but a request for an internal parameter. */
  166890. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  166891. }else{
  166892. char **pzErr = &pTab->base.zErrMsg;
  166893. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
  166894. if( rc==SQLITE_OK ){
  166895. if( bOrderByRank ){
  166896. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  166897. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  166898. }else{
  166899. pCsr->ePlan = FTS5_PLAN_MATCH;
  166900. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  166901. }
  166902. }
  166903. }
  166904. }
  166905. }else if( pConfig->zContent==0 ){
  166906. *pConfig->pzErrmsg = sqlite3_mprintf(
  166907. "%s: table does not support scanning", pConfig->zName
  166908. );
  166909. rc = SQLITE_ERROR;
  166910. }else{
  166911. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  166912. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  166913. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  166914. rc = sqlite3Fts5StorageStmt(
  166915. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  166916. );
  166917. if( rc==SQLITE_OK ){
  166918. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  166919. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  166920. }else{
  166921. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  166922. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  166923. }
  166924. rc = fts5NextMethod(pCursor);
  166925. }
  166926. }
  166927. pConfig->pzErrmsg = pzErrmsg;
  166928. return rc;
  166929. }
  166930. /*
  166931. ** This is the xEof method of the virtual table. SQLite calls this
  166932. ** routine to find out if it has reached the end of a result set.
  166933. */
  166934. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  166935. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  166936. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  166937. }
  166938. /*
  166939. ** Return the rowid that the cursor currently points to.
  166940. */
  166941. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  166942. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  166943. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  166944. || pCsr->ePlan==FTS5_PLAN_SOURCE
  166945. );
  166946. if( pCsr->pSorter ){
  166947. return pCsr->pSorter->iRowid;
  166948. }else{
  166949. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  166950. }
  166951. }
  166952. /*
  166953. ** This is the xRowid method. The SQLite core calls this routine to
  166954. ** retrieve the rowid for the current row of the result set. fts5
  166955. ** exposes %_content.rowid as the rowid for the virtual table. The
  166956. ** rowid should be written to *pRowid.
  166957. */
  166958. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  166959. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  166960. int ePlan = pCsr->ePlan;
  166961. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  166962. switch( ePlan ){
  166963. case FTS5_PLAN_SPECIAL:
  166964. *pRowid = 0;
  166965. break;
  166966. case FTS5_PLAN_SOURCE:
  166967. case FTS5_PLAN_MATCH:
  166968. case FTS5_PLAN_SORTED_MATCH:
  166969. *pRowid = fts5CursorRowid(pCsr);
  166970. break;
  166971. default:
  166972. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  166973. break;
  166974. }
  166975. return SQLITE_OK;
  166976. }
  166977. /*
  166978. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  166979. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  166980. **
  166981. ** If argument bErrormsg is true and an error occurs, an error message may
  166982. ** be left in sqlite3_vtab.zErrMsg.
  166983. */
  166984. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  166985. int rc = SQLITE_OK;
  166986. /* If the cursor does not yet have a statement handle, obtain one now. */
  166987. if( pCsr->pStmt==0 ){
  166988. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  166989. int eStmt = fts5StmtType(pCsr);
  166990. rc = sqlite3Fts5StorageStmt(
  166991. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  166992. );
  166993. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  166994. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  166995. }
  166996. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  166997. assert( pCsr->pExpr );
  166998. sqlite3_reset(pCsr->pStmt);
  166999. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  167000. rc = sqlite3_step(pCsr->pStmt);
  167001. if( rc==SQLITE_ROW ){
  167002. rc = SQLITE_OK;
  167003. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  167004. }else{
  167005. rc = sqlite3_reset(pCsr->pStmt);
  167006. if( rc==SQLITE_OK ){
  167007. rc = FTS5_CORRUPT;
  167008. }
  167009. }
  167010. }
  167011. return rc;
  167012. }
  167013. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  167014. va_list ap; /* ... printf arguments */
  167015. va_start(ap, zFormat);
  167016. assert( p->base.zErrMsg==0 );
  167017. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  167018. va_end(ap);
  167019. }
  167020. /*
  167021. ** This function is called to handle an FTS INSERT command. In other words,
  167022. ** an INSERT statement of the form:
  167023. **
  167024. ** INSERT INTO fts(fts) VALUES($pCmd)
  167025. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  167026. **
  167027. ** Argument pVal is the value assigned to column "fts" by the INSERT
  167028. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  167029. ** error code if an error occurs.
  167030. **
  167031. ** The commands implemented by this function are documented in the "Special
  167032. ** INSERT Directives" section of the documentation. It should be updated if
  167033. ** more commands are added to this function.
  167034. */
  167035. static int fts5SpecialInsert(
  167036. Fts5Table *pTab, /* Fts5 table object */
  167037. const char *zCmd, /* Text inserted into table-name column */
  167038. sqlite3_value *pVal /* Value inserted into rank column */
  167039. ){
  167040. Fts5Config *pConfig = pTab->pConfig;
  167041. int rc = SQLITE_OK;
  167042. int bError = 0;
  167043. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  167044. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  167045. fts5SetVtabError(pTab,
  167046. "'delete-all' may only be used with a "
  167047. "contentless or external content fts5 table"
  167048. );
  167049. rc = SQLITE_ERROR;
  167050. }else{
  167051. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  167052. }
  167053. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  167054. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  167055. fts5SetVtabError(pTab,
  167056. "'rebuild' may not be used with a contentless fts5 table"
  167057. );
  167058. rc = SQLITE_ERROR;
  167059. }else{
  167060. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  167061. }
  167062. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  167063. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  167064. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  167065. int nMerge = sqlite3_value_int(pVal);
  167066. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  167067. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  167068. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  167069. #ifdef SQLITE_DEBUG
  167070. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  167071. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  167072. #endif
  167073. }else{
  167074. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  167075. if( rc==SQLITE_OK ){
  167076. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  167077. }
  167078. if( rc==SQLITE_OK ){
  167079. if( bError ){
  167080. rc = SQLITE_ERROR;
  167081. }else{
  167082. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  167083. }
  167084. }
  167085. }
  167086. return rc;
  167087. }
  167088. static int fts5SpecialDelete(
  167089. Fts5Table *pTab,
  167090. sqlite3_value **apVal,
  167091. sqlite3_int64 *piRowid
  167092. ){
  167093. int rc = SQLITE_OK;
  167094. int eType1 = sqlite3_value_type(apVal[1]);
  167095. if( eType1==SQLITE_INTEGER ){
  167096. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  167097. rc = sqlite3Fts5StorageSpecialDelete(pTab->pStorage, iDel, &apVal[2]);
  167098. }
  167099. return rc;
  167100. }
  167101. static void fts5StorageInsert(
  167102. int *pRc,
  167103. Fts5Table *pTab,
  167104. sqlite3_value **apVal,
  167105. i64 *piRowid
  167106. ){
  167107. int rc = *pRc;
  167108. if( rc==SQLITE_OK ){
  167109. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  167110. }
  167111. if( rc==SQLITE_OK ){
  167112. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  167113. }
  167114. *pRc = rc;
  167115. }
  167116. /*
  167117. ** This function is the implementation of the xUpdate callback used by
  167118. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  167119. ** inserted, updated or deleted.
  167120. **
  167121. ** A delete specifies a single argument - the rowid of the row to remove.
  167122. **
  167123. ** Update and insert operations pass:
  167124. **
  167125. ** 1. The "old" rowid, or NULL.
  167126. ** 2. The "new" rowid.
  167127. ** 3. Values for each of the nCol matchable columns.
  167128. ** 4. Values for the two hidden columns (<tablename> and "rank").
  167129. */
  167130. static int fts5UpdateMethod(
  167131. sqlite3_vtab *pVtab, /* Virtual table handle */
  167132. int nArg, /* Size of argument array */
  167133. sqlite3_value **apVal, /* Array of arguments */
  167134. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  167135. ){
  167136. Fts5Table *pTab = (Fts5Table*)pVtab;
  167137. Fts5Config *pConfig = pTab->pConfig;
  167138. int eType0; /* value_type() of apVal[0] */
  167139. int rc = SQLITE_OK; /* Return code */
  167140. /* A transaction must be open when this is called. */
  167141. assert( pTab->ts.eState==1 );
  167142. assert( pVtab->zErrMsg==0 );
  167143. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  167144. assert( nArg==1
  167145. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  167146. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  167147. );
  167148. assert( pTab->pConfig->pzErrmsg==0 );
  167149. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  167150. /* Put any active cursors into REQUIRE_SEEK state. */
  167151. fts5TripCursors(pTab);
  167152. eType0 = sqlite3_value_type(apVal[0]);
  167153. if( eType0==SQLITE_NULL
  167154. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  167155. ){
  167156. /* A "special" INSERT op. These are handled separately. */
  167157. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  167158. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  167159. && 0==sqlite3_stricmp("delete", z)
  167160. ){
  167161. rc = fts5SpecialDelete(pTab, apVal, pRowid);
  167162. }else{
  167163. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  167164. }
  167165. }else{
  167166. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  167167. ** any conflict on the rowid value must be detected before any
  167168. ** modifications are made to the database file. There are 4 cases:
  167169. **
  167170. ** 1) DELETE
  167171. ** 2) UPDATE (rowid not modified)
  167172. ** 3) UPDATE (rowid modified)
  167173. ** 4) INSERT
  167174. **
  167175. ** Cases 3 and 4 may violate the rowid constraint.
  167176. */
  167177. int eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  167178. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  167179. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  167180. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  167181. ** This is not suported. */
  167182. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  167183. pTab->base.zErrMsg = sqlite3_mprintf(
  167184. "cannot %s contentless fts5 table: %s",
  167185. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  167186. );
  167187. rc = SQLITE_ERROR;
  167188. }
  167189. /* Case 1: DELETE */
  167190. else if( nArg==1 ){
  167191. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  167192. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel);
  167193. }
  167194. /* Case 2: INSERT */
  167195. else if( eType0!=SQLITE_INTEGER ){
  167196. /* If this is a REPLACE, first remove the current entry (if any) */
  167197. if( eConflict==SQLITE_REPLACE
  167198. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  167199. ){
  167200. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  167201. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
  167202. }
  167203. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  167204. }
  167205. /* Case 2: UPDATE */
  167206. else{
  167207. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  167208. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  167209. if( iOld!=iNew ){
  167210. if( eConflict==SQLITE_REPLACE ){
  167211. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  167212. if( rc==SQLITE_OK ){
  167213. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
  167214. }
  167215. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  167216. }else{
  167217. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  167218. if( rc==SQLITE_OK ){
  167219. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  167220. }
  167221. if( rc==SQLITE_OK ){
  167222. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  167223. }
  167224. }
  167225. }else{
  167226. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  167227. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  167228. }
  167229. }
  167230. }
  167231. pTab->pConfig->pzErrmsg = 0;
  167232. return rc;
  167233. }
  167234. /*
  167235. ** Implementation of xSync() method.
  167236. */
  167237. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  167238. int rc;
  167239. Fts5Table *pTab = (Fts5Table*)pVtab;
  167240. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  167241. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  167242. fts5TripCursors(pTab);
  167243. rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
  167244. pTab->pConfig->pzErrmsg = 0;
  167245. return rc;
  167246. }
  167247. /*
  167248. ** Implementation of xBegin() method.
  167249. */
  167250. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  167251. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  167252. return SQLITE_OK;
  167253. }
  167254. /*
  167255. ** Implementation of xCommit() method. This is a no-op. The contents of
  167256. ** the pending-terms hash-table have already been flushed into the database
  167257. ** by fts5SyncMethod().
  167258. */
  167259. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  167260. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  167261. return SQLITE_OK;
  167262. }
  167263. /*
  167264. ** Implementation of xRollback(). Discard the contents of the pending-terms
  167265. ** hash-table. Any changes made to the database are reverted by SQLite.
  167266. */
  167267. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  167268. int rc;
  167269. Fts5Table *pTab = (Fts5Table*)pVtab;
  167270. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  167271. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  167272. return rc;
  167273. }
  167274. static void *fts5ApiUserData(Fts5Context *pCtx){
  167275. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167276. return pCsr->pAux->pUserData;
  167277. }
  167278. static int fts5ApiColumnCount(Fts5Context *pCtx){
  167279. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167280. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  167281. }
  167282. static int fts5ApiColumnTotalSize(
  167283. Fts5Context *pCtx,
  167284. int iCol,
  167285. sqlite3_int64 *pnToken
  167286. ){
  167287. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167288. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  167289. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  167290. }
  167291. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  167292. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167293. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  167294. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  167295. }
  167296. static int fts5ApiTokenize(
  167297. Fts5Context *pCtx,
  167298. const char *pText, int nText,
  167299. void *pUserData,
  167300. int (*xToken)(void*, int, const char*, int, int, int)
  167301. ){
  167302. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167303. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  167304. return sqlite3Fts5Tokenize(
  167305. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  167306. );
  167307. }
  167308. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  167309. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167310. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  167311. }
  167312. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  167313. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167314. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  167315. }
  167316. static int fts5CsrPoslist(Fts5Cursor *pCsr, int iPhrase, const u8 **pa){
  167317. int n;
  167318. if( pCsr->pSorter ){
  167319. Fts5Sorter *pSorter = pCsr->pSorter;
  167320. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  167321. n = pSorter->aIdx[iPhrase] - i1;
  167322. *pa = &pSorter->aPoslist[i1];
  167323. }else{
  167324. n = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  167325. }
  167326. return n;
  167327. }
  167328. /*
  167329. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  167330. ** correctly for the current view. Return SQLITE_OK if successful, or an
  167331. ** SQLite error code otherwise.
  167332. */
  167333. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  167334. int rc = SQLITE_OK;
  167335. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  167336. int nIter; /* Number of iterators/phrases */
  167337. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  167338. if( pCsr->aInstIter==0 ){
  167339. int nByte = sizeof(Fts5PoslistReader) * nIter;
  167340. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  167341. }
  167342. aIter = pCsr->aInstIter;
  167343. if( aIter ){
  167344. int nInst = 0; /* Number instances seen so far */
  167345. int i;
  167346. /* Initialize all iterators */
  167347. for(i=0; i<nIter; i++){
  167348. const u8 *a;
  167349. int n = fts5CsrPoslist(pCsr, i, &a);
  167350. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  167351. }
  167352. while( 1 ){
  167353. int *aInst;
  167354. int iBest = -1;
  167355. for(i=0; i<nIter; i++){
  167356. if( (aIter[i].bEof==0)
  167357. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  167358. ){
  167359. iBest = i;
  167360. }
  167361. }
  167362. if( iBest<0 ) break;
  167363. nInst++;
  167364. if( nInst>=pCsr->nInstAlloc ){
  167365. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  167366. aInst = (int*)sqlite3_realloc(
  167367. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  167368. );
  167369. if( aInst ){
  167370. pCsr->aInst = aInst;
  167371. }else{
  167372. rc = SQLITE_NOMEM;
  167373. break;
  167374. }
  167375. }
  167376. aInst = &pCsr->aInst[3 * (nInst-1)];
  167377. aInst[0] = iBest;
  167378. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  167379. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  167380. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  167381. }
  167382. pCsr->nInstCount = nInst;
  167383. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  167384. }
  167385. return rc;
  167386. }
  167387. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  167388. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167389. int rc = SQLITE_OK;
  167390. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  167391. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  167392. *pnInst = pCsr->nInstCount;
  167393. }
  167394. return rc;
  167395. }
  167396. static int fts5ApiInst(
  167397. Fts5Context *pCtx,
  167398. int iIdx,
  167399. int *piPhrase,
  167400. int *piCol,
  167401. int *piOff
  167402. ){
  167403. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167404. int rc = SQLITE_OK;
  167405. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  167406. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  167407. ){
  167408. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  167409. rc = SQLITE_RANGE;
  167410. }else{
  167411. *piPhrase = pCsr->aInst[iIdx*3];
  167412. *piCol = pCsr->aInst[iIdx*3 + 1];
  167413. *piOff = pCsr->aInst[iIdx*3 + 2];
  167414. }
  167415. }
  167416. return rc;
  167417. }
  167418. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  167419. return fts5CursorRowid((Fts5Cursor*)pCtx);
  167420. }
  167421. static int fts5ApiColumnText(
  167422. Fts5Context *pCtx,
  167423. int iCol,
  167424. const char **pz,
  167425. int *pn
  167426. ){
  167427. int rc = SQLITE_OK;
  167428. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167429. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  167430. *pz = 0;
  167431. *pn = 0;
  167432. }else{
  167433. rc = fts5SeekCursor(pCsr, 0);
  167434. if( rc==SQLITE_OK ){
  167435. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  167436. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  167437. }
  167438. }
  167439. return rc;
  167440. }
  167441. static int fts5ColumnSizeCb(
  167442. void *pContext, /* Pointer to int */
  167443. int tflags,
  167444. const char *pToken, /* Buffer containing token */
  167445. int nToken, /* Size of token in bytes */
  167446. int iStart, /* Start offset of token */
  167447. int iEnd /* End offset of token */
  167448. ){
  167449. int *pCnt = (int*)pContext;
  167450. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  167451. (*pCnt)++;
  167452. }
  167453. return SQLITE_OK;
  167454. }
  167455. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  167456. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167457. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  167458. Fts5Config *pConfig = pTab->pConfig;
  167459. int rc = SQLITE_OK;
  167460. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  167461. if( pConfig->bColumnsize ){
  167462. i64 iRowid = fts5CursorRowid(pCsr);
  167463. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  167464. }else if( pConfig->zContent==0 ){
  167465. int i;
  167466. for(i=0; i<pConfig->nCol; i++){
  167467. if( pConfig->abUnindexed[i]==0 ){
  167468. pCsr->aColumnSize[i] = -1;
  167469. }
  167470. }
  167471. }else{
  167472. int i;
  167473. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  167474. if( pConfig->abUnindexed[i]==0 ){
  167475. const char *z; int n;
  167476. void *p = (void*)(&pCsr->aColumnSize[i]);
  167477. pCsr->aColumnSize[i] = 0;
  167478. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  167479. if( rc==SQLITE_OK ){
  167480. rc = sqlite3Fts5Tokenize(
  167481. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  167482. );
  167483. }
  167484. }
  167485. }
  167486. }
  167487. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  167488. }
  167489. if( iCol<0 ){
  167490. int i;
  167491. *pnToken = 0;
  167492. for(i=0; i<pConfig->nCol; i++){
  167493. *pnToken += pCsr->aColumnSize[i];
  167494. }
  167495. }else if( iCol<pConfig->nCol ){
  167496. *pnToken = pCsr->aColumnSize[iCol];
  167497. }else{
  167498. *pnToken = 0;
  167499. rc = SQLITE_RANGE;
  167500. }
  167501. return rc;
  167502. }
  167503. /*
  167504. ** Implementation of the xSetAuxdata() method.
  167505. */
  167506. static int fts5ApiSetAuxdata(
  167507. Fts5Context *pCtx, /* Fts5 context */
  167508. void *pPtr, /* Pointer to save as auxdata */
  167509. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  167510. ){
  167511. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167512. Fts5Auxdata *pData;
  167513. /* Search through the cursors list of Fts5Auxdata objects for one that
  167514. ** corresponds to the currently executing auxiliary function. */
  167515. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  167516. if( pData->pAux==pCsr->pAux ) break;
  167517. }
  167518. if( pData ){
  167519. if( pData->xDelete ){
  167520. pData->xDelete(pData->pPtr);
  167521. }
  167522. }else{
  167523. int rc = SQLITE_OK;
  167524. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  167525. if( pData==0 ){
  167526. if( xDelete ) xDelete(pPtr);
  167527. return rc;
  167528. }
  167529. pData->pAux = pCsr->pAux;
  167530. pData->pNext = pCsr->pAuxdata;
  167531. pCsr->pAuxdata = pData;
  167532. }
  167533. pData->xDelete = xDelete;
  167534. pData->pPtr = pPtr;
  167535. return SQLITE_OK;
  167536. }
  167537. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  167538. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167539. Fts5Auxdata *pData;
  167540. void *pRet = 0;
  167541. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  167542. if( pData->pAux==pCsr->pAux ) break;
  167543. }
  167544. if( pData ){
  167545. pRet = pData->pPtr;
  167546. if( bClear ){
  167547. pData->pPtr = 0;
  167548. pData->xDelete = 0;
  167549. }
  167550. }
  167551. return pRet;
  167552. }
  167553. static void fts5ApiPhraseNext(
  167554. Fts5Context *pCtx,
  167555. Fts5PhraseIter *pIter,
  167556. int *piCol, int *piOff
  167557. ){
  167558. if( pIter->a>=pIter->b ){
  167559. *piCol = -1;
  167560. *piOff = -1;
  167561. }else{
  167562. int iVal;
  167563. pIter->a += fts5GetVarint32(pIter->a, iVal);
  167564. if( iVal==1 ){
  167565. pIter->a += fts5GetVarint32(pIter->a, iVal);
  167566. *piCol = iVal;
  167567. *piOff = 0;
  167568. pIter->a += fts5GetVarint32(pIter->a, iVal);
  167569. }
  167570. *piOff += (iVal-2);
  167571. }
  167572. }
  167573. static void fts5ApiPhraseFirst(
  167574. Fts5Context *pCtx,
  167575. int iPhrase,
  167576. Fts5PhraseIter *pIter,
  167577. int *piCol, int *piOff
  167578. ){
  167579. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167580. int n = fts5CsrPoslist(pCsr, iPhrase, &pIter->a);
  167581. pIter->b = &pIter->a[n];
  167582. *piCol = 0;
  167583. *piOff = 0;
  167584. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  167585. }
  167586. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  167587. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  167588. );
  167589. static const Fts5ExtensionApi sFts5Api = {
  167590. 2, /* iVersion */
  167591. fts5ApiUserData,
  167592. fts5ApiColumnCount,
  167593. fts5ApiRowCount,
  167594. fts5ApiColumnTotalSize,
  167595. fts5ApiTokenize,
  167596. fts5ApiPhraseCount,
  167597. fts5ApiPhraseSize,
  167598. fts5ApiInstCount,
  167599. fts5ApiInst,
  167600. fts5ApiRowid,
  167601. fts5ApiColumnText,
  167602. fts5ApiColumnSize,
  167603. fts5ApiQueryPhrase,
  167604. fts5ApiSetAuxdata,
  167605. fts5ApiGetAuxdata,
  167606. fts5ApiPhraseFirst,
  167607. fts5ApiPhraseNext,
  167608. };
  167609. /*
  167610. ** Implementation of API function xQueryPhrase().
  167611. */
  167612. static int fts5ApiQueryPhrase(
  167613. Fts5Context *pCtx,
  167614. int iPhrase,
  167615. void *pUserData,
  167616. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  167617. ){
  167618. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  167619. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  167620. int rc;
  167621. Fts5Cursor *pNew = 0;
  167622. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  167623. if( rc==SQLITE_OK ){
  167624. Fts5Config *pConf = pTab->pConfig;
  167625. pNew->ePlan = FTS5_PLAN_MATCH;
  167626. pNew->iFirstRowid = SMALLEST_INT64;
  167627. pNew->iLastRowid = LARGEST_INT64;
  167628. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  167629. rc = sqlite3Fts5ExprClonePhrase(pConf, pCsr->pExpr, iPhrase, &pNew->pExpr);
  167630. }
  167631. if( rc==SQLITE_OK ){
  167632. for(rc = fts5CursorFirst(pTab, pNew, 0);
  167633. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  167634. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  167635. ){
  167636. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  167637. if( rc!=SQLITE_OK ){
  167638. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  167639. break;
  167640. }
  167641. }
  167642. }
  167643. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  167644. return rc;
  167645. }
  167646. static void fts5ApiInvoke(
  167647. Fts5Auxiliary *pAux,
  167648. Fts5Cursor *pCsr,
  167649. sqlite3_context *context,
  167650. int argc,
  167651. sqlite3_value **argv
  167652. ){
  167653. assert( pCsr->pAux==0 );
  167654. pCsr->pAux = pAux;
  167655. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  167656. pCsr->pAux = 0;
  167657. }
  167658. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  167659. Fts5Cursor *pCsr;
  167660. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  167661. if( pCsr->iCsrId==iCsrId ) break;
  167662. }
  167663. return pCsr;
  167664. }
  167665. static void fts5ApiCallback(
  167666. sqlite3_context *context,
  167667. int argc,
  167668. sqlite3_value **argv
  167669. ){
  167670. Fts5Auxiliary *pAux;
  167671. Fts5Cursor *pCsr;
  167672. i64 iCsrId;
  167673. assert( argc>=1 );
  167674. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  167675. iCsrId = sqlite3_value_int64(argv[0]);
  167676. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  167677. if( pCsr==0 ){
  167678. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  167679. sqlite3_result_error(context, zErr, -1);
  167680. sqlite3_free(zErr);
  167681. }else{
  167682. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  167683. }
  167684. }
  167685. /*
  167686. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  167687. ** object. Or NULL If the cursor id does not exist.
  167688. **
  167689. ** If successful, set *pnCol to the number of indexed columns in the
  167690. ** table before returning.
  167691. */
  167692. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  167693. Fts5Global *pGlobal,
  167694. i64 iCsrId,
  167695. int *pnCol
  167696. ){
  167697. Fts5Cursor *pCsr;
  167698. Fts5Table *pTab;
  167699. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  167700. pTab = (Fts5Table*)pCsr->base.pVtab;
  167701. *pnCol = pTab->pConfig->nCol;
  167702. return pTab->pIndex;
  167703. }
  167704. /*
  167705. ** Return a "position-list blob" corresponding to the current position of
  167706. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  167707. ** the current position-list for each phrase in the query associated with
  167708. ** cursor pCsr.
  167709. **
  167710. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  167711. ** the number of phrases in the query. Following the varints are the
  167712. ** concatenated position lists for each phrase, in order.
  167713. **
  167714. ** The first varint (if it exists) contains the size of the position list
  167715. ** for phrase 0. The second (same disclaimer) contains the size of position
  167716. ** list 1. And so on. There is no size field for the final position list,
  167717. ** as it can be derived from the total size of the blob.
  167718. */
  167719. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  167720. int i;
  167721. int rc = SQLITE_OK;
  167722. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  167723. Fts5Buffer val;
  167724. memset(&val, 0, sizeof(Fts5Buffer));
  167725. /* Append the varints */
  167726. for(i=0; i<(nPhrase-1); i++){
  167727. const u8 *dummy;
  167728. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  167729. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  167730. }
  167731. /* Append the position lists */
  167732. for(i=0; i<nPhrase; i++){
  167733. const u8 *pPoslist;
  167734. int nPoslist;
  167735. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  167736. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  167737. }
  167738. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  167739. return rc;
  167740. }
  167741. /*
  167742. ** This is the xColumn method, called by SQLite to request a value from
  167743. ** the row that the supplied cursor currently points to.
  167744. */
  167745. static int fts5ColumnMethod(
  167746. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  167747. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  167748. int iCol /* Index of column to read value from */
  167749. ){
  167750. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  167751. Fts5Config *pConfig = pTab->pConfig;
  167752. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  167753. int rc = SQLITE_OK;
  167754. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  167755. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  167756. if( iCol==pConfig->nCol ){
  167757. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  167758. }
  167759. }else
  167760. if( iCol==pConfig->nCol ){
  167761. /* User is requesting the value of the special column with the same name
  167762. ** as the table. Return the cursor integer id number. This value is only
  167763. ** useful in that it may be passed as the first argument to an FTS5
  167764. ** auxiliary function. */
  167765. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  167766. }else if( iCol==pConfig->nCol+1 ){
  167767. /* The value of the "rank" column. */
  167768. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  167769. fts5PoslistBlob(pCtx, pCsr);
  167770. }else if(
  167771. pCsr->ePlan==FTS5_PLAN_MATCH
  167772. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  167773. ){
  167774. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  167775. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  167776. }
  167777. }
  167778. }else if( !fts5IsContentless(pTab) ){
  167779. rc = fts5SeekCursor(pCsr, 1);
  167780. if( rc==SQLITE_OK ){
  167781. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  167782. }
  167783. }
  167784. return rc;
  167785. }
  167786. /*
  167787. ** This routine implements the xFindFunction method for the FTS3
  167788. ** virtual table.
  167789. */
  167790. static int fts5FindFunctionMethod(
  167791. sqlite3_vtab *pVtab, /* Virtual table handle */
  167792. int nArg, /* Number of SQL function arguments */
  167793. const char *zName, /* Name of SQL function */
  167794. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  167795. void **ppArg /* OUT: User data for *pxFunc */
  167796. ){
  167797. Fts5Table *pTab = (Fts5Table*)pVtab;
  167798. Fts5Auxiliary *pAux;
  167799. pAux = fts5FindAuxiliary(pTab, zName);
  167800. if( pAux ){
  167801. *pxFunc = fts5ApiCallback;
  167802. *ppArg = (void*)pAux;
  167803. return 1;
  167804. }
  167805. /* No function of the specified name was found. Return 0. */
  167806. return 0;
  167807. }
  167808. /*
  167809. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  167810. */
  167811. static int fts5RenameMethod(
  167812. sqlite3_vtab *pVtab, /* Virtual table handle */
  167813. const char *zName /* New name of table */
  167814. ){
  167815. Fts5Table *pTab = (Fts5Table*)pVtab;
  167816. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  167817. }
  167818. /*
  167819. ** The xSavepoint() method.
  167820. **
  167821. ** Flush the contents of the pending-terms table to disk.
  167822. */
  167823. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  167824. Fts5Table *pTab = (Fts5Table*)pVtab;
  167825. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  167826. fts5TripCursors(pTab);
  167827. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  167828. }
  167829. /*
  167830. ** The xRelease() method.
  167831. **
  167832. ** This is a no-op.
  167833. */
  167834. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  167835. Fts5Table *pTab = (Fts5Table*)pVtab;
  167836. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  167837. fts5TripCursors(pTab);
  167838. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  167839. }
  167840. /*
  167841. ** The xRollbackTo() method.
  167842. **
  167843. ** Discard the contents of the pending terms table.
  167844. */
  167845. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  167846. Fts5Table *pTab = (Fts5Table*)pVtab;
  167847. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  167848. fts5TripCursors(pTab);
  167849. return sqlite3Fts5StorageRollback(pTab->pStorage);
  167850. }
  167851. /*
  167852. ** Register a new auxiliary function with global context pGlobal.
  167853. */
  167854. static int fts5CreateAux(
  167855. fts5_api *pApi, /* Global context (one per db handle) */
  167856. const char *zName, /* Name of new function */
  167857. void *pUserData, /* User data for aux. function */
  167858. fts5_extension_function xFunc, /* Aux. function implementation */
  167859. void(*xDestroy)(void*) /* Destructor for pUserData */
  167860. ){
  167861. Fts5Global *pGlobal = (Fts5Global*)pApi;
  167862. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  167863. if( rc==SQLITE_OK ){
  167864. Fts5Auxiliary *pAux;
  167865. int nName; /* Size of zName in bytes, including \0 */
  167866. int nByte; /* Bytes of space to allocate */
  167867. nName = (int)strlen(zName) + 1;
  167868. nByte = sizeof(Fts5Auxiliary) + nName;
  167869. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  167870. if( pAux ){
  167871. memset(pAux, 0, nByte);
  167872. pAux->zFunc = (char*)&pAux[1];
  167873. memcpy(pAux->zFunc, zName, nName);
  167874. pAux->pGlobal = pGlobal;
  167875. pAux->pUserData = pUserData;
  167876. pAux->xFunc = xFunc;
  167877. pAux->xDestroy = xDestroy;
  167878. pAux->pNext = pGlobal->pAux;
  167879. pGlobal->pAux = pAux;
  167880. }else{
  167881. rc = SQLITE_NOMEM;
  167882. }
  167883. }
  167884. return rc;
  167885. }
  167886. /*
  167887. ** Register a new tokenizer. This is the implementation of the
  167888. ** fts5_api.xCreateTokenizer() method.
  167889. */
  167890. static int fts5CreateTokenizer(
  167891. fts5_api *pApi, /* Global context (one per db handle) */
  167892. const char *zName, /* Name of new function */
  167893. void *pUserData, /* User data for aux. function */
  167894. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  167895. void(*xDestroy)(void*) /* Destructor for pUserData */
  167896. ){
  167897. Fts5Global *pGlobal = (Fts5Global*)pApi;
  167898. Fts5TokenizerModule *pNew;
  167899. int nName; /* Size of zName and its \0 terminator */
  167900. int nByte; /* Bytes of space to allocate */
  167901. int rc = SQLITE_OK;
  167902. nName = (int)strlen(zName) + 1;
  167903. nByte = sizeof(Fts5TokenizerModule) + nName;
  167904. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  167905. if( pNew ){
  167906. memset(pNew, 0, nByte);
  167907. pNew->zName = (char*)&pNew[1];
  167908. memcpy(pNew->zName, zName, nName);
  167909. pNew->pUserData = pUserData;
  167910. pNew->x = *pTokenizer;
  167911. pNew->xDestroy = xDestroy;
  167912. pNew->pNext = pGlobal->pTok;
  167913. pGlobal->pTok = pNew;
  167914. if( pNew->pNext==0 ){
  167915. pGlobal->pDfltTok = pNew;
  167916. }
  167917. }else{
  167918. rc = SQLITE_NOMEM;
  167919. }
  167920. return rc;
  167921. }
  167922. static Fts5TokenizerModule *fts5LocateTokenizer(
  167923. Fts5Global *pGlobal,
  167924. const char *zName
  167925. ){
  167926. Fts5TokenizerModule *pMod = 0;
  167927. if( zName==0 ){
  167928. pMod = pGlobal->pDfltTok;
  167929. }else{
  167930. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  167931. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  167932. }
  167933. }
  167934. return pMod;
  167935. }
  167936. /*
  167937. ** Find a tokenizer. This is the implementation of the
  167938. ** fts5_api.xFindTokenizer() method.
  167939. */
  167940. static int fts5FindTokenizer(
  167941. fts5_api *pApi, /* Global context (one per db handle) */
  167942. const char *zName, /* Name of new function */
  167943. void **ppUserData,
  167944. fts5_tokenizer *pTokenizer /* Populate this object */
  167945. ){
  167946. int rc = SQLITE_OK;
  167947. Fts5TokenizerModule *pMod;
  167948. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  167949. if( pMod ){
  167950. *pTokenizer = pMod->x;
  167951. *ppUserData = pMod->pUserData;
  167952. }else{
  167953. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  167954. rc = SQLITE_ERROR;
  167955. }
  167956. return rc;
  167957. }
  167958. static int sqlite3Fts5GetTokenizer(
  167959. Fts5Global *pGlobal,
  167960. const char **azArg,
  167961. int nArg,
  167962. Fts5Tokenizer **ppTok,
  167963. fts5_tokenizer **ppTokApi,
  167964. char **pzErr
  167965. ){
  167966. Fts5TokenizerModule *pMod;
  167967. int rc = SQLITE_OK;
  167968. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  167969. if( pMod==0 ){
  167970. assert( nArg>0 );
  167971. rc = SQLITE_ERROR;
  167972. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  167973. }else{
  167974. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  167975. *ppTokApi = &pMod->x;
  167976. if( rc!=SQLITE_OK && pzErr ){
  167977. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  167978. }
  167979. }
  167980. if( rc!=SQLITE_OK ){
  167981. *ppTokApi = 0;
  167982. *ppTok = 0;
  167983. }
  167984. return rc;
  167985. }
  167986. static void fts5ModuleDestroy(void *pCtx){
  167987. Fts5TokenizerModule *pTok, *pNextTok;
  167988. Fts5Auxiliary *pAux, *pNextAux;
  167989. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  167990. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  167991. pNextAux = pAux->pNext;
  167992. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  167993. sqlite3_free(pAux);
  167994. }
  167995. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  167996. pNextTok = pTok->pNext;
  167997. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  167998. sqlite3_free(pTok);
  167999. }
  168000. sqlite3_free(pGlobal);
  168001. }
  168002. static void fts5Fts5Func(
  168003. sqlite3_context *pCtx, /* Function call context */
  168004. int nArg, /* Number of args */
  168005. sqlite3_value **apVal /* Function arguments */
  168006. ){
  168007. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  168008. char buf[8];
  168009. assert( nArg==0 );
  168010. assert( sizeof(buf)>=sizeof(pGlobal) );
  168011. memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
  168012. sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
  168013. }
  168014. /*
  168015. ** Implementation of fts5_source_id() function.
  168016. */
  168017. static void fts5SourceIdFunc(
  168018. sqlite3_context *pCtx, /* Function call context */
  168019. int nArg, /* Number of args */
  168020. sqlite3_value **apVal /* Function arguments */
  168021. ){
  168022. assert( nArg==0 );
  168023. sqlite3_result_text(pCtx, "fts5: 2015-10-16 17:31:12 767c1727fec4ce11b83f25b3f1bfcfe68a2c8b02", -1, SQLITE_TRANSIENT);
  168024. }
  168025. static int fts5Init(sqlite3 *db){
  168026. static const sqlite3_module fts5Mod = {
  168027. /* iVersion */ 2,
  168028. /* xCreate */ fts5CreateMethod,
  168029. /* xConnect */ fts5ConnectMethod,
  168030. /* xBestIndex */ fts5BestIndexMethod,
  168031. /* xDisconnect */ fts5DisconnectMethod,
  168032. /* xDestroy */ fts5DestroyMethod,
  168033. /* xOpen */ fts5OpenMethod,
  168034. /* xClose */ fts5CloseMethod,
  168035. /* xFilter */ fts5FilterMethod,
  168036. /* xNext */ fts5NextMethod,
  168037. /* xEof */ fts5EofMethod,
  168038. /* xColumn */ fts5ColumnMethod,
  168039. /* xRowid */ fts5RowidMethod,
  168040. /* xUpdate */ fts5UpdateMethod,
  168041. /* xBegin */ fts5BeginMethod,
  168042. /* xSync */ fts5SyncMethod,
  168043. /* xCommit */ fts5CommitMethod,
  168044. /* xRollback */ fts5RollbackMethod,
  168045. /* xFindFunction */ fts5FindFunctionMethod,
  168046. /* xRename */ fts5RenameMethod,
  168047. /* xSavepoint */ fts5SavepointMethod,
  168048. /* xRelease */ fts5ReleaseMethod,
  168049. /* xRollbackTo */ fts5RollbackToMethod,
  168050. };
  168051. int rc;
  168052. Fts5Global *pGlobal = 0;
  168053. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  168054. if( pGlobal==0 ){
  168055. rc = SQLITE_NOMEM;
  168056. }else{
  168057. void *p = (void*)pGlobal;
  168058. memset(pGlobal, 0, sizeof(Fts5Global));
  168059. pGlobal->db = db;
  168060. pGlobal->api.iVersion = 2;
  168061. pGlobal->api.xCreateFunction = fts5CreateAux;
  168062. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  168063. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  168064. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  168065. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  168066. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  168067. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  168068. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  168069. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  168070. if( rc==SQLITE_OK ){
  168071. rc = sqlite3_create_function(
  168072. db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  168073. );
  168074. }
  168075. if( rc==SQLITE_OK ){
  168076. rc = sqlite3_create_function(
  168077. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  168078. );
  168079. }
  168080. }
  168081. return rc;
  168082. }
  168083. /*
  168084. ** The following functions are used to register the module with SQLite. If
  168085. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  168086. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  168087. **
  168088. ** Or, if this module is being built as a loadable extension,
  168089. ** sqlite3Fts5Init() is omitted and the two standard entry points
  168090. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  168091. */
  168092. #ifndef SQLITE_CORE
  168093. #ifdef _WIN32
  168094. __declspec(dllexport)
  168095. #endif
  168096. SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
  168097. sqlite3 *db,
  168098. char **pzErrMsg,
  168099. const sqlite3_api_routines *pApi
  168100. ){
  168101. SQLITE_EXTENSION_INIT2(pApi);
  168102. (void)pzErrMsg; /* Unused parameter */
  168103. return fts5Init(db);
  168104. }
  168105. #ifdef _WIN32
  168106. __declspec(dllexport)
  168107. #endif
  168108. SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
  168109. sqlite3 *db,
  168110. char **pzErrMsg,
  168111. const sqlite3_api_routines *pApi
  168112. ){
  168113. SQLITE_EXTENSION_INIT2(pApi);
  168114. (void)pzErrMsg; /* Unused parameter */
  168115. return fts5Init(db);
  168116. }
  168117. #else
  168118. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  168119. return fts5Init(db);
  168120. }
  168121. #endif
  168122. /*
  168123. ** 2014 May 31
  168124. **
  168125. ** The author disclaims copyright to this source code. In place of
  168126. ** a legal notice, here is a blessing:
  168127. **
  168128. ** May you do good and not evil.
  168129. ** May you find forgiveness for yourself and forgive others.
  168130. ** May you share freely, never taking more than you give.
  168131. **
  168132. ******************************************************************************
  168133. **
  168134. */
  168135. struct Fts5Storage {
  168136. Fts5Config *pConfig;
  168137. Fts5Index *pIndex;
  168138. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  168139. i64 nTotalRow; /* Total number of rows in FTS table */
  168140. i64 *aTotalSize; /* Total sizes of each column */
  168141. sqlite3_stmt *aStmt[11];
  168142. };
  168143. #if FTS5_STMT_SCAN_ASC!=0
  168144. # error "FTS5_STMT_SCAN_ASC mismatch"
  168145. #endif
  168146. #if FTS5_STMT_SCAN_DESC!=1
  168147. # error "FTS5_STMT_SCAN_DESC mismatch"
  168148. #endif
  168149. #if FTS5_STMT_LOOKUP!=2
  168150. # error "FTS5_STMT_LOOKUP mismatch"
  168151. #endif
  168152. #define FTS5_STMT_INSERT_CONTENT 3
  168153. #define FTS5_STMT_REPLACE_CONTENT 4
  168154. #define FTS5_STMT_DELETE_CONTENT 5
  168155. #define FTS5_STMT_REPLACE_DOCSIZE 6
  168156. #define FTS5_STMT_DELETE_DOCSIZE 7
  168157. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  168158. #define FTS5_STMT_REPLACE_CONFIG 9
  168159. #define FTS5_STMT_SCAN 10
  168160. /*
  168161. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  168162. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  168163. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  168164. ** occurs.
  168165. */
  168166. static int fts5StorageGetStmt(
  168167. Fts5Storage *p, /* Storage handle */
  168168. int eStmt, /* FTS5_STMT_XXX constant */
  168169. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  168170. char **pzErrMsg /* OUT: Error message (if any) */
  168171. ){
  168172. int rc = SQLITE_OK;
  168173. /* If there is no %_docsize table, there should be no requests for
  168174. ** statements to operate on it. */
  168175. assert( p->pConfig->bColumnsize || (
  168176. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  168177. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  168178. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  168179. ));
  168180. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  168181. if( p->aStmt[eStmt]==0 ){
  168182. const char *azStmt[] = {
  168183. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  168184. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  168185. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  168186. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  168187. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  168188. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  168189. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  168190. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  168191. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  168192. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  168193. "SELECT %s FROM %s AS T", /* SCAN */
  168194. };
  168195. Fts5Config *pC = p->pConfig;
  168196. char *zSql = 0;
  168197. switch( eStmt ){
  168198. case FTS5_STMT_SCAN:
  168199. zSql = sqlite3_mprintf(azStmt[eStmt],
  168200. pC->zContentExprlist, pC->zContent
  168201. );
  168202. break;
  168203. case FTS5_STMT_SCAN_ASC:
  168204. case FTS5_STMT_SCAN_DESC:
  168205. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  168206. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  168207. pC->zContentRowid
  168208. );
  168209. break;
  168210. case FTS5_STMT_LOOKUP:
  168211. zSql = sqlite3_mprintf(azStmt[eStmt],
  168212. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  168213. );
  168214. break;
  168215. case FTS5_STMT_INSERT_CONTENT:
  168216. case FTS5_STMT_REPLACE_CONTENT: {
  168217. int nCol = pC->nCol + 1;
  168218. char *zBind;
  168219. int i;
  168220. zBind = sqlite3_malloc(1 + nCol*2);
  168221. if( zBind ){
  168222. for(i=0; i<nCol; i++){
  168223. zBind[i*2] = '?';
  168224. zBind[i*2 + 1] = ',';
  168225. }
  168226. zBind[i*2-1] = '\0';
  168227. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  168228. sqlite3_free(zBind);
  168229. }
  168230. break;
  168231. }
  168232. default:
  168233. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  168234. break;
  168235. }
  168236. if( zSql==0 ){
  168237. rc = SQLITE_NOMEM;
  168238. }else{
  168239. rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
  168240. sqlite3_free(zSql);
  168241. if( rc!=SQLITE_OK && pzErrMsg ){
  168242. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  168243. }
  168244. }
  168245. }
  168246. *ppStmt = p->aStmt[eStmt];
  168247. return rc;
  168248. }
  168249. static int fts5ExecPrintf(
  168250. sqlite3 *db,
  168251. char **pzErr,
  168252. const char *zFormat,
  168253. ...
  168254. ){
  168255. int rc;
  168256. va_list ap; /* ... printf arguments */
  168257. char *zSql;
  168258. va_start(ap, zFormat);
  168259. zSql = sqlite3_vmprintf(zFormat, ap);
  168260. if( zSql==0 ){
  168261. rc = SQLITE_NOMEM;
  168262. }else{
  168263. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  168264. sqlite3_free(zSql);
  168265. }
  168266. va_end(ap);
  168267. return rc;
  168268. }
  168269. /*
  168270. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  168271. ** code otherwise.
  168272. */
  168273. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  168274. int rc = fts5ExecPrintf(pConfig->db, 0,
  168275. "DROP TABLE IF EXISTS %Q.'%q_data';"
  168276. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  168277. "DROP TABLE IF EXISTS %Q.'%q_config';",
  168278. pConfig->zDb, pConfig->zName,
  168279. pConfig->zDb, pConfig->zName,
  168280. pConfig->zDb, pConfig->zName
  168281. );
  168282. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  168283. rc = fts5ExecPrintf(pConfig->db, 0,
  168284. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  168285. pConfig->zDb, pConfig->zName
  168286. );
  168287. }
  168288. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168289. rc = fts5ExecPrintf(pConfig->db, 0,
  168290. "DROP TABLE IF EXISTS %Q.'%q_content';",
  168291. pConfig->zDb, pConfig->zName
  168292. );
  168293. }
  168294. return rc;
  168295. }
  168296. static void fts5StorageRenameOne(
  168297. Fts5Config *pConfig, /* Current FTS5 configuration */
  168298. int *pRc, /* IN/OUT: Error code */
  168299. const char *zTail, /* Tail of table name e.g. "data", "config" */
  168300. const char *zName /* New name of FTS5 table */
  168301. ){
  168302. if( *pRc==SQLITE_OK ){
  168303. *pRc = fts5ExecPrintf(pConfig->db, 0,
  168304. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  168305. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  168306. );
  168307. }
  168308. }
  168309. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  168310. Fts5Config *pConfig = pStorage->pConfig;
  168311. int rc = sqlite3Fts5StorageSync(pStorage, 1);
  168312. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  168313. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  168314. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  168315. if( pConfig->bColumnsize ){
  168316. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  168317. }
  168318. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168319. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  168320. }
  168321. return rc;
  168322. }
  168323. /*
  168324. ** Create the shadow table named zPost, with definition zDefn. Return
  168325. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  168326. */
  168327. static int sqlite3Fts5CreateTable(
  168328. Fts5Config *pConfig, /* FTS5 configuration */
  168329. const char *zPost, /* Shadow table to create (e.g. "content") */
  168330. const char *zDefn, /* Columns etc. for shadow table */
  168331. int bWithout, /* True for without rowid */
  168332. char **pzErr /* OUT: Error message */
  168333. ){
  168334. int rc;
  168335. char *zErr = 0;
  168336. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  168337. pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
  168338. );
  168339. if( zErr ){
  168340. *pzErr = sqlite3_mprintf(
  168341. "fts5: error creating shadow table %q_%s: %s",
  168342. pConfig->zName, zPost, zErr
  168343. );
  168344. sqlite3_free(zErr);
  168345. }
  168346. return rc;
  168347. }
  168348. /*
  168349. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  168350. ** and initialize the underlying tables
  168351. **
  168352. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  168353. ** Otherwise, set *pp to NULL and return an SQLite error code.
  168354. */
  168355. static int sqlite3Fts5StorageOpen(
  168356. Fts5Config *pConfig,
  168357. Fts5Index *pIndex,
  168358. int bCreate,
  168359. Fts5Storage **pp,
  168360. char **pzErr /* OUT: Error message */
  168361. ){
  168362. int rc = SQLITE_OK;
  168363. Fts5Storage *p; /* New object */
  168364. int nByte; /* Bytes of space to allocate */
  168365. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  168366. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  168367. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  168368. if( !p ) return SQLITE_NOMEM;
  168369. memset(p, 0, nByte);
  168370. p->aTotalSize = (i64*)&p[1];
  168371. p->pConfig = pConfig;
  168372. p->pIndex = pIndex;
  168373. if( bCreate ){
  168374. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168375. int nDefn = 32 + pConfig->nCol*10;
  168376. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  168377. if( zDefn==0 ){
  168378. rc = SQLITE_NOMEM;
  168379. }else{
  168380. int i;
  168381. int iOff;
  168382. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  168383. iOff = strlen(zDefn);
  168384. for(i=0; i<pConfig->nCol; i++){
  168385. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  168386. iOff += strlen(&zDefn[iOff]);
  168387. }
  168388. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  168389. }
  168390. sqlite3_free(zDefn);
  168391. }
  168392. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  168393. rc = sqlite3Fts5CreateTable(
  168394. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  168395. );
  168396. }
  168397. if( rc==SQLITE_OK ){
  168398. rc = sqlite3Fts5CreateTable(
  168399. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  168400. );
  168401. }
  168402. if( rc==SQLITE_OK ){
  168403. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  168404. }
  168405. }
  168406. if( rc ){
  168407. sqlite3Fts5StorageClose(p);
  168408. *pp = 0;
  168409. }
  168410. return rc;
  168411. }
  168412. /*
  168413. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  168414. */
  168415. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  168416. int rc = SQLITE_OK;
  168417. if( p ){
  168418. int i;
  168419. /* Finalize all SQL statements */
  168420. for(i=0; i<ArraySize(p->aStmt); i++){
  168421. sqlite3_finalize(p->aStmt[i]);
  168422. }
  168423. sqlite3_free(p);
  168424. }
  168425. return rc;
  168426. }
  168427. typedef struct Fts5InsertCtx Fts5InsertCtx;
  168428. struct Fts5InsertCtx {
  168429. Fts5Storage *pStorage;
  168430. int iCol;
  168431. int szCol; /* Size of column value in tokens */
  168432. };
  168433. /*
  168434. ** Tokenization callback used when inserting tokens into the FTS index.
  168435. */
  168436. static int fts5StorageInsertCallback(
  168437. void *pContext, /* Pointer to Fts5InsertCtx object */
  168438. int tflags,
  168439. const char *pToken, /* Buffer containing token */
  168440. int nToken, /* Size of token in bytes */
  168441. int iStart, /* Start offset of token */
  168442. int iEnd /* End offset of token */
  168443. ){
  168444. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  168445. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  168446. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  168447. pCtx->szCol++;
  168448. }
  168449. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  168450. }
  168451. /*
  168452. ** If a row with rowid iDel is present in the %_content table, add the
  168453. ** delete-markers to the FTS index necessary to delete it. Do not actually
  168454. ** remove the %_content row at this time though.
  168455. */
  168456. static int fts5StorageDeleteFromIndex(Fts5Storage *p, i64 iDel){
  168457. Fts5Config *pConfig = p->pConfig;
  168458. sqlite3_stmt *pSeek; /* SELECT to read row iDel from %_data */
  168459. int rc; /* Return code */
  168460. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  168461. if( rc==SQLITE_OK ){
  168462. int rc2;
  168463. sqlite3_bind_int64(pSeek, 1, iDel);
  168464. if( sqlite3_step(pSeek)==SQLITE_ROW ){
  168465. int iCol;
  168466. Fts5InsertCtx ctx;
  168467. ctx.pStorage = p;
  168468. ctx.iCol = -1;
  168469. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  168470. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  168471. if( pConfig->abUnindexed[iCol-1] ) continue;
  168472. ctx.szCol = 0;
  168473. rc = sqlite3Fts5Tokenize(pConfig,
  168474. FTS5_TOKENIZE_DOCUMENT,
  168475. (const char*)sqlite3_column_text(pSeek, iCol),
  168476. sqlite3_column_bytes(pSeek, iCol),
  168477. (void*)&ctx,
  168478. fts5StorageInsertCallback
  168479. );
  168480. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  168481. }
  168482. p->nTotalRow--;
  168483. }
  168484. rc2 = sqlite3_reset(pSeek);
  168485. if( rc==SQLITE_OK ) rc = rc2;
  168486. }
  168487. return rc;
  168488. }
  168489. /*
  168490. ** Insert a record into the %_docsize table. Specifically, do:
  168491. **
  168492. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  168493. **
  168494. ** If there is no %_docsize table (as happens if the columnsize=0 option
  168495. ** is specified when the FTS5 table is created), this function is a no-op.
  168496. */
  168497. static int fts5StorageInsertDocsize(
  168498. Fts5Storage *p, /* Storage module to write to */
  168499. i64 iRowid, /* id value */
  168500. Fts5Buffer *pBuf /* sz value */
  168501. ){
  168502. int rc = SQLITE_OK;
  168503. if( p->pConfig->bColumnsize ){
  168504. sqlite3_stmt *pReplace = 0;
  168505. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  168506. if( rc==SQLITE_OK ){
  168507. sqlite3_bind_int64(pReplace, 1, iRowid);
  168508. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  168509. sqlite3_step(pReplace);
  168510. rc = sqlite3_reset(pReplace);
  168511. }
  168512. }
  168513. return rc;
  168514. }
  168515. /*
  168516. ** Load the contents of the "averages" record from disk into the
  168517. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  168518. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  168519. ** that the contents of aTotalSize[] and nTotalRow are valid until
  168520. ** further notice.
  168521. **
  168522. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  168523. ** occurs.
  168524. */
  168525. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  168526. int rc = SQLITE_OK;
  168527. if( p->bTotalsValid==0 ){
  168528. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  168529. p->bTotalsValid = bCache;
  168530. }
  168531. return rc;
  168532. }
  168533. /*
  168534. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  168535. ** variables in the "averages" record on disk.
  168536. **
  168537. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  168538. ** occurs.
  168539. */
  168540. static int fts5StorageSaveTotals(Fts5Storage *p){
  168541. int nCol = p->pConfig->nCol;
  168542. int i;
  168543. Fts5Buffer buf;
  168544. int rc = SQLITE_OK;
  168545. memset(&buf, 0, sizeof(buf));
  168546. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  168547. for(i=0; i<nCol; i++){
  168548. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  168549. }
  168550. if( rc==SQLITE_OK ){
  168551. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  168552. }
  168553. sqlite3_free(buf.p);
  168554. return rc;
  168555. }
  168556. /*
  168557. ** Remove a row from the FTS table.
  168558. */
  168559. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel){
  168560. Fts5Config *pConfig = p->pConfig;
  168561. int rc;
  168562. sqlite3_stmt *pDel = 0;
  168563. rc = fts5StorageLoadTotals(p, 1);
  168564. /* Delete the index records */
  168565. if( rc==SQLITE_OK ){
  168566. rc = fts5StorageDeleteFromIndex(p, iDel);
  168567. }
  168568. /* Delete the %_docsize record */
  168569. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  168570. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  168571. if( rc==SQLITE_OK ){
  168572. sqlite3_bind_int64(pDel, 1, iDel);
  168573. sqlite3_step(pDel);
  168574. rc = sqlite3_reset(pDel);
  168575. }
  168576. }
  168577. /* Delete the %_content record */
  168578. if( rc==SQLITE_OK ){
  168579. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  168580. }
  168581. if( rc==SQLITE_OK ){
  168582. sqlite3_bind_int64(pDel, 1, iDel);
  168583. sqlite3_step(pDel);
  168584. rc = sqlite3_reset(pDel);
  168585. }
  168586. /* Write the averages record */
  168587. if( rc==SQLITE_OK ){
  168588. rc = fts5StorageSaveTotals(p);
  168589. }
  168590. return rc;
  168591. }
  168592. static int sqlite3Fts5StorageSpecialDelete(
  168593. Fts5Storage *p,
  168594. i64 iDel,
  168595. sqlite3_value **apVal
  168596. ){
  168597. Fts5Config *pConfig = p->pConfig;
  168598. int rc;
  168599. sqlite3_stmt *pDel = 0;
  168600. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL );
  168601. rc = fts5StorageLoadTotals(p, 1);
  168602. /* Delete the index records */
  168603. if( rc==SQLITE_OK ){
  168604. int iCol;
  168605. Fts5InsertCtx ctx;
  168606. ctx.pStorage = p;
  168607. ctx.iCol = -1;
  168608. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  168609. for(iCol=0; rc==SQLITE_OK && iCol<pConfig->nCol; iCol++){
  168610. if( pConfig->abUnindexed[iCol] ) continue;
  168611. ctx.szCol = 0;
  168612. rc = sqlite3Fts5Tokenize(pConfig,
  168613. FTS5_TOKENIZE_DOCUMENT,
  168614. (const char*)sqlite3_value_text(apVal[iCol]),
  168615. sqlite3_value_bytes(apVal[iCol]),
  168616. (void*)&ctx,
  168617. fts5StorageInsertCallback
  168618. );
  168619. p->aTotalSize[iCol] -= (i64)ctx.szCol;
  168620. }
  168621. p->nTotalRow--;
  168622. }
  168623. /* Delete the %_docsize record */
  168624. if( pConfig->bColumnsize ){
  168625. if( rc==SQLITE_OK ){
  168626. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  168627. }
  168628. if( rc==SQLITE_OK ){
  168629. sqlite3_bind_int64(pDel, 1, iDel);
  168630. sqlite3_step(pDel);
  168631. rc = sqlite3_reset(pDel);
  168632. }
  168633. }
  168634. /* Write the averages record */
  168635. if( rc==SQLITE_OK ){
  168636. rc = fts5StorageSaveTotals(p);
  168637. }
  168638. return rc;
  168639. }
  168640. /*
  168641. ** Delete all entries in the FTS5 index.
  168642. */
  168643. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  168644. Fts5Config *pConfig = p->pConfig;
  168645. int rc;
  168646. /* Delete the contents of the %_data and %_docsize tables. */
  168647. rc = fts5ExecPrintf(pConfig->db, 0,
  168648. "DELETE FROM %Q.'%q_data';"
  168649. "DELETE FROM %Q.'%q_idx';",
  168650. pConfig->zDb, pConfig->zName,
  168651. pConfig->zDb, pConfig->zName
  168652. );
  168653. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  168654. rc = fts5ExecPrintf(pConfig->db, 0,
  168655. "DELETE FROM %Q.'%q_docsize';",
  168656. pConfig->zDb, pConfig->zName
  168657. );
  168658. }
  168659. /* Reinitialize the %_data table. This call creates the initial structure
  168660. ** and averages records. */
  168661. if( rc==SQLITE_OK ){
  168662. rc = sqlite3Fts5IndexReinit(p->pIndex);
  168663. }
  168664. if( rc==SQLITE_OK ){
  168665. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  168666. }
  168667. return rc;
  168668. }
  168669. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  168670. Fts5Buffer buf = {0,0,0};
  168671. Fts5Config *pConfig = p->pConfig;
  168672. sqlite3_stmt *pScan = 0;
  168673. Fts5InsertCtx ctx;
  168674. int rc;
  168675. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  168676. ctx.pStorage = p;
  168677. rc = sqlite3Fts5StorageDeleteAll(p);
  168678. if( rc==SQLITE_OK ){
  168679. rc = fts5StorageLoadTotals(p, 1);
  168680. }
  168681. if( rc==SQLITE_OK ){
  168682. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  168683. }
  168684. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  168685. i64 iRowid = sqlite3_column_int64(pScan, 0);
  168686. sqlite3Fts5BufferZero(&buf);
  168687. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  168688. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  168689. ctx.szCol = 0;
  168690. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  168691. rc = sqlite3Fts5Tokenize(pConfig,
  168692. FTS5_TOKENIZE_DOCUMENT,
  168693. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  168694. sqlite3_column_bytes(pScan, ctx.iCol+1),
  168695. (void*)&ctx,
  168696. fts5StorageInsertCallback
  168697. );
  168698. }
  168699. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  168700. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  168701. }
  168702. p->nTotalRow++;
  168703. if( rc==SQLITE_OK ){
  168704. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  168705. }
  168706. }
  168707. sqlite3_free(buf.p);
  168708. /* Write the averages record */
  168709. if( rc==SQLITE_OK ){
  168710. rc = fts5StorageSaveTotals(p);
  168711. }
  168712. return rc;
  168713. }
  168714. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  168715. return sqlite3Fts5IndexOptimize(p->pIndex);
  168716. }
  168717. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  168718. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  168719. }
  168720. /*
  168721. ** Allocate a new rowid. This is used for "external content" tables when
  168722. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  168723. ** by inserting a dummy row into the %_docsize table. The dummy will be
  168724. ** overwritten later.
  168725. **
  168726. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  168727. ** this case the user is required to provide a rowid explicitly.
  168728. */
  168729. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  168730. int rc = SQLITE_MISMATCH;
  168731. if( p->pConfig->bColumnsize ){
  168732. sqlite3_stmt *pReplace = 0;
  168733. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  168734. if( rc==SQLITE_OK ){
  168735. sqlite3_bind_null(pReplace, 1);
  168736. sqlite3_bind_null(pReplace, 2);
  168737. sqlite3_step(pReplace);
  168738. rc = sqlite3_reset(pReplace);
  168739. }
  168740. if( rc==SQLITE_OK ){
  168741. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  168742. }
  168743. }
  168744. return rc;
  168745. }
  168746. /*
  168747. ** Insert a new row into the FTS content table.
  168748. */
  168749. static int sqlite3Fts5StorageContentInsert(
  168750. Fts5Storage *p,
  168751. sqlite3_value **apVal,
  168752. i64 *piRowid
  168753. ){
  168754. Fts5Config *pConfig = p->pConfig;
  168755. int rc = SQLITE_OK;
  168756. /* Insert the new row into the %_content table. */
  168757. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  168758. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  168759. *piRowid = sqlite3_value_int64(apVal[1]);
  168760. }else{
  168761. rc = fts5StorageNewRowid(p, piRowid);
  168762. }
  168763. }else{
  168764. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  168765. int i; /* Counter variable */
  168766. #if 0
  168767. if( eConflict==SQLITE_REPLACE ){
  168768. eStmt = FTS5_STMT_REPLACE_CONTENT;
  168769. rc = fts5StorageDeleteFromIndex(p, sqlite3_value_int64(apVal[1]));
  168770. }else{
  168771. eStmt = FTS5_STMT_INSERT_CONTENT;
  168772. }
  168773. #endif
  168774. if( rc==SQLITE_OK ){
  168775. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  168776. }
  168777. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  168778. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  168779. }
  168780. if( rc==SQLITE_OK ){
  168781. sqlite3_step(pInsert);
  168782. rc = sqlite3_reset(pInsert);
  168783. }
  168784. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  168785. }
  168786. return rc;
  168787. }
  168788. /*
  168789. ** Insert new entries into the FTS index and %_docsize table.
  168790. */
  168791. static int sqlite3Fts5StorageIndexInsert(
  168792. Fts5Storage *p,
  168793. sqlite3_value **apVal,
  168794. i64 iRowid
  168795. ){
  168796. Fts5Config *pConfig = p->pConfig;
  168797. int rc = SQLITE_OK; /* Return code */
  168798. Fts5InsertCtx ctx; /* Tokenization callback context object */
  168799. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  168800. memset(&buf, 0, sizeof(Fts5Buffer));
  168801. ctx.pStorage = p;
  168802. rc = fts5StorageLoadTotals(p, 1);
  168803. if( rc==SQLITE_OK ){
  168804. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  168805. }
  168806. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  168807. ctx.szCol = 0;
  168808. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  168809. rc = sqlite3Fts5Tokenize(pConfig,
  168810. FTS5_TOKENIZE_DOCUMENT,
  168811. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  168812. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  168813. (void*)&ctx,
  168814. fts5StorageInsertCallback
  168815. );
  168816. }
  168817. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  168818. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  168819. }
  168820. p->nTotalRow++;
  168821. /* Write the %_docsize record */
  168822. if( rc==SQLITE_OK ){
  168823. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  168824. }
  168825. sqlite3_free(buf.p);
  168826. /* Write the averages record */
  168827. if( rc==SQLITE_OK ){
  168828. rc = fts5StorageSaveTotals(p);
  168829. }
  168830. return rc;
  168831. }
  168832. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  168833. Fts5Config *pConfig = p->pConfig;
  168834. char *zSql;
  168835. int rc;
  168836. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  168837. pConfig->zDb, pConfig->zName, zSuffix
  168838. );
  168839. if( zSql==0 ){
  168840. rc = SQLITE_NOMEM;
  168841. }else{
  168842. sqlite3_stmt *pCnt = 0;
  168843. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  168844. if( rc==SQLITE_OK ){
  168845. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  168846. *pnRow = sqlite3_column_int64(pCnt, 0);
  168847. }
  168848. rc = sqlite3_finalize(pCnt);
  168849. }
  168850. }
  168851. sqlite3_free(zSql);
  168852. return rc;
  168853. }
  168854. /*
  168855. ** Context object used by sqlite3Fts5StorageIntegrity().
  168856. */
  168857. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  168858. struct Fts5IntegrityCtx {
  168859. i64 iRowid;
  168860. int iCol;
  168861. int szCol;
  168862. u64 cksum;
  168863. Fts5Config *pConfig;
  168864. };
  168865. /*
  168866. ** Tokenization callback used by integrity check.
  168867. */
  168868. static int fts5StorageIntegrityCallback(
  168869. void *pContext, /* Pointer to Fts5InsertCtx object */
  168870. int tflags,
  168871. const char *pToken, /* Buffer containing token */
  168872. int nToken, /* Size of token in bytes */
  168873. int iStart, /* Start offset of token */
  168874. int iEnd /* End offset of token */
  168875. ){
  168876. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  168877. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  168878. pCtx->szCol++;
  168879. }
  168880. pCtx->cksum ^= sqlite3Fts5IndexCksum(
  168881. pCtx->pConfig, pCtx->iRowid, pCtx->iCol, pCtx->szCol-1, pToken, nToken
  168882. );
  168883. return SQLITE_OK;
  168884. }
  168885. /*
  168886. ** Check that the contents of the FTS index match that of the %_content
  168887. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  168888. ** some other SQLite error code if an error occurs while attempting to
  168889. ** determine this.
  168890. */
  168891. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  168892. Fts5Config *pConfig = p->pConfig;
  168893. int rc; /* Return code */
  168894. int *aColSize; /* Array of size pConfig->nCol */
  168895. i64 *aTotalSize; /* Array of size pConfig->nCol */
  168896. Fts5IntegrityCtx ctx;
  168897. sqlite3_stmt *pScan;
  168898. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  168899. ctx.pConfig = p->pConfig;
  168900. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  168901. if( !aTotalSize ) return SQLITE_NOMEM;
  168902. aColSize = (int*)&aTotalSize[pConfig->nCol];
  168903. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  168904. /* Generate the expected index checksum based on the contents of the
  168905. ** %_content table. This block stores the checksum in ctx.cksum. */
  168906. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  168907. if( rc==SQLITE_OK ){
  168908. int rc2;
  168909. while( SQLITE_ROW==sqlite3_step(pScan) ){
  168910. int i;
  168911. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  168912. ctx.szCol = 0;
  168913. if( pConfig->bColumnsize ){
  168914. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  168915. }
  168916. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  168917. if( pConfig->abUnindexed[i] ) continue;
  168918. ctx.iCol = i;
  168919. ctx.szCol = 0;
  168920. rc = sqlite3Fts5Tokenize(pConfig,
  168921. FTS5_TOKENIZE_DOCUMENT,
  168922. (const char*)sqlite3_column_text(pScan, i+1),
  168923. sqlite3_column_bytes(pScan, i+1),
  168924. (void*)&ctx,
  168925. fts5StorageIntegrityCallback
  168926. );
  168927. if( pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  168928. rc = FTS5_CORRUPT;
  168929. }
  168930. aTotalSize[i] += ctx.szCol;
  168931. }
  168932. if( rc!=SQLITE_OK ) break;
  168933. }
  168934. rc2 = sqlite3_reset(pScan);
  168935. if( rc==SQLITE_OK ) rc = rc2;
  168936. }
  168937. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  168938. if( rc==SQLITE_OK ){
  168939. int i;
  168940. rc = fts5StorageLoadTotals(p, 0);
  168941. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  168942. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  168943. }
  168944. }
  168945. /* Check that the %_docsize and %_content tables contain the expected
  168946. ** number of rows. */
  168947. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168948. i64 nRow;
  168949. rc = fts5StorageCount(p, "content", &nRow);
  168950. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  168951. }
  168952. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  168953. i64 nRow;
  168954. rc = fts5StorageCount(p, "docsize", &nRow);
  168955. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  168956. }
  168957. /* Pass the expected checksum down to the FTS index module. It will
  168958. ** verify, amongst other things, that it matches the checksum generated by
  168959. ** inspecting the index itself. */
  168960. if( rc==SQLITE_OK ){
  168961. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  168962. }
  168963. sqlite3_free(aTotalSize);
  168964. return rc;
  168965. }
  168966. /*
  168967. ** Obtain an SQLite statement handle that may be used to read data from the
  168968. ** %_content table.
  168969. */
  168970. static int sqlite3Fts5StorageStmt(
  168971. Fts5Storage *p,
  168972. int eStmt,
  168973. sqlite3_stmt **pp,
  168974. char **pzErrMsg
  168975. ){
  168976. int rc;
  168977. assert( eStmt==FTS5_STMT_SCAN_ASC
  168978. || eStmt==FTS5_STMT_SCAN_DESC
  168979. || eStmt==FTS5_STMT_LOOKUP
  168980. );
  168981. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  168982. if( rc==SQLITE_OK ){
  168983. assert( p->aStmt[eStmt]==*pp );
  168984. p->aStmt[eStmt] = 0;
  168985. }
  168986. return rc;
  168987. }
  168988. /*
  168989. ** Release an SQLite statement handle obtained via an earlier call to
  168990. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  168991. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  168992. */
  168993. static void sqlite3Fts5StorageStmtRelease(
  168994. Fts5Storage *p,
  168995. int eStmt,
  168996. sqlite3_stmt *pStmt
  168997. ){
  168998. assert( eStmt==FTS5_STMT_SCAN_ASC
  168999. || eStmt==FTS5_STMT_SCAN_DESC
  169000. || eStmt==FTS5_STMT_LOOKUP
  169001. );
  169002. if( p->aStmt[eStmt]==0 ){
  169003. sqlite3_reset(pStmt);
  169004. p->aStmt[eStmt] = pStmt;
  169005. }else{
  169006. sqlite3_finalize(pStmt);
  169007. }
  169008. }
  169009. static int fts5StorageDecodeSizeArray(
  169010. int *aCol, int nCol, /* Array to populate */
  169011. const u8 *aBlob, int nBlob /* Record to read varints from */
  169012. ){
  169013. int i;
  169014. int iOff = 0;
  169015. for(i=0; i<nCol; i++){
  169016. if( iOff>=nBlob ) return 1;
  169017. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  169018. }
  169019. return (iOff!=nBlob);
  169020. }
  169021. /*
  169022. ** Argument aCol points to an array of integers containing one entry for
  169023. ** each table column. This function reads the %_docsize record for the
  169024. ** specified rowid and populates aCol[] with the results.
  169025. **
  169026. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  169027. ** otherwise.
  169028. */
  169029. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  169030. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  169031. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  169032. int rc; /* Return Code */
  169033. assert( p->pConfig->bColumnsize );
  169034. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  169035. if( rc==SQLITE_OK ){
  169036. int bCorrupt = 1;
  169037. sqlite3_bind_int64(pLookup, 1, iRowid);
  169038. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  169039. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  169040. int nBlob = sqlite3_column_bytes(pLookup, 0);
  169041. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  169042. bCorrupt = 0;
  169043. }
  169044. }
  169045. rc = sqlite3_reset(pLookup);
  169046. if( bCorrupt && rc==SQLITE_OK ){
  169047. rc = FTS5_CORRUPT;
  169048. }
  169049. }
  169050. return rc;
  169051. }
  169052. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  169053. int rc = fts5StorageLoadTotals(p, 0);
  169054. if( rc==SQLITE_OK ){
  169055. *pnToken = 0;
  169056. if( iCol<0 ){
  169057. int i;
  169058. for(i=0; i<p->pConfig->nCol; i++){
  169059. *pnToken += p->aTotalSize[i];
  169060. }
  169061. }else if( iCol<p->pConfig->nCol ){
  169062. *pnToken = p->aTotalSize[iCol];
  169063. }else{
  169064. rc = SQLITE_RANGE;
  169065. }
  169066. }
  169067. return rc;
  169068. }
  169069. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  169070. int rc = fts5StorageLoadTotals(p, 0);
  169071. if( rc==SQLITE_OK ){
  169072. *pnRow = p->nTotalRow;
  169073. }
  169074. return rc;
  169075. }
  169076. /*
  169077. ** Flush any data currently held in-memory to disk.
  169078. */
  169079. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
  169080. if( bCommit && p->bTotalsValid ){
  169081. int rc = fts5StorageSaveTotals(p);
  169082. p->bTotalsValid = 0;
  169083. if( rc!=SQLITE_OK ) return rc;
  169084. }
  169085. return sqlite3Fts5IndexSync(p->pIndex, bCommit);
  169086. }
  169087. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  169088. p->bTotalsValid = 0;
  169089. return sqlite3Fts5IndexRollback(p->pIndex);
  169090. }
  169091. static int sqlite3Fts5StorageConfigValue(
  169092. Fts5Storage *p,
  169093. const char *z,
  169094. sqlite3_value *pVal,
  169095. int iVal
  169096. ){
  169097. sqlite3_stmt *pReplace = 0;
  169098. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  169099. if( rc==SQLITE_OK ){
  169100. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  169101. if( pVal ){
  169102. sqlite3_bind_value(pReplace, 2, pVal);
  169103. }else{
  169104. sqlite3_bind_int(pReplace, 2, iVal);
  169105. }
  169106. sqlite3_step(pReplace);
  169107. rc = sqlite3_reset(pReplace);
  169108. }
  169109. if( rc==SQLITE_OK && pVal ){
  169110. int iNew = p->pConfig->iCookie + 1;
  169111. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  169112. if( rc==SQLITE_OK ){
  169113. p->pConfig->iCookie = iNew;
  169114. }
  169115. }
  169116. return rc;
  169117. }
  169118. /*
  169119. ** 2014 May 31
  169120. **
  169121. ** The author disclaims copyright to this source code. In place of
  169122. ** a legal notice, here is a blessing:
  169123. **
  169124. ** May you do good and not evil.
  169125. ** May you find forgiveness for yourself and forgive others.
  169126. ** May you share freely, never taking more than you give.
  169127. **
  169128. ******************************************************************************
  169129. */
  169130. /**************************************************************************
  169131. ** Start of ascii tokenizer implementation.
  169132. */
  169133. /*
  169134. ** For tokenizers with no "unicode" modifier, the set of token characters
  169135. ** is the same as the set of ASCII range alphanumeric characters.
  169136. */
  169137. static unsigned char aAsciiTokenChar[128] = {
  169138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  169139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  169140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  169141. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  169142. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  169143. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  169144. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  169145. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  169146. };
  169147. typedef struct AsciiTokenizer AsciiTokenizer;
  169148. struct AsciiTokenizer {
  169149. unsigned char aTokenChar[128];
  169150. };
  169151. static void fts5AsciiAddExceptions(
  169152. AsciiTokenizer *p,
  169153. const char *zArg,
  169154. int bTokenChars
  169155. ){
  169156. int i;
  169157. for(i=0; zArg[i]; i++){
  169158. if( (zArg[i] & 0x80)==0 ){
  169159. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  169160. }
  169161. }
  169162. }
  169163. /*
  169164. ** Delete a "ascii" tokenizer.
  169165. */
  169166. static void fts5AsciiDelete(Fts5Tokenizer *p){
  169167. sqlite3_free(p);
  169168. }
  169169. /*
  169170. ** Create an "ascii" tokenizer.
  169171. */
  169172. static int fts5AsciiCreate(
  169173. void *pCtx,
  169174. const char **azArg, int nArg,
  169175. Fts5Tokenizer **ppOut
  169176. ){
  169177. int rc = SQLITE_OK;
  169178. AsciiTokenizer *p = 0;
  169179. if( nArg%2 ){
  169180. rc = SQLITE_ERROR;
  169181. }else{
  169182. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  169183. if( p==0 ){
  169184. rc = SQLITE_NOMEM;
  169185. }else{
  169186. int i;
  169187. memset(p, 0, sizeof(AsciiTokenizer));
  169188. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  169189. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  169190. const char *zArg = azArg[i+1];
  169191. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  169192. fts5AsciiAddExceptions(p, zArg, 1);
  169193. }else
  169194. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  169195. fts5AsciiAddExceptions(p, zArg, 0);
  169196. }else{
  169197. rc = SQLITE_ERROR;
  169198. }
  169199. }
  169200. if( rc!=SQLITE_OK ){
  169201. fts5AsciiDelete((Fts5Tokenizer*)p);
  169202. p = 0;
  169203. }
  169204. }
  169205. }
  169206. *ppOut = (Fts5Tokenizer*)p;
  169207. return rc;
  169208. }
  169209. static void asciiFold(char *aOut, const char *aIn, int nByte){
  169210. int i;
  169211. for(i=0; i<nByte; i++){
  169212. char c = aIn[i];
  169213. if( c>='A' && c<='Z' ) c += 32;
  169214. aOut[i] = c;
  169215. }
  169216. }
  169217. /*
  169218. ** Tokenize some text using the ascii tokenizer.
  169219. */
  169220. static int fts5AsciiTokenize(
  169221. Fts5Tokenizer *pTokenizer,
  169222. void *pCtx,
  169223. int flags,
  169224. const char *pText, int nText,
  169225. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  169226. ){
  169227. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  169228. int rc = SQLITE_OK;
  169229. int ie;
  169230. int is = 0;
  169231. char aFold[64];
  169232. int nFold = sizeof(aFold);
  169233. char *pFold = aFold;
  169234. unsigned char *a = p->aTokenChar;
  169235. while( is<nText && rc==SQLITE_OK ){
  169236. int nByte;
  169237. /* Skip any leading divider characters. */
  169238. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  169239. is++;
  169240. }
  169241. if( is==nText ) break;
  169242. /* Count the token characters */
  169243. ie = is+1;
  169244. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  169245. ie++;
  169246. }
  169247. /* Fold to lower case */
  169248. nByte = ie-is;
  169249. if( nByte>nFold ){
  169250. if( pFold!=aFold ) sqlite3_free(pFold);
  169251. pFold = sqlite3_malloc(nByte*2);
  169252. if( pFold==0 ){
  169253. rc = SQLITE_NOMEM;
  169254. break;
  169255. }
  169256. nFold = nByte*2;
  169257. }
  169258. asciiFold(pFold, &pText[is], nByte);
  169259. /* Invoke the token callback */
  169260. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  169261. is = ie+1;
  169262. }
  169263. if( pFold!=aFold ) sqlite3_free(pFold);
  169264. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  169265. return rc;
  169266. }
  169267. /**************************************************************************
  169268. ** Start of unicode61 tokenizer implementation.
  169269. */
  169270. /*
  169271. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  169272. ** from the sqlite3 source file utf.c. If this file is compiled as part
  169273. ** of the amalgamation, they are not required.
  169274. */
  169275. #ifndef SQLITE_AMALGAMATION
  169276. static const unsigned char sqlite3Utf8Trans1[] = {
  169277. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  169278. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  169279. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  169280. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  169281. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  169282. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  169283. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  169284. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  169285. };
  169286. #define READ_UTF8(zIn, zTerm, c) \
  169287. c = *(zIn++); \
  169288. if( c>=0xc0 ){ \
  169289. c = sqlite3Utf8Trans1[c-0xc0]; \
  169290. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  169291. c = (c<<6) + (0x3f & *(zIn++)); \
  169292. } \
  169293. if( c<0x80 \
  169294. || (c&0xFFFFF800)==0xD800 \
  169295. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  169296. }
  169297. #define WRITE_UTF8(zOut, c) { \
  169298. if( c<0x00080 ){ \
  169299. *zOut++ = (unsigned char)(c&0xFF); \
  169300. } \
  169301. else if( c<0x00800 ){ \
  169302. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  169303. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  169304. } \
  169305. else if( c<0x10000 ){ \
  169306. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  169307. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  169308. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  169309. }else{ \
  169310. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  169311. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  169312. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  169313. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  169314. } \
  169315. }
  169316. #endif /* ifndef SQLITE_AMALGAMATION */
  169317. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  169318. struct Unicode61Tokenizer {
  169319. unsigned char aTokenChar[128]; /* ASCII range token characters */
  169320. char *aFold; /* Buffer to fold text into */
  169321. int nFold; /* Size of aFold[] in bytes */
  169322. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  169323. int nException;
  169324. int *aiException;
  169325. };
  169326. static int fts5UnicodeAddExceptions(
  169327. Unicode61Tokenizer *p, /* Tokenizer object */
  169328. const char *z, /* Characters to treat as exceptions */
  169329. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  169330. ){
  169331. int rc = SQLITE_OK;
  169332. int n = strlen(z);
  169333. int *aNew;
  169334. if( n>0 ){
  169335. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  169336. if( aNew ){
  169337. int nNew = p->nException;
  169338. const unsigned char *zCsr = (const unsigned char*)z;
  169339. const unsigned char *zTerm = (const unsigned char*)&z[n];
  169340. while( zCsr<zTerm ){
  169341. int iCode;
  169342. int bToken;
  169343. READ_UTF8(zCsr, zTerm, iCode);
  169344. if( iCode<128 ){
  169345. p->aTokenChar[iCode] = bTokenChars;
  169346. }else{
  169347. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  169348. assert( (bToken==0 || bToken==1) );
  169349. assert( (bTokenChars==0 || bTokenChars==1) );
  169350. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  169351. int i;
  169352. for(i=0; i<nNew; i++){
  169353. if( aNew[i]>iCode ) break;
  169354. }
  169355. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  169356. aNew[i] = iCode;
  169357. nNew++;
  169358. }
  169359. }
  169360. }
  169361. p->aiException = aNew;
  169362. p->nException = nNew;
  169363. }else{
  169364. rc = SQLITE_NOMEM;
  169365. }
  169366. }
  169367. return rc;
  169368. }
  169369. /*
  169370. ** Return true if the p->aiException[] array contains the value iCode.
  169371. */
  169372. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  169373. if( p->nException>0 ){
  169374. int *a = p->aiException;
  169375. int iLo = 0;
  169376. int iHi = p->nException-1;
  169377. while( iHi>=iLo ){
  169378. int iTest = (iHi + iLo) / 2;
  169379. if( iCode==a[iTest] ){
  169380. return 1;
  169381. }else if( iCode>a[iTest] ){
  169382. iLo = iTest+1;
  169383. }else{
  169384. iHi = iTest-1;
  169385. }
  169386. }
  169387. }
  169388. return 0;
  169389. }
  169390. /*
  169391. ** Delete a "unicode61" tokenizer.
  169392. */
  169393. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  169394. if( pTok ){
  169395. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  169396. sqlite3_free(p->aiException);
  169397. sqlite3_free(p->aFold);
  169398. sqlite3_free(p);
  169399. }
  169400. return;
  169401. }
  169402. /*
  169403. ** Create a "unicode61" tokenizer.
  169404. */
  169405. static int fts5UnicodeCreate(
  169406. void *pCtx,
  169407. const char **azArg, int nArg,
  169408. Fts5Tokenizer **ppOut
  169409. ){
  169410. int rc = SQLITE_OK; /* Return code */
  169411. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  169412. if( nArg%2 ){
  169413. rc = SQLITE_ERROR;
  169414. }else{
  169415. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  169416. if( p ){
  169417. int i;
  169418. memset(p, 0, sizeof(Unicode61Tokenizer));
  169419. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  169420. p->bRemoveDiacritic = 1;
  169421. p->nFold = 64;
  169422. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  169423. if( p->aFold==0 ){
  169424. rc = SQLITE_NOMEM;
  169425. }
  169426. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  169427. const char *zArg = azArg[i+1];
  169428. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  169429. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  169430. rc = SQLITE_ERROR;
  169431. }
  169432. p->bRemoveDiacritic = (zArg[0]=='1');
  169433. }else
  169434. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  169435. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  169436. }else
  169437. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  169438. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  169439. }else{
  169440. rc = SQLITE_ERROR;
  169441. }
  169442. }
  169443. }else{
  169444. rc = SQLITE_NOMEM;
  169445. }
  169446. if( rc!=SQLITE_OK ){
  169447. fts5UnicodeDelete((Fts5Tokenizer*)p);
  169448. p = 0;
  169449. }
  169450. *ppOut = (Fts5Tokenizer*)p;
  169451. }
  169452. return rc;
  169453. }
  169454. /*
  169455. ** Return true if, for the purposes of tokenizing with the tokenizer
  169456. ** passed as the first argument, codepoint iCode is considered a token
  169457. ** character (not a separator).
  169458. */
  169459. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  169460. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  169461. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  169462. }
  169463. static int fts5UnicodeTokenize(
  169464. Fts5Tokenizer *pTokenizer,
  169465. void *pCtx,
  169466. int flags,
  169467. const char *pText, int nText,
  169468. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  169469. ){
  169470. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  169471. int rc = SQLITE_OK;
  169472. unsigned char *a = p->aTokenChar;
  169473. unsigned char *zTerm = (unsigned char*)&pText[nText];
  169474. unsigned char *zCsr = (unsigned char *)pText;
  169475. /* Output buffer */
  169476. char *aFold = p->aFold;
  169477. int nFold = p->nFold;
  169478. const char *pEnd = &aFold[nFold-6];
  169479. /* Each iteration of this loop gobbles up a contiguous run of separators,
  169480. ** then the next token. */
  169481. while( rc==SQLITE_OK ){
  169482. int iCode; /* non-ASCII codepoint read from input */
  169483. char *zOut = aFold;
  169484. int is;
  169485. int ie;
  169486. /* Skip any separator characters. */
  169487. while( 1 ){
  169488. if( zCsr>=zTerm ) goto tokenize_done;
  169489. if( *zCsr & 0x80 ) {
  169490. /* A character outside of the ascii range. Skip past it if it is
  169491. ** a separator character. Or break out of the loop if it is not. */
  169492. is = zCsr - (unsigned char*)pText;
  169493. READ_UTF8(zCsr, zTerm, iCode);
  169494. if( fts5UnicodeIsAlnum(p, iCode) ){
  169495. goto non_ascii_tokenchar;
  169496. }
  169497. }else{
  169498. if( a[*zCsr] ){
  169499. is = zCsr - (unsigned char*)pText;
  169500. goto ascii_tokenchar;
  169501. }
  169502. zCsr++;
  169503. }
  169504. }
  169505. /* Run through the tokenchars. Fold them into the output buffer along
  169506. ** the way. */
  169507. while( zCsr<zTerm ){
  169508. /* Grow the output buffer so that there is sufficient space to fit the
  169509. ** largest possible utf-8 character. */
  169510. if( zOut>pEnd ){
  169511. aFold = sqlite3_malloc(nFold*2);
  169512. if( aFold==0 ){
  169513. rc = SQLITE_NOMEM;
  169514. goto tokenize_done;
  169515. }
  169516. zOut = &aFold[zOut - p->aFold];
  169517. memcpy(aFold, p->aFold, nFold);
  169518. sqlite3_free(p->aFold);
  169519. p->aFold = aFold;
  169520. p->nFold = nFold = nFold*2;
  169521. pEnd = &aFold[nFold-6];
  169522. }
  169523. if( *zCsr & 0x80 ){
  169524. /* An non-ascii-range character. Fold it into the output buffer if
  169525. ** it is a token character, or break out of the loop if it is not. */
  169526. READ_UTF8(zCsr, zTerm, iCode);
  169527. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  169528. non_ascii_tokenchar:
  169529. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  169530. if( iCode ) WRITE_UTF8(zOut, iCode);
  169531. }else{
  169532. break;
  169533. }
  169534. }else if( a[*zCsr]==0 ){
  169535. /* An ascii-range separator character. End of token. */
  169536. break;
  169537. }else{
  169538. ascii_tokenchar:
  169539. if( *zCsr>='A' && *zCsr<='Z' ){
  169540. *zOut++ = *zCsr + 32;
  169541. }else{
  169542. *zOut++ = *zCsr;
  169543. }
  169544. zCsr++;
  169545. }
  169546. ie = zCsr - (unsigned char*)pText;
  169547. }
  169548. /* Invoke the token callback */
  169549. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  169550. }
  169551. tokenize_done:
  169552. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  169553. return rc;
  169554. }
  169555. /**************************************************************************
  169556. ** Start of porter stemmer implementation.
  169557. */
  169558. /* Any tokens larger than this (in bytes) are passed through without
  169559. ** stemming. */
  169560. #define FTS5_PORTER_MAX_TOKEN 64
  169561. typedef struct PorterTokenizer PorterTokenizer;
  169562. struct PorterTokenizer {
  169563. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  169564. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  169565. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  169566. };
  169567. /*
  169568. ** Delete a "porter" tokenizer.
  169569. */
  169570. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  169571. if( pTok ){
  169572. PorterTokenizer *p = (PorterTokenizer*)pTok;
  169573. if( p->pTokenizer ){
  169574. p->tokenizer.xDelete(p->pTokenizer);
  169575. }
  169576. sqlite3_free(p);
  169577. }
  169578. }
  169579. /*
  169580. ** Create a "porter" tokenizer.
  169581. */
  169582. static int fts5PorterCreate(
  169583. void *pCtx,
  169584. const char **azArg, int nArg,
  169585. Fts5Tokenizer **ppOut
  169586. ){
  169587. fts5_api *pApi = (fts5_api*)pCtx;
  169588. int rc = SQLITE_OK;
  169589. PorterTokenizer *pRet;
  169590. void *pUserdata = 0;
  169591. const char *zBase = "unicode61";
  169592. if( nArg>0 ){
  169593. zBase = azArg[0];
  169594. }
  169595. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  169596. if( pRet ){
  169597. memset(pRet, 0, sizeof(PorterTokenizer));
  169598. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  169599. }else{
  169600. rc = SQLITE_NOMEM;
  169601. }
  169602. if( rc==SQLITE_OK ){
  169603. int nArg2 = (nArg>0 ? nArg-1 : 0);
  169604. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  169605. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  169606. }
  169607. if( rc!=SQLITE_OK ){
  169608. fts5PorterDelete((Fts5Tokenizer*)pRet);
  169609. pRet = 0;
  169610. }
  169611. *ppOut = (Fts5Tokenizer*)pRet;
  169612. return rc;
  169613. }
  169614. typedef struct PorterContext PorterContext;
  169615. struct PorterContext {
  169616. void *pCtx;
  169617. int (*xToken)(void*, int, const char*, int, int, int);
  169618. char *aBuf;
  169619. };
  169620. typedef struct PorterRule PorterRule;
  169621. struct PorterRule {
  169622. const char *zSuffix;
  169623. int nSuffix;
  169624. int (*xCond)(char *zStem, int nStem);
  169625. const char *zOutput;
  169626. int nOutput;
  169627. };
  169628. #if 0
  169629. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  169630. int ret = -1;
  169631. int nBuf = *pnBuf;
  169632. PorterRule *p;
  169633. for(p=aRule; p->zSuffix; p++){
  169634. assert( strlen(p->zSuffix)==p->nSuffix );
  169635. assert( strlen(p->zOutput)==p->nOutput );
  169636. if( nBuf<p->nSuffix ) continue;
  169637. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  169638. }
  169639. if( p->zSuffix ){
  169640. int nStem = nBuf - p->nSuffix;
  169641. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  169642. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  169643. *pnBuf = nStem + p->nOutput;
  169644. ret = p - aRule;
  169645. }
  169646. }
  169647. return ret;
  169648. }
  169649. #endif
  169650. static int fts5PorterIsVowel(char c, int bYIsVowel){
  169651. return (
  169652. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  169653. );
  169654. }
  169655. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  169656. int i;
  169657. int bCons = bPrevCons;
  169658. /* Scan for a vowel */
  169659. for(i=0; i<nStem; i++){
  169660. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  169661. }
  169662. /* Scan for a consonent */
  169663. for(i++; i<nStem; i++){
  169664. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  169665. }
  169666. return 0;
  169667. }
  169668. /* porter rule condition: (m > 0) */
  169669. static int fts5Porter_MGt0(char *zStem, int nStem){
  169670. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  169671. }
  169672. /* porter rule condition: (m > 1) */
  169673. static int fts5Porter_MGt1(char *zStem, int nStem){
  169674. int n;
  169675. n = fts5PorterGobbleVC(zStem, nStem, 0);
  169676. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  169677. return 1;
  169678. }
  169679. return 0;
  169680. }
  169681. /* porter rule condition: (m = 1) */
  169682. static int fts5Porter_MEq1(char *zStem, int nStem){
  169683. int n;
  169684. n = fts5PorterGobbleVC(zStem, nStem, 0);
  169685. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  169686. return 1;
  169687. }
  169688. return 0;
  169689. }
  169690. /* porter rule condition: (*o) */
  169691. static int fts5Porter_Ostar(char *zStem, int nStem){
  169692. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  169693. return 0;
  169694. }else{
  169695. int i;
  169696. int mask = 0;
  169697. int bCons = 0;
  169698. for(i=0; i<nStem; i++){
  169699. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  169700. assert( bCons==0 || bCons==1 );
  169701. mask = (mask << 1) + bCons;
  169702. }
  169703. return ((mask & 0x0007)==0x0005);
  169704. }
  169705. }
  169706. /* porter rule condition: (m > 1 and (*S or *T)) */
  169707. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  169708. assert( nStem>0 );
  169709. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  169710. && fts5Porter_MGt1(zStem, nStem);
  169711. }
  169712. /* porter rule condition: (*v*) */
  169713. static int fts5Porter_Vowel(char *zStem, int nStem){
  169714. int i;
  169715. for(i=0; i<nStem; i++){
  169716. if( fts5PorterIsVowel(zStem[i], i>0) ){
  169717. return 1;
  169718. }
  169719. }
  169720. return 0;
  169721. }
  169722. /**************************************************************************
  169723. ***************************************************************************
  169724. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  169725. */
  169726. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  169727. int ret = 0;
  169728. int nBuf = *pnBuf;
  169729. switch( aBuf[nBuf-2] ){
  169730. case 'a':
  169731. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  169732. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  169733. *pnBuf = nBuf - 2;
  169734. }
  169735. }
  169736. break;
  169737. case 'c':
  169738. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  169739. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  169740. *pnBuf = nBuf - 4;
  169741. }
  169742. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  169743. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  169744. *pnBuf = nBuf - 4;
  169745. }
  169746. }
  169747. break;
  169748. case 'e':
  169749. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  169750. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  169751. *pnBuf = nBuf - 2;
  169752. }
  169753. }
  169754. break;
  169755. case 'i':
  169756. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  169757. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  169758. *pnBuf = nBuf - 2;
  169759. }
  169760. }
  169761. break;
  169762. case 'l':
  169763. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  169764. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  169765. *pnBuf = nBuf - 4;
  169766. }
  169767. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  169768. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  169769. *pnBuf = nBuf - 4;
  169770. }
  169771. }
  169772. break;
  169773. case 'n':
  169774. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  169775. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169776. *pnBuf = nBuf - 3;
  169777. }
  169778. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  169779. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  169780. *pnBuf = nBuf - 5;
  169781. }
  169782. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  169783. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  169784. *pnBuf = nBuf - 4;
  169785. }
  169786. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  169787. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169788. *pnBuf = nBuf - 3;
  169789. }
  169790. }
  169791. break;
  169792. case 'o':
  169793. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  169794. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  169795. *pnBuf = nBuf - 3;
  169796. }
  169797. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  169798. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  169799. *pnBuf = nBuf - 2;
  169800. }
  169801. }
  169802. break;
  169803. case 's':
  169804. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  169805. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169806. *pnBuf = nBuf - 3;
  169807. }
  169808. }
  169809. break;
  169810. case 't':
  169811. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  169812. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169813. *pnBuf = nBuf - 3;
  169814. }
  169815. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  169816. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169817. *pnBuf = nBuf - 3;
  169818. }
  169819. }
  169820. break;
  169821. case 'u':
  169822. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  169823. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169824. *pnBuf = nBuf - 3;
  169825. }
  169826. }
  169827. break;
  169828. case 'v':
  169829. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  169830. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169831. *pnBuf = nBuf - 3;
  169832. }
  169833. }
  169834. break;
  169835. case 'z':
  169836. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  169837. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  169838. *pnBuf = nBuf - 3;
  169839. }
  169840. }
  169841. break;
  169842. }
  169843. return ret;
  169844. }
  169845. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  169846. int ret = 0;
  169847. int nBuf = *pnBuf;
  169848. switch( aBuf[nBuf-2] ){
  169849. case 'a':
  169850. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  169851. memcpy(&aBuf[nBuf-2], "ate", 3);
  169852. *pnBuf = nBuf - 2 + 3;
  169853. ret = 1;
  169854. }
  169855. break;
  169856. case 'b':
  169857. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  169858. memcpy(&aBuf[nBuf-2], "ble", 3);
  169859. *pnBuf = nBuf - 2 + 3;
  169860. ret = 1;
  169861. }
  169862. break;
  169863. case 'i':
  169864. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  169865. memcpy(&aBuf[nBuf-2], "ize", 3);
  169866. *pnBuf = nBuf - 2 + 3;
  169867. ret = 1;
  169868. }
  169869. break;
  169870. }
  169871. return ret;
  169872. }
  169873. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  169874. int ret = 0;
  169875. int nBuf = *pnBuf;
  169876. switch( aBuf[nBuf-2] ){
  169877. case 'a':
  169878. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  169879. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  169880. memcpy(&aBuf[nBuf-7], "ate", 3);
  169881. *pnBuf = nBuf - 7 + 3;
  169882. }
  169883. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  169884. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  169885. memcpy(&aBuf[nBuf-6], "tion", 4);
  169886. *pnBuf = nBuf - 6 + 4;
  169887. }
  169888. }
  169889. break;
  169890. case 'c':
  169891. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  169892. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169893. memcpy(&aBuf[nBuf-4], "ence", 4);
  169894. *pnBuf = nBuf - 4 + 4;
  169895. }
  169896. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  169897. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169898. memcpy(&aBuf[nBuf-4], "ance", 4);
  169899. *pnBuf = nBuf - 4 + 4;
  169900. }
  169901. }
  169902. break;
  169903. case 'e':
  169904. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  169905. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169906. memcpy(&aBuf[nBuf-4], "ize", 3);
  169907. *pnBuf = nBuf - 4 + 3;
  169908. }
  169909. }
  169910. break;
  169911. case 'g':
  169912. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  169913. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169914. memcpy(&aBuf[nBuf-4], "log", 3);
  169915. *pnBuf = nBuf - 4 + 3;
  169916. }
  169917. }
  169918. break;
  169919. case 'l':
  169920. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  169921. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  169922. memcpy(&aBuf[nBuf-3], "ble", 3);
  169923. *pnBuf = nBuf - 3 + 3;
  169924. }
  169925. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  169926. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169927. memcpy(&aBuf[nBuf-4], "al", 2);
  169928. *pnBuf = nBuf - 4 + 2;
  169929. }
  169930. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  169931. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169932. memcpy(&aBuf[nBuf-5], "ent", 3);
  169933. *pnBuf = nBuf - 5 + 3;
  169934. }
  169935. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  169936. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  169937. memcpy(&aBuf[nBuf-3], "e", 1);
  169938. *pnBuf = nBuf - 3 + 1;
  169939. }
  169940. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  169941. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169942. memcpy(&aBuf[nBuf-5], "ous", 3);
  169943. *pnBuf = nBuf - 5 + 3;
  169944. }
  169945. }
  169946. break;
  169947. case 'o':
  169948. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  169949. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  169950. memcpy(&aBuf[nBuf-7], "ize", 3);
  169951. *pnBuf = nBuf - 7 + 3;
  169952. }
  169953. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  169954. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169955. memcpy(&aBuf[nBuf-5], "ate", 3);
  169956. *pnBuf = nBuf - 5 + 3;
  169957. }
  169958. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  169959. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  169960. memcpy(&aBuf[nBuf-4], "ate", 3);
  169961. *pnBuf = nBuf - 4 + 3;
  169962. }
  169963. }
  169964. break;
  169965. case 's':
  169966. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  169967. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169968. memcpy(&aBuf[nBuf-5], "al", 2);
  169969. *pnBuf = nBuf - 5 + 2;
  169970. }
  169971. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  169972. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  169973. memcpy(&aBuf[nBuf-7], "ive", 3);
  169974. *pnBuf = nBuf - 7 + 3;
  169975. }
  169976. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  169977. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  169978. memcpy(&aBuf[nBuf-7], "ful", 3);
  169979. *pnBuf = nBuf - 7 + 3;
  169980. }
  169981. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  169982. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  169983. memcpy(&aBuf[nBuf-7], "ous", 3);
  169984. *pnBuf = nBuf - 7 + 3;
  169985. }
  169986. }
  169987. break;
  169988. case 't':
  169989. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  169990. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169991. memcpy(&aBuf[nBuf-5], "al", 2);
  169992. *pnBuf = nBuf - 5 + 2;
  169993. }
  169994. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  169995. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  169996. memcpy(&aBuf[nBuf-5], "ive", 3);
  169997. *pnBuf = nBuf - 5 + 3;
  169998. }
  169999. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  170000. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  170001. memcpy(&aBuf[nBuf-6], "ble", 3);
  170002. *pnBuf = nBuf - 6 + 3;
  170003. }
  170004. }
  170005. break;
  170006. }
  170007. return ret;
  170008. }
  170009. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  170010. int ret = 0;
  170011. int nBuf = *pnBuf;
  170012. switch( aBuf[nBuf-2] ){
  170013. case 'a':
  170014. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  170015. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  170016. memcpy(&aBuf[nBuf-4], "ic", 2);
  170017. *pnBuf = nBuf - 4 + 2;
  170018. }
  170019. }
  170020. break;
  170021. case 's':
  170022. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  170023. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  170024. *pnBuf = nBuf - 4;
  170025. }
  170026. }
  170027. break;
  170028. case 't':
  170029. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  170030. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  170031. memcpy(&aBuf[nBuf-5], "ic", 2);
  170032. *pnBuf = nBuf - 5 + 2;
  170033. }
  170034. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  170035. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  170036. memcpy(&aBuf[nBuf-5], "ic", 2);
  170037. *pnBuf = nBuf - 5 + 2;
  170038. }
  170039. }
  170040. break;
  170041. case 'u':
  170042. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  170043. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  170044. *pnBuf = nBuf - 3;
  170045. }
  170046. }
  170047. break;
  170048. case 'v':
  170049. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  170050. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  170051. *pnBuf = nBuf - 5;
  170052. }
  170053. }
  170054. break;
  170055. case 'z':
  170056. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  170057. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  170058. memcpy(&aBuf[nBuf-5], "al", 2);
  170059. *pnBuf = nBuf - 5 + 2;
  170060. }
  170061. }
  170062. break;
  170063. }
  170064. return ret;
  170065. }
  170066. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  170067. int ret = 0;
  170068. int nBuf = *pnBuf;
  170069. switch( aBuf[nBuf-2] ){
  170070. case 'e':
  170071. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  170072. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  170073. memcpy(&aBuf[nBuf-3], "ee", 2);
  170074. *pnBuf = nBuf - 3 + 2;
  170075. }
  170076. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  170077. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  170078. *pnBuf = nBuf - 2;
  170079. ret = 1;
  170080. }
  170081. }
  170082. break;
  170083. case 'n':
  170084. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  170085. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  170086. *pnBuf = nBuf - 3;
  170087. ret = 1;
  170088. }
  170089. }
  170090. break;
  170091. }
  170092. return ret;
  170093. }
  170094. /*
  170095. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  170096. ***************************************************************************
  170097. **************************************************************************/
  170098. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  170099. int nBuf = *pnBuf;
  170100. if( aBuf[nBuf-1]=='s' ){
  170101. if( aBuf[nBuf-2]=='e' ){
  170102. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  170103. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  170104. ){
  170105. *pnBuf = nBuf-2;
  170106. }else{
  170107. *pnBuf = nBuf-1;
  170108. }
  170109. }
  170110. else if( aBuf[nBuf-2]!='s' ){
  170111. *pnBuf = nBuf-1;
  170112. }
  170113. }
  170114. }
  170115. static int fts5PorterCb(
  170116. void *pCtx,
  170117. int tflags,
  170118. const char *pToken,
  170119. int nToken,
  170120. int iStart,
  170121. int iEnd
  170122. ){
  170123. PorterContext *p = (PorterContext*)pCtx;
  170124. char *aBuf;
  170125. int nBuf;
  170126. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  170127. aBuf = p->aBuf;
  170128. nBuf = nToken;
  170129. memcpy(aBuf, pToken, nBuf);
  170130. /* Step 1. */
  170131. fts5PorterStep1A(aBuf, &nBuf);
  170132. if( fts5PorterStep1B(aBuf, &nBuf) ){
  170133. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  170134. char c = aBuf[nBuf-1];
  170135. if( fts5PorterIsVowel(c, 0)==0
  170136. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  170137. ){
  170138. nBuf--;
  170139. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  170140. aBuf[nBuf++] = 'e';
  170141. }
  170142. }
  170143. }
  170144. /* Step 1C. */
  170145. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  170146. aBuf[nBuf-1] = 'i';
  170147. }
  170148. /* Steps 2 through 4. */
  170149. fts5PorterStep2(aBuf, &nBuf);
  170150. fts5PorterStep3(aBuf, &nBuf);
  170151. fts5PorterStep4(aBuf, &nBuf);
  170152. /* Step 5a. */
  170153. assert( nBuf>0 );
  170154. if( aBuf[nBuf-1]=='e' ){
  170155. if( fts5Porter_MGt1(aBuf, nBuf-1)
  170156. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  170157. ){
  170158. nBuf--;
  170159. }
  170160. }
  170161. /* Step 5b. */
  170162. if( nBuf>1 && aBuf[nBuf-1]=='l'
  170163. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  170164. ){
  170165. nBuf--;
  170166. }
  170167. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  170168. pass_through:
  170169. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  170170. }
  170171. /*
  170172. ** Tokenize using the porter tokenizer.
  170173. */
  170174. static int fts5PorterTokenize(
  170175. Fts5Tokenizer *pTokenizer,
  170176. void *pCtx,
  170177. int flags,
  170178. const char *pText, int nText,
  170179. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  170180. ){
  170181. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  170182. PorterContext sCtx;
  170183. sCtx.xToken = xToken;
  170184. sCtx.pCtx = pCtx;
  170185. sCtx.aBuf = p->aBuf;
  170186. return p->tokenizer.xTokenize(
  170187. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  170188. );
  170189. }
  170190. /*
  170191. ** Register all built-in tokenizers with FTS5.
  170192. */
  170193. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  170194. struct BuiltinTokenizer {
  170195. const char *zName;
  170196. fts5_tokenizer x;
  170197. } aBuiltin[] = {
  170198. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  170199. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  170200. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  170201. };
  170202. int rc = SQLITE_OK; /* Return code */
  170203. int i; /* To iterate through builtin functions */
  170204. for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
  170205. rc = pApi->xCreateTokenizer(pApi,
  170206. aBuiltin[i].zName,
  170207. (void*)pApi,
  170208. &aBuiltin[i].x,
  170209. 0
  170210. );
  170211. }
  170212. return rc;
  170213. }
  170214. /*
  170215. ** 2012 May 25
  170216. **
  170217. ** The author disclaims copyright to this source code. In place of
  170218. ** a legal notice, here is a blessing:
  170219. **
  170220. ** May you do good and not evil.
  170221. ** May you find forgiveness for yourself and forgive others.
  170222. ** May you share freely, never taking more than you give.
  170223. **
  170224. ******************************************************************************
  170225. */
  170226. /*
  170227. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  170228. */
  170229. /* #include <assert.h> */
  170230. /*
  170231. ** Return true if the argument corresponds to a unicode codepoint
  170232. ** classified as either a letter or a number. Otherwise false.
  170233. **
  170234. ** The results are undefined if the value passed to this function
  170235. ** is less than zero.
  170236. */
  170237. static int sqlite3Fts5UnicodeIsalnum(int c){
  170238. /* Each unsigned integer in the following array corresponds to a contiguous
  170239. ** range of unicode codepoints that are not either letters or numbers (i.e.
  170240. ** codepoints for which this function should return 0).
  170241. **
  170242. ** The most significant 22 bits in each 32-bit value contain the first
  170243. ** codepoint in the range. The least significant 10 bits are used to store
  170244. ** the size of the range (always at least 1). In other words, the value
  170245. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  170246. ** C. It is not possible to represent a range larger than 1023 codepoints
  170247. ** using this format.
  170248. */
  170249. static const unsigned int aEntry[] = {
  170250. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  170251. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  170252. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  170253. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  170254. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  170255. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  170256. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  170257. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  170258. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  170259. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  170260. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  170261. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  170262. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  170263. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  170264. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  170265. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  170266. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  170267. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  170268. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  170269. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  170270. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  170271. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  170272. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  170273. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  170274. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  170275. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  170276. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  170277. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  170278. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  170279. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  170280. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  170281. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  170282. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  170283. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  170284. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  170285. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  170286. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  170287. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  170288. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  170289. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  170290. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  170291. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  170292. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  170293. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  170294. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  170295. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  170296. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  170297. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  170298. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  170299. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  170300. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  170301. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  170302. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  170303. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  170304. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  170305. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  170306. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  170307. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  170308. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  170309. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  170310. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  170311. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  170312. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  170313. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  170314. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  170315. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  170316. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  170317. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  170318. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  170319. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  170320. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  170321. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  170322. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  170323. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  170324. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  170325. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  170326. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  170327. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  170328. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  170329. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  170330. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  170331. 0x380400F0,
  170332. };
  170333. static const unsigned int aAscii[4] = {
  170334. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  170335. };
  170336. if( c<128 ){
  170337. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  170338. }else if( c<(1<<22) ){
  170339. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  170340. int iRes = 0;
  170341. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  170342. int iLo = 0;
  170343. while( iHi>=iLo ){
  170344. int iTest = (iHi + iLo) / 2;
  170345. if( key >= aEntry[iTest] ){
  170346. iRes = iTest;
  170347. iLo = iTest+1;
  170348. }else{
  170349. iHi = iTest-1;
  170350. }
  170351. }
  170352. assert( aEntry[0]<key );
  170353. assert( key>=aEntry[iRes] );
  170354. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  170355. }
  170356. return 1;
  170357. }
  170358. /*
  170359. ** If the argument is a codepoint corresponding to a lowercase letter
  170360. ** in the ASCII range with a diacritic added, return the codepoint
  170361. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  170362. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  170363. ** E"). The resuls of passing a codepoint that corresponds to an
  170364. ** uppercase letter are undefined.
  170365. */
  170366. static int fts5_remove_diacritic(int c){
  170367. unsigned short aDia[] = {
  170368. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  170369. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  170370. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  170371. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  170372. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  170373. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  170374. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  170375. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  170376. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  170377. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  170378. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  170379. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  170380. 62924, 63050, 63082, 63274, 63390,
  170381. };
  170382. char aChar[] = {
  170383. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  170384. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  170385. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  170386. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  170387. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  170388. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  170389. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  170390. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  170391. 'e', 'i', 'o', 'u', 'y',
  170392. };
  170393. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  170394. int iRes = 0;
  170395. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  170396. int iLo = 0;
  170397. while( iHi>=iLo ){
  170398. int iTest = (iHi + iLo) / 2;
  170399. if( key >= aDia[iTest] ){
  170400. iRes = iTest;
  170401. iLo = iTest+1;
  170402. }else{
  170403. iHi = iTest-1;
  170404. }
  170405. }
  170406. assert( key>=aDia[iRes] );
  170407. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  170408. }
  170409. /*
  170410. ** Return true if the argument interpreted as a unicode codepoint
  170411. ** is a diacritical modifier character.
  170412. */
  170413. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  170414. unsigned int mask0 = 0x08029FDF;
  170415. unsigned int mask1 = 0x000361F8;
  170416. if( c<768 || c>817 ) return 0;
  170417. return (c < 768+32) ?
  170418. (mask0 & (1 << (c-768))) :
  170419. (mask1 & (1 << (c-768-32)));
  170420. }
  170421. /*
  170422. ** Interpret the argument as a unicode codepoint. If the codepoint
  170423. ** is an upper case character that has a lower case equivalent,
  170424. ** return the codepoint corresponding to the lower case version.
  170425. ** Otherwise, return a copy of the argument.
  170426. **
  170427. ** The results are undefined if the value passed to this function
  170428. ** is less than zero.
  170429. */
  170430. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  170431. /* Each entry in the following array defines a rule for folding a range
  170432. ** of codepoints to lower case. The rule applies to a range of nRange
  170433. ** codepoints starting at codepoint iCode.
  170434. **
  170435. ** If the least significant bit in flags is clear, then the rule applies
  170436. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  170437. ** need to be folded). Or, if it is set, then the rule only applies to
  170438. ** every second codepoint in the range, starting with codepoint C.
  170439. **
  170440. ** The 7 most significant bits in flags are an index into the aiOff[]
  170441. ** array. If a specific codepoint C does require folding, then its lower
  170442. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  170443. **
  170444. ** The contents of this array are generated by parsing the CaseFolding.txt
  170445. ** file distributed as part of the "Unicode Character Database". See
  170446. ** http://www.unicode.org for details.
  170447. */
  170448. static const struct TableEntry {
  170449. unsigned short iCode;
  170450. unsigned char flags;
  170451. unsigned char nRange;
  170452. } aEntry[] = {
  170453. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  170454. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  170455. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  170456. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  170457. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  170458. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  170459. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  170460. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  170461. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  170462. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  170463. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  170464. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  170465. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  170466. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  170467. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  170468. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  170469. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  170470. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  170471. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  170472. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  170473. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  170474. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  170475. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  170476. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  170477. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  170478. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  170479. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  170480. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  170481. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  170482. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  170483. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  170484. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  170485. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  170486. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  170487. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  170488. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  170489. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  170490. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  170491. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  170492. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  170493. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  170494. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  170495. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  170496. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  170497. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  170498. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  170499. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  170500. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  170501. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  170502. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  170503. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  170504. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  170505. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  170506. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  170507. {65313, 14, 26},
  170508. };
  170509. static const unsigned short aiOff[] = {
  170510. 1, 2, 8, 15, 16, 26, 28, 32,
  170511. 37, 38, 40, 48, 63, 64, 69, 71,
  170512. 79, 80, 116, 202, 203, 205, 206, 207,
  170513. 209, 210, 211, 213, 214, 217, 218, 219,
  170514. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  170515. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  170516. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  170517. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  170518. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  170519. 65514, 65521, 65527, 65528, 65529,
  170520. };
  170521. int ret = c;
  170522. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  170523. if( c<128 ){
  170524. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  170525. }else if( c<65536 ){
  170526. const struct TableEntry *p;
  170527. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  170528. int iLo = 0;
  170529. int iRes = -1;
  170530. assert( c>aEntry[0].iCode );
  170531. while( iHi>=iLo ){
  170532. int iTest = (iHi + iLo) / 2;
  170533. int cmp = (c - aEntry[iTest].iCode);
  170534. if( cmp>=0 ){
  170535. iRes = iTest;
  170536. iLo = iTest+1;
  170537. }else{
  170538. iHi = iTest-1;
  170539. }
  170540. }
  170541. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  170542. p = &aEntry[iRes];
  170543. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  170544. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  170545. assert( ret>0 );
  170546. }
  170547. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  170548. }
  170549. else if( c>=66560 && c<66600 ){
  170550. ret = c + 40;
  170551. }
  170552. return ret;
  170553. }
  170554. /*
  170555. ** 2015 May 30
  170556. **
  170557. ** The author disclaims copyright to this source code. In place of
  170558. ** a legal notice, here is a blessing:
  170559. **
  170560. ** May you do good and not evil.
  170561. ** May you find forgiveness for yourself and forgive others.
  170562. ** May you share freely, never taking more than you give.
  170563. **
  170564. ******************************************************************************
  170565. **
  170566. ** Routines for varint serialization and deserialization.
  170567. */
  170568. /*
  170569. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  170570. ** Except, this version does handle the single byte case that the core
  170571. ** version depends on being handled before its function is called.
  170572. */
  170573. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  170574. u32 a,b;
  170575. /* The 1-byte case. Overwhelmingly the most common. */
  170576. a = *p;
  170577. /* a: p0 (unmasked) */
  170578. if (!(a&0x80))
  170579. {
  170580. /* Values between 0 and 127 */
  170581. *v = a;
  170582. return 1;
  170583. }
  170584. /* The 2-byte case */
  170585. p++;
  170586. b = *p;
  170587. /* b: p1 (unmasked) */
  170588. if (!(b&0x80))
  170589. {
  170590. /* Values between 128 and 16383 */
  170591. a &= 0x7f;
  170592. a = a<<7;
  170593. *v = a | b;
  170594. return 2;
  170595. }
  170596. /* The 3-byte case */
  170597. p++;
  170598. a = a<<14;
  170599. a |= *p;
  170600. /* a: p0<<14 | p2 (unmasked) */
  170601. if (!(a&0x80))
  170602. {
  170603. /* Values between 16384 and 2097151 */
  170604. a &= (0x7f<<14)|(0x7f);
  170605. b &= 0x7f;
  170606. b = b<<7;
  170607. *v = a | b;
  170608. return 3;
  170609. }
  170610. /* A 32-bit varint is used to store size information in btrees.
  170611. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  170612. ** A 3-byte varint is sufficient, for example, to record the size
  170613. ** of a 1048569-byte BLOB or string.
  170614. **
  170615. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  170616. ** rare larger cases can be handled by the slower 64-bit varint
  170617. ** routine.
  170618. */
  170619. {
  170620. u64 v64;
  170621. u8 n;
  170622. p -= 2;
  170623. n = sqlite3Fts5GetVarint(p, &v64);
  170624. *v = (u32)v64;
  170625. assert( n>3 && n<=9 );
  170626. return n;
  170627. }
  170628. }
  170629. /*
  170630. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  170631. ** are defined here rather than simply putting the constant expressions
  170632. ** inline in order to work around bugs in the RVT compiler.
  170633. **
  170634. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  170635. **
  170636. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  170637. */
  170638. #define SLOT_2_0 0x001fc07f
  170639. #define SLOT_4_2_0 0xf01fc07f
  170640. /*
  170641. ** Read a 64-bit variable-length integer from memory starting at p[0].
  170642. ** Return the number of bytes read. The value is stored in *v.
  170643. */
  170644. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  170645. u32 a,b,s;
  170646. a = *p;
  170647. /* a: p0 (unmasked) */
  170648. if (!(a&0x80))
  170649. {
  170650. *v = a;
  170651. return 1;
  170652. }
  170653. p++;
  170654. b = *p;
  170655. /* b: p1 (unmasked) */
  170656. if (!(b&0x80))
  170657. {
  170658. a &= 0x7f;
  170659. a = a<<7;
  170660. a |= b;
  170661. *v = a;
  170662. return 2;
  170663. }
  170664. /* Verify that constants are precomputed correctly */
  170665. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  170666. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  170667. p++;
  170668. a = a<<14;
  170669. a |= *p;
  170670. /* a: p0<<14 | p2 (unmasked) */
  170671. if (!(a&0x80))
  170672. {
  170673. a &= SLOT_2_0;
  170674. b &= 0x7f;
  170675. b = b<<7;
  170676. a |= b;
  170677. *v = a;
  170678. return 3;
  170679. }
  170680. /* CSE1 from below */
  170681. a &= SLOT_2_0;
  170682. p++;
  170683. b = b<<14;
  170684. b |= *p;
  170685. /* b: p1<<14 | p3 (unmasked) */
  170686. if (!(b&0x80))
  170687. {
  170688. b &= SLOT_2_0;
  170689. /* moved CSE1 up */
  170690. /* a &= (0x7f<<14)|(0x7f); */
  170691. a = a<<7;
  170692. a |= b;
  170693. *v = a;
  170694. return 4;
  170695. }
  170696. /* a: p0<<14 | p2 (masked) */
  170697. /* b: p1<<14 | p3 (unmasked) */
  170698. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  170699. /* moved CSE1 up */
  170700. /* a &= (0x7f<<14)|(0x7f); */
  170701. b &= SLOT_2_0;
  170702. s = a;
  170703. /* s: p0<<14 | p2 (masked) */
  170704. p++;
  170705. a = a<<14;
  170706. a |= *p;
  170707. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  170708. if (!(a&0x80))
  170709. {
  170710. /* we can skip these cause they were (effectively) done above in calc'ing s */
  170711. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  170712. /* b &= (0x7f<<14)|(0x7f); */
  170713. b = b<<7;
  170714. a |= b;
  170715. s = s>>18;
  170716. *v = ((u64)s)<<32 | a;
  170717. return 5;
  170718. }
  170719. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  170720. s = s<<7;
  170721. s |= b;
  170722. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  170723. p++;
  170724. b = b<<14;
  170725. b |= *p;
  170726. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  170727. if (!(b&0x80))
  170728. {
  170729. /* we can skip this cause it was (effectively) done above in calc'ing s */
  170730. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  170731. a &= SLOT_2_0;
  170732. a = a<<7;
  170733. a |= b;
  170734. s = s>>18;
  170735. *v = ((u64)s)<<32 | a;
  170736. return 6;
  170737. }
  170738. p++;
  170739. a = a<<14;
  170740. a |= *p;
  170741. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  170742. if (!(a&0x80))
  170743. {
  170744. a &= SLOT_4_2_0;
  170745. b &= SLOT_2_0;
  170746. b = b<<7;
  170747. a |= b;
  170748. s = s>>11;
  170749. *v = ((u64)s)<<32 | a;
  170750. return 7;
  170751. }
  170752. /* CSE2 from below */
  170753. a &= SLOT_2_0;
  170754. p++;
  170755. b = b<<14;
  170756. b |= *p;
  170757. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  170758. if (!(b&0x80))
  170759. {
  170760. b &= SLOT_4_2_0;
  170761. /* moved CSE2 up */
  170762. /* a &= (0x7f<<14)|(0x7f); */
  170763. a = a<<7;
  170764. a |= b;
  170765. s = s>>4;
  170766. *v = ((u64)s)<<32 | a;
  170767. return 8;
  170768. }
  170769. p++;
  170770. a = a<<15;
  170771. a |= *p;
  170772. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  170773. /* moved CSE2 up */
  170774. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  170775. b &= SLOT_2_0;
  170776. b = b<<8;
  170777. a |= b;
  170778. s = s<<4;
  170779. b = p[-4];
  170780. b &= 0x7f;
  170781. b = b>>3;
  170782. s |= b;
  170783. *v = ((u64)s)<<32 | a;
  170784. return 9;
  170785. }
  170786. /*
  170787. ** The variable-length integer encoding is as follows:
  170788. **
  170789. ** KEY:
  170790. ** A = 0xxxxxxx 7 bits of data and one flag bit
  170791. ** B = 1xxxxxxx 7 bits of data and one flag bit
  170792. ** C = xxxxxxxx 8 bits of data
  170793. **
  170794. ** 7 bits - A
  170795. ** 14 bits - BA
  170796. ** 21 bits - BBA
  170797. ** 28 bits - BBBA
  170798. ** 35 bits - BBBBA
  170799. ** 42 bits - BBBBBA
  170800. ** 49 bits - BBBBBBA
  170801. ** 56 bits - BBBBBBBA
  170802. ** 64 bits - BBBBBBBBC
  170803. */
  170804. #ifdef SQLITE_NOINLINE
  170805. # define FTS5_NOINLINE SQLITE_NOINLINE
  170806. #else
  170807. # define FTS5_NOINLINE
  170808. #endif
  170809. /*
  170810. ** Write a 64-bit variable-length integer to memory starting at p[0].
  170811. ** The length of data write will be between 1 and 9 bytes. The number
  170812. ** of bytes written is returned.
  170813. **
  170814. ** A variable-length integer consists of the lower 7 bits of each byte
  170815. ** for all bytes that have the 8th bit set and one byte with the 8th
  170816. ** bit clear. Except, if we get to the 9th byte, it stores the full
  170817. ** 8 bits and is the last byte.
  170818. */
  170819. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  170820. int i, j, n;
  170821. u8 buf[10];
  170822. if( v & (((u64)0xff000000)<<32) ){
  170823. p[8] = (u8)v;
  170824. v >>= 8;
  170825. for(i=7; i>=0; i--){
  170826. p[i] = (u8)((v & 0x7f) | 0x80);
  170827. v >>= 7;
  170828. }
  170829. return 9;
  170830. }
  170831. n = 0;
  170832. do{
  170833. buf[n++] = (u8)((v & 0x7f) | 0x80);
  170834. v >>= 7;
  170835. }while( v!=0 );
  170836. buf[0] &= 0x7f;
  170837. assert( n<=9 );
  170838. for(i=0, j=n-1; j>=0; j--, i++){
  170839. p[i] = buf[j];
  170840. }
  170841. return n;
  170842. }
  170843. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  170844. if( v<=0x7f ){
  170845. p[0] = v&0x7f;
  170846. return 1;
  170847. }
  170848. if( v<=0x3fff ){
  170849. p[0] = ((v>>7)&0x7f)|0x80;
  170850. p[1] = v&0x7f;
  170851. return 2;
  170852. }
  170853. return fts5PutVarint64(p,v);
  170854. }
  170855. static int sqlite3Fts5GetVarintLen(u32 iVal){
  170856. if( iVal<(1 << 7 ) ) return 1;
  170857. if( iVal<(1 << 14) ) return 2;
  170858. if( iVal<(1 << 21) ) return 3;
  170859. if( iVal<(1 << 28) ) return 4;
  170860. return 5;
  170861. }
  170862. /*
  170863. ** 2015 May 08
  170864. **
  170865. ** The author disclaims copyright to this source code. In place of
  170866. ** a legal notice, here is a blessing:
  170867. **
  170868. ** May you do good and not evil.
  170869. ** May you find forgiveness for yourself and forgive others.
  170870. ** May you share freely, never taking more than you give.
  170871. **
  170872. ******************************************************************************
  170873. **
  170874. ** This is an SQLite virtual table module implementing direct access to an
  170875. ** existing FTS5 index. The module may create several different types of
  170876. ** tables:
  170877. **
  170878. ** col:
  170879. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  170880. **
  170881. ** One row for each term/column combination. The value of $doc is set to
  170882. ** the number of fts5 rows that contain at least one instance of term
  170883. ** $term within column $col. Field $cnt is set to the total number of
  170884. ** instances of term $term in column $col (in any row of the fts5 table).
  170885. **
  170886. ** row:
  170887. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  170888. **
  170889. ** One row for each term in the database. The value of $doc is set to
  170890. ** the number of fts5 rows that contain at least one instance of term
  170891. ** $term. Field $cnt is set to the total number of instances of term
  170892. ** $term in the database.
  170893. */
  170894. typedef struct Fts5VocabTable Fts5VocabTable;
  170895. typedef struct Fts5VocabCursor Fts5VocabCursor;
  170896. struct Fts5VocabTable {
  170897. sqlite3_vtab base;
  170898. char *zFts5Tbl; /* Name of fts5 table */
  170899. char *zFts5Db; /* Db containing fts5 table */
  170900. sqlite3 *db; /* Database handle */
  170901. Fts5Global *pGlobal; /* FTS5 global object for this database */
  170902. int eType; /* FTS5_VOCAB_COL or ROW */
  170903. };
  170904. struct Fts5VocabCursor {
  170905. sqlite3_vtab_cursor base;
  170906. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  170907. Fts5Index *pIndex; /* Associated FTS5 index */
  170908. int bEof; /* True if this cursor is at EOF */
  170909. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  170910. /* These are used by 'col' tables only */
  170911. int nCol;
  170912. int iCol;
  170913. i64 *aCnt;
  170914. i64 *aDoc;
  170915. /* Output values */
  170916. i64 rowid; /* This table's current rowid value */
  170917. Fts5Buffer term; /* Current value of 'term' column */
  170918. i64 aVal[3]; /* Up to three columns left of 'term' */
  170919. };
  170920. #define FTS5_VOCAB_COL 0
  170921. #define FTS5_VOCAB_ROW 1
  170922. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  170923. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  170924. /*
  170925. ** Translate a string containing an fts5vocab table type to an
  170926. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  170927. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  170928. ** and return SQLITE_ERROR.
  170929. */
  170930. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  170931. int rc = SQLITE_OK;
  170932. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  170933. if( rc==SQLITE_OK ){
  170934. sqlite3Fts5Dequote(zCopy);
  170935. if( sqlite3_stricmp(zCopy, "col")==0 ){
  170936. *peType = FTS5_VOCAB_COL;
  170937. }else
  170938. if( sqlite3_stricmp(zCopy, "row")==0 ){
  170939. *peType = FTS5_VOCAB_ROW;
  170940. }else
  170941. {
  170942. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  170943. rc = SQLITE_ERROR;
  170944. }
  170945. sqlite3_free(zCopy);
  170946. }
  170947. return rc;
  170948. }
  170949. /*
  170950. ** The xDisconnect() virtual table method.
  170951. */
  170952. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  170953. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  170954. sqlite3_free(pTab);
  170955. return SQLITE_OK;
  170956. }
  170957. /*
  170958. ** The xDestroy() virtual table method.
  170959. */
  170960. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  170961. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  170962. sqlite3_free(pTab);
  170963. return SQLITE_OK;
  170964. }
  170965. /*
  170966. ** This function is the implementation of both the xConnect and xCreate
  170967. ** methods of the FTS3 virtual table.
  170968. **
  170969. ** The argv[] array contains the following:
  170970. **
  170971. ** argv[0] -> module name ("fts5vocab")
  170972. ** argv[1] -> database name
  170973. ** argv[2] -> table name
  170974. **
  170975. ** then:
  170976. **
  170977. ** argv[3] -> name of fts5 table
  170978. ** argv[4] -> type of fts5vocab table
  170979. **
  170980. ** or, for tables in the TEMP schema only.
  170981. **
  170982. ** argv[3] -> name of fts5 tables database
  170983. ** argv[4] -> name of fts5 table
  170984. ** argv[5] -> type of fts5vocab table
  170985. */
  170986. static int fts5VocabInitVtab(
  170987. sqlite3 *db, /* The SQLite database connection */
  170988. void *pAux, /* Pointer to Fts5Global object */
  170989. int argc, /* Number of elements in argv array */
  170990. const char * const *argv, /* xCreate/xConnect argument array */
  170991. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  170992. char **pzErr /* Write any error message here */
  170993. ){
  170994. const char *azSchema[] = {
  170995. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  170996. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
  170997. };
  170998. Fts5VocabTable *pRet = 0;
  170999. int rc = SQLITE_OK; /* Return code */
  171000. int bDb;
  171001. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  171002. if( argc!=5 && bDb==0 ){
  171003. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  171004. rc = SQLITE_ERROR;
  171005. }else{
  171006. int nByte; /* Bytes of space to allocate */
  171007. const char *zDb = bDb ? argv[3] : argv[1];
  171008. const char *zTab = bDb ? argv[4] : argv[3];
  171009. const char *zType = bDb ? argv[5] : argv[4];
  171010. int nDb = strlen(zDb)+1;
  171011. int nTab = strlen(zTab)+1;
  171012. int eType;
  171013. rc = fts5VocabTableType(zType, pzErr, &eType);
  171014. if( rc==SQLITE_OK ){
  171015. assert( eType>=0 && eType<sizeof(azSchema)/sizeof(azSchema[0]) );
  171016. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  171017. }
  171018. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  171019. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  171020. if( pRet ){
  171021. pRet->pGlobal = (Fts5Global*)pAux;
  171022. pRet->eType = eType;
  171023. pRet->db = db;
  171024. pRet->zFts5Tbl = (char*)&pRet[1];
  171025. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  171026. memcpy(pRet->zFts5Tbl, zTab, nTab);
  171027. memcpy(pRet->zFts5Db, zDb, nDb);
  171028. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  171029. sqlite3Fts5Dequote(pRet->zFts5Db);
  171030. }
  171031. }
  171032. *ppVTab = (sqlite3_vtab*)pRet;
  171033. return rc;
  171034. }
  171035. /*
  171036. ** The xConnect() and xCreate() methods for the virtual table. All the
  171037. ** work is done in function fts5VocabInitVtab().
  171038. */
  171039. static int fts5VocabConnectMethod(
  171040. sqlite3 *db, /* Database connection */
  171041. void *pAux, /* Pointer to tokenizer hash table */
  171042. int argc, /* Number of elements in argv array */
  171043. const char * const *argv, /* xCreate/xConnect argument array */
  171044. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  171045. char **pzErr /* OUT: sqlite3_malloc'd error message */
  171046. ){
  171047. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  171048. }
  171049. static int fts5VocabCreateMethod(
  171050. sqlite3 *db, /* Database connection */
  171051. void *pAux, /* Pointer to tokenizer hash table */
  171052. int argc, /* Number of elements in argv array */
  171053. const char * const *argv, /* xCreate/xConnect argument array */
  171054. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  171055. char **pzErr /* OUT: sqlite3_malloc'd error message */
  171056. ){
  171057. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  171058. }
  171059. /*
  171060. ** Implementation of the xBestIndex method.
  171061. */
  171062. static int fts5VocabBestIndexMethod(
  171063. sqlite3_vtab *pVTab,
  171064. sqlite3_index_info *pInfo
  171065. ){
  171066. return SQLITE_OK;
  171067. }
  171068. /*
  171069. ** Implementation of xOpen method.
  171070. */
  171071. static int fts5VocabOpenMethod(
  171072. sqlite3_vtab *pVTab,
  171073. sqlite3_vtab_cursor **ppCsr
  171074. ){
  171075. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  171076. Fts5Index *pIndex = 0;
  171077. int nCol = 0;
  171078. Fts5VocabCursor *pCsr = 0;
  171079. int rc = SQLITE_OK;
  171080. sqlite3_stmt *pStmt = 0;
  171081. char *zSql = 0;
  171082. int nByte;
  171083. zSql = sqlite3Fts5Mprintf(&rc,
  171084. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  171085. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  171086. );
  171087. if( zSql ){
  171088. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  171089. }
  171090. sqlite3_free(zSql);
  171091. assert( rc==SQLITE_OK || pStmt==0 );
  171092. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  171093. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  171094. i64 iId = sqlite3_column_int64(pStmt, 0);
  171095. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &nCol);
  171096. }
  171097. if( rc==SQLITE_OK && pIndex==0 ){
  171098. rc = sqlite3_finalize(pStmt);
  171099. pStmt = 0;
  171100. if( rc==SQLITE_OK ){
  171101. pVTab->zErrMsg = sqlite3_mprintf(
  171102. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  171103. );
  171104. rc = SQLITE_ERROR;
  171105. }
  171106. }
  171107. nByte = nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  171108. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  171109. if( pCsr ){
  171110. pCsr->pIndex = pIndex;
  171111. pCsr->pStmt = pStmt;
  171112. pCsr->nCol = nCol;
  171113. pCsr->aCnt = (i64*)&pCsr[1];
  171114. pCsr->aDoc = &pCsr->aCnt[nCol];
  171115. }else{
  171116. sqlite3_finalize(pStmt);
  171117. }
  171118. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  171119. return rc;
  171120. }
  171121. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  171122. pCsr->rowid = 0;
  171123. sqlite3Fts5IterClose(pCsr->pIter);
  171124. pCsr->pIter = 0;
  171125. }
  171126. /*
  171127. ** Close the cursor. For additional information see the documentation
  171128. ** on the xClose method of the virtual table interface.
  171129. */
  171130. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  171131. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171132. fts5VocabResetCursor(pCsr);
  171133. sqlite3Fts5BufferFree(&pCsr->term);
  171134. sqlite3_finalize(pCsr->pStmt);
  171135. sqlite3_free(pCsr);
  171136. return SQLITE_OK;
  171137. }
  171138. /*
  171139. ** Advance the cursor to the next row in the table.
  171140. */
  171141. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  171142. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171143. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  171144. int rc = SQLITE_OK;
  171145. pCsr->rowid++;
  171146. if( pTab->eType==FTS5_VOCAB_COL ){
  171147. for(pCsr->iCol++; pCsr->iCol<pCsr->nCol; pCsr->iCol++){
  171148. if( pCsr->aCnt[pCsr->iCol] ) break;
  171149. }
  171150. }
  171151. if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=pCsr->nCol ){
  171152. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  171153. pCsr->bEof = 1;
  171154. }else{
  171155. const char *zTerm;
  171156. int nTerm;
  171157. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  171158. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  171159. memset(pCsr->aVal, 0, sizeof(pCsr->aVal));
  171160. memset(pCsr->aCnt, 0, pCsr->nCol * sizeof(i64));
  171161. memset(pCsr->aDoc, 0, pCsr->nCol * sizeof(i64));
  171162. pCsr->iCol = 0;
  171163. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  171164. while( rc==SQLITE_OK ){
  171165. i64 dummy;
  171166. const u8 *pPos; int nPos; /* Position list */
  171167. i64 iPos = 0; /* 64-bit position read from poslist */
  171168. int iOff = 0; /* Current offset within position list */
  171169. rc = sqlite3Fts5IterPoslist(pCsr->pIter, 0, &pPos, &nPos, &dummy);
  171170. if( rc==SQLITE_OK ){
  171171. if( pTab->eType==FTS5_VOCAB_ROW ){
  171172. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  171173. pCsr->aVal[1]++;
  171174. }
  171175. pCsr->aVal[0]++;
  171176. }else{
  171177. int iCol = -1;
  171178. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  171179. int ii = FTS5_POS2COLUMN(iPos);
  171180. pCsr->aCnt[ii]++;
  171181. if( iCol!=ii ){
  171182. pCsr->aDoc[ii]++;
  171183. iCol = ii;
  171184. }
  171185. }
  171186. }
  171187. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  171188. }
  171189. if( rc==SQLITE_OK ){
  171190. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  171191. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ) break;
  171192. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  171193. }
  171194. }
  171195. }
  171196. }
  171197. if( pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  171198. while( pCsr->aCnt[pCsr->iCol]==0 ) pCsr->iCol++;
  171199. pCsr->aVal[0] = pCsr->iCol;
  171200. pCsr->aVal[1] = pCsr->aDoc[pCsr->iCol];
  171201. pCsr->aVal[2] = pCsr->aCnt[pCsr->iCol];
  171202. }
  171203. return rc;
  171204. }
  171205. /*
  171206. ** This is the xFilter implementation for the virtual table.
  171207. */
  171208. static int fts5VocabFilterMethod(
  171209. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  171210. int idxNum, /* Strategy index */
  171211. const char *idxStr, /* Unused */
  171212. int nVal, /* Number of elements in apVal */
  171213. sqlite3_value **apVal /* Arguments for the indexing scheme */
  171214. ){
  171215. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171216. int rc;
  171217. const int flags = FTS5INDEX_QUERY_SCAN;
  171218. fts5VocabResetCursor(pCsr);
  171219. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, 0, 0, flags, 0, &pCsr->pIter);
  171220. if( rc==SQLITE_OK ){
  171221. rc = fts5VocabNextMethod(pCursor);
  171222. }
  171223. return rc;
  171224. }
  171225. /*
  171226. ** This is the xEof method of the virtual table. SQLite calls this
  171227. ** routine to find out if it has reached the end of a result set.
  171228. */
  171229. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  171230. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171231. return pCsr->bEof;
  171232. }
  171233. static int fts5VocabColumnMethod(
  171234. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  171235. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  171236. int iCol /* Index of column to read value from */
  171237. ){
  171238. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171239. switch( iCol ){
  171240. case 0: /* term */
  171241. sqlite3_result_text(
  171242. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  171243. );
  171244. break;
  171245. default:
  171246. assert( iCol<4 && iCol>0 );
  171247. sqlite3_result_int64(pCtx, pCsr->aVal[iCol-1]);
  171248. break;
  171249. }
  171250. return SQLITE_OK;
  171251. }
  171252. /*
  171253. ** This is the xRowid method. The SQLite core calls this routine to
  171254. ** retrieve the rowid for the current row of the result set. The
  171255. ** rowid should be written to *pRowid.
  171256. */
  171257. static int fts5VocabRowidMethod(
  171258. sqlite3_vtab_cursor *pCursor,
  171259. sqlite_int64 *pRowid
  171260. ){
  171261. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  171262. *pRowid = pCsr->rowid;
  171263. return SQLITE_OK;
  171264. }
  171265. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  171266. static const sqlite3_module fts5Vocab = {
  171267. /* iVersion */ 2,
  171268. /* xCreate */ fts5VocabCreateMethod,
  171269. /* xConnect */ fts5VocabConnectMethod,
  171270. /* xBestIndex */ fts5VocabBestIndexMethod,
  171271. /* xDisconnect */ fts5VocabDisconnectMethod,
  171272. /* xDestroy */ fts5VocabDestroyMethod,
  171273. /* xOpen */ fts5VocabOpenMethod,
  171274. /* xClose */ fts5VocabCloseMethod,
  171275. /* xFilter */ fts5VocabFilterMethod,
  171276. /* xNext */ fts5VocabNextMethod,
  171277. /* xEof */ fts5VocabEofMethod,
  171278. /* xColumn */ fts5VocabColumnMethod,
  171279. /* xRowid */ fts5VocabRowidMethod,
  171280. /* xUpdate */ 0,
  171281. /* xBegin */ 0,
  171282. /* xSync */ 0,
  171283. /* xCommit */ 0,
  171284. /* xRollback */ 0,
  171285. /* xFindFunction */ 0,
  171286. /* xRename */ 0,
  171287. /* xSavepoint */ 0,
  171288. /* xRelease */ 0,
  171289. /* xRollbackTo */ 0,
  171290. };
  171291. void *p = (void*)pGlobal;
  171292. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  171293. }
  171294. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  171295. /************** End of fts5.c ************************************************/